blob: 9c0ae9ed9914fa5ea903a3153eb59ab5a66acf18 [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
Alex Lorenzee024992014-08-04 18:41:51 +000010#include "CoverageMappingGen.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"
Hans Wennborga926d842014-05-23 20:37:38 +000013#include "clang/AST/DeclCXX.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000014#include "clang/AST/DeclGroup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/Basic/FileManager.h"
16#include "clang/Basic/SourceManager.h"
17#include "clang/Basic/TargetInfo.h"
Daniel Dunbarc1b17292010-06-15 17:48:49 +000018#include "clang/CodeGen/BackendUtil.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000019#include "clang/CodeGen/CodeGenAction.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000020#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000021#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbaracadc552009-12-03 09:12:54 +000022#include "clang/Frontend/FrontendDiagnostic.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "llvm/ADT/SmallString.h"
25#include "llvm/Bitcode/ReaderWriter.h"
Diego Novillo829b1702014-04-16 16:54:24 +000026#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000027#include "llvm/IR/DiagnosticInfo.h"
28#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnsonaff22322015-12-07 19:21:34 +000029#include "llvm/IR/FunctionInfo.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Module.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000032#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000033#include "llvm/Linker/Linker.h"
Teresa Johnsonaff22322015-12-07 19:21:34 +000034#include "llvm/Object/FunctionIndexObjectFile.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000035#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000036#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000038#include "llvm/Support/Timer.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000039#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000040using namespace clang;
41using namespace llvm;
42
Nico Weber2992efa2011-01-25 20:34:14 +000043namespace clang {
Teresa Johnsonaff22322015-12-07 19:21:34 +000044/// Diagnostic handler used by invocations of Linker::LinkModules
45static void linkerDiagnosticHandler(const DiagnosticInfo &DI,
46 const llvm::Module *LinkModule,
47 DiagnosticsEngine &Diags) {
48 if (DI.getSeverity() != DS_Error)
49 return;
50
51 std::string MsgStorage;
52 {
53 raw_string_ostream Stream(MsgStorage);
54 DiagnosticPrinterRawOStream DP(Stream);
55 DI.print(DP);
56 }
57
58 Diags.Report(diag::err_fe_cannot_link_module)
59 << LinkModule->getModuleIdentifier() << MsgStorage;
60}
61
Benjamin Kramer16634c22009-11-28 10:07:24 +000062 class BackendConsumer : public ASTConsumer {
David Blaikie68e081d2011-12-20 02:48:34 +000063 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000064 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000065 BackendAction Action;
Daniel Dunbarde182242009-11-30 08:39:32 +000066 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000067 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000068 const LangOptions &LangOpts;
Rafael Espindola2f16bc12015-04-14 15:15:49 +000069 raw_pwrite_stream *AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000070 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000071
Chris Lattner263d64c2009-02-18 01:37:30 +000072 Timer LLVMIRGeneration;
Mike Stump11289f42009-09-09 15:08:12 +000073
Ahmed Charlesb8984322014-03-07 20:03:18 +000074 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000075
Artem Belevich5d40ae32015-10-27 17:56:59 +000076 std::unique_ptr<llvm::Module> TheModule;
77 SmallVector<std::pair<unsigned, std::unique_ptr<llvm::Module>>, 4>
78 LinkModules;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000079
Mike Stump11289f42009-09-09 15:08:12 +000080 public:
Artem Belevich5d40ae32015-10-27 17:56:59 +000081 BackendConsumer(
82 BackendAction Action, DiagnosticsEngine &Diags,
83 const HeaderSearchOptions &HeaderSearchOpts,
84 const PreprocessorOptions &PPOpts, const CodeGenOptions &CodeGenOpts,
85 const TargetOptions &TargetOpts, const LangOptions &LangOpts,
86 bool TimePasses, const std::string &InFile,
87 const SmallVectorImpl<std::pair<unsigned, llvm::Module *>> &LinkModules,
88 raw_pwrite_stream *OS, LLVMContext &C,
89 CoverageSourceInfo *CoverageInfo = nullptr)
Justin Bognercb082992015-05-22 22:16:55 +000090 : Diags(Diags), Action(Action), CodeGenOpts(CodeGenOpts),
91 TargetOpts(TargetOpts), LangOpts(LangOpts), AsmOutStream(OS),
Yaron Keren2f5ec2f2014-12-25 12:21:56 +000092 Context(nullptr), LLVMIRGeneration("LLVM IR Generation Time"),
Adrian Prantle74f5252015-06-30 02:26:03 +000093 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
Artem Belevich5d40ae32015-10-27 17:56:59 +000094 CodeGenOpts, C, CoverageInfo)) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000095 llvm::TimePassesIsEnabled = TimePasses;
Artem Belevich5d40ae32015-10-27 17:56:59 +000096 for (auto &I : LinkModules)
97 this->LinkModules.push_back(
98 std::make_pair(I.first, std::unique_ptr<llvm::Module>(I.second)));
Chris Lattnerdeffa132009-02-18 01:23:44 +000099 }
David Blaikie780dd3b2014-08-29 05:08:19 +0000100 std::unique_ptr<llvm::Module> takeModule() { return std::move(TheModule); }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000101 void releaseLinkModules() {
102 for (auto &I : LinkModules)
103 I.second.release();
104 }
Daniel Dunbar400a6932010-02-25 04:37:50 +0000105
Craig Topper4f12f102014-03-12 06:41:41 +0000106 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +0000107 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +0000108 }
109
Craig Topper4f12f102014-03-12 06:41:41 +0000110 void Initialize(ASTContext &Ctx) override {
Richard Smith293534b2015-08-18 20:39:29 +0000111 assert(!Context && "initialized multiple times");
112
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000113 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +0000114
Daniel Dunbar8e705052009-11-30 08:39:52 +0000115 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000116 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +0000117
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000118 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000119
Daniel Dunbar400a6932010-02-25 04:37:50 +0000120 TheModule.reset(Gen->GetModule());
Mike Stump11289f42009-09-09 15:08:12 +0000121
Daniel Dunbar8e705052009-11-30 08:39:52 +0000122 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000123 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000124 }
Mike Stump11289f42009-09-09 15:08:12 +0000125
Craig Topper4f12f102014-03-12 06:41:41 +0000126 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000127 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +0000128 Context->getSourceManager(),
129 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +0000130
Daniel Dunbar8e705052009-11-30 08:39:52 +0000131 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000132 LLVMIRGeneration.startTimer();
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000133
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000134 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000135
Daniel Dunbar8e705052009-11-30 08:39:52 +0000136 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000137 LLVMIRGeneration.stopTimer();
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000138
139 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000140 }
Mike Stump11289f42009-09-09 15:08:12 +0000141
Hans Wennborga926d842014-05-23 20:37:38 +0000142 void HandleInlineMethodDefinition(CXXMethodDecl *D) override {
143 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
144 Context->getSourceManager(),
145 "LLVM IR generation of inline method");
146 if (llvm::TimePassesIsEnabled)
147 LLVMIRGeneration.startTimer();
148
149 Gen->HandleInlineMethodDefinition(D);
150
151 if (llvm::TimePassesIsEnabled)
152 LLVMIRGeneration.stopTimer();
153 }
154
Craig Topper4f12f102014-03-12 06:41:41 +0000155 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000156 {
Chris Lattnere46de752009-03-06 06:46:31 +0000157 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Daniel Dunbar8e705052009-11-30 08:39:52 +0000158 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000159 LLVMIRGeneration.startTimer();
Chris Lattner263d64c2009-02-18 01:37:30 +0000160
Chris Lattnercf169832009-03-28 04:11:33 +0000161 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000162
Daniel Dunbar8e705052009-11-30 08:39:52 +0000163 if (llvm::TimePassesIsEnabled)
Chris Lattnereae6cb62009-03-05 08:00:35 +0000164 LLVMIRGeneration.stopTimer();
165 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000166
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000167 // Silently ignore if we weren't initialized for some reason.
Daniel Dunbar3e111522010-06-07 23:21:04 +0000168 if (!TheModule)
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000169 return;
Mike Stump11289f42009-09-09 15:08:12 +0000170
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000171 // Make sure IR generation is happy with the module. This is released by
172 // the module provider.
Douglas Gregorde3ef502011-11-30 23:21:26 +0000173 llvm::Module *M = Gen->ReleaseModule();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000174 if (!M) {
175 // The module has been released by IR gen on failures, do not double
176 // free.
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000177 TheModule.release();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000178 return;
179 }
180
181 assert(TheModule.get() == M &&
182 "Unexpected module change during IR generation");
183
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000184 // Link LinkModule into this module if present, preserving its validity.
Artem Belevich5d40ae32015-10-27 17:56:59 +0000185 for (auto &I : LinkModules) {
186 unsigned LinkFlags = I.first;
187 llvm::Module *LinkModule = I.second.get();
Rafael Espindolaf0202c42015-12-01 19:51:03 +0000188 if (Linker::linkModules(*M, *LinkModule,
Artem Belevich5d40ae32015-10-27 17:56:59 +0000189 [=](const DiagnosticInfo &DI) {
Teresa Johnsonaff22322015-12-07 19:21:34 +0000190 linkerDiagnosticHandler(DI, LinkModule, Diags);
Artem Belevich5d40ae32015-10-27 17:56:59 +0000191 },
192 LinkFlags))
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000193 return;
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000194 }
195
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000196 // Install an inline asm handler so that diagnostics get printed through
197 // our diagnostics hooks.
198 LLVMContext &Ctx = TheModule->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000199 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
200 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000201 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000202 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000203
Quentin Colombet728c5542014-02-06 18:30:43 +0000204 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
205 Ctx.getDiagnosticHandler();
206 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
207 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
208
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000209 EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
Eric Christopher964a5f32015-08-05 23:48:05 +0000210 C.getTargetInfo().getDataLayoutString(),
Daniel Dunbar3e111522010-06-07 23:21:04 +0000211 TheModule.get(), Action, AsmOutStream);
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000212
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000213 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000214
215 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000216 }
Mike Stump11289f42009-09-09 15:08:12 +0000217
Craig Topper4f12f102014-03-12 06:41:41 +0000218 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000219 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
220 Context->getSourceManager(),
221 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000222 Gen->HandleTagDeclDefinition(D);
223 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000224
Craig Topper4f12f102014-03-12 06:41:41 +0000225 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000226 Gen->HandleTagDeclRequiredDefinition(D);
227 }
228
Craig Topper4f12f102014-03-12 06:41:41 +0000229 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000230 Gen->CompleteTentativeDefinition(D);
231 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000232
Nico Weberb6a5d052015-01-15 04:07:35 +0000233 void HandleVTable(CXXRecordDecl *RD) override {
234 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000235 }
236
Craig Topper4f12f102014-03-12 06:41:41 +0000237 void HandleLinkerOptionPragma(llvm::StringRef Opts) override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000238 Gen->HandleLinkerOptionPragma(Opts);
239 }
240
Craig Topper4f12f102014-03-12 06:41:41 +0000241 void HandleDetectMismatch(llvm::StringRef Name,
242 llvm::StringRef Value) override {
Aaron Ballman5d041be2013-06-04 02:07:14 +0000243 Gen->HandleDetectMismatch(Name, Value);
244 }
245
Craig Topper4f12f102014-03-12 06:41:41 +0000246 void HandleDependentLibrary(llvm::StringRef Opts) override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000247 Gen->HandleDependentLibrary(Opts);
248 }
249
Chris Lattner5ec32e72010-04-06 18:38:50 +0000250 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
251 unsigned LocCookie) {
252 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
253 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
254 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000255
Quentin Colombet728c5542014-02-06 18:30:43 +0000256 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
257 void *Context) {
258 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
259 }
260
Chris Lattner5ec32e72010-04-06 18:38:50 +0000261 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
262 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000263
264 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
265 /// \brief Specialized handler for InlineAsm diagnostic.
266 /// \return True if the diagnostic has been successfully reported, false
267 /// otherwise.
268 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
269 /// \brief Specialized handler for StackSize diagnostic.
270 /// \return True if the diagnostic has been successfully reported, false
271 /// otherwise.
272 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000273 /// \brief Specialized handlers for optimization remarks.
274 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000275 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000276 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
277 unsigned DiagID);
Diego Novillod23ec942014-05-29 19:55:06 +0000278 void
Diego Novillo829b1702014-04-16 16:54:24 +0000279 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationRemark &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000280 void OptimizationRemarkHandler(
281 const llvm::DiagnosticInfoOptimizationRemarkMissed &D);
282 void OptimizationRemarkHandler(
283 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D);
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000284 void OptimizationRemarkHandler(
285 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D);
Tyler Nowicki034baf62015-08-10 23:05:16 +0000286 void OptimizationRemarkHandler(
287 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000288 void OptimizationFailureHandler(
289 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000290 };
David Blaikie68e081d2011-12-20 02:48:34 +0000291
292 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000293}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000294
Chris Lattner79f67a72010-04-08 00:23:06 +0000295/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
296/// buffer to be a valid FullSourceLoc.
297static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
298 SourceManager &CSM) {
299 // Get both the clang and llvm source managers. The location is relative to
300 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000301 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000302 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000303
Chris Lattner79f67a72010-04-08 00:23:06 +0000304 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
305 // already owns its one and clang::SourceManager wants to own its one.
306 const MemoryBuffer *LBuf =
307 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000308
Chris Lattner79f67a72010-04-08 00:23:06 +0000309 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000310 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000311 std::unique_ptr<llvm::MemoryBuffer> CBuf =
312 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
313 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000314 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000315 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000316
Chris Lattner79f67a72010-04-08 00:23:06 +0000317 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000318 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000319 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000320 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000321 return FullSourceLoc(NewLoc, CSM);
322}
323
Chris Lattner6d672132010-04-06 17:52:14 +0000324
Chris Lattner5ec32e72010-04-06 18:38:50 +0000325/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
326/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000327/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000328void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
329 SourceLocation LocCookie) {
330 // There are a couple of different kinds of errors we could get here. First,
331 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000332
333 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000334 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000335 if (Message.startswith("error: "))
336 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000337
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000338 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000339 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000340 if (D.getLoc() != SMLoc())
341 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000342
Joey Gouly5798b262014-06-05 21:23:42 +0000343 unsigned DiagID;
344 switch (D.getKind()) {
345 case llvm::SourceMgr::DK_Error:
346 DiagID = diag::err_fe_inline_asm;
347 break;
348 case llvm::SourceMgr::DK_Warning:
349 DiagID = diag::warn_fe_inline_asm;
350 break;
351 case llvm::SourceMgr::DK_Note:
352 DiagID = diag::note_fe_inline_asm;
353 break;
354 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000355 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000356 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000357 // code.
358 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000359 Diags.Report(LocCookie, DiagID).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000360
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000361 if (D.getLoc().isValid()) {
362 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
363 // Convert the SMDiagnostic ranges into SourceRange and attach them
364 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000365 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000366 unsigned Column = D.getColumnNo();
367 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
368 Loc.getLocWithOffset(Range.second - Column));
369 }
370 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000371 return;
372 }
373
Joey Gouly5798b262014-06-05 21:23:42 +0000374 // Otherwise, report the backend issue as occurring in the generated .s file.
375 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000376 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000377 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000378}
379
Quentin Colombet728c5542014-02-06 18:30:43 +0000380#define ComputeDiagID(Severity, GroupName, DiagID) \
381 do { \
382 switch (Severity) { \
383 case llvm::DS_Error: \
384 DiagID = diag::err_fe_##GroupName; \
385 break; \
386 case llvm::DS_Warning: \
387 DiagID = diag::warn_fe_##GroupName; \
388 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000389 case llvm::DS_Remark: \
390 llvm_unreachable("'remark' severity not expected"); \
391 break; \
392 case llvm::DS_Note: \
393 DiagID = diag::note_fe_##GroupName; \
394 break; \
395 } \
396 } while (false)
397
398#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
399 do { \
400 switch (Severity) { \
401 case llvm::DS_Error: \
402 DiagID = diag::err_fe_##GroupName; \
403 break; \
404 case llvm::DS_Warning: \
405 DiagID = diag::warn_fe_##GroupName; \
406 break; \
407 case llvm::DS_Remark: \
408 DiagID = diag::remark_fe_##GroupName; \
409 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000410 case llvm::DS_Note: \
411 DiagID = diag::note_fe_##GroupName; \
412 break; \
413 } \
414 } while (false)
415
416bool
417BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
418 unsigned DiagID;
419 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
420 std::string Message = D.getMsgStr().str();
421
422 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000423 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000424 // code.
425 SourceLocation LocCookie =
426 SourceLocation::getFromRawEncoding(D.getLocCookie());
427 if (LocCookie.isValid())
428 Diags.Report(LocCookie, DiagID).AddString(Message);
429 else {
430 // Otherwise, report the backend diagnostic as occurring in the generated
431 // .s file.
432 // If Loc is invalid, we still need to report the diagnostic, it just gets
433 // no location info.
434 FullSourceLoc Loc;
435 Diags.Report(Loc, DiagID).AddString(Message);
436 }
437 // We handled all the possible severities.
438 return true;
439}
440
441bool
442BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
443 if (D.getSeverity() != llvm::DS_Warning)
444 // For now, the only support we have for StackSize diagnostic is warning.
445 // We do not know how to format other severities.
446 return false;
447
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000448 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
449 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
450 diag::warn_fe_frame_larger_than)
451 << D.getStackSize() << Decl::castToDeclContext(ND);
452 return true;
453 }
454
455 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000456}
457
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000458void BackendConsumer::EmitOptimizationMessage(
Tyler Nowickie4707712014-07-16 00:40:42 +0000459 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000460 // We only support warnings and remarks.
461 assert(D.getSeverity() == llvm::DS_Remark ||
462 D.getSeverity() == llvm::DS_Warning);
Diego Novillo829b1702014-04-16 16:54:24 +0000463
Diego Novillod23ec942014-05-29 19:55:06 +0000464 SourceManager &SourceMgr = Context->getSourceManager();
465 FileManager &FileMgr = SourceMgr.getFileManager();
466 StringRef Filename;
467 unsigned Line, Column;
Alp Toker27506272014-06-05 22:11:12 +0000468 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000469
470 if (D.isLocationAvailable()) {
471 D.getLocation(&Filename, &Line, &Column);
472 const FileEntry *FE = FileMgr.getFile(Filename);
473 if (FE && Line > 0) {
474 // If -gcolumn-info was not used, Column will be 0. This upsets the
475 // source manager, so pass 1 if Column is not set.
476 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
477 }
Diego Novillo829b1702014-04-16 16:54:24 +0000478 }
Alp Toker27506272014-06-05 22:11:12 +0000479
480 // If a location isn't available, try to approximate it using the associated
481 // function definition. We use the definition's right brace to differentiate
482 // from diagnostics that genuinely relate to the function itself.
483 FullSourceLoc Loc(DILoc, SourceMgr);
484 if (Loc.isInvalid())
485 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
486 Loc = FD->getASTContext().getFullLoc(FD->getBodyRBrace());
487
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000488 Diags.Report(Loc, DiagID)
489 << AddFlagValue(D.getPassName() ? D.getPassName() : "")
490 << D.getMsg().str();
Diego Novillod23ec942014-05-29 19:55:06 +0000491
Diego Novillo86f884e2015-05-08 20:59:56 +0000492 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000493 // If we were not able to translate the file:line:col information
494 // back to a SourceLocation, at least emit a note stating that
495 // we could not translate this location. This can happen in the
496 // case of #line directives.
Alp Toker27506272014-06-05 22:11:12 +0000497 Diags.Report(Loc, diag::note_fe_backend_optimization_remark_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000498 << Filename << Line << Column;
499}
500
501void BackendConsumer::OptimizationRemarkHandler(
502 const llvm::DiagnosticInfoOptimizationRemark &D) {
503 // Optimization remarks are active only if the -Rpass flag has a regular
504 // expression that matches the name of the pass name in \p D.
505 if (CodeGenOpts.OptimizationRemarkPattern &&
506 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000507 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
Diego Novillod23ec942014-05-29 19:55:06 +0000508}
509
510void BackendConsumer::OptimizationRemarkHandler(
511 const llvm::DiagnosticInfoOptimizationRemarkMissed &D) {
512 // Missed optimization remarks are active only if the -Rpass-missed
513 // flag has a regular expression that matches the name of the pass
514 // name in \p D.
515 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
516 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000517 EmitOptimizationMessage(D,
518 diag::remark_fe_backend_optimization_remark_missed);
Diego Novillod23ec942014-05-29 19:55:06 +0000519}
520
521void BackendConsumer::OptimizationRemarkHandler(
522 const llvm::DiagnosticInfoOptimizationRemarkAnalysis &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000523 // Optimization analysis remarks are active if the pass name is set to
524 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
525 // regular expression that matches the name of the pass name in \p D.
526
527 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
528 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
529 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000530 EmitOptimizationMessage(
Diego Novillod23ec942014-05-29 19:55:06 +0000531 D, diag::remark_fe_backend_optimization_remark_analysis);
Diego Novillo829b1702014-04-16 16:54:24 +0000532}
533
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000534void BackendConsumer::OptimizationRemarkHandler(
535 const llvm::DiagnosticInfoOptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000536 // Optimization analysis remarks are active if the pass name is set to
537 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
538 // regular expression that matches the name of the pass name in \p D.
539
540 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
541 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
542 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000543 EmitOptimizationMessage(
544 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
545}
546
Tyler Nowicki034baf62015-08-10 23:05:16 +0000547void BackendConsumer::OptimizationRemarkHandler(
548 const llvm::DiagnosticInfoOptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000549 // Optimization analysis remarks are active if the pass name is set to
550 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
551 // regular expression that matches the name of the pass name in \p D.
552
553 if (D.getPassName() == llvm::DiagnosticInfo::AlwaysPrint ||
554 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
555 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000556 EmitOptimizationMessage(
557 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
558}
559
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000560void BackendConsumer::OptimizationFailureHandler(
561 const llvm::DiagnosticInfoOptimizationFailure &D) {
562 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
563}
564
Quentin Colombet728c5542014-02-06 18:30:43 +0000565/// \brief This function is invoked when the backend needs
566/// to report something to the user.
567void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
568 unsigned DiagID = diag::err_fe_inline_asm;
569 llvm::DiagnosticSeverity Severity = DI.getSeverity();
570 // Get the diagnostic ID based.
571 switch (DI.getKind()) {
572 case llvm::DK_InlineAsm:
573 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
574 return;
575 ComputeDiagID(Severity, inline_asm, DiagID);
576 break;
577 case llvm::DK_StackSize:
578 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
579 return;
580 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
581 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000582 case llvm::DK_OptimizationRemark:
583 // Optimization remarks are always handled completely by this
584 // handler. There is no generic way of emitting them.
585 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemark>(DI));
586 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000587 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000588 // Optimization remarks are always handled completely by this
589 // handler. There is no generic way of emitting them.
590 OptimizationRemarkHandler(cast<DiagnosticInfoOptimizationRemarkMissed>(DI));
591 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000592 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000593 // Optimization remarks are always handled completely by this
594 // handler. There is no generic way of emitting them.
595 OptimizationRemarkHandler(
596 cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000597 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000598 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
599 // Optimization remarks are always handled completely by this
600 // handler. There is no generic way of emitting them.
601 OptimizationRemarkHandler(
602 cast<DiagnosticInfoOptimizationRemarkAnalysisFPCommute>(DI));
603 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000604 case llvm::DK_OptimizationRemarkAnalysisAliasing:
605 // Optimization remarks are always handled completely by this
606 // handler. There is no generic way of emitting them.
607 OptimizationRemarkHandler(
608 cast<DiagnosticInfoOptimizationRemarkAnalysisAliasing>(DI));
609 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000610 case llvm::DK_OptimizationFailure:
611 // Optimization failures are always handled completely by this
612 // handler.
613 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
614 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000615 default:
616 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000617 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000618 break;
619 }
620 std::string MsgStorage;
621 {
622 raw_string_ostream Stream(MsgStorage);
623 DiagnosticPrinterRawOStream DP(Stream);
624 DI.print(DP);
625 }
626
627 // Report the backend message using the usual diagnostic mechanism.
628 FullSourceLoc Loc;
629 Diags.Report(Loc, DiagID).AddString(MsgStorage);
630}
631#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000632
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000633CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000634 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
635 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000636
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000637CodeGenAction::~CodeGenAction() {
638 TheModule.reset();
639 if (OwnsVMContext)
640 delete VMContext;
641}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000642
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000643bool CodeGenAction::hasIRSupport() const { return true; }
644
Daniel Dunbar400a6932010-02-25 04:37:50 +0000645void CodeGenAction::EndSourceFileAction() {
646 // If the consumer creation failed, do nothing.
647 if (!getCompilerInstance().hasASTConsumer())
648 return;
649
Artem Belevich5d40ae32015-10-27 17:56:59 +0000650 // Take back ownership of link modules we passed to consumer.
651 if (!LinkModules.empty())
652 BEConsumer->releaseLinkModules();
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000653
Daniel Dunbar400a6932010-02-25 04:37:50 +0000654 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000655 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000656}
657
Rafael Espindolae8337302014-08-19 14:36:35 +0000658std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
659 return std::move(TheModule);
660}
661
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000662llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
663 OwnsVMContext = false;
664 return VMContext;
665}
666
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000667static raw_pwrite_stream *
668GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000669 switch (Action) {
670 case Backend_EmitAssembly:
671 return CI.createDefaultOutputFile(false, InFile, "s");
672 case Backend_EmitLL:
673 return CI.createDefaultOutputFile(false, InFile, "ll");
674 case Backend_EmitBC:
675 return CI.createDefaultOutputFile(true, InFile, "bc");
676 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000677 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000678 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000679 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000680 case Backend_EmitObj:
681 return CI.createDefaultOutputFile(true, InFile, "o");
682 }
683
David Blaikie83d382b2011-09-23 05:06:16 +0000684 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000685}
686
David Blaikie6beb6aa2014-08-10 19:56:51 +0000687std::unique_ptr<ASTConsumer>
688CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000689 BackendAction BA = static_cast<BackendAction>(Act);
Artem Beleviched0577c2015-05-12 17:44:15 +0000690 raw_pwrite_stream *OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000691 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000692 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000693
Artem Belevich5d40ae32015-10-27 17:56:59 +0000694 // Load bitcode modules to link with, if we need to.
695 if (LinkModules.empty())
696 for (auto &I : CI.getCodeGenOpts().LinkBitcodeFiles) {
697 const std::string &LinkBCFile = I.second;
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000698
Artem Belevich5d40ae32015-10-27 17:56:59 +0000699 auto BCBuf = CI.getFileManager().getBufferForFile(LinkBCFile);
700 if (!BCBuf) {
701 CI.getDiagnostics().Report(diag::err_cannot_open_file)
702 << LinkBCFile << BCBuf.getError().message();
703 LinkModules.clear();
704 return nullptr;
705 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000706
Artem Belevich5d40ae32015-10-27 17:56:59 +0000707 ErrorOr<std::unique_ptr<llvm::Module>> ModuleOrErr =
708 getLazyBitcodeModule(std::move(*BCBuf), *VMContext);
709 if (std::error_code EC = ModuleOrErr.getError()) {
710 CI.getDiagnostics().Report(diag::err_cannot_open_file) << LinkBCFile
711 << EC.message();
712 LinkModules.clear();
713 return nullptr;
714 }
715 addLinkModule(ModuleOrErr.get().release(), I.first);
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000716 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000717
Alex Lorenzee024992014-08-04 18:41:51 +0000718 CoverageSourceInfo *CoverageInfo = nullptr;
719 // Add the preprocessor callback only when the coverage mapping is generated.
720 if (CI.getCodeGenOpts().CoverageMapping) {
721 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000722 CI.getPreprocessor().addPPCallbacks(
723 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000724 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000725
David Blaikie037e75b2014-08-10 21:06:17 +0000726 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000727 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
728 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Artem Belevich5d40ae32015-10-27 17:56:59 +0000729 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile, LinkModules,
730 OS, *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000731 BEConsumer = Result.get();
732 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000733}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000734
Steven Wu15b385f2015-02-12 02:06:55 +0000735static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
736 void *Context,
737 unsigned LocCookie) {
738 SM.print(nullptr, llvm::errs());
739}
740
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000741void CodeGenAction::ExecuteAction() {
742 // If this is an IR file, we have to treat it specially.
743 if (getCurrentFileKind() == IK_LLVM_IR) {
744 BackendAction BA = static_cast<BackendAction>(Act);
745 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000746 raw_pwrite_stream *OS = GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000747 if (BA != Backend_EmitNothing && !OS)
748 return;
749
750 bool Invalid;
751 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000752 FileID FID = SM.getMainFileID();
753 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000754 if (Invalid)
755 return;
756
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000757 llvm::SMDiagnostic Err;
Rafael Espindola32327732014-08-26 21:49:29 +0000758 TheModule = parseIR(MainFile->getMemBufferRef(), Err, *VMContext);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000759 if (!TheModule) {
Alp Toker7b463d52014-06-30 01:33:59 +0000760 // Translate from the diagnostic info to the SourceManager location if
761 // available.
762 // TODO: Unify this with ConvertBackendLocation()
763 SourceLocation Loc;
764 if (Err.getLineNo() > 0) {
765 assert(Err.getColumnNo() >= 0);
766 Loc = SM.translateFileLineCol(SM.getFileEntryForID(FID),
767 Err.getLineNo(), Err.getColumnNo() + 1);
768 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000769
Alp Tokerbc043f22013-12-21 05:20:03 +0000770 // Strip off a leading diagnostic code if there is one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000771 StringRef Msg = Err.getMessage();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000772 if (Msg.startswith("error: "))
773 Msg = Msg.substr(7);
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000774
Alp Tokerbc043f22013-12-21 05:20:03 +0000775 unsigned DiagID =
776 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
Benjamin Kramer778b8b82012-03-16 22:31:42 +0000777
Alp Tokerbc043f22013-12-21 05:20:03 +0000778 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000779 return;
780 }
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000781 const TargetOptions &TargetOpts = CI.getTargetOpts();
782 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000783 CI.getDiagnostics().Report(SourceLocation(),
784 diag::warn_fe_override_module)
785 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000786 TheModule->setTargetTriple(TargetOpts.Triple);
787 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000788
Teresa Johnsonaff22322015-12-07 19:21:34 +0000789 auto DiagHandler = [&](const DiagnosticInfo &DI) {
790 linkerDiagnosticHandler(DI, TheModule.get(),
791 getCompilerInstance().getDiagnostics());
792 };
793
794 // If we are performing ThinLTO importing compilation (indicated by
795 // a non-empty index file option), then we need promote to global scope
796 // and rename any local values that are potentially exported to other
797 // modules. Do this early so that the rest of the compilation sees the
798 // promoted symbols.
799 std::unique_ptr<FunctionInfoIndex> Index;
800 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
801 ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
802 llvm::getFunctionIndexForFile(CI.getCodeGenOpts().ThinLTOIndexFile,
803 DiagHandler);
804 if (std::error_code EC = IndexOrErr.getError()) {
805 std::string Error = EC.message();
806 errs() << "Error loading index file '"
807 << CI.getCodeGenOpts().ThinLTOIndexFile << "': " << Error
808 << "\n";
809 return;
810 }
811 Index = std::move(IndexOrErr.get());
812 assert(Index);
813 // Currently this requires creating a new Module object.
814 std::unique_ptr<llvm::Module> RenamedModule =
815 renameModuleForThinLTO(TheModule, Index.get(), DiagHandler);
816 if (!RenamedModule)
817 return;
818
819 TheModule = std::move(RenamedModule);
820 }
821
Steven Wu15b385f2015-02-12 02:06:55 +0000822 LLVMContext &Ctx = TheModule->getContext();
823 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler);
Alp Tokere83b9062014-01-02 15:08:04 +0000824 EmitBackendOutput(CI.getDiagnostics(), CI.getCodeGenOpts(), TargetOpts,
Eric Christopher964a5f32015-08-05 23:48:05 +0000825 CI.getLangOpts(), CI.getTarget().getDataLayoutString(),
Teresa Johnsonaff22322015-12-07 19:21:34 +0000826 TheModule.get(), BA, OS, std::move(Index));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000827 return;
828 }
829
830 // Otherwise follow the normal AST path.
831 this->ASTFrontendAction::ExecuteAction();
832}
833
834//
835
David Blaikie68e081d2011-12-20 02:48:34 +0000836void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000837EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
838 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000839
David Blaikie68e081d2011-12-20 02:48:34 +0000840void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000841EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
842 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000843
David Blaikie68e081d2011-12-20 02:48:34 +0000844void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000845EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
846 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000847
David Blaikie68e081d2011-12-20 02:48:34 +0000848void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000849EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
850 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000851
David Blaikie68e081d2011-12-20 02:48:34 +0000852void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000853EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
854 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000855
David Blaikie68e081d2011-12-20 02:48:34 +0000856void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000857EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
858 : CodeGenAction(Backend_EmitObj, _VMContext) {}