blob: ba033d9413c19bccb2015315b4215e3251bbb5e9 [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
Justin Lebarb080b632017-01-25 21:29:48 +000010#include "clang/CodeGen/CodeGenAction.h"
11#include "CodeGenModule.h"
Alex Lorenzee024992014-08-04 18:41:51 +000012#include "CoverageMappingGen.h"
Amjad Aboud546bc112017-02-09 22:07:24 +000013#include "MacroPPCallbacks.h"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000014#include "clang/AST/ASTConsumer.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000015#include "clang/AST/ASTContext.h"
Hans Wennborga926d842014-05-23 20:37:38 +000016#include "clang/AST/DeclCXX.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000017#include "clang/AST/DeclGroup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Basic/FileManager.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/TargetInfo.h"
Daniel Dunbarc1b17292010-06-15 17:48:49 +000021#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000022#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000023#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbaracadc552009-12-03 09:12:54 +000024#include "clang/Frontend/FrontendDiagnostic.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000025#include "clang/Lex/Preprocessor.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000026#include "llvm/Bitcode/BitcodeReader.h"
Adam Nemet7b796f82017-01-26 04:07:11 +000027#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Diego Novillo829b1702014-04-16 16:54:24 +000028#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000029#include "llvm/IR/DiagnosticInfo.h"
30#include "llvm/IR/DiagnosticPrinter.h"
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +000031#include "llvm/IR/GlobalValue.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000034#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000035#include "llvm/Linker/Linker.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000036#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000037#include "llvm/Support/MemoryBuffer.h"
38#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000039#include "llvm/Support/Timer.h"
Hal Finkel8f96e822016-10-11 00:26:09 +000040#include "llvm/Support/ToolOutputFile.h"
41#include "llvm/Support/YAMLTraits.h"
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +000042#include "llvm/Transforms/IPO/Internalize.h"
43
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000044#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000045using namespace clang;
46using namespace llvm;
47
Nico Weber2992efa2011-01-25 20:34:14 +000048namespace clang {
Benjamin Kramer16634c22009-11-28 10:07:24 +000049 class BackendConsumer : public ASTConsumer {
Justin Lebarb080b632017-01-25 21:29:48 +000050 using LinkModule = CodeGenAction::LinkModule;
51
David Blaikie68e081d2011-12-20 02:48:34 +000052 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000053 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000054 BackendAction Action;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000055 const HeaderSearchOptions &HeaderSearchOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000056 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000057 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000058 const LangOptions &LangOpts;
Peter Collingbourne03f89072016-07-15 00:55:40 +000059 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000060 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000061
Chris Lattner263d64c2009-02-18 01:37:30 +000062 Timer LLVMIRGeneration;
Davide Italianob99fabd2016-07-21 06:28:48 +000063 unsigned LLVMIRGenerationRefCount;
Mike Stump11289f42009-09-09 15:08:12 +000064
Reid Kleckner15241ba2016-11-30 00:25:36 +000065 /// True if we've finished generating IR. This prevents us from generating
66 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
67 /// can happen when Clang plugins trigger additional AST deserialization.
68 bool IRGenFinished = false;
69
Ahmed Charlesb8984322014-03-07 20:03:18 +000070 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000071
Justin Lebarb080b632017-01-25 21:29:48 +000072 SmallVector<LinkModule, 4> LinkModules;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000073
Rafael Espindola8ce88a52015-12-14 23:17:07 +000074 // This is here so that the diagnostic printer knows the module a diagnostic
75 // refers to.
76 llvm::Module *CurLinkModule = nullptr;
77
Mike Stump11289f42009-09-09 15:08:12 +000078 public:
Justin Lebarb080b632017-01-25 21:29:48 +000079 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
80 const HeaderSearchOptions &HeaderSearchOpts,
81 const PreprocessorOptions &PPOpts,
82 const CodeGenOptions &CodeGenOpts,
83 const TargetOptions &TargetOpts,
84 const LangOptions &LangOpts, bool TimePasses,
85 const std::string &InFile,
86 SmallVector<LinkModule, 4> LinkModules,
87 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
88 CoverageSourceInfo *CoverageInfo = nullptr)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000089 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
90 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
Peter Collingbourne03f89072016-07-15 00:55:40 +000091 AsmOutStream(std::move(OS)), Context(nullptr),
Matthias Braunae032b62016-11-18 19:43:25 +000092 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
Davide Italianob99fabd2016-07-21 06:28:48 +000093 LLVMIRGenerationRefCount(0),
Adrian Prantle74f5252015-06-30 02:26:03 +000094 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
Justin Lebarb080b632017-01-25 21:29:48 +000095 CodeGenOpts, C, CoverageInfo)),
96 LinkModules(std::move(LinkModules)) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000097 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattnerdeffa132009-02-18 01:23:44 +000098 }
Serge Pavlov41c1f792016-02-18 16:42:09 +000099 llvm::Module *getModule() const { return Gen->GetModule(); }
100 std::unique_ptr<llvm::Module> takeModule() {
101 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
102 }
Daniel Dunbar400a6932010-02-25 04:37:50 +0000103
Amjad Aboud546bc112017-02-09 22:07:24 +0000104 CodeGenerator *getCodeGenerator() { return Gen.get(); }
105
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 Dunbar8e705052009-11-30 08:39:52 +0000120 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000121 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000122 }
Mike Stump11289f42009-09-09 15:08:12 +0000123
Craig Topper4f12f102014-03-12 06:41:41 +0000124 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000125 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +0000126 Context->getSourceManager(),
127 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +0000128
Davide Italianob99fabd2016-07-21 06:28:48 +0000129 // Recurse.
130 if (llvm::TimePassesIsEnabled) {
131 LLVMIRGenerationRefCount += 1;
132 if (LLVMIRGenerationRefCount == 1)
133 LLVMIRGeneration.startTimer();
134 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000135
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000136 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000137
Davide Italianob99fabd2016-07-21 06:28:48 +0000138 if (llvm::TimePassesIsEnabled) {
139 LLVMIRGenerationRefCount -= 1;
140 if (LLVMIRGenerationRefCount == 0)
141 LLVMIRGeneration.stopTimer();
142 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000143
144 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000145 }
Mike Stump11289f42009-09-09 15:08:12 +0000146
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000147 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000148 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
149 Context->getSourceManager(),
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000150 "LLVM IR generation of inline function");
Hans Wennborga926d842014-05-23 20:37:38 +0000151 if (llvm::TimePassesIsEnabled)
152 LLVMIRGeneration.startTimer();
153
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000154 Gen->HandleInlineFunctionDefinition(D);
Hans Wennborga926d842014-05-23 20:37:38 +0000155
156 if (llvm::TimePassesIsEnabled)
157 LLVMIRGeneration.stopTimer();
158 }
159
Reid Kleckner68c4bb52016-11-30 01:32:53 +0000160 void HandleInterestingDecl(DeclGroupRef D) override {
Reid Kleckner15241ba2016-11-30 00:25:36 +0000161 // Ignore interesting decls from the AST reader after IRGen is finished.
162 if (!IRGenFinished)
163 HandleTopLevelDecl(D);
164 }
165
Justin Lebarb080b632017-01-25 21:29:48 +0000166 // Links each entry in LinkModules into our module. Returns true on error.
167 bool LinkInModules() {
168 for (auto &LM : LinkModules) {
169 if (LM.PropagateAttrs)
170 for (Function &F : *LM.Module)
171 Gen->CGM().AddDefaultFnAttrs(F);
172
173 CurLinkModule = LM.Module.get();
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000174
175 bool Err;
176 if (LM.Internalize) {
177 Err = Linker::linkModules(
178 *getModule(), std::move(LM.Module), LM.LinkFlags,
179 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
Reid Kleckner987a2812017-03-13 22:33:07 +0000180 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000181 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
182 });
183 });
184 } else {
185 Err = Linker::linkModules(*getModule(), std::move(LM.Module),
186 LM.LinkFlags);
187 }
188
189 if (Err)
Justin Lebarb080b632017-01-25 21:29:48 +0000190 return true;
191 }
192 return false; // success
193 }
194
Craig Topper4f12f102014-03-12 06:41:41 +0000195 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000196 {
Chris Lattnere46de752009-03-06 06:46:31 +0000197 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Davide Italianob99fabd2016-07-21 06:28:48 +0000198 if (llvm::TimePassesIsEnabled) {
199 LLVMIRGenerationRefCount += 1;
200 if (LLVMIRGenerationRefCount == 1)
201 LLVMIRGeneration.startTimer();
202 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000203
Chris Lattnercf169832009-03-28 04:11:33 +0000204 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000205
Davide Italianob99fabd2016-07-21 06:28:48 +0000206 if (llvm::TimePassesIsEnabled) {
207 LLVMIRGenerationRefCount -= 1;
208 if (LLVMIRGenerationRefCount == 0)
209 LLVMIRGeneration.stopTimer();
210 }
Reid Kleckner15241ba2016-11-30 00:25:36 +0000211
212 IRGenFinished = true;
Chris Lattnereae6cb62009-03-05 08:00:35 +0000213 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000214
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000215 // Silently ignore if we weren't initialized for some reason.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000216 if (!getModule())
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000217 return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000219 // Install an inline asm handler so that diagnostics get printed through
220 // our diagnostics hooks.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000221 LLVMContext &Ctx = getModule()->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000222 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
223 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000224 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000225 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000226
Quentin Colombet728c5542014-02-06 18:30:43 +0000227 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
228 Ctx.getDiagnosticHandler();
229 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
230 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
Brian Gesiak9f59da82017-06-30 19:37:11 +0000231 Ctx.setDiagnosticsHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
Quentin Colombet728c5542014-02-06 18:30:43 +0000232
Hal Finkel8f96e822016-10-11 00:26:09 +0000233 std::unique_ptr<llvm::tool_output_file> OptRecordFile;
234 if (!CodeGenOpts.OptRecordFile.empty()) {
235 std::error_code EC;
236 OptRecordFile =
237 llvm::make_unique<llvm::tool_output_file>(CodeGenOpts.OptRecordFile,
238 EC, sys::fs::F_None);
239 if (EC) {
240 Diags.Report(diag::err_cannot_open_file) <<
241 CodeGenOpts.OptRecordFile << EC.message();
242 return;
243 }
244
Mehdi Amini6f408362016-11-19 18:19:41 +0000245 Ctx.setDiagnosticsOutputFile(
246 llvm::make_unique<yaml::Output>(OptRecordFile->os()));
Hal Finkel8f96e822016-10-11 00:26:09 +0000247
248 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
Brian Gesiak9f59da82017-06-30 19:37:11 +0000249 Ctx.setDiagnosticsHotnessRequested(true);
Hal Finkel8f96e822016-10-11 00:26:09 +0000250 }
251
Justin Lebarb080b632017-01-25 21:29:48 +0000252 // Link each LinkModule into our module.
253 if (LinkInModules())
254 return;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000255
Steven Wu27fb5222016-05-11 16:26:03 +0000256 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
257
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000258 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
259 LangOpts, C.getTargetInfo().getDataLayout(),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000260 getModule(), Action, std::move(AsmOutStream));
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000261
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000262 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000263
264 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Hal Finkel8f96e822016-10-11 00:26:09 +0000265
266 if (OptRecordFile)
267 OptRecordFile->keep();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000268 }
Mike Stump11289f42009-09-09 15:08:12 +0000269
Craig Topper4f12f102014-03-12 06:41:41 +0000270 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000271 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
272 Context->getSourceManager(),
273 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000274 Gen->HandleTagDeclDefinition(D);
275 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000276
Craig Topper4f12f102014-03-12 06:41:41 +0000277 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000278 Gen->HandleTagDeclRequiredDefinition(D);
279 }
280
Craig Topper4f12f102014-03-12 06:41:41 +0000281 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000282 Gen->CompleteTentativeDefinition(D);
283 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000284
David Majnemer929025d2016-01-26 19:30:26 +0000285 void AssignInheritanceModel(CXXRecordDecl *RD) override {
286 Gen->AssignInheritanceModel(RD);
287 }
288
Nico Weberb6a5d052015-01-15 04:07:35 +0000289 void HandleVTable(CXXRecordDecl *RD) override {
290 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000291 }
292
Chris Lattner5ec32e72010-04-06 18:38:50 +0000293 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
294 unsigned LocCookie) {
295 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
296 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
297 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000298
Quentin Colombet728c5542014-02-06 18:30:43 +0000299 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
300 void *Context) {
301 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
302 }
303
Oliver Stannard91817852016-02-02 13:52:52 +0000304 /// Get the best possible source location to represent a diagnostic that
305 /// may have associated debug info.
306 const FullSourceLoc
Justin Bognere91e9dd2017-02-17 17:34:49 +0000307 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
Oliver Stannard91817852016-02-02 13:52:52 +0000308 bool &BadDebugInfo, StringRef &Filename,
309 unsigned &Line, unsigned &Column) const;
310
Chris Lattner5ec32e72010-04-06 18:38:50 +0000311 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
312 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000313
314 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
315 /// \brief Specialized handler for InlineAsm diagnostic.
316 /// \return True if the diagnostic has been successfully reported, false
317 /// otherwise.
318 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
319 /// \brief Specialized handler for StackSize diagnostic.
320 /// \return True if the diagnostic has been successfully reported, false
321 /// otherwise.
322 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Oliver Stannard91817852016-02-02 13:52:52 +0000323 /// \brief Specialized handler for unsupported backend feature diagnostic.
324 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000325 /// \brief Specialized handlers for optimization remarks.
326 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000327 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000328 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
329 unsigned DiagID);
Adam Nemet7b796f82017-01-26 04:07:11 +0000330 void
331 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000332 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000333 const llvm::OptimizationRemarkAnalysisFPCommute &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000334 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000335 const llvm::OptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000336 void OptimizationFailureHandler(
337 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000338 };
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000339
David Blaikie68e081d2011-12-20 02:48:34 +0000340 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000341}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000342
Chris Lattner79f67a72010-04-08 00:23:06 +0000343/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
344/// buffer to be a valid FullSourceLoc.
345static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
346 SourceManager &CSM) {
347 // Get both the clang and llvm source managers. The location is relative to
348 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000349 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000350 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000351
Chris Lattner79f67a72010-04-08 00:23:06 +0000352 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
353 // already owns its one and clang::SourceManager wants to own its one.
354 const MemoryBuffer *LBuf =
355 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000356
Chris Lattner79f67a72010-04-08 00:23:06 +0000357 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000358 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000359 std::unique_ptr<llvm::MemoryBuffer> CBuf =
360 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
361 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000362 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000363 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000364
Chris Lattner79f67a72010-04-08 00:23:06 +0000365 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000366 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000367 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000368 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000369 return FullSourceLoc(NewLoc, CSM);
370}
371
Chris Lattner6d672132010-04-06 17:52:14 +0000372
Chris Lattner5ec32e72010-04-06 18:38:50 +0000373/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
374/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000375/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000376void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
377 SourceLocation LocCookie) {
378 // There are a couple of different kinds of errors we could get here. First,
379 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000380
381 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000382 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000383 if (Message.startswith("error: "))
384 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000385
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000386 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000387 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000388 if (D.getLoc() != SMLoc())
389 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000390
Joey Gouly5798b262014-06-05 21:23:42 +0000391 unsigned DiagID;
392 switch (D.getKind()) {
393 case llvm::SourceMgr::DK_Error:
394 DiagID = diag::err_fe_inline_asm;
395 break;
396 case llvm::SourceMgr::DK_Warning:
397 DiagID = diag::warn_fe_inline_asm;
398 break;
399 case llvm::SourceMgr::DK_Note:
400 DiagID = diag::note_fe_inline_asm;
401 break;
402 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000403 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000404 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000405 // code.
406 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000407 Diags.Report(LocCookie, DiagID).AddString(Message);
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000408
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000409 if (D.getLoc().isValid()) {
410 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
411 // Convert the SMDiagnostic ranges into SourceRange and attach them
412 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000413 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000414 unsigned Column = D.getColumnNo();
415 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
416 Loc.getLocWithOffset(Range.second - Column));
417 }
418 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000419 return;
420 }
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000421
Joey Gouly5798b262014-06-05 21:23:42 +0000422 // Otherwise, report the backend issue as occurring in the generated .s file.
423 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000424 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000425 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000426}
427
Quentin Colombet728c5542014-02-06 18:30:43 +0000428#define ComputeDiagID(Severity, GroupName, DiagID) \
429 do { \
430 switch (Severity) { \
431 case llvm::DS_Error: \
432 DiagID = diag::err_fe_##GroupName; \
433 break; \
434 case llvm::DS_Warning: \
435 DiagID = diag::warn_fe_##GroupName; \
436 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000437 case llvm::DS_Remark: \
438 llvm_unreachable("'remark' severity not expected"); \
439 break; \
440 case llvm::DS_Note: \
441 DiagID = diag::note_fe_##GroupName; \
442 break; \
443 } \
444 } while (false)
445
446#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
447 do { \
448 switch (Severity) { \
449 case llvm::DS_Error: \
450 DiagID = diag::err_fe_##GroupName; \
451 break; \
452 case llvm::DS_Warning: \
453 DiagID = diag::warn_fe_##GroupName; \
454 break; \
455 case llvm::DS_Remark: \
456 DiagID = diag::remark_fe_##GroupName; \
457 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000458 case llvm::DS_Note: \
459 DiagID = diag::note_fe_##GroupName; \
460 break; \
461 } \
462 } while (false)
463
464bool
465BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
466 unsigned DiagID;
467 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
468 std::string Message = D.getMsgStr().str();
469
470 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000471 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000472 // code.
473 SourceLocation LocCookie =
474 SourceLocation::getFromRawEncoding(D.getLocCookie());
475 if (LocCookie.isValid())
476 Diags.Report(LocCookie, DiagID).AddString(Message);
477 else {
478 // Otherwise, report the backend diagnostic as occurring in the generated
479 // .s file.
480 // If Loc is invalid, we still need to report the diagnostic, it just gets
481 // no location info.
482 FullSourceLoc Loc;
483 Diags.Report(Loc, DiagID).AddString(Message);
484 }
485 // We handled all the possible severities.
486 return true;
487}
488
489bool
490BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
491 if (D.getSeverity() != llvm::DS_Warning)
492 // For now, the only support we have for StackSize diagnostic is warning.
493 // We do not know how to format other severities.
494 return false;
495
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000496 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000497 // FIXME: Shouldn't need to truncate to uint32_t
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000498 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
499 diag::warn_fe_frame_larger_than)
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000500 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000501 return true;
502 }
503
504 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000505}
506
Oliver Stannard91817852016-02-02 13:52:52 +0000507const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
Justin Bognere91e9dd2017-02-17 17:34:49 +0000508 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
509 StringRef &Filename, unsigned &Line, unsigned &Column) const {
Diego Novillod23ec942014-05-29 19:55:06 +0000510 SourceManager &SourceMgr = Context->getSourceManager();
511 FileManager &FileMgr = SourceMgr.getFileManager();
Alp Toker27506272014-06-05 22:11:12 +0000512 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000513
514 if (D.isLocationAvailable()) {
515 D.getLocation(&Filename, &Line, &Column);
516 const FileEntry *FE = FileMgr.getFile(Filename);
517 if (FE && Line > 0) {
518 // If -gcolumn-info was not used, Column will be 0. This upsets the
519 // source manager, so pass 1 if Column is not set.
520 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
521 }
Oliver Stannard91817852016-02-02 13:52:52 +0000522 BadDebugInfo = DILoc.isInvalid();
Diego Novillo829b1702014-04-16 16:54:24 +0000523 }
Alp Toker27506272014-06-05 22:11:12 +0000524
525 // If a location isn't available, try to approximate it using the associated
526 // function definition. We use the definition's right brace to differentiate
527 // from diagnostics that genuinely relate to the function itself.
528 FullSourceLoc Loc(DILoc, SourceMgr);
529 if (Loc.isInvalid())
530 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Oliver Stannard91817852016-02-02 13:52:52 +0000531 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
Diego Novillod23ec942014-05-29 19:55:06 +0000532
Diego Novillo86f884e2015-05-08 20:59:56 +0000533 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000534 // If we were not able to translate the file:line:col information
535 // back to a SourceLocation, at least emit a note stating that
536 // we could not translate this location. This can happen in the
537 // case of #line directives.
Oliver Stannard91817852016-02-02 13:52:52 +0000538 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Ben Craig6e4695a2016-05-06 13:29:46 +0000539 << Filename << Line << Column;
Oliver Stannard91817852016-02-02 13:52:52 +0000540
541 return Loc;
542}
543
544void BackendConsumer::UnsupportedDiagHandler(
545 const llvm::DiagnosticInfoUnsupported &D) {
546 // We only support errors.
547 assert(D.getSeverity() == llvm::DS_Error);
548
549 StringRef Filename;
550 unsigned Line, Column;
Reid Klecknerf70ee602017-05-12 00:10:49 +0000551 bool BadDebugInfo = false;
552 FullSourceLoc Loc =
553 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
Oliver Stannard91817852016-02-02 13:52:52 +0000554
555 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
556
557 if (BadDebugInfo)
558 // If we were not able to translate the file:line:col information
559 // back to a SourceLocation, at least emit a note stating that
560 // we could not translate this location. This can happen in the
561 // case of #line directives.
562 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
563 << Filename << Line << Column;
564}
565
566void BackendConsumer::EmitOptimizationMessage(
567 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
568 // We only support warnings and remarks.
569 assert(D.getSeverity() == llvm::DS_Remark ||
570 D.getSeverity() == llvm::DS_Warning);
571
572 StringRef Filename;
573 unsigned Line, Column;
574 bool BadDebugInfo = false;
Reid Klecknerf70ee602017-05-12 00:10:49 +0000575 FullSourceLoc Loc =
576 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
Oliver Stannard91817852016-02-02 13:52:52 +0000577
Adam Nemet1eea3e52016-09-13 04:32:40 +0000578 std::string Msg;
579 raw_string_ostream MsgStream(Msg);
Adam Nemet699fc5b2016-09-27 20:55:12 +0000580 MsgStream << D.getMsg();
Adam Nemet1eea3e52016-09-13 04:32:40 +0000581
582 if (D.getHotness())
583 MsgStream << " (hotness: " << *D.getHotness() << ")";
584
Oliver Stannard91817852016-02-02 13:52:52 +0000585 Diags.Report(Loc, DiagID)
Mehdi Amini117296c2016-10-01 02:56:57 +0000586 << AddFlagValue(D.getPassName())
Adam Nemet1eea3e52016-09-13 04:32:40 +0000587 << MsgStream.str();
Oliver Stannard91817852016-02-02 13:52:52 +0000588
589 if (BadDebugInfo)
590 // If we were not able to translate the file:line:col information
591 // back to a SourceLocation, at least emit a note stating that
592 // we could not translate this location. This can happen in the
593 // case of #line directives.
594 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000595 << Filename << Line << Column;
596}
597
598void BackendConsumer::OptimizationRemarkHandler(
Adam Nemet7b796f82017-01-26 04:07:11 +0000599 const llvm::DiagnosticInfoOptimizationBase &D) {
600 if (D.isPassed()) {
601 // Optimization remarks are active only if the -Rpass flag has a regular
602 // expression that matches the name of the pass name in \p D.
603 if (CodeGenOpts.OptimizationRemarkPattern &&
604 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
605 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
606 } else if (D.isMissed()) {
607 // Missed optimization remarks are active only if the -Rpass-missed
608 // flag has a regular expression that matches the name of the pass
609 // name in \p D.
610 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
611 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
612 EmitOptimizationMessage(
613 D, diag::remark_fe_backend_optimization_remark_missed);
614 } else {
615 assert(D.isAnalysis() && "Unknown remark type");
Diego Novillod23ec942014-05-29 19:55:06 +0000616
Adam Nemet7b796f82017-01-26 04:07:11 +0000617 bool ShouldAlwaysPrint = false;
618 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
619 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
Diego Novillod23ec942014-05-29 19:55:06 +0000620
Adam Nemet7b796f82017-01-26 04:07:11 +0000621 if (ShouldAlwaysPrint ||
622 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
623 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
624 EmitOptimizationMessage(
625 D, diag::remark_fe_backend_optimization_remark_analysis);
626 }
Diego Novillo829b1702014-04-16 16:54:24 +0000627}
628
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000629void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000630 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000631 // Optimization analysis remarks are active if the pass name is set to
632 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
633 // regular expression that matches the name of the pass name in \p D.
634
Adam Nemetb5beb972016-06-29 04:55:31 +0000635 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000636 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
637 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000638 EmitOptimizationMessage(
639 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
640}
641
Tyler Nowicki034baf62015-08-10 23:05:16 +0000642void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000643 const llvm::OptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000644 // Optimization analysis remarks are active if the pass name is set to
645 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
646 // regular expression that matches the name of the pass name in \p D.
647
Adam Nemetb5beb972016-06-29 04:55:31 +0000648 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000649 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
650 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000651 EmitOptimizationMessage(
652 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
653}
654
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000655void BackendConsumer::OptimizationFailureHandler(
656 const llvm::DiagnosticInfoOptimizationFailure &D) {
657 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
658}
659
Quentin Colombet728c5542014-02-06 18:30:43 +0000660/// \brief This function is invoked when the backend needs
661/// to report something to the user.
662void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
663 unsigned DiagID = diag::err_fe_inline_asm;
664 llvm::DiagnosticSeverity Severity = DI.getSeverity();
665 // Get the diagnostic ID based.
666 switch (DI.getKind()) {
667 case llvm::DK_InlineAsm:
668 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
669 return;
670 ComputeDiagID(Severity, inline_asm, DiagID);
671 break;
672 case llvm::DK_StackSize:
673 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
674 return;
675 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
676 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000677 case DK_Linker:
678 assert(CurLinkModule);
679 // FIXME: stop eating the warnings and notes.
680 if (Severity != DS_Error)
681 return;
682 DiagID = diag::err_fe_cannot_link_module;
683 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000684 case llvm::DK_OptimizationRemark:
685 // Optimization remarks are always handled completely by this
686 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000687 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
Diego Novillo829b1702014-04-16 16:54:24 +0000688 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000689 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000690 // Optimization remarks are always handled completely by this
691 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000692 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
Diego Novillod23ec942014-05-29 19:55:06 +0000693 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000694 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000695 // Optimization remarks are always handled completely by this
696 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000697 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000698 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000699 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
700 // Optimization remarks are always handled completely by this
701 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000702 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000703 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000704 case llvm::DK_OptimizationRemarkAnalysisAliasing:
705 // Optimization remarks are always handled completely by this
706 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000707 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
Tyler Nowicki034baf62015-08-10 23:05:16 +0000708 return;
Adam Nemet7b796f82017-01-26 04:07:11 +0000709 case llvm::DK_MachineOptimizationRemark:
710 // Optimization remarks are always handled completely by this
711 // handler. There is no generic way of emitting them.
712 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
713 return;
714 case llvm::DK_MachineOptimizationRemarkMissed:
715 // Optimization remarks are always handled completely by this
716 // handler. There is no generic way of emitting them.
717 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
718 return;
719 case llvm::DK_MachineOptimizationRemarkAnalysis:
720 // Optimization remarks are always handled completely by this
721 // handler. There is no generic way of emitting them.
722 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
723 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000724 case llvm::DK_OptimizationFailure:
725 // Optimization failures are always handled completely by this
726 // handler.
727 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
728 return;
Oliver Stannard91817852016-02-02 13:52:52 +0000729 case llvm::DK_Unsupported:
730 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
731 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000732 default:
733 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000734 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000735 break;
736 }
737 std::string MsgStorage;
738 {
739 raw_string_ostream Stream(MsgStorage);
740 DiagnosticPrinterRawOStream DP(Stream);
741 DI.print(DP);
742 }
743
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000744 if (DiagID == diag::err_fe_cannot_link_module) {
745 Diags.Report(diag::err_fe_cannot_link_module)
746 << CurLinkModule->getModuleIdentifier() << MsgStorage;
747 return;
748 }
749
Quentin Colombet728c5542014-02-06 18:30:43 +0000750 // Report the backend message using the usual diagnostic mechanism.
751 FullSourceLoc Loc;
752 Diags.Report(Loc, DiagID).AddString(MsgStorage);
753}
754#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000755
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000756CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000757 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
Eric Christopher02e3dd42016-03-12 01:47:11 +0000758 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000759
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000760CodeGenAction::~CodeGenAction() {
761 TheModule.reset();
762 if (OwnsVMContext)
763 delete VMContext;
764}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000765
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000766bool CodeGenAction::hasIRSupport() const { return true; }
767
Daniel Dunbar400a6932010-02-25 04:37:50 +0000768void CodeGenAction::EndSourceFileAction() {
769 // If the consumer creation failed, do nothing.
770 if (!getCompilerInstance().hasASTConsumer())
771 return;
772
773 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000774 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000775}
776
Rafael Espindolae8337302014-08-19 14:36:35 +0000777std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
778 return std::move(TheModule);
779}
780
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000781llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
782 OwnsVMContext = false;
783 return VMContext;
784}
785
Peter Collingbourne03f89072016-07-15 00:55:40 +0000786static std::unique_ptr<raw_pwrite_stream>
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000787GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000788 switch (Action) {
789 case Backend_EmitAssembly:
790 return CI.createDefaultOutputFile(false, InFile, "s");
791 case Backend_EmitLL:
792 return CI.createDefaultOutputFile(false, InFile, "ll");
793 case Backend_EmitBC:
794 return CI.createDefaultOutputFile(true, InFile, "bc");
795 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000796 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000797 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000798 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000799 case Backend_EmitObj:
800 return CI.createDefaultOutputFile(true, InFile, "o");
801 }
802
David Blaikie83d382b2011-09-23 05:06:16 +0000803 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000804}
805
David Blaikie6beb6aa2014-08-10 19:56:51 +0000806std::unique_ptr<ASTConsumer>
807CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000808 BackendAction BA = static_cast<BackendAction>(Act);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000809 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000810 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000811 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000812
Artem Belevich5d40ae32015-10-27 17:56:59 +0000813 // Load bitcode modules to link with, if we need to.
814 if (LinkModules.empty())
Justin Lebarb080b632017-01-25 21:29:48 +0000815 for (const CodeGenOptions::BitcodeFileToLink &F :
816 CI.getCodeGenOpts().LinkBitcodeFiles) {
817 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
Artem Belevich5d40ae32015-10-27 17:56:59 +0000818 if (!BCBuf) {
819 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Justin Lebarb080b632017-01-25 21:29:48 +0000820 << F.Filename << BCBuf.getError().message();
Artem Belevich5d40ae32015-10-27 17:56:59 +0000821 LinkModules.clear();
822 return nullptr;
823 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000824
Peter Collingbourned9445c42016-11-13 07:00:17 +0000825 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000826 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000827 if (!ModuleOrErr) {
828 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
829 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Justin Lebarb080b632017-01-25 21:29:48 +0000830 << F.Filename << EIB.message();
Peter Collingbourned9445c42016-11-13 07:00:17 +0000831 });
Artem Belevich5d40ae32015-10-27 17:56:59 +0000832 LinkModules.clear();
833 return nullptr;
834 }
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000835 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
836 F.Internalize, F.LinkFlags});
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000837 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000838
Alex Lorenzee024992014-08-04 18:41:51 +0000839 CoverageSourceInfo *CoverageInfo = nullptr;
840 // Add the preprocessor callback only when the coverage mapping is generated.
841 if (CI.getCodeGenOpts().CoverageMapping) {
842 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000843 CI.getPreprocessor().addPPCallbacks(
844 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000845 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000846
David Blaikie037e75b2014-08-10 21:06:17 +0000847 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000848 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
849 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Justin Lebarb080b632017-01-25 21:29:48 +0000850 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
851 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000852 BEConsumer = Result.get();
Amjad Aboud546bc112017-02-09 22:07:24 +0000853
854 // Enable generating macro debug info only when debug info is not disabled and
855 // also macro debug info is enabled.
856 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
857 CI.getCodeGenOpts().MacroDebugInfo) {
858 std::unique_ptr<PPCallbacks> Callbacks =
859 llvm::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
860 CI.getPreprocessor());
861 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
862 }
863
David Blaikie6beb6aa2014-08-10 19:56:51 +0000864 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000865}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000866
Tim Northover1390b442016-04-06 19:58:07 +0000867static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
868 void *Context,
869 unsigned LocCookie) {
870 SM.print(nullptr, llvm::errs());
871
872 auto Diags = static_cast<DiagnosticsEngine *>(Context);
873 unsigned DiagID;
874 switch (SM.getKind()) {
875 case llvm::SourceMgr::DK_Error:
876 DiagID = diag::err_fe_inline_asm;
877 break;
878 case llvm::SourceMgr::DK_Warning:
879 DiagID = diag::warn_fe_inline_asm;
880 break;
881 case llvm::SourceMgr::DK_Note:
882 DiagID = diag::note_fe_inline_asm;
883 break;
884 }
885
886 Diags->Report(DiagID).AddString("cannot compile inline asm");
887}
888
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000889std::unique_ptr<llvm::Module> CodeGenAction::loadModule(MemoryBufferRef MBRef) {
890 CompilerInstance &CI = getCompilerInstance();
891 SourceManager &SM = CI.getSourceManager();
892
893 // For ThinLTO backend invocations, ensure that the context
Peter Collingbournef5d17122017-01-26 21:09:48 +0000894 // merges types based on ODR identifiers. We also need to read
895 // the correct module out of a multi-module bitcode file.
896 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000897 VMContext->enableDebugTypeODRUniquing();
898
Peter Collingbournef5d17122017-01-26 21:09:48 +0000899 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
900 unsigned DiagID =
901 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
902 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
903 CI.getDiagnostics().Report(DiagID) << EIB.message();
904 });
905 return {};
906 };
907
908 Expected<llvm::BitcodeModule> BMOrErr = FindThinLTOModule(MBRef);
909 if (!BMOrErr)
910 return DiagErrors(BMOrErr.takeError());
911
912 Expected<std::unique_ptr<llvm::Module>> MOrErr =
913 BMOrErr->parseModule(*VMContext);
914 if (!MOrErr)
915 return DiagErrors(MOrErr.takeError());
916 return std::move(*MOrErr);
917 }
918
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000919 llvm::SMDiagnostic Err;
920 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
921 return M;
922
923 // Translate from the diagnostic info to the SourceManager location if
924 // available.
925 // TODO: Unify this with ConvertBackendLocation()
926 SourceLocation Loc;
927 if (Err.getLineNo() > 0) {
928 assert(Err.getColumnNo() >= 0);
929 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
930 Err.getLineNo(), Err.getColumnNo() + 1);
931 }
932
933 // Strip off a leading diagnostic code if there is one.
934 StringRef Msg = Err.getMessage();
935 if (Msg.startswith("error: "))
936 Msg = Msg.substr(7);
937
938 unsigned DiagID =
939 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
940
941 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
942 return {};
943}
944
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000945void CodeGenAction::ExecuteAction() {
946 // If this is an IR file, we have to treat it specially.
Richard Smith40c0efa2017-04-26 18:57:40 +0000947 if (getCurrentFileKind().getLanguage() == InputKind::LLVM_IR) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000948 BackendAction BA = static_cast<BackendAction>(Act);
949 CompilerInstance &CI = getCompilerInstance();
Peter Collingbourne03f89072016-07-15 00:55:40 +0000950 std::unique_ptr<raw_pwrite_stream> OS =
951 GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000952 if (BA != Backend_EmitNothing && !OS)
953 return;
954
955 bool Invalid;
956 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000957 FileID FID = SM.getMainFileID();
958 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000959 if (Invalid)
960 return;
961
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000962 TheModule = loadModule(*MainFile);
963 if (!TheModule)
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000964 return;
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000965
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000966 const TargetOptions &TargetOpts = CI.getTargetOpts();
967 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000968 CI.getDiagnostics().Report(SourceLocation(),
969 diag::warn_fe_override_module)
970 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000971 TheModule->setTargetTriple(TargetOpts.Triple);
972 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000973
Steven Wu27fb5222016-05-11 16:26:03 +0000974 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
975 MainFile->getMemBufferRef());
976
Tim Northover1390b442016-04-06 19:58:07 +0000977 LLVMContext &Ctx = TheModule->getContext();
978 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
979 &CI.getDiagnostics());
Steven Wu27fb5222016-05-11 16:26:03 +0000980
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000981 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
982 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
983 CI.getTarget().getDataLayout(), TheModule.get(), BA,
984 std::move(OS));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000985 return;
986 }
987
988 // Otherwise follow the normal AST path.
989 this->ASTFrontendAction::ExecuteAction();
990}
991
992//
993
David Blaikie68e081d2011-12-20 02:48:34 +0000994void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000995EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
996 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000997
David Blaikie68e081d2011-12-20 02:48:34 +0000998void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000999EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1000 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001001
David Blaikie68e081d2011-12-20 02:48:34 +00001002void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001003EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1004 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001005
David Blaikie68e081d2011-12-20 02:48:34 +00001006void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001007EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1008 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001009
David Blaikie68e081d2011-12-20 02:48:34 +00001010void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001011EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1012 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +00001013
David Blaikie68e081d2011-12-20 02:48:34 +00001014void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001015EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1016 : CodeGenAction(Backend_EmitObj, _VMContext) {}