blob: 573f8e98e77c9d61bffe0154ddd18d8318fb94a0 [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 Lattner682bf922009-03-29 16:50:03 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000012#include "clang/AST/ASTContext.h"
Chris Lattner682bf922009-03-29 16:50:03 +000013#include "clang/AST/DeclGroup.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/Basic/FileManager.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Basic/TargetInfo.h"
Daniel Dunbar9b414d32010-06-15 17:48:49 +000017#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbard58c03f2009-11-15 06:48:46 +000018#include "clang/CodeGen/ModuleBuilder.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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "llvm/ADT/SmallString.h"
22#include "llvm/Bitcode/ReaderWriter.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070023#include "llvm/IR/DiagnosticInfo.h"
24#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000025#include "llvm/IR/LLVMContext.h"
26#include "llvm/IR/Module.h"
Chandler Carruth9cc935b2013-03-26 02:25:54 +000027#include "llvm/IRReader/IRReader.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070028#include "llvm/Linker/Linker.h"
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +000029#include "llvm/Pass.h"
Chris Lattner6da9eb62010-04-06 18:38:50 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/SourceMgr.h"
Chris Lattner6f114eb2009-02-18 01:37:30 +000032#include "llvm/Support/Timer.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070033#include <memory>
Daniel Dunbard69bacc2008-10-21 23:49:24 +000034using namespace clang;
35using namespace llvm;
36
Nico Weber5aa74af2011-01-25 20:34:14 +000037namespace clang {
Benjamin Kramerbd218282009-11-28 10:07:24 +000038 class BackendConsumer : public ASTConsumer {
David Blaikie99ba9e32011-12-20 02:48:34 +000039 virtual void anchor();
David Blaikied6471f72011-09-25 23:23:43 +000040 DiagnosticsEngine &Diags;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000041 BackendAction Action;
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000042 const CodeGenOptions &CodeGenOpts;
Daniel Dunbar3636e1d2009-11-30 08:39:32 +000043 const TargetOptions &TargetOpts;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000044 const LangOptions &LangOpts;
Chris Lattner5f9e2722011-07-23 10:55:15 +000045 raw_ostream *AsmOutStream;
Chris Lattner49f28ca2009-03-05 08:00:35 +000046 ASTContext *Context;
Daniel Dunbar90f41302008-10-29 08:50:02 +000047
Chris Lattner6f114eb2009-02-18 01:37:30 +000048 Timer LLVMIRGeneration;
Mike Stump1eb44332009-09-09 15:08:12 +000049
Stephen Hines651f13c2014-04-23 16:59:28 -070050 std::unique_ptr<CodeGenerator> Gen;
Mike Stump1eb44332009-09-09 15:08:12 +000051
Stephen Hines651f13c2014-04-23 16:59:28 -070052 std::unique_ptr<llvm::Module> TheModule, LinkModule;
Daniel Dunbard69bacc2008-10-21 23:49:24 +000053
Mike Stump1eb44332009-09-09 15:08:12 +000054 public:
David Blaikied6471f72011-09-25 23:23:43 +000055 BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
Daniel Dunbar6b0cf672010-06-07 23:19:17 +000056 const CodeGenOptions &compopts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000057 const TargetOptions &targetopts,
Stephen Hines651f13c2014-04-23 16:59:28 -070058 const LangOptions &langopts, bool TimePasses,
59 const std::string &infile, llvm::Module *LinkModule,
60 raw_ostream *OS, LLVMContext &C)
61 : Diags(_Diags), Action(action), CodeGenOpts(compopts),
62 TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
63 Context(), LLVMIRGeneration("LLVM IR Generation Time"),
64 Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
65 LinkModule(LinkModule) {
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000066 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattner44502662009-02-18 01:23:44 +000067 }
Daniel Dunbard69bacc2008-10-21 23:49:24 +000068
Stephen Hines651f13c2014-04-23 16:59:28 -070069 llvm::Module *takeModule() { return TheModule.release(); }
70 llvm::Module *takeLinkModule() { return LinkModule.release(); }
Daniel Dunbarb954e982010-02-25 04:37:50 +000071
Stephen Hines651f13c2014-04-23 16:59:28 -070072 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindola02503932012-03-08 15:51:03 +000073 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola234fe652012-03-05 10:54:55 +000074 }
75
Stephen Hines651f13c2014-04-23 16:59:28 -070076 void Initialize(ASTContext &Ctx) override {
Chris Lattner7bb0da02009-03-28 02:18:25 +000077 Context = &Ctx;
Mike Stump1eb44332009-09-09 15:08:12 +000078
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000079 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000080 LLVMIRGeneration.startTimer();
Mike Stump1eb44332009-09-09 15:08:12 +000081
Chris Lattner7bb0da02009-03-28 02:18:25 +000082 Gen->Initialize(Ctx);
Daniel Dunbard69bacc2008-10-21 23:49:24 +000083
Daniel Dunbarb954e982010-02-25 04:37:50 +000084 TheModule.reset(Gen->GetModule());
Mike Stump1eb44332009-09-09 15:08:12 +000085
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000086 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000087 LLVMIRGeneration.stopTimer();
Daniel Dunbard69bacc2008-10-21 23:49:24 +000088 }
Mike Stump1eb44332009-09-09 15:08:12 +000089
Stephen Hines651f13c2014-04-23 16:59:28 -070090 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner682bf922009-03-29 16:50:03 +000091 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattner49f28ca2009-03-05 08:00:35 +000092 Context->getSourceManager(),
93 "LLVM IR generation of declaration");
Mike Stump1eb44332009-09-09 15:08:12 +000094
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +000095 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +000096 LLVMIRGeneration.startTimer();
Chris Lattner682bf922009-03-29 16:50:03 +000097
Daniel Dunbard69bacc2008-10-21 23:49:24 +000098 Gen->HandleTopLevelDecl(D);
Chris Lattner6f114eb2009-02-18 01:37:30 +000099
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000100 if (llvm::TimePassesIsEnabled)
Chris Lattner6f114eb2009-02-18 01:37:30 +0000101 LLVMIRGeneration.stopTimer();
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000102
103 return true;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000104 }
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Stephen Hines651f13c2014-04-23 16:59:28 -0700106 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000107 {
Chris Lattner14f234e2009-03-06 06:46:31 +0000108 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000109 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +0000110 LLVMIRGeneration.startTimer();
Chris Lattner6f114eb2009-02-18 01:37:30 +0000111
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000112 Gen->HandleTranslationUnit(C);
Daniel Dunbard68ba0e2008-11-11 06:35:39 +0000113
Daniel Dunbarb33fbaa2009-11-30 08:39:52 +0000114 if (llvm::TimePassesIsEnabled)
Chris Lattner49f28ca2009-03-05 08:00:35 +0000115 LLVMIRGeneration.stopTimer();
116 }
Chris Lattner6f114eb2009-02-18 01:37:30 +0000117
Daniel Dunbar897c6762010-06-07 23:20:08 +0000118 // Silently ignore if we weren't initialized for some reason.
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000119 if (!TheModule)
Daniel Dunbar897c6762010-06-07 23:20:08 +0000120 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Daniel Dunbar897c6762010-06-07 23:20:08 +0000122 // Make sure IR generation is happy with the module. This is released by
123 // the module provider.
Douglas Gregor1a4761e2011-11-30 23:21:26 +0000124 llvm::Module *M = Gen->ReleaseModule();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000125 if (!M) {
126 // The module has been released by IR gen on failures, do not double
127 // free.
Stephen Hines651f13c2014-04-23 16:59:28 -0700128 TheModule.release();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000129 return;
130 }
131
132 assert(TheModule.get() == M &&
133 "Unexpected module change during IR generation");
134
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000135 // Link LinkModule into this module if present, preserving its validity.
136 if (LinkModule) {
137 std::string ErrorMsg;
138 if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
139 &ErrorMsg)) {
140 Diags.Report(diag::err_fe_cannot_link_module)
141 << LinkModule->getModuleIdentifier() << ErrorMsg;
142 return;
143 }
144 }
145
Daniel Dunbar897c6762010-06-07 23:20:08 +0000146 // Install an inline asm handler so that diagnostics get printed through
147 // our diagnostics hooks.
148 LLVMContext &Ctx = TheModule->getContext();
Chris Lattner063e4762010-11-17 08:13:04 +0000149 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
150 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000151 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner063e4762010-11-17 08:13:04 +0000152 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000153
Stephen Hines651f13c2014-04-23 16:59:28 -0700154 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
155 Ctx.getDiagnosticHandler();
156 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
157 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
158
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000159 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
Stephen Hines651f13c2014-04-23 16:59:28 -0700160 C.getTargetInfo().getTargetDescription(),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000161 TheModule.get(), Action, AsmOutStream);
Stephen Hines651f13c2014-04-23 16:59:28 -0700162
Daniel Dunbar897c6762010-06-07 23:20:08 +0000163 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Stephen Hines651f13c2014-04-23 16:59:28 -0700164
165 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000166 }
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Stephen Hines651f13c2014-04-23 16:59:28 -0700168 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattner49f28ca2009-03-05 08:00:35 +0000169 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
170 Context->getSourceManager(),
171 "LLVM IR generation of declaration");
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000172 Gen->HandleTagDeclDefinition(D);
173 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000174
Stephen Hines651f13c2014-04-23 16:59:28 -0700175 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie658cd2c2013-07-13 21:08:14 +0000176 Gen->HandleTagDeclRequiredDefinition(D);
177 }
178
Stephen Hines651f13c2014-04-23 16:59:28 -0700179 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000180 Gen->CompleteTentativeDefinition(D);
181 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000182
Stephen Hines651f13c2014-04-23 16:59:28 -0700183 void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000184 Gen->HandleVTable(RD, DefinitionRequired);
185 }
186
Stephen Hines651f13c2014-04-23 16:59:28 -0700187 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
Reid Kleckner3190ca92013-05-08 13:44:39 +0000188 Gen->HandleLinkerOptionPragma(Opts);
189 }
190
Stephen Hines651f13c2014-04-23 16:59:28 -0700191 void HandleDetectMismatch(llvm::StringRef Name,
192 llvm::StringRef Value) override {
Aaron Ballmana7ff62f2013-06-04 02:07:14 +0000193 Gen->HandleDetectMismatch(Name, Value);
194 }
195
Stephen Hines651f13c2014-04-23 16:59:28 -0700196 void HandleDependentLibrary(llvm::StringRef Opts) override {
Reid Kleckner3190ca92013-05-08 13:44:39 +0000197 Gen->HandleDependentLibrary(Opts);
198 }
199
Chris Lattner6da9eb62010-04-06 18:38:50 +0000200 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
201 unsigned LocCookie) {
202 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
203 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
204 }
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000205
Stephen Hines651f13c2014-04-23 16:59:28 -0700206 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
207 void *Context) {
208 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
209 }
210
Chris Lattner6da9eb62010-04-06 18:38:50 +0000211 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
212 SourceLocation LocCookie);
Stephen Hines651f13c2014-04-23 16:59:28 -0700213
214 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
215 /// \brief Specialized handler for InlineAsm diagnostic.
216 /// \return True if the diagnostic has been successfully reported, false
217 /// otherwise.
218 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
219 /// \brief Specialized handler for StackSize diagnostic.
220 /// \return True if the diagnostic has been successfully reported, false
221 /// otherwise.
222 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Mike Stump1eb44332009-09-09 15:08:12 +0000223 };
David Blaikie99ba9e32011-12-20 02:48:34 +0000224
225 void BackendConsumer::anchor() {}
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000226}
227
Chris Lattnerd6f19062010-04-08 00:23:06 +0000228/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
229/// buffer to be a valid FullSourceLoc.
230static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
231 SourceManager &CSM) {
232 // Get both the clang and llvm source managers. The location is relative to
233 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000234 // a copy to the Clang source manager.
Chris Lattnerd6f19062010-04-08 00:23:06 +0000235 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000236
Chris Lattnerd6f19062010-04-08 00:23:06 +0000237 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
238 // already owns its one and clang::SourceManager wants to own its one.
239 const MemoryBuffer *LBuf =
240 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000241
Chris Lattnerd6f19062010-04-08 00:23:06 +0000242 // Create the copy and transfer ownership to clang::SourceManager.
243 llvm::MemoryBuffer *CBuf =
244 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
245 LBuf->getBufferIdentifier());
246 FileID FID = CSM.createFileIDForMemBuffer(CBuf);
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000247
Chris Lattnerd6f19062010-04-08 00:23:06 +0000248 // Translate the offset into the file.
249 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000250 SourceLocation NewLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000251 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattnerd6f19062010-04-08 00:23:06 +0000252 return FullSourceLoc(NewLoc, CSM);
253}
254
Chris Lattnercabae682010-04-06 17:52:14 +0000255
Chris Lattner6da9eb62010-04-06 18:38:50 +0000256/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
257/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbarf80cb752010-04-29 16:29:09 +0000258/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner6da9eb62010-04-06 18:38:50 +0000259void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
260 SourceLocation LocCookie) {
261 // There are a couple of different kinds of errors we could get here. First,
262 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidis5d3a4bb2012-02-01 06:36:49 +0000263
264 // Strip "error: " off the start of the message string.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000265 StringRef Message = D.getMessage();
Argyrios Kyrtzidis5d3a4bb2012-02-01 06:36:49 +0000266 if (Message.startswith("error: "))
267 Message = Message.substr(7);
Chris Lattner6da9eb62010-04-06 18:38:50 +0000268
Chris Lattner99e14a02010-06-15 00:03:12 +0000269 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner6da9eb62010-04-06 18:38:50 +0000270 FullSourceLoc Loc;
Chris Lattnerd6f19062010-04-08 00:23:06 +0000271 if (D.getLoc() != SMLoc())
272 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Chris Lattnerff8f9ec2012-01-31 06:13:55 +0000273
Argyrios Kyrtzidis5d3a4bb2012-02-01 06:36:49 +0000274
Chris Lattner99e14a02010-06-15 00:03:12 +0000275 // If this problem has clang-level source location information, report the
276 // issue as being an error in the source with a note showing the instantiated
277 // code.
278 if (LocCookie.isValid()) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000279 Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
Chris Lattner99e14a02010-06-15 00:03:12 +0000280
Benjamin Kramer96fda0c2011-10-16 10:48:28 +0000281 if (D.getLoc().isValid()) {
282 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
283 // Convert the SMDiagnostic ranges into SourceRange and attach them
284 // to the diagnostic.
285 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
286 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
287 unsigned Column = D.getColumnNo();
288 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
289 Loc.getLocWithOffset(Range.second - Column));
290 }
291 }
Chris Lattner99e14a02010-06-15 00:03:12 +0000292 return;
293 }
294
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000295 // Otherwise, report the backend error as occurring in the generated .s file.
Chris Lattner99e14a02010-06-15 00:03:12 +0000296 // If Loc is invalid, we still need to report the error, it just gets no
297 // location info.
298 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
Chris Lattner6da9eb62010-04-06 18:38:50 +0000299}
300
Stephen Hines651f13c2014-04-23 16:59:28 -0700301#define ComputeDiagID(Severity, GroupName, DiagID) \
302 do { \
303 switch (Severity) { \
304 case llvm::DS_Error: \
305 DiagID = diag::err_fe_##GroupName; \
306 break; \
307 case llvm::DS_Warning: \
308 DiagID = diag::warn_fe_##GroupName; \
309 break; \
310 case llvm::DS_Remark: \
311 llvm_unreachable("'remark' severity not expected"); \
312 break; \
313 case llvm::DS_Note: \
314 DiagID = diag::note_fe_##GroupName; \
315 break; \
316 } \
317 } while (false)
318
319#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
320 do { \
321 switch (Severity) { \
322 case llvm::DS_Error: \
323 DiagID = diag::err_fe_##GroupName; \
324 break; \
325 case llvm::DS_Warning: \
326 DiagID = diag::warn_fe_##GroupName; \
327 break; \
328 case llvm::DS_Remark: \
329 DiagID = diag::remark_fe_##GroupName; \
330 break; \
331 case llvm::DS_Note: \
332 DiagID = diag::note_fe_##GroupName; \
333 break; \
334 } \
335 } while (false)
336
337bool
338BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
339 unsigned DiagID;
340 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
341 std::string Message = D.getMsgStr().str();
342
343 // If this problem has clang-level source location information, report the
344 // issue as being a problem in the source with a note showing the instantiated
345 // code.
346 SourceLocation LocCookie =
347 SourceLocation::getFromRawEncoding(D.getLocCookie());
348 if (LocCookie.isValid())
349 Diags.Report(LocCookie, DiagID).AddString(Message);
350 else {
351 // Otherwise, report the backend diagnostic as occurring in the generated
352 // .s file.
353 // If Loc is invalid, we still need to report the diagnostic, it just gets
354 // no location info.
355 FullSourceLoc Loc;
356 Diags.Report(Loc, DiagID).AddString(Message);
357 }
358 // We handled all the possible severities.
359 return true;
360}
361
362bool
363BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
364 if (D.getSeverity() != llvm::DS_Warning)
365 // For now, the only support we have for StackSize diagnostic is warning.
366 // We do not know how to format other severities.
367 return false;
368
369 // FIXME: We should demangle the function name.
370 // FIXME: Is there a way to get a location for that function?
371 FullSourceLoc Loc;
372 Diags.Report(Loc, diag::warn_fe_backend_frame_larger_than)
373 << D.getStackSize() << D.getFunction().getName();
374 return true;
375}
376
377/// \brief This function is invoked when the backend needs
378/// to report something to the user.
379void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
380 unsigned DiagID = diag::err_fe_inline_asm;
381 llvm::DiagnosticSeverity Severity = DI.getSeverity();
382 // Get the diagnostic ID based.
383 switch (DI.getKind()) {
384 case llvm::DK_InlineAsm:
385 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
386 return;
387 ComputeDiagID(Severity, inline_asm, DiagID);
388 break;
389 case llvm::DK_StackSize:
390 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
391 return;
392 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
393 break;
394 default:
395 // Plugin IDs are not bound to any value as they are set dynamically.
396 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
397 break;
398 }
399 std::string MsgStorage;
400 {
401 raw_string_ostream Stream(MsgStorage);
402 DiagnosticPrinterRawOStream DP(Stream);
403 DI.print(DP);
404 }
405
406 // Report the backend message using the usual diagnostic mechanism.
407 FullSourceLoc Loc;
408 Diags.Report(Loc, DiagID).AddString(MsgStorage);
409}
410#undef ComputeDiagID
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000411
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000412CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000413 : Act(_Act), LinkModule(0),
414 VMContext(_VMContext ? _VMContext : new LLVMContext),
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000415 OwnsVMContext(!_VMContext) {}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000416
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000417CodeGenAction::~CodeGenAction() {
418 TheModule.reset();
419 if (OwnsVMContext)
420 delete VMContext;
421}
Daniel Dunbar9ad1c022010-02-25 20:37:44 +0000422
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000423bool CodeGenAction::hasIRSupport() const { return true; }
424
Daniel Dunbarb954e982010-02-25 04:37:50 +0000425void CodeGenAction::EndSourceFileAction() {
426 // If the consumer creation failed, do nothing.
427 if (!getCompilerInstance().hasASTConsumer())
428 return;
429
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000430 // If we were given a link module, release consumer's ownership of it.
431 if (LinkModule)
432 BEConsumer->takeLinkModule();
433
Daniel Dunbarb954e982010-02-25 04:37:50 +0000434 // Steal the module from the consumer.
Nico Weber5aa74af2011-01-25 20:34:14 +0000435 TheModule.reset(BEConsumer->takeModule());
Daniel Dunbarb954e982010-02-25 04:37:50 +0000436}
437
Stephen Hines651f13c2014-04-23 16:59:28 -0700438llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); }
Daniel Dunbarb954e982010-02-25 04:37:50 +0000439
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000440llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
441 OwnsVMContext = false;
442 return VMContext;
443}
444
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000445static raw_ostream *GetOutputStream(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000446 StringRef InFile,
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000447 BackendAction Action) {
448 switch (Action) {
449 case Backend_EmitAssembly:
450 return CI.createDefaultOutputFile(false, InFile, "s");
451 case Backend_EmitLL:
452 return CI.createDefaultOutputFile(false, InFile, "ll");
453 case Backend_EmitBC:
454 return CI.createDefaultOutputFile(true, InFile, "bc");
455 case Backend_EmitNothing:
456 return 0;
457 case Backend_EmitMCNull:
458 case Backend_EmitObj:
459 return CI.createDefaultOutputFile(true, InFile, "o");
460 }
461
David Blaikieb219cfc2011-09-23 05:06:16 +0000462 llvm_unreachable("Invalid action!");
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000463}
464
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000465ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000466 StringRef InFile) {
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000467 BackendAction BA = static_cast<BackendAction>(Act);
Stephen Hines651f13c2014-04-23 16:59:28 -0700468 std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000469 if (BA != Backend_EmitNothing && !OS)
470 return 0;
471
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000472 llvm::Module *LinkModuleToUse = LinkModule;
473
474 // If we were not given a link module, and the user requested that one be
475 // loaded from bitcode, do so now.
476 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
477 if (!LinkModuleToUse && !LinkBCFile.empty()) {
478 std::string ErrorStr;
479
480 llvm::MemoryBuffer *BCBuf =
481 CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
482 if (!BCBuf) {
483 CI.getDiagnostics().Report(diag::err_cannot_open_file)
484 << LinkBCFile << ErrorStr;
485 return 0;
486 }
487
Stephen Hines651f13c2014-04-23 16:59:28 -0700488 ErrorOr<llvm::Module *> ModuleOrErr =
489 getLazyBitcodeModule(BCBuf, *VMContext);
490 if (error_code EC = ModuleOrErr.getError()) {
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000491 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Stephen Hines651f13c2014-04-23 16:59:28 -0700492 << LinkBCFile << EC.message();
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000493 return 0;
494 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700495 LinkModuleToUse = ModuleOrErr.get();
Peter Collingbourne22a7dfe2011-10-30 17:30:44 +0000496 }
497
Stephen Hines651f13c2014-04-23 16:59:28 -0700498 BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(),
499 CI.getTargetOpts(), CI.getLangOpts(),
500 CI.getFrontendOpts().ShowTimers, InFile,
501 LinkModuleToUse, OS.release(), *VMContext);
Nico Weber5aa74af2011-01-25 20:34:14 +0000502 return BEConsumer;
Daniel Dunbard69bacc2008-10-21 23:49:24 +0000503}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000504
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000505void CodeGenAction::ExecuteAction() {
506 // If this is an IR file, we have to treat it specially.
507 if (getCurrentFileKind() == IK_LLVM_IR) {
508 BackendAction BA = static_cast<BackendAction>(Act);
509 CompilerInstance &CI = getCompilerInstance();
510 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
511 if (BA != Backend_EmitNothing && !OS)
512 return;
513
514 bool Invalid;
515 SourceManager &SM = CI.getSourceManager();
516 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
517 &Invalid);
518 if (Invalid)
519 return;
520
521 // FIXME: This is stupid, IRReader shouldn't take ownership.
522 llvm::MemoryBuffer *MainFileCopy =
523 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
Argyrios Kyrtzidis8616f9a2012-11-09 19:40:39 +0000524 getCurrentFile());
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000525
526 llvm::SMDiagnostic Err;
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000527 TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000528 if (!TheModule) {
529 // Translate from the diagnostic info to the SourceManager location.
Argyrios Kyrtzidis5a9ee202011-09-19 20:40:38 +0000530 SourceLocation Loc = SM.translateFileLineCol(
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000531 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
532 Err.getColumnNo() + 1);
533
Stephen Hines651f13c2014-04-23 16:59:28 -0700534 // Strip off a leading diagnostic code if there is one.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000535 StringRef Msg = Err.getMessage();
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000536 if (Msg.startswith("error: "))
537 Msg = Msg.substr(7);
Benjamin Kramerc9b47f92012-03-16 22:31:42 +0000538
Stephen Hines651f13c2014-04-23 16:59:28 -0700539 unsigned DiagID =
540 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramerc9b47f92012-03-16 22:31:42 +0000541
Stephen Hines651f13c2014-04-23 16:59:28 -0700542 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000543 return;
544 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700545 const TargetOptions &TargetOpts = CI.getTargetOpts();
546 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
547 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
548 DiagnosticsEngine::Warning,
549 "overriding the module target triple with %0");
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000550
Stephen Hines651f13c2014-04-23 16:59:28 -0700551 CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
552 TheModule->setTargetTriple(TargetOpts.Triple);
553 }
554
555 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
556 CI.getLangOpts(), CI.getTarget().getTargetDescription(),
557 TheModule.get(), BA, OS);
Daniel Dunbar4cbbd942010-06-07 23:27:59 +0000558 return;
559 }
560
561 // Otherwise follow the normal AST path.
562 this->ASTFrontendAction::ExecuteAction();
563}
564
565//
566
David Blaikie99ba9e32011-12-20 02:48:34 +0000567void EmitAssemblyAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000568EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
569 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000570
David Blaikie99ba9e32011-12-20 02:48:34 +0000571void EmitBCAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000572EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
573 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000574
David Blaikie99ba9e32011-12-20 02:48:34 +0000575void EmitLLVMAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000576EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
577 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000578
David Blaikie99ba9e32011-12-20 02:48:34 +0000579void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000580EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
581 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbar4ee34612010-02-25 04:37:45 +0000582
David Blaikie99ba9e32011-12-20 02:48:34 +0000583void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000584EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
585 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar32148ce2010-05-25 18:41:01 +0000586
David Blaikie99ba9e32011-12-20 02:48:34 +0000587void EmitObjAction::anchor() { }
Peter Collingbourne4b93d662011-02-19 23:03:58 +0000588EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
589 : CodeGenAction(Backend_EmitObj, _VMContext) {}