blob: 22b3bd416d8cdad31119a3a418f2f5110780bbdb [file] [log] [blame]
Daniel Dunbar4ee34612010-02-25 04:37:45 +00001//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
Daniel Dunbard69bacc2008-10-21 23:49:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Dunbar4ee34612010-02-25 04:37:45 +000010#include "clang/Frontend/CodeGenAction.h"
Chris Lattner6da9eb62010-04-06 18:38:50 +000011#include "clang/Basic/SourceManager.h"
12#include "clang/Basic/TargetInfo.h"
Chris Lattner682bf922009-03-29 16:50:03 +000013#include "clang/AST/ASTConsumer.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000014#include "clang/AST/ASTContext.h"
Chris Lattner682bf922009-03-29 16:50:03 +000015#include "clang/AST/DeclGroup.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000016#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbar4ee34612010-02-25 04:37:45 +000017#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000018#include "clang/Frontend/BackendUtil.h"
Daniel Dunbar4ee34612010-02-25 04:37:45 +000019#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar3be0d192009-12-03 09:12:54 +000020#include "clang/Frontend/FrontendDiagnostic.h"
Chris Lattnercabae682010-04-06 17:52:14 +000021#include "llvm/LLVMContext.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000022#include "llvm/Module.h"
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000023#include "llvm/Pass.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000024#include "llvm/ADT/OwningPtr.h"
Daniel Dunbar4cbbd942010-06-07 23:27:59 +000025#include "llvm/Support/IRReader.h"
Chris Lattner6da9eb62010-04-06 18:38:50 +000026#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/Support/SourceMgr.h"
Chris Lattner6f114eb2009-02-18 01:37:30 +000028#include "llvm/Support/Timer.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000029using namespace clang;
30using namespace llvm;
31
32namespace {
Benjamin Kramerbd218282009-11-28 10:07:24 +000033 class BackendConsumer : public ASTConsumer {
Daniel Dunbar125bbbe2009-12-04 08:17:40 +000034 Diagnostic &Diags;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000035 BackendAction Action;
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000036 const CodeGenOptions &CodeGenOpts;
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000037 const TargetOptions &TargetOpts;
Eli Friedman66d6f042009-05-18 22:20:00 +000038 llvm::raw_ostream *AsmOutStream;
Chris Lattner49f28ca2009-03-05 08:00:35 +000039 ASTContext *Context;
Daniel Dunbar90f41302008-10-29 08:50:02 +000040
Chris Lattner6f114eb2009-02-18 01:37:30 +000041 Timer LLVMIRGeneration;
Mike Stump1eb44332009-09-09 15:08:12 +000042
Daniel Dunbard69bacc2008-10-21 23:49:24 +000043 llvm::OwningPtr<CodeGenerator> Gen;
Mike Stump1eb44332009-09-09 15:08:12 +000044
Daniel Dunbarb954e982010-02-25 04:37:50 +000045 llvm::OwningPtr<llvm::Module> TheModule;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000046
Mike Stump1eb44332009-09-09 15:08:12 +000047 public:
Daniel Dunbar3be0d192009-12-03 09:12:54 +000048 BackendConsumer(BackendAction action, Diagnostic &_Diags,
Daniel Dunbar6b0cf672010-06-07 23:19:17 +000049 const CodeGenOptions &compopts,
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000050 const TargetOptions &targetopts, bool TimePasses,
51 const std::string &infile, llvm::raw_ostream *OS,
Chris Lattnercabae682010-04-06 17:52:14 +000052 LLVMContext &C) :
Daniel Dunbar3be0d192009-12-03 09:12:54 +000053 Diags(_Diags),
Mike Stump1eb44332009-09-09 15:08:12 +000054 Action(action),
Chandler Carruth2811ccf2009-11-12 17:24:48 +000055 CodeGenOpts(compopts),
Daniel Dunbard58c03f2009-11-15 06:48:46 +000056 TargetOpts(targetopts),
Chris Lattner03eacc72009-07-14 20:39:15 +000057 AsmOutStream(OS),
Chris Lattner6f114eb2009-02-18 01:37:30 +000058 LLVMIRGeneration("LLVM IR Generation Time"),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000059 Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)) {
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000060 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattner44502662009-02-18 01:23:44 +000061 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +000062
Daniel Dunbarb954e982010-02-25 04:37:50 +000063 llvm::Module *takeModule() { return TheModule.take(); }
64
Chris Lattner7bb0da02009-03-28 02:18:25 +000065 virtual void Initialize(ASTContext &Ctx) {
66 Context = &Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +000067
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000068 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000069 LLVMIRGeneration.startTimer();
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattner7bb0da02009-03-28 02:18:25 +000071 Gen->Initialize(Ctx);
Daniel Dunbard69bacc2008-10-21 23:49:24 +000072
Daniel Dunbarb954e982010-02-25 04:37:50 +000073 TheModule.reset(Gen->GetModule());
Mike Stump1eb44332009-09-09 15:08:12 +000074
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000075 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000076 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +000077 }
Mike Stump1eb44332009-09-09 15:08:12 +000078
Chris Lattner682bf922009-03-29 16:50:03 +000079 virtual void HandleTopLevelDecl(DeclGroupRef D) {
80 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattner49f28ca2009-03-05 08:00:35 +000081 Context->getSourceManager(),
82 "LLVM IR generation of declaration");
Mike Stump1eb44332009-09-09 15:08:12 +000083
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000084 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000085 LLVMIRGeneration.startTimer();
Chris Lattner682bf922009-03-29 16:50:03 +000086
Daniel Dunbard69bacc2008-10-21 23:49:24 +000087 Gen->HandleTopLevelDecl(D);
Chris Lattner6f114eb2009-02-18 01:37:30 +000088
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000089 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000090 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +000091 }
Mike Stump1eb44332009-09-09 15:08:12 +000092
Chris Lattnerdacbc5d2009-03-28 04:11:33 +000093 virtual void HandleTranslationUnit(ASTContext &C) {
Chris Lattner49f28ca2009-03-05 08:00:35 +000094 {
Chris Lattner14f234e2009-03-06 06:46:31 +000095 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000096 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +000097 LLVMIRGeneration.startTimer();
Chris Lattner6f114eb2009-02-18 01:37:30 +000098
Chris Lattnerdacbc5d2009-03-28 04:11:33 +000099 Gen->HandleTranslationUnit(C);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000100
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000101 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +0000102 LLVMIRGeneration.stopTimer();
103 }
Chris Lattner6f114eb2009-02-18 01:37:30 +0000104
Daniel Dunbar897c6762010-06-07 23:20:08 +0000105 // Silently ignore if we weren't initialized for some reason.
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000106 if (!TheModule)
Daniel Dunbar897c6762010-06-07 23:20:08 +0000107 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Daniel Dunbar897c6762010-06-07 23:20:08 +0000109 // Make sure IR generation is happy with the module. This is released by
110 // the module provider.
111 Module *M = Gen->ReleaseModule();
112 if (!M) {
113 // The module has been released by IR gen on failures, do not double
114 // free.
115 TheModule.take();
116 return;
117 }
118
119 assert(TheModule.get() == M &&
120 "Unexpected module change during IR generation");
121
122 // Install an inline asm handler so that diagnostics get printed through
123 // our diagnostics hooks.
124 LLVMContext &Ctx = TheModule->getContext();
125 void *OldHandler = Ctx.getInlineAsmDiagnosticHandler();
126 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
127 Ctx.setInlineAsmDiagnosticHandler((void*)(intptr_t)InlineAsmDiagHandler,
128 this);
129
130 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000131 TheModule.get(), Action, AsmOutStream);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000132
133 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000134 }
Mike Stump1eb44332009-09-09 15:08:12 +0000135
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000136 virtual void HandleTagDeclDefinition(TagDecl *D) {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000137 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
138 Context->getSourceManager(),
139 "LLVM IR generation of declaration");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000140 Gen->HandleTagDeclDefinition(D);
141 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000142
143 virtual void CompleteTentativeDefinition(VarDecl *D) {
144 Gen->CompleteTentativeDefinition(D);
145 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000146
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000147 virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
148 Gen->HandleVTable(RD, DefinitionRequired);
149 }
150
Chris Lattner6da9eb62010-04-06 18:38:50 +0000151 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
152 unsigned LocCookie) {
153 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
154 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
155 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000156
Chris Lattner6da9eb62010-04-06 18:38:50 +0000157 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
158 SourceLocation LocCookie);
Mike Stump1eb44332009-09-09 15:08:12 +0000159 };
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000160}
161
Chris Lattnerd6f19062010-04-08 00:23:06 +0000162/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
163/// buffer to be a valid FullSourceLoc.
164static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
165 SourceManager &CSM) {
166 // Get both the clang and llvm source managers. The location is relative to
167 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000168 // a copy to the Clang source manager.
Chris Lattnerd6f19062010-04-08 00:23:06 +0000169 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000170
Chris Lattnerd6f19062010-04-08 00:23:06 +0000171 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
172 // already owns its one and clang::SourceManager wants to own its one.
173 const MemoryBuffer *LBuf =
174 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000175
Chris Lattnerd6f19062010-04-08 00:23:06 +0000176 // Create the copy and transfer ownership to clang::SourceManager.
177 llvm::MemoryBuffer *CBuf =
178 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
179 LBuf->getBufferIdentifier());
180 FileID FID = CSM.createFileIDForMemBuffer(CBuf);
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000181
Chris Lattnerd6f19062010-04-08 00:23:06 +0000182 // Translate the offset into the file.
183 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000184 SourceLocation NewLoc =
Chris Lattnerd6f19062010-04-08 00:23:06 +0000185 CSM.getLocForStartOfFile(FID).getFileLocWithOffset(Offset);
186 return FullSourceLoc(NewLoc, CSM);
187}
188
Chris Lattnercabae682010-04-06 17:52:14 +0000189
Chris Lattner6da9eb62010-04-06 18:38:50 +0000190/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
191/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000192/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner6da9eb62010-04-06 18:38:50 +0000193void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
194 SourceLocation LocCookie) {
195 // There are a couple of different kinds of errors we could get here. First,
196 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000197
Chris Lattner6da9eb62010-04-06 18:38:50 +0000198 // Strip "error: " off the start of the message string.
199 llvm::StringRef Message = D.getMessage();
200 if (Message.startswith("error: "))
201 Message = Message.substr(7);
202
203 // There are two cases: the SMDiagnostic could have a inline asm source
204 // location or it might not. If it does, translate the location.
205 FullSourceLoc Loc;
Chris Lattnerd6f19062010-04-08 00:23:06 +0000206 if (D.getLoc() != SMLoc())
207 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Chris Lattner6da9eb62010-04-06 18:38:50 +0000208 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000209
Chris Lattner6da9eb62010-04-06 18:38:50 +0000210 // This could be a problem with no clang-level source location information.
211 // In this case, LocCookie is invalid. If there is source level information,
212 // print an "generated from" note.
213 if (LocCookie.isValid())
214 Diags.Report(FullSourceLoc(LocCookie, Context->getSourceManager()),
215 diag::note_fe_inline_asm_here);
216}
217
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000218//
219
220CodeGenAction::CodeGenAction(unsigned _Act) : Act(_Act) {}
221
Daniel Dunbar9ad1c022010-02-25 20:37:44 +0000222CodeGenAction::~CodeGenAction() {}
223
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000224bool CodeGenAction::hasIRSupport() const { return true; }
225
Daniel Dunbarb954e982010-02-25 04:37:50 +0000226void CodeGenAction::EndSourceFileAction() {
227 // If the consumer creation failed, do nothing.
228 if (!getCompilerInstance().hasASTConsumer())
229 return;
230
231 // Steal the module from the consumer.
232 BackendConsumer *Consumer = static_cast<BackendConsumer*>(
233 &getCompilerInstance().getASTConsumer());
234
235 TheModule.reset(Consumer->takeModule());
236}
237
238llvm::Module *CodeGenAction::takeModule() {
239 return TheModule.take();
240}
241
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000242static raw_ostream *GetOutputStream(CompilerInstance &CI,
243 llvm::StringRef InFile,
244 BackendAction Action) {
245 switch (Action) {
246 case Backend_EmitAssembly:
247 return CI.createDefaultOutputFile(false, InFile, "s");
248 case Backend_EmitLL:
249 return CI.createDefaultOutputFile(false, InFile, "ll");
250 case Backend_EmitBC:
251 return CI.createDefaultOutputFile(true, InFile, "bc");
252 case Backend_EmitNothing:
253 return 0;
254 case Backend_EmitMCNull:
255 case Backend_EmitObj:
256 return CI.createDefaultOutputFile(true, InFile, "o");
257 }
258
259 assert(0 && "Invalid action!");
260 return 0;
261}
262
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000263ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
264 llvm::StringRef InFile) {
265 BackendAction BA = static_cast<BackendAction>(Act);
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000266 llvm::OwningPtr<llvm::raw_ostream> OS(GetOutputStream(CI, InFile, BA));
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000267 if (BA != Backend_EmitNothing && !OS)
268 return 0;
269
Daniel Dunbar6b0cf672010-06-07 23:19:17 +0000270 return new BackendConsumer(BA, CI.getDiagnostics(),
John McCall468ec6c2010-03-04 04:29:44 +0000271 CI.getCodeGenOpts(), CI.getTargetOpts(),
272 CI.getFrontendOpts().ShowTimers, InFile, OS.take(),
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000273 CI.getLLVMContext());
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000274}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000275
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000276void CodeGenAction::ExecuteAction() {
277 // If this is an IR file, we have to treat it specially.
278 if (getCurrentFileKind() == IK_LLVM_IR) {
279 BackendAction BA = static_cast<BackendAction>(Act);
280 CompilerInstance &CI = getCompilerInstance();
281 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
282 if (BA != Backend_EmitNothing && !OS)
283 return;
284
285 bool Invalid;
286 SourceManager &SM = CI.getSourceManager();
287 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
288 &Invalid);
289 if (Invalid)
290 return;
291
292 // FIXME: This is stupid, IRReader shouldn't take ownership.
293 llvm::MemoryBuffer *MainFileCopy =
294 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
295 getCurrentFile().c_str());
296
297 llvm::SMDiagnostic Err;
298 TheModule.reset(ParseIR(MainFileCopy, Err, CI.getLLVMContext()));
299 if (!TheModule) {
300 // Translate from the diagnostic info to the SourceManager location.
301 SourceLocation Loc = SM.getLocation(
302 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
303 Err.getColumnNo() + 1);
304
305 // Get a custom diagnostic for the error. We strip off a leading
306 // diagnostic code if there is one.
307 llvm::StringRef Msg = Err.getMessage();
308 if (Msg.startswith("error: "))
309 Msg = Msg.substr(7);
310 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(Diagnostic::Error,
311 Msg);
312
313 CI.getDiagnostics().Report(FullSourceLoc(Loc, SM), DiagID);
314 return;
315 }
316
317 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
318 CI.getTargetOpts(), TheModule.get(),
319 BA, OS);
320 return;
321 }
322
323 // Otherwise follow the normal AST path.
324 this->ASTFrontendAction::ExecuteAction();
325}
326
327//
328
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000329EmitAssemblyAction::EmitAssemblyAction()
330 : CodeGenAction(Backend_EmitAssembly) {}
331
332EmitBCAction::EmitBCAction() : CodeGenAction(Backend_EmitBC) {}
333
334EmitLLVMAction::EmitLLVMAction() : CodeGenAction(Backend_EmitLL) {}
335
336EmitLLVMOnlyAction::EmitLLVMOnlyAction() : CodeGenAction(Backend_EmitNothing) {}
337
Daniel Dunbar32148ce2010-05-25 18:41:01 +0000338EmitCodeGenOnlyAction::EmitCodeGenOnlyAction() : CodeGenAction(Backend_EmitMCNull) {}
339
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000340EmitObjAction::EmitObjAction() : CodeGenAction(Backend_EmitObj) {}