blob: 69ac995a468b9c0b9a70c74e9fc46dbe6e43e701 [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 Dunbar9b414d32010-06-15 17:48:49 +000010#include "clang/CodeGen/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 Dunbar9b414d32010-06-15 17:48:49 +000016#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000017#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbar4ee34612010-02-25 04:37:45 +000018#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar3be0d192009-12-03 09:12:54 +000019#include "clang/Frontend/FrontendDiagnostic.h"
Chris Lattnercabae682010-04-06 17:52:14 +000020#include "llvm/LLVMContext.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000021#include "llvm/Module.h"
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000022#include "llvm/Pass.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000023#include "llvm/ADT/OwningPtr.h"
Daniel Dunbar4cbbd942010-06-07 23:27:59 +000024#include "llvm/Support/IRReader.h"
Chris Lattner6da9eb62010-04-06 18:38:50 +000025#include "llvm/Support/MemoryBuffer.h"
26#include "llvm/Support/SourceMgr.h"
Chris Lattner6f114eb2009-02-18 01:37:30 +000027#include "llvm/Support/Timer.h"
Daniel Dunbard69bacc2008-10-21 23:49:24 +000028using namespace clang;
29using namespace llvm;
30
Nico Weber5aa74af2011-01-25 20:34:14 +000031namespace clang {
Benjamin Kramerbd218282009-11-28 10:07:24 +000032 class BackendConsumer : public ASTConsumer {
Daniel Dunbar125bbbe2009-12-04 08:17:40 +000033 Diagnostic &Diags;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000034 BackendAction Action;
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000035 const CodeGenOptions &CodeGenOpts;
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000036 const TargetOptions &TargetOpts;
Eli Friedman66d6f042009-05-18 22:20:00 +000037 llvm::raw_ostream *AsmOutStream;
Chris Lattner49f28ca2009-03-05 08:00:35 +000038 ASTContext *Context;
Daniel Dunbar90f41302008-10-29 08:50:02 +000039
Chris Lattner6f114eb2009-02-18 01:37:30 +000040 Timer LLVMIRGeneration;
Mike Stump1eb44332009-09-09 15:08:12 +000041
Daniel Dunbard69bacc2008-10-21 23:49:24 +000042 llvm::OwningPtr<CodeGenerator> Gen;
Mike Stump1eb44332009-09-09 15:08:12 +000043
Daniel Dunbarb954e982010-02-25 04:37:50 +000044 llvm::OwningPtr<llvm::Module> TheModule;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000045
Mike Stump1eb44332009-09-09 15:08:12 +000046 public:
Daniel Dunbar3be0d192009-12-03 09:12:54 +000047 BackendConsumer(BackendAction action, Diagnostic &_Diags,
Daniel Dunbar6b0cf672010-06-07 23:19:17 +000048 const CodeGenOptions &compopts,
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000049 const TargetOptions &targetopts, bool TimePasses,
50 const std::string &infile, llvm::raw_ostream *OS,
Chris Lattnercabae682010-04-06 17:52:14 +000051 LLVMContext &C) :
Daniel Dunbar3be0d192009-12-03 09:12:54 +000052 Diags(_Diags),
Mike Stump1eb44332009-09-09 15:08:12 +000053 Action(action),
Chandler Carruth2811ccf2009-11-12 17:24:48 +000054 CodeGenOpts(compopts),
Daniel Dunbard58c03f2009-11-15 06:48:46 +000055 TargetOpts(targetopts),
Chris Lattner03eacc72009-07-14 20:39:15 +000056 AsmOutStream(OS),
Chris Lattner6f114eb2009-02-18 01:37:30 +000057 LLVMIRGeneration("LLVM IR Generation Time"),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000058 Gen(CreateLLVMCodeGen(Diags, infile, compopts, C)) {
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000059 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattner44502662009-02-18 01:23:44 +000060 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +000061
Daniel Dunbarb954e982010-02-25 04:37:50 +000062 llvm::Module *takeModule() { return TheModule.take(); }
63
Chris Lattner7bb0da02009-03-28 02:18:25 +000064 virtual void Initialize(ASTContext &Ctx) {
65 Context = &Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +000066
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000067 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000068 LLVMIRGeneration.startTimer();
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner7bb0da02009-03-28 02:18:25 +000070 Gen->Initialize(Ctx);
Daniel Dunbard69bacc2008-10-21 23:49:24 +000071
Daniel Dunbarb954e982010-02-25 04:37:50 +000072 TheModule.reset(Gen->GetModule());
Mike Stump1eb44332009-09-09 15:08:12 +000073
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000074 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000075 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +000076 }
Mike Stump1eb44332009-09-09 15:08:12 +000077
Chris Lattner682bf922009-03-29 16:50:03 +000078 virtual void HandleTopLevelDecl(DeclGroupRef D) {
79 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattner49f28ca2009-03-05 08:00:35 +000080 Context->getSourceManager(),
81 "LLVM IR generation of declaration");
Mike Stump1eb44332009-09-09 15:08:12 +000082
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000083 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000084 LLVMIRGeneration.startTimer();
Chris Lattner682bf922009-03-29 16:50:03 +000085
Daniel Dunbard69bacc2008-10-21 23:49:24 +000086 Gen->HandleTopLevelDecl(D);
Chris Lattner6f114eb2009-02-18 01:37:30 +000087
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000088 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000089 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +000090 }
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnerdacbc5d2009-03-28 04:11:33 +000092 virtual void HandleTranslationUnit(ASTContext &C) {
Chris Lattner49f28ca2009-03-05 08:00:35 +000093 {
Chris Lattner14f234e2009-03-06 06:46:31 +000094 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000095 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +000096 LLVMIRGeneration.startTimer();
Chris Lattner6f114eb2009-02-18 01:37:30 +000097
Chris Lattnerdacbc5d2009-03-28 04:11:33 +000098 Gen->HandleTranslationUnit(C);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +000099
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000100 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +0000101 LLVMIRGeneration.stopTimer();
102 }
Chris Lattner6f114eb2009-02-18 01:37:30 +0000103
Daniel Dunbar897c6762010-06-07 23:20:08 +0000104 // Silently ignore if we weren't initialized for some reason.
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000105 if (!TheModule)
Daniel Dunbar897c6762010-06-07 23:20:08 +0000106 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Daniel Dunbar897c6762010-06-07 23:20:08 +0000108 // Make sure IR generation is happy with the module. This is released by
109 // the module provider.
110 Module *M = Gen->ReleaseModule();
111 if (!M) {
112 // The module has been released by IR gen on failures, do not double
113 // free.
114 TheModule.take();
115 return;
116 }
117
118 assert(TheModule.get() == M &&
119 "Unexpected module change during IR generation");
120
121 // Install an inline asm handler so that diagnostics get printed through
122 // our diagnostics hooks.
123 LLVMContext &Ctx = TheModule->getContext();
Chris Lattner063e4762010-11-17 08:13:04 +0000124 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
125 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000126 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner063e4762010-11-17 08:13:04 +0000127 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000128
129 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000130 TheModule.get(), Action, AsmOutStream);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000131
132 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000133 }
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000135 virtual void HandleTagDeclDefinition(TagDecl *D) {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000136 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
137 Context->getSourceManager(),
138 "LLVM IR generation of declaration");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000139 Gen->HandleTagDeclDefinition(D);
140 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000141
142 virtual void CompleteTentativeDefinition(VarDecl *D) {
143 Gen->CompleteTentativeDefinition(D);
144 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000145
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000146 virtual void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) {
147 Gen->HandleVTable(RD, DefinitionRequired);
148 }
149
Chris Lattner6da9eb62010-04-06 18:38:50 +0000150 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
151 unsigned LocCookie) {
152 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
153 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
154 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000155
Chris Lattner6da9eb62010-04-06 18:38:50 +0000156 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
157 SourceLocation LocCookie);
Mike Stump1eb44332009-09-09 15:08:12 +0000158 };
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000159}
160
Chris Lattnerd6f19062010-04-08 00:23:06 +0000161/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
162/// buffer to be a valid FullSourceLoc.
163static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
164 SourceManager &CSM) {
165 // Get both the clang and llvm source managers. The location is relative to
166 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000167 // a copy to the Clang source manager.
Chris Lattnerd6f19062010-04-08 00:23:06 +0000168 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000169
Chris Lattnerd6f19062010-04-08 00:23:06 +0000170 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
171 // already owns its one and clang::SourceManager wants to own its one.
172 const MemoryBuffer *LBuf =
173 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000174
Chris Lattnerd6f19062010-04-08 00:23:06 +0000175 // Create the copy and transfer ownership to clang::SourceManager.
176 llvm::MemoryBuffer *CBuf =
177 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
178 LBuf->getBufferIdentifier());
179 FileID FID = CSM.createFileIDForMemBuffer(CBuf);
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000180
Chris Lattnerd6f19062010-04-08 00:23:06 +0000181 // Translate the offset into the file.
182 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000183 SourceLocation NewLoc =
Chris Lattnerd6f19062010-04-08 00:23:06 +0000184 CSM.getLocForStartOfFile(FID).getFileLocWithOffset(Offset);
185 return FullSourceLoc(NewLoc, CSM);
186}
187
Chris Lattnercabae682010-04-06 17:52:14 +0000188
Chris Lattner6da9eb62010-04-06 18:38:50 +0000189/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
190/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000191/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner6da9eb62010-04-06 18:38:50 +0000192void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
193 SourceLocation LocCookie) {
194 // There are a couple of different kinds of errors we could get here. First,
195 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000196
Chris Lattner6da9eb62010-04-06 18:38:50 +0000197 // Strip "error: " off the start of the message string.
198 llvm::StringRef Message = D.getMessage();
199 if (Message.startswith("error: "))
200 Message = Message.substr(7);
201
Chris Lattner99e14a02010-06-15 00:03:12 +0000202 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner6da9eb62010-04-06 18:38:50 +0000203 FullSourceLoc Loc;
Chris Lattnerd6f19062010-04-08 00:23:06 +0000204 if (D.getLoc() != SMLoc())
205 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Chris Lattner99e14a02010-06-15 00:03:12 +0000206
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000207
Chris Lattner99e14a02010-06-15 00:03:12 +0000208 // If this problem has clang-level source location information, report the
209 // issue as being an error in the source with a note showing the instantiated
210 // code.
211 if (LocCookie.isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000212 Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
Chris Lattner99e14a02010-06-15 00:03:12 +0000213
214 if (D.getLoc().isValid())
215 Diags.Report(Loc, diag::note_fe_inline_asm_here);
216 return;
217 }
218
219 // Otherwise, report the backend error as occuring in the generated .s file.
220 // If Loc is invalid, we still need to report the error, it just gets no
221 // location info.
222 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
Chris Lattner6da9eb62010-04-06 18:38:50 +0000223}
224
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000225//
226
227CodeGenAction::CodeGenAction(unsigned _Act) : Act(_Act) {}
228
Daniel Dunbar9ad1c022010-02-25 20:37:44 +0000229CodeGenAction::~CodeGenAction() {}
230
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000231bool CodeGenAction::hasIRSupport() const { return true; }
232
Daniel Dunbarb954e982010-02-25 04:37:50 +0000233void CodeGenAction::EndSourceFileAction() {
234 // If the consumer creation failed, do nothing.
235 if (!getCompilerInstance().hasASTConsumer())
236 return;
237
238 // Steal the module from the consumer.
Nico Weber5aa74af2011-01-25 20:34:14 +0000239 TheModule.reset(BEConsumer->takeModule());
Daniel Dunbarb954e982010-02-25 04:37:50 +0000240}
241
242llvm::Module *CodeGenAction::takeModule() {
243 return TheModule.take();
244}
245
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000246static raw_ostream *GetOutputStream(CompilerInstance &CI,
247 llvm::StringRef InFile,
248 BackendAction Action) {
249 switch (Action) {
250 case Backend_EmitAssembly:
251 return CI.createDefaultOutputFile(false, InFile, "s");
252 case Backend_EmitLL:
253 return CI.createDefaultOutputFile(false, InFile, "ll");
254 case Backend_EmitBC:
255 return CI.createDefaultOutputFile(true, InFile, "bc");
256 case Backend_EmitNothing:
257 return 0;
258 case Backend_EmitMCNull:
259 case Backend_EmitObj:
260 return CI.createDefaultOutputFile(true, InFile, "o");
261 }
262
263 assert(0 && "Invalid action!");
264 return 0;
265}
266
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000267ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
268 llvm::StringRef InFile) {
269 BackendAction BA = static_cast<BackendAction>(Act);
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000270 llvm::OwningPtr<llvm::raw_ostream> OS(GetOutputStream(CI, InFile, BA));
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000271 if (BA != Backend_EmitNothing && !OS)
272 return 0;
273
Nico Weber5aa74af2011-01-25 20:34:14 +0000274 BEConsumer =
275 new BackendConsumer(BA, CI.getDiagnostics(),
276 CI.getCodeGenOpts(), CI.getTargetOpts(),
277 CI.getFrontendOpts().ShowTimers, InFile, OS.take(),
278 CI.getLLVMContext());
279 return BEConsumer;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000280}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000281
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000282void CodeGenAction::ExecuteAction() {
283 // If this is an IR file, we have to treat it specially.
284 if (getCurrentFileKind() == IK_LLVM_IR) {
285 BackendAction BA = static_cast<BackendAction>(Act);
286 CompilerInstance &CI = getCompilerInstance();
287 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
288 if (BA != Backend_EmitNothing && !OS)
289 return;
290
291 bool Invalid;
292 SourceManager &SM = CI.getSourceManager();
293 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
294 &Invalid);
295 if (Invalid)
296 return;
297
298 // FIXME: This is stupid, IRReader shouldn't take ownership.
299 llvm::MemoryBuffer *MainFileCopy =
300 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
301 getCurrentFile().c_str());
302
303 llvm::SMDiagnostic Err;
304 TheModule.reset(ParseIR(MainFileCopy, Err, CI.getLLVMContext()));
305 if (!TheModule) {
306 // Translate from the diagnostic info to the SourceManager location.
307 SourceLocation Loc = SM.getLocation(
308 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
309 Err.getColumnNo() + 1);
310
311 // Get a custom diagnostic for the error. We strip off a leading
312 // diagnostic code if there is one.
313 llvm::StringRef Msg = Err.getMessage();
314 if (Msg.startswith("error: "))
315 Msg = Msg.substr(7);
316 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(Diagnostic::Error,
317 Msg);
318
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000319 CI.getDiagnostics().Report(Loc, DiagID);
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000320 return;
321 }
322
323 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
324 CI.getTargetOpts(), TheModule.get(),
325 BA, OS);
326 return;
327 }
328
329 // Otherwise follow the normal AST path.
330 this->ASTFrontendAction::ExecuteAction();
331}
332
333//
334
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000335EmitAssemblyAction::EmitAssemblyAction()
336 : CodeGenAction(Backend_EmitAssembly) {}
337
338EmitBCAction::EmitBCAction() : CodeGenAction(Backend_EmitBC) {}
339
340EmitLLVMAction::EmitLLVMAction() : CodeGenAction(Backend_EmitLL) {}
341
342EmitLLVMOnlyAction::EmitLLVMOnlyAction() : CodeGenAction(Backend_EmitNothing) {}
343
Daniel Dunbar32148ce2010-05-25 18:41:01 +0000344EmitCodeGenOnlyAction::EmitCodeGenOnlyAction() : CodeGenAction(Backend_EmitMCNull) {}
345
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000346EmitObjAction::EmitObjAction() : CodeGenAction(Backend_EmitObj) {}