blob: 9b5b9f59ab98a82707607b8f17de5bce0231f0bb [file] [log] [blame]
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
Daniel Dunbarc13935e2008-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 Dunbarc1b17292010-06-15 17:48:49 +000010#include "clang/CodeGen/CodeGenAction.h"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000012#include "clang/AST/ASTContext.h"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000013#include "clang/AST/DeclGroup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Basic/FileManager.h"
15#include "clang/Basic/SourceManager.h"
16#include "clang/Basic/TargetInfo.h"
Daniel Dunbarc1b17292010-06-15 17:48:49 +000017#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000018#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000019#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbaracadc552009-12-03 09:12:54 +000020#include "clang/Frontend/FrontendDiagnostic.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "llvm/ADT/SmallString.h"
22#include "llvm/Bitcode/ReaderWriter.h"
Diego Novillo829b1702014-04-16 16:54:24 +000023#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000024#include "llvm/IR/DiagnosticInfo.h"
25#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Module.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000028#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000029#include "llvm/Linker/Linker.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000030#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000031#include "llvm/Support/MemoryBuffer.h"
32#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000033#include "llvm/Support/Timer.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000034#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000035using namespace clang;
36using namespace llvm;
37
Nico Weber2992efa2011-01-25 20:34:14 +000038namespace clang {
Benjamin Kramer16634c22009-11-28 10:07:24 +000039 class BackendConsumer : public ASTConsumer {
David Blaikie68e081d2011-12-20 02:48:34 +000040 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000041 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000042 BackendAction Action;
Daniel Dunbarde182242009-11-30 08:39:32 +000043 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000044 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000045 const LangOptions &LangOpts;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000046 raw_ostream *AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000047 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000048
Chris Lattner263d64c2009-02-18 01:37:30 +000049 Timer LLVMIRGeneration;
Mike Stump11289f42009-09-09 15:08:12 +000050
Ahmed Charlesb8984322014-03-07 20:03:18 +000051 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000052
Ahmed Charlesb8984322014-03-07 20:03:18 +000053 std::unique_ptr<llvm::Module> TheModule, LinkModule;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000054
Mike Stump11289f42009-09-09 15:08:12 +000055 public:
David Blaikie9c902b52011-09-25 23:23:43 +000056 BackendConsumer(BackendAction action, DiagnosticsEngine &_Diags,
Daniel Dunbar6d5824f2010-06-07 23:19:17 +000057 const CodeGenOptions &compopts,
Dan Gohmanfec0ff82011-07-05 22:02:36 +000058 const TargetOptions &targetopts,
Rafael Espindola666a2ab2013-12-18 16:38:48 +000059 const LangOptions &langopts, bool TimePasses,
60 const std::string &infile, llvm::Module *LinkModule,
61 raw_ostream *OS, LLVMContext &C)
62 : Diags(_Diags), Action(action), CodeGenOpts(compopts),
63 TargetOpts(targetopts), LangOpts(langopts), AsmOutStream(OS),
64 Context(), LLVMIRGeneration("LLVM IR Generation Time"),
65 Gen(CreateLLVMCodeGen(Diags, infile, compopts, targetopts, C)),
66 LinkModule(LinkModule) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000067 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattnerdeffa132009-02-18 01:23:44 +000068 }
Daniel Dunbarc13935e2008-10-21 23:49:24 +000069
Ahmed Charles9a16beb2014-03-07 19:33:25 +000070 llvm::Module *takeModule() { return TheModule.release(); }
71 llvm::Module *takeLinkModule() { return LinkModule.release(); }
Daniel Dunbar400a6932010-02-25 04:37:50 +000072
Craig Topper4f12f102014-03-12 06:41:41 +000073 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +000074 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +000075 }
76
Craig Topper4f12f102014-03-12 06:41:41 +000077 void Initialize(ASTContext &Ctx) override {
Chris Lattner5cf49fe2009-03-28 02:18:25 +000078 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +000079
Daniel Dunbar8e705052009-11-30 08:39:52 +000080 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +000081 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +000082
Chris Lattner5cf49fe2009-03-28 02:18:25 +000083 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +000084
Daniel Dunbar400a6932010-02-25 04:37:50 +000085 TheModule.reset(Gen->GetModule());
Mike Stump11289f42009-09-09 15:08:12 +000086
Daniel Dunbar8e705052009-11-30 08:39:52 +000087 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +000088 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +000089 }
Mike Stump11289f42009-09-09 15:08:12 +000090
Craig Topper4f12f102014-03-12 06:41:41 +000091 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +000092 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +000093 Context->getSourceManager(),
94 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +000095
Daniel Dunbar8e705052009-11-30 08:39:52 +000096 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +000097 LLVMIRGeneration.startTimer();
Chris Lattner5bbb3c82009-03-29 16:50:03 +000098
Daniel Dunbarc13935e2008-10-21 23:49:24 +000099 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000100
Daniel Dunbar8e705052009-11-30 08:39:52 +0000101 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000102 LLVMIRGeneration.stopTimer();
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000103
104 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000105 }
Mike Stump11289f42009-09-09 15:08:12 +0000106
Craig Topper4f12f102014-03-12 06:41:41 +0000107 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000108 {
Chris Lattnere46de752009-03-06 06:46:31 +0000109 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbar8e705052009-11-30 08:39:52 +0000110 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000111 LLVMIRGeneration.startTimer();
Chris Lattner263d64c2009-02-18 01:37:30 +0000112
Chris Lattnercf169832009-03-28 04:11:33 +0000113 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000114
Daniel Dunbar8e705052009-11-30 08:39:52 +0000115 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000116 LLVMIRGeneration.stopTimer();
117 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000118
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000119 // Silently ignore if we weren't initialized for some reason.
Daniel Dunbar3e111522010-06-07 23:21:04 +0000120 if (!TheModule)
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000121 return;
Mike Stump11289f42009-09-09 15:08:12 +0000122
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000123 // Make sure IR generation is happy with the module. This is released by
124 // the module provider.
Douglas Gregorde3ef502011-11-30 23:21:26 +0000125 llvm::Module *M = Gen->ReleaseModule();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000126 if (!M) {
127 // The module has been released by IR gen on failures, do not double
128 // free.
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000129 TheModule.release();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000130 return;
131 }
132
133 assert(TheModule.get() == M &&
134 "Unexpected module change during IR generation");
135
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000136 // Link LinkModule into this module if present, preserving its validity.
137 if (LinkModule) {
138 std::string ErrorMsg;
139 if (Linker::LinkModules(M, LinkModule.get(), Linker::PreserveSource,
140 &ErrorMsg)) {
141 Diags.Report(diag::err_fe_cannot_link_module)
142 << LinkModule->getModuleIdentifier() << ErrorMsg;
143 return;
144 }
145 }
146
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000147 // Install an inline asm handler so that diagnostics get printed through
148 // our diagnostics hooks.
149 LLVMContext &Ctx = TheModule->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000150 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
151 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000152 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000153 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000154
Quentin Colombet728c5542014-02-06 18:30:43 +0000155 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
156 Ctx.getDiagnosticHandler();
157 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
158 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
159
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000160 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
Alp Tokere83b9062014-01-02 15:08:04 +0000161 C.getTargetInfo().getTargetDescription(),
Daniel Dunbar3e111522010-06-07 23:21:04 +0000162 TheModule.get(), Action, AsmOutStream);
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000163
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000164 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000165
166 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000167 }
Mike Stump11289f42009-09-09 15:08:12 +0000168
Craig Topper4f12f102014-03-12 06:41:41 +0000169 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000170 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
171 Context->getSourceManager(),
172 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000173 Gen->HandleTagDeclDefinition(D);
174 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000175
Craig Topper4f12f102014-03-12 06:41:41 +0000176 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000177 Gen->HandleTagDeclRequiredDefinition(D);
178 }
179
Craig Topper4f12f102014-03-12 06:41:41 +0000180 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000181 Gen->CompleteTentativeDefinition(D);
182 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000183
Craig Topper4f12f102014-03-12 06:41:41 +0000184 void HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired) override {
Douglas Gregor88d292c2010-05-13 16:44:06 +0000185 Gen->HandleVTable(RD, DefinitionRequired);
186 }
187
Craig Topper4f12f102014-03-12 06:41:41 +0000188 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000189 Gen->HandleLinkerOptionPragma(Opts);
190 }
191
Craig Topper4f12f102014-03-12 06:41:41 +0000192 void HandleDetectMismatch(llvm::StringRef Name,
193 llvm::StringRef Value) override {
Aaron Ballman5d041be2013-06-04 02:07:14 +0000194 Gen->HandleDetectMismatch(Name, Value);
195 }
196
Craig Topper4f12f102014-03-12 06:41:41 +0000197 void HandleDependentLibrary(llvm::StringRef Opts) override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000198 Gen->HandleDependentLibrary(Opts);
199 }
200
Chris Lattner5ec32e72010-04-06 18:38:50 +0000201 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
202 unsigned LocCookie) {
203 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
204 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
205 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000206
Quentin Colombet728c5542014-02-06 18:30:43 +0000207 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
208 void *Context) {
209 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
210 }
211
Chris Lattner5ec32e72010-04-06 18:38:50 +0000212 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
213 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000214
215 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
216 /// \brief Specialized handler for InlineAsm diagnostic.
217 /// \return True if the diagnostic has been successfully reported, false
218 /// otherwise.
219 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
220 /// \brief Specialized handler for StackSize diagnostic.
221 /// \return True if the diagnostic has been successfully reported, false
222 /// otherwise.
223 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Diego Novillo829b1702014-04-16 16:54:24 +0000224 /// \brief Specialized handler for the optimization diagnostic.
225 /// Note that this handler only accepts remarks and it always handles
226 /// them.
227 void
228 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
Mike Stump11289f42009-09-09 15:08:12 +0000229 };
David Blaikie68e081d2011-12-20 02:48:34 +0000230
231 void BackendConsumer::anchor() {}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000232}
233
Chris Lattner79f67a72010-04-08 00:23:06 +0000234/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
235/// buffer to be a valid FullSourceLoc.
236static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
237 SourceManager &CSM) {
238 // Get both the clang and llvm source managers. The location is relative to
239 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000240 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000241 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000242
Chris Lattner79f67a72010-04-08 00:23:06 +0000243 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
244 // already owns its one and clang::SourceManager wants to own its one.
245 const MemoryBuffer *LBuf =
246 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000247
Chris Lattner79f67a72010-04-08 00:23:06 +0000248 // Create the copy and transfer ownership to clang::SourceManager.
249 llvm::MemoryBuffer *CBuf =
250 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
251 LBuf->getBufferIdentifier());
Alp Toker6ac2cd02014-05-16 17:23:01 +0000252 FileID FID = CSM.createFileID(CBuf);
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000253
Chris Lattner79f67a72010-04-08 00:23:06 +0000254 // Translate the offset into the file.
255 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000256 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000257 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000258 return FullSourceLoc(NewLoc, CSM);
259}
260
Chris Lattner6d672132010-04-06 17:52:14 +0000261
Chris Lattner5ec32e72010-04-06 18:38:50 +0000262/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
263/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000264/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000265void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
266 SourceLocation LocCookie) {
267 // There are a couple of different kinds of errors we could get here. First,
268 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000269
270 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000271 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000272 if (Message.startswith("error: "))
273 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000274
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000275 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000276 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000277 if (D.getLoc() != SMLoc())
278 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Chris Lattnerf4a4bec2012-01-31 06:13:55 +0000279
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000280
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000281 // If this problem has clang-level source location information, report the
282 // issue as being an error in the source with a note showing the instantiated
283 // code.
284 if (LocCookie.isValid()) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000285 Diags.Report(LocCookie, diag::err_fe_inline_asm).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000286
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000287 if (D.getLoc().isValid()) {
288 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
289 // Convert the SMDiagnostic ranges into SourceRange and attach them
290 // to the diagnostic.
291 for (unsigned i = 0, e = D.getRanges().size(); i != e; ++i) {
292 std::pair<unsigned, unsigned> Range = D.getRanges()[i];
293 unsigned Column = D.getColumnNo();
294 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
295 Loc.getLocWithOffset(Range.second - Column));
296 }
297 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000298 return;
299 }
300
Chris Lattner57540c52011-04-15 05:22:18 +0000301 // Otherwise, report the backend error as occurring in the generated .s file.
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000302 // If Loc is invalid, we still need to report the error, it just gets no
303 // location info.
304 Diags.Report(Loc, diag::err_fe_inline_asm).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000305}
306
Quentin Colombet728c5542014-02-06 18:30:43 +0000307#define ComputeDiagID(Severity, GroupName, DiagID) \
308 do { \
309 switch (Severity) { \
310 case llvm::DS_Error: \
311 DiagID = diag::err_fe_##GroupName; \
312 break; \
313 case llvm::DS_Warning: \
314 DiagID = diag::warn_fe_##GroupName; \
315 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000316 case llvm::DS_Remark: \
317 llvm_unreachable("'remark' severity not expected"); \
318 break; \
319 case llvm::DS_Note: \
320 DiagID = diag::note_fe_##GroupName; \
321 break; \
322 } \
323 } while (false)
324
325#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
326 do { \
327 switch (Severity) { \
328 case llvm::DS_Error: \
329 DiagID = diag::err_fe_##GroupName; \
330 break; \
331 case llvm::DS_Warning: \
332 DiagID = diag::warn_fe_##GroupName; \
333 break; \
334 case llvm::DS_Remark: \
335 DiagID = diag::remark_fe_##GroupName; \
336 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000337 case llvm::DS_Note: \
338 DiagID = diag::note_fe_##GroupName; \
339 break; \
340 } \
341 } while (false)
342
343bool
344BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
345 unsigned DiagID;
346 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
347 std::string Message = D.getMsgStr().str();
348
349 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000350 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000351 // code.
352 SourceLocation LocCookie =
353 SourceLocation::getFromRawEncoding(D.getLocCookie());
354 if (LocCookie.isValid())
355 Diags.Report(LocCookie, DiagID).AddString(Message);
356 else {
357 // Otherwise, report the backend diagnostic as occurring in the generated
358 // .s file.
359 // If Loc is invalid, we still need to report the diagnostic, it just gets
360 // no location info.
361 FullSourceLoc Loc;
362 Diags.Report(Loc, DiagID).AddString(Message);
363 }
364 // We handled all the possible severities.
365 return true;
366}
367
368bool
369BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
370 if (D.getSeverity() != llvm::DS_Warning)
371 // For now, the only support we have for StackSize diagnostic is warning.
372 // We do not know how to format other severities.
373 return false;
374
375 // FIXME: We should demangle the function name.
376 // FIXME: Is there a way to get a location for that function?
377 FullSourceLoc Loc;
378 Diags.Report(Loc, diag::warn_fe_backend_frame_larger_than)
379 << D.getStackSize() << D.getFunction().getName();
380 return true;
381}
382
Diego Novillo829b1702014-04-16 16:54:24 +0000383void BackendConsumer::OptimizationRemarkHandler(
384 const llvm::DiagnosticInfoOptimizationRemark &D) {
385 // We only support remarks.
Eric Christopher25c4e672014-05-02 17:52:19 +0000386 assert(D.getSeverity() == llvm::DS_Remark);
Diego Novillo829b1702014-04-16 16:54:24 +0000387
388 // Optimization remarks are active only if -Rpass=regexp is given and the
389 // regular expression pattern in 'regexp' matches the name of the pass
390 // name in \p D.
391 if (CodeGenOpts.OptimizationRemarkPattern &&
392 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName())) {
393 SourceManager &SourceMgr = Context->getSourceManager();
394 FileManager &FileMgr = SourceMgr.getFileManager();
395 StringRef Filename;
396 unsigned Line, Column;
397 D.getLocation(&Filename, &Line, &Column);
398 SourceLocation Loc;
Diego Novillo6dc9c482014-05-08 13:49:54 +0000399 const FileEntry *FE = FileMgr.getFile(Filename);
400 if (FE && Line > 0) {
Diego Novillo829b1702014-04-16 16:54:24 +0000401 // If -gcolumn-info was not used, Column will be 0. This upsets the
402 // source manager, so if Column is not set, set it to 1.
403 if (Column == 0)
404 Column = 1;
Diego Novillo6dc9c482014-05-08 13:49:54 +0000405 Loc = SourceMgr.translateFileLineCol(FE, Line, Column);
Diego Novillo829b1702014-04-16 16:54:24 +0000406 }
Diego Novillob3442242014-04-22 19:56:49 +0000407 Diags.Report(Loc, diag::remark_fe_backend_optimization_remark)
408 << AddFlagValue(D.getPassName()) << D.getMsg().str();
Diego Novillo829b1702014-04-16 16:54:24 +0000409
410 if (Line == 0)
411 // If we could not extract a source location for the diagnostic,
412 // inform the user how they can get source locations back.
413 //
414 // FIXME: We should really be generating !srcloc annotations when
415 // -Rpass is used. !srcloc annotations need to be emitted in
416 // approximately the same spots as !dbg nodes.
417 Diags.Report(diag::note_fe_backend_optimization_remark_missing_loc);
Diego Novillo6dc9c482014-05-08 13:49:54 +0000418 else if (Loc.isInvalid())
419 // If we were not able to translate the file:line:col information
420 // back to a SourceLocation, at least emit a note stating that
421 // we could not translate this location. This can happen in the
422 // case of #line directives.
423 Diags.Report(diag::note_fe_backend_optimization_remark_invalid_loc)
424 << Filename << Line << Column;
Diego Novillo829b1702014-04-16 16:54:24 +0000425 }
426}
427
Quentin Colombet728c5542014-02-06 18:30:43 +0000428/// \brief This function is invoked when the backend needs
429/// to report something to the user.
430void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
431 unsigned DiagID = diag::err_fe_inline_asm;
432 llvm::DiagnosticSeverity Severity = DI.getSeverity();
433 // Get the diagnostic ID based.
434 switch (DI.getKind()) {
435 case llvm::DK_InlineAsm:
436 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
437 return;
438 ComputeDiagID(Severity, inline_asm, DiagID);
439 break;
440 case llvm::DK_StackSize:
441 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
442 return;
443 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
444 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000445 case llvm::DK_OptimizationRemark:
446 // Optimization remarks are always handled completely by this
447 // handler. There is no generic way of emitting them.
448 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
449 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000450 default:
451 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000452 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000453 break;
454 }
455 std::string MsgStorage;
456 {
457 raw_string_ostream Stream(MsgStorage);
458 DiagnosticPrinterRawOStream DP(Stream);
459 DI.print(DP);
460 }
461
462 // Report the backend message using the usual diagnostic mechanism.
463 FullSourceLoc Loc;
464 Diags.Report(Loc, DiagID).AddString(MsgStorage);
465}
466#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000467
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000468CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000469 : Act(_Act), LinkModule(0),
470 VMContext(_VMContext ? _VMContext : new LLVMContext),
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000471 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000472
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000473CodeGenAction::~CodeGenAction() {
474 TheModule.reset();
475 if (OwnsVMContext)
476 delete VMContext;
477}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000478
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000479bool CodeGenAction::hasIRSupport() const { return true; }
480
Daniel Dunbar400a6932010-02-25 04:37:50 +0000481void CodeGenAction::EndSourceFileAction() {
482 // If the consumer creation failed, do nothing.
483 if (!getCompilerInstance().hasASTConsumer())
484 return;
485
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000486 // If we were given a link module, release consumer's ownership of it.
487 if (LinkModule)
488 BEConsumer->takeLinkModule();
489
Daniel Dunbar400a6932010-02-25 04:37:50 +0000490 // Steal the module from the consumer.
Nico Weber2992efa2011-01-25 20:34:14 +0000491 TheModule.reset(BEConsumer->takeModule());
Daniel Dunbar400a6932010-02-25 04:37:50 +0000492}
493
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000494llvm::Module *CodeGenAction::takeModule() { return TheModule.release(); }
Daniel Dunbar400a6932010-02-25 04:37:50 +0000495
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000496llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
497 OwnsVMContext = false;
498 return VMContext;
499}
500
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000501static raw_ostream *GetOutputStream(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000502 StringRef InFile,
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000503 BackendAction Action) {
504 switch (Action) {
505 case Backend_EmitAssembly:
506 return CI.createDefaultOutputFile(false, InFile, "s");
507 case Backend_EmitLL:
508 return CI.createDefaultOutputFile(false, InFile, "ll");
509 case Backend_EmitBC:
510 return CI.createDefaultOutputFile(true, InFile, "bc");
511 case Backend_EmitNothing:
512 return 0;
513 case Backend_EmitMCNull:
514 case Backend_EmitObj:
515 return CI.createDefaultOutputFile(true, InFile, "o");
516 }
517
David Blaikie83d382b2011-09-23 05:06:16 +0000518 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000519}
520
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000521ASTConsumer *CodeGenAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000522 StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000523 BackendAction BA = static_cast<BackendAction>(Act);
Ahmed Charlesb8984322014-03-07 20:03:18 +0000524 std::unique_ptr<raw_ostream> OS(GetOutputStream(CI, InFile, BA));
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000525 if (BA != Backend_EmitNothing && !OS)
526 return 0;
527
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000528 llvm::Module *LinkModuleToUse = LinkModule;
529
530 // If we were not given a link module, and the user requested that one be
531 // loaded from bitcode, do so now.
532 const std::string &LinkBCFile = CI.getCodeGenOpts().LinkBitcodeFile;
533 if (!LinkModuleToUse && !LinkBCFile.empty()) {
534 std::string ErrorStr;
535
536 llvm::MemoryBuffer *BCBuf =
537 CI.getFileManager().getBufferForFile(LinkBCFile, &ErrorStr);
538 if (!BCBuf) {
539 CI.getDiagnostics().Report(diag::err_cannot_open_file)
540 << LinkBCFile << ErrorStr;
541 return 0;
542 }
543
Rafael Espindola6b6004a2014-01-13 18:31:09 +0000544 ErrorOr<llvm::Module *> ModuleOrErr =
545 getLazyBitcodeModule(BCBuf, *VMContext);
546 if (error_code EC = ModuleOrErr.getError()) {
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000547 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Rafael Espindola6b6004a2014-01-13 18:31:09 +0000548 << LinkBCFile << EC.message();
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000549 return 0;
550 }
Rafael Espindola6b6004a2014-01-13 18:31:09 +0000551 LinkModuleToUse = ModuleOrErr.get();
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000552 }
553
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000554 BEConsumer = new BackendConsumer(BA, CI.getDiagnostics(), CI.getCodeGenOpts(),
555 CI.getTargetOpts(), CI.getLangOpts(),
556 CI.getFrontendOpts().ShowTimers, InFile,
557 LinkModuleToUse, OS.release(), *VMContext);
Nico Weber2992efa2011-01-25 20:34:14 +0000558 return BEConsumer;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000559}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000560
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000561void CodeGenAction::ExecuteAction() {
562 // If this is an IR file, we have to treat it specially.
563 if (getCurrentFileKind() == IK_LLVM_IR) {
564 BackendAction BA = static_cast<BackendAction>(Act);
565 CompilerInstance &CI = getCompilerInstance();
566 raw_ostream *OS = GetOutputStream(CI, getCurrentFile(), BA);
567 if (BA != Backend_EmitNothing && !OS)
568 return;
569
570 bool Invalid;
571 SourceManager &SM = CI.getSourceManager();
572 const llvm::MemoryBuffer *MainFile = SM.getBuffer(SM.getMainFileID(),
573 &Invalid);
574 if (Invalid)
575 return;
576
577 // FIXME: This is stupid, IRReader shouldn't take ownership.
578 llvm::MemoryBuffer *MainFileCopy =
579 llvm::MemoryBuffer::getMemBufferCopy(MainFile->getBuffer(),
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000580 getCurrentFile());
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000581
582 llvm::SMDiagnostic Err;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000583 TheModule.reset(ParseIR(MainFileCopy, Err, *VMContext));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000584 if (!TheModule) {
585 // Translate from the diagnostic info to the SourceManager location.
Argyrios Kyrtzidis27bf76d2011-09-19 20:40:38 +0000586 SourceLocation Loc = SM.translateFileLineCol(
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000587 SM.getFileEntryForID(SM.getMainFileID()), Err.getLineNo(),
588 Err.getColumnNo() + 1);
589
Alp Tokerbc043f22013-12-21 05:20:03 +0000590 // Strip off a leading diagnostic code if there is one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000591 StringRef Msg = Err.getMessage();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000592 if (Msg.startswith("error: "))
593 Msg = Msg.substr(7);
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000594
Alp Tokerbc043f22013-12-21 05:20:03 +0000595 unsigned DiagID =
596 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000597
Alp Tokerbc043f22013-12-21 05:20:03 +0000598 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000599 return;
600 }
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000601 const TargetOptions &TargetOpts = CI.getTargetOpts();
602 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
603 unsigned DiagID = CI.getDiagnostics().getCustomDiagID(
604 DiagnosticsEngine::Warning,
605 "overriding the module target triple with %0");
606
607 CI.getDiagnostics().Report(SourceLocation(), DiagID) << TargetOpts.Triple;
608 TheModule->setTargetTriple(TargetOpts.Triple);
609 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000610
Alp Tokere83b9062014-01-02 15:08:04 +0000611 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
612 CI.getLangOpts(), CI.getTarget().getTargetDescription(),
613 TheModule.get(), BA, OS);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000614 return;
615 }
616
617 // Otherwise follow the normal AST path.
618 this->ASTFrontendAction::ExecuteAction();
619}
620
621//
622
David Blaikie68e081d2011-12-20 02:48:34 +0000623void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000624EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
625 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000626
David Blaikie68e081d2011-12-20 02:48:34 +0000627void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000628EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
629 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000630
David Blaikie68e081d2011-12-20 02:48:34 +0000631void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000632EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
633 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000634
David Blaikie68e081d2011-12-20 02:48:34 +0000635void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000636EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
637 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000638
David Blaikie68e081d2011-12-20 02:48:34 +0000639void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000640EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
641 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000642
David Blaikie68e081d2011-12-20 02:48:34 +0000643void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000644EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
645 : CodeGenAction(Backend_EmitObj, _VMContext) {}