blob: 51c55a1a8390061efa86e1650046d41871041702 [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
31namespace {
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();
124 void *OldHandler = Ctx.getInlineAsmDiagnosticHandler();
125 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
126 Ctx.setInlineAsmDiagnosticHandler((void*)(intptr_t)InlineAsmDiagHandler,
127 this);
128
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()) {
Chris Lattner6da9eb62010-04-06 18:38:50 +0000212 Diags.Report(FullSourceLoc(LocCookie, Context->getSourceManager()),
Chris Lattner99e14a02010-06-15 00:03:12 +0000213 diag::err_fe_inline_asm).AddString(Message);
214
215 if (D.getLoc().isValid())
216 Diags.Report(Loc, diag::note_fe_inline_asm_here);
217 return;
218 }
219
220 // Otherwise, report the backend error as occuring in the generated .s file.
221 // If Loc is invalid, we still need to report the error, it just gets no
222 // location info.
223 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
Chris Lattner6da9eb62010-04-06 18:38:50 +0000224}
225
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000226//
227
228CodeGenAction::CodeGenAction(unsigned _Act) : Act(_Act) {}
229
Daniel Dunbar9ad1c022010-02-25 20:37:44 +0000230CodeGenAction::~CodeGenAction() {}
231
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000232bool CodeGenAction::hasIRSupport() const { return true; }
233
Daniel Dunbarb954e982010-02-25 04:37:50 +0000234void CodeGenAction::EndSourceFileAction() {
235 // If the consumer creation failed, do nothing.
236 if (!getCompilerInstance().hasASTConsumer())
237 return;
238
239 // Steal the module from the consumer.
240 BackendConsumer *Consumer = static_cast<BackendConsumer*>(
241 &getCompilerInstance().getASTConsumer());
242
243 TheModule.reset(Consumer->takeModule());
244}
245
246llvm::Module *CodeGenAction::takeModule() {
247 return TheModule.take();
248}
249
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000250static raw_ostream *GetOutputStream(CompilerInstance &CI,
251 llvm::StringRef InFile,
252 BackendAction Action) {
253 switch (Action) {
254 case Backend_EmitAssembly:
255 return CI.createDefaultOutputFile(false, InFile, "s");
256 case Backend_EmitLL:
257 return CI.createDefaultOutputFile(false, InFile, "ll");
258 case Backend_EmitBC:
259 return CI.createDefaultOutputFile(true, InFile, "bc");
260 case Backend_EmitNothing:
261 return 0;
262 case Backend_EmitMCNull:
263 case Backend_EmitObj:
264 return CI.createDefaultOutputFile(true, InFile, "o");
265 }
266
267 assert(0 && "Invalid action!");
268 return 0;
269}
270
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000271ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
272 llvm::StringRef InFile) {
273 BackendAction BA = static_cast<BackendAction>(Act);
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000274 llvm::OwningPtr<llvm::raw_ostream> OS(GetOutputStream(CI, InFile, BA));
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000275 if (BA != Backend_EmitNothing && !OS)
276 return 0;
277
Daniel Dunbar6b0cf672010-06-07 23:19:17 +0000278 return new BackendConsumer(BA, CI.getDiagnostics(),
John McCall468ec6c2010-03-04 04:29:44 +0000279 CI.getCodeGenOpts(), CI.getTargetOpts(),
280 CI.getFrontendOpts().ShowTimers, InFile, OS.take(),
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000281 CI.getLLVMContext());
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000282}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000283
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000284void CodeGenAction::ExecuteAction() {
285 // If this is an IR file, we have to treat it specially.
286 if (getCurrentFileKind() == IK_LLVM_IR) {
287 BackendAction BA = static_cast<BackendAction>(Act);
288 CompilerInstance &CI = getCompilerInstance();
289 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
290 if (BA != Backend_EmitNothing && !OS)
291 return;
292
293 bool Invalid;
294 SourceManager &SM = CI.getSourceManager();
295 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
296 &Invalid);
297 if (Invalid)
298 return;
299
300 // FIXME: This is stupid, IRReader shouldn't take ownership.
301 llvm::MemoryBuffer *MainFileCopy =
302 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
303 getCurrentFile().c_str());
304
305 llvm::SMDiagnostic Err;
306 TheModule.reset(ParseIR(MainFileCopy, Err, CI.getLLVMContext()));
307 if (!TheModule) {
308 // Translate from the diagnostic info to the SourceManager location.
309 SourceLocation Loc = SM.getLocation(
310 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
311 Err.getColumnNo() + 1);
312
313 // Get a custom diagnostic for the error. We strip off a leading
314 // diagnostic code if there is one.
315 llvm::StringRef Msg = Err.getMessage();
316 if (Msg.startswith("error: "))
317 Msg = Msg.substr(7);
318 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(Diagnostic::Error,
319 Msg);
320
321 CI.getDiagnostics().Report(FullSourceLoc(Loc, SM), DiagID);
322 return;
323 }
324
325 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(),
326 CI.getTargetOpts(), TheModule.get(),
327 BA, OS);
328 return;
329 }
330
331 // Otherwise follow the normal AST path.
332 this->ASTFrontendAction::ExecuteAction();
333}
334
335//
336
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000337EmitAssemblyAction::EmitAssemblyAction()
338 : CodeGenAction(Backend_EmitAssembly) {}
339
340EmitBCAction::EmitBCAction() : CodeGenAction(Backend_EmitBC) {}
341
342EmitLLVMAction::EmitLLVMAction() : CodeGenAction(Backend_EmitLL) {}
343
344EmitLLVMOnlyAction::EmitLLVMOnlyAction() : CodeGenAction(Backend_EmitNothing) {}
345
Daniel Dunbar32148ce2010-05-25 18:41:01 +0000346EmitCodeGenOnlyAction::EmitCodeGenOnlyAction() : CodeGenAction(Backend_EmitMCNull) {}
347
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000348EmitObjAction::EmitObjAction() : CodeGenAction(Backend_EmitObj) {}