blob: 4f03de55149b89346b8f226877bbdbc97d1cebf7 [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);
Brian Gesiak562eab92017-07-01 05:45:26 +0000232 if (CodeGenOpts.DiagnosticsHotnessThreshold != 0)
233 Ctx.setDiagnosticsHotnessThreshold(
234 CodeGenOpts.DiagnosticsHotnessThreshold);
Quentin Colombet728c5542014-02-06 18:30:43 +0000235
Hal Finkel8f96e822016-10-11 00:26:09 +0000236 std::unique_ptr<llvm::tool_output_file> OptRecordFile;
237 if (!CodeGenOpts.OptRecordFile.empty()) {
238 std::error_code EC;
239 OptRecordFile =
240 llvm::make_unique<llvm::tool_output_file>(CodeGenOpts.OptRecordFile,
241 EC, sys::fs::F_None);
242 if (EC) {
243 Diags.Report(diag::err_cannot_open_file) <<
244 CodeGenOpts.OptRecordFile << EC.message();
245 return;
246 }
247
Mehdi Amini6f408362016-11-19 18:19:41 +0000248 Ctx.setDiagnosticsOutputFile(
249 llvm::make_unique<yaml::Output>(OptRecordFile->os()));
Hal Finkel8f96e822016-10-11 00:26:09 +0000250
251 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
Brian Gesiak9f59da82017-06-30 19:37:11 +0000252 Ctx.setDiagnosticsHotnessRequested(true);
Hal Finkel8f96e822016-10-11 00:26:09 +0000253 }
254
Justin Lebarb080b632017-01-25 21:29:48 +0000255 // Link each LinkModule into our module.
256 if (LinkInModules())
257 return;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000258
Steven Wu27fb5222016-05-11 16:26:03 +0000259 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
260
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000261 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
262 LangOpts, C.getTargetInfo().getDataLayout(),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000263 getModule(), Action, std::move(AsmOutStream));
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000264
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000265 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000266
267 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Hal Finkel8f96e822016-10-11 00:26:09 +0000268
269 if (OptRecordFile)
270 OptRecordFile->keep();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000271 }
Mike Stump11289f42009-09-09 15:08:12 +0000272
Craig Topper4f12f102014-03-12 06:41:41 +0000273 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000274 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
275 Context->getSourceManager(),
276 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000277 Gen->HandleTagDeclDefinition(D);
278 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000279
Craig Topper4f12f102014-03-12 06:41:41 +0000280 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000281 Gen->HandleTagDeclRequiredDefinition(D);
282 }
283
Craig Topper4f12f102014-03-12 06:41:41 +0000284 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000285 Gen->CompleteTentativeDefinition(D);
286 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000287
David Majnemer929025d2016-01-26 19:30:26 +0000288 void AssignInheritanceModel(CXXRecordDecl *RD) override {
289 Gen->AssignInheritanceModel(RD);
290 }
291
Nico Weberb6a5d052015-01-15 04:07:35 +0000292 void HandleVTable(CXXRecordDecl *RD) override {
293 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000294 }
295
Chris Lattner5ec32e72010-04-06 18:38:50 +0000296 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
297 unsigned LocCookie) {
298 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
299 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
300 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000301
Quentin Colombet728c5542014-02-06 18:30:43 +0000302 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
303 void *Context) {
304 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
305 }
306
Oliver Stannard91817852016-02-02 13:52:52 +0000307 /// Get the best possible source location to represent a diagnostic that
308 /// may have associated debug info.
309 const FullSourceLoc
Justin Bognere91e9dd2017-02-17 17:34:49 +0000310 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
Oliver Stannard91817852016-02-02 13:52:52 +0000311 bool &BadDebugInfo, StringRef &Filename,
312 unsigned &Line, unsigned &Column) const;
313
Chris Lattner5ec32e72010-04-06 18:38:50 +0000314 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
315 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000316
317 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
318 /// \brief Specialized handler for InlineAsm diagnostic.
319 /// \return True if the diagnostic has been successfully reported, false
320 /// otherwise.
321 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
322 /// \brief Specialized handler for StackSize diagnostic.
323 /// \return True if the diagnostic has been successfully reported, false
324 /// otherwise.
325 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Oliver Stannard91817852016-02-02 13:52:52 +0000326 /// \brief Specialized handler for unsupported backend feature diagnostic.
327 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000328 /// \brief Specialized handlers for optimization remarks.
329 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000330 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000331 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
332 unsigned DiagID);
Adam Nemet7b796f82017-01-26 04:07:11 +0000333 void
334 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000335 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000336 const llvm::OptimizationRemarkAnalysisFPCommute &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000337 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000338 const llvm::OptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000339 void OptimizationFailureHandler(
340 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000341 };
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000342
David Blaikie68e081d2011-12-20 02:48:34 +0000343 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000344}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000345
Chris Lattner79f67a72010-04-08 00:23:06 +0000346/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
347/// buffer to be a valid FullSourceLoc.
348static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
349 SourceManager &CSM) {
350 // Get both the clang and llvm source managers. The location is relative to
351 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000352 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000353 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000354
Chris Lattner79f67a72010-04-08 00:23:06 +0000355 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
356 // already owns its one and clang::SourceManager wants to own its one.
357 const MemoryBuffer *LBuf =
358 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000359
Chris Lattner79f67a72010-04-08 00:23:06 +0000360 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000361 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000362 std::unique_ptr<llvm::MemoryBuffer> CBuf =
363 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
364 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000365 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000366 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000367
Chris Lattner79f67a72010-04-08 00:23:06 +0000368 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000369 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000370 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000371 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000372 return FullSourceLoc(NewLoc, CSM);
373}
374
Chris Lattner6d672132010-04-06 17:52:14 +0000375
Chris Lattner5ec32e72010-04-06 18:38:50 +0000376/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
377/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000378/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000379void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
380 SourceLocation LocCookie) {
381 // There are a couple of different kinds of errors we could get here. First,
382 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000383
384 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000385 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000386 if (Message.startswith("error: "))
387 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000388
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000389 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000390 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000391 if (D.getLoc() != SMLoc())
392 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000393
Joey Gouly5798b262014-06-05 21:23:42 +0000394 unsigned DiagID;
395 switch (D.getKind()) {
396 case llvm::SourceMgr::DK_Error:
397 DiagID = diag::err_fe_inline_asm;
398 break;
399 case llvm::SourceMgr::DK_Warning:
400 DiagID = diag::warn_fe_inline_asm;
401 break;
402 case llvm::SourceMgr::DK_Note:
403 DiagID = diag::note_fe_inline_asm;
404 break;
405 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000406 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000407 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000408 // code.
409 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000410 Diags.Report(LocCookie, DiagID).AddString(Message);
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000411
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000412 if (D.getLoc().isValid()) {
413 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
414 // Convert the SMDiagnostic ranges into SourceRange and attach them
415 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000416 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000417 unsigned Column = D.getColumnNo();
418 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
419 Loc.getLocWithOffset(Range.second - Column));
420 }
421 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000422 return;
423 }
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000424
Joey Gouly5798b262014-06-05 21:23:42 +0000425 // Otherwise, report the backend issue as occurring in the generated .s file.
426 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000427 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000428 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000429}
430
Quentin Colombet728c5542014-02-06 18:30:43 +0000431#define ComputeDiagID(Severity, GroupName, DiagID) \
432 do { \
433 switch (Severity) { \
434 case llvm::DS_Error: \
435 DiagID = diag::err_fe_##GroupName; \
436 break; \
437 case llvm::DS_Warning: \
438 DiagID = diag::warn_fe_##GroupName; \
439 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000440 case llvm::DS_Remark: \
441 llvm_unreachable("'remark' severity not expected"); \
442 break; \
443 case llvm::DS_Note: \
444 DiagID = diag::note_fe_##GroupName; \
445 break; \
446 } \
447 } while (false)
448
449#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
450 do { \
451 switch (Severity) { \
452 case llvm::DS_Error: \
453 DiagID = diag::err_fe_##GroupName; \
454 break; \
455 case llvm::DS_Warning: \
456 DiagID = diag::warn_fe_##GroupName; \
457 break; \
458 case llvm::DS_Remark: \
459 DiagID = diag::remark_fe_##GroupName; \
460 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000461 case llvm::DS_Note: \
462 DiagID = diag::note_fe_##GroupName; \
463 break; \
464 } \
465 } while (false)
466
467bool
468BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
469 unsigned DiagID;
470 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
471 std::string Message = D.getMsgStr().str();
472
473 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000474 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000475 // code.
476 SourceLocation LocCookie =
477 SourceLocation::getFromRawEncoding(D.getLocCookie());
478 if (LocCookie.isValid())
479 Diags.Report(LocCookie, DiagID).AddString(Message);
480 else {
481 // Otherwise, report the backend diagnostic as occurring in the generated
482 // .s file.
483 // If Loc is invalid, we still need to report the diagnostic, it just gets
484 // no location info.
485 FullSourceLoc Loc;
486 Diags.Report(Loc, DiagID).AddString(Message);
487 }
488 // We handled all the possible severities.
489 return true;
490}
491
492bool
493BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
494 if (D.getSeverity() != llvm::DS_Warning)
495 // For now, the only support we have for StackSize diagnostic is warning.
496 // We do not know how to format other severities.
497 return false;
498
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000499 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000500 // FIXME: Shouldn't need to truncate to uint32_t
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000501 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
502 diag::warn_fe_frame_larger_than)
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000503 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000504 return true;
505 }
506
507 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000508}
509
Oliver Stannard91817852016-02-02 13:52:52 +0000510const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
Justin Bognere91e9dd2017-02-17 17:34:49 +0000511 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
512 StringRef &Filename, unsigned &Line, unsigned &Column) const {
Diego Novillod23ec942014-05-29 19:55:06 +0000513 SourceManager &SourceMgr = Context->getSourceManager();
514 FileManager &FileMgr = SourceMgr.getFileManager();
Alp Toker27506272014-06-05 22:11:12 +0000515 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000516
517 if (D.isLocationAvailable()) {
518 D.getLocation(&Filename, &Line, &Column);
519 const FileEntry *FE = FileMgr.getFile(Filename);
520 if (FE && Line > 0) {
521 // If -gcolumn-info was not used, Column will be 0. This upsets the
522 // source manager, so pass 1 if Column is not set.
523 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
524 }
Oliver Stannard91817852016-02-02 13:52:52 +0000525 BadDebugInfo = DILoc.isInvalid();
Diego Novillo829b1702014-04-16 16:54:24 +0000526 }
Alp Toker27506272014-06-05 22:11:12 +0000527
528 // If a location isn't available, try to approximate it using the associated
529 // function definition. We use the definition's right brace to differentiate
530 // from diagnostics that genuinely relate to the function itself.
531 FullSourceLoc Loc(DILoc, SourceMgr);
532 if (Loc.isInvalid())
533 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Oliver Stannard91817852016-02-02 13:52:52 +0000534 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
Diego Novillod23ec942014-05-29 19:55:06 +0000535
Diego Novillo86f884e2015-05-08 20:59:56 +0000536 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000537 // If we were not able to translate the file:line:col information
538 // back to a SourceLocation, at least emit a note stating that
539 // we could not translate this location. This can happen in the
540 // case of #line directives.
Oliver Stannard91817852016-02-02 13:52:52 +0000541 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Ben Craig6e4695a2016-05-06 13:29:46 +0000542 << Filename << Line << Column;
Oliver Stannard91817852016-02-02 13:52:52 +0000543
544 return Loc;
545}
546
547void BackendConsumer::UnsupportedDiagHandler(
548 const llvm::DiagnosticInfoUnsupported &D) {
549 // We only support errors.
550 assert(D.getSeverity() == llvm::DS_Error);
551
552 StringRef Filename;
553 unsigned Line, Column;
Reid Klecknerf70ee602017-05-12 00:10:49 +0000554 bool BadDebugInfo = false;
555 FullSourceLoc Loc =
556 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
Oliver Stannard91817852016-02-02 13:52:52 +0000557
558 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
559
560 if (BadDebugInfo)
561 // If we were not able to translate the file:line:col information
562 // back to a SourceLocation, at least emit a note stating that
563 // we could not translate this location. This can happen in the
564 // case of #line directives.
565 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
566 << Filename << Line << Column;
567}
568
569void BackendConsumer::EmitOptimizationMessage(
570 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
571 // We only support warnings and remarks.
572 assert(D.getSeverity() == llvm::DS_Remark ||
573 D.getSeverity() == llvm::DS_Warning);
574
575 StringRef Filename;
576 unsigned Line, Column;
577 bool BadDebugInfo = false;
Reid Klecknerf70ee602017-05-12 00:10:49 +0000578 FullSourceLoc Loc =
579 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
Oliver Stannard91817852016-02-02 13:52:52 +0000580
Adam Nemet1eea3e52016-09-13 04:32:40 +0000581 std::string Msg;
582 raw_string_ostream MsgStream(Msg);
Adam Nemet699fc5b2016-09-27 20:55:12 +0000583 MsgStream << D.getMsg();
Adam Nemet1eea3e52016-09-13 04:32:40 +0000584
585 if (D.getHotness())
586 MsgStream << " (hotness: " << *D.getHotness() << ")";
587
Oliver Stannard91817852016-02-02 13:52:52 +0000588 Diags.Report(Loc, DiagID)
Mehdi Amini117296c2016-10-01 02:56:57 +0000589 << AddFlagValue(D.getPassName())
Adam Nemet1eea3e52016-09-13 04:32:40 +0000590 << MsgStream.str();
Oliver Stannard91817852016-02-02 13:52:52 +0000591
592 if (BadDebugInfo)
593 // If we were not able to translate the file:line:col information
594 // back to a SourceLocation, at least emit a note stating that
595 // we could not translate this location. This can happen in the
596 // case of #line directives.
597 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000598 << Filename << Line << Column;
599}
600
601void BackendConsumer::OptimizationRemarkHandler(
Adam Nemet7b796f82017-01-26 04:07:11 +0000602 const llvm::DiagnosticInfoOptimizationBase &D) {
603 if (D.isPassed()) {
604 // Optimization remarks are active only if the -Rpass flag has a regular
605 // expression that matches the name of the pass name in \p D.
606 if (CodeGenOpts.OptimizationRemarkPattern &&
607 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
608 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
609 } else if (D.isMissed()) {
610 // Missed optimization remarks are active only if the -Rpass-missed
611 // flag has a regular expression that matches the name of the pass
612 // name in \p D.
613 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
614 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
615 EmitOptimizationMessage(
616 D, diag::remark_fe_backend_optimization_remark_missed);
617 } else {
618 assert(D.isAnalysis() && "Unknown remark type");
Diego Novillod23ec942014-05-29 19:55:06 +0000619
Adam Nemet7b796f82017-01-26 04:07:11 +0000620 bool ShouldAlwaysPrint = false;
621 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
622 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
Diego Novillod23ec942014-05-29 19:55:06 +0000623
Adam Nemet7b796f82017-01-26 04:07:11 +0000624 if (ShouldAlwaysPrint ||
625 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
626 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
627 EmitOptimizationMessage(
628 D, diag::remark_fe_backend_optimization_remark_analysis);
629 }
Diego Novillo829b1702014-04-16 16:54:24 +0000630}
631
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000632void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000633 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000634 // Optimization analysis remarks are active if the pass name is set to
635 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
636 // regular expression that matches the name of the pass name in \p D.
637
Adam Nemetb5beb972016-06-29 04:55:31 +0000638 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000639 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
640 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000641 EmitOptimizationMessage(
642 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
643}
644
Tyler Nowicki034baf62015-08-10 23:05:16 +0000645void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000646 const llvm::OptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000647 // Optimization analysis remarks are active if the pass name is set to
648 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
649 // regular expression that matches the name of the pass name in \p D.
650
Adam Nemetb5beb972016-06-29 04:55:31 +0000651 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000652 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
653 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000654 EmitOptimizationMessage(
655 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
656}
657
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000658void BackendConsumer::OptimizationFailureHandler(
659 const llvm::DiagnosticInfoOptimizationFailure &D) {
660 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
661}
662
Quentin Colombet728c5542014-02-06 18:30:43 +0000663/// \brief This function is invoked when the backend needs
664/// to report something to the user.
665void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
666 unsigned DiagID = diag::err_fe_inline_asm;
667 llvm::DiagnosticSeverity Severity = DI.getSeverity();
668 // Get the diagnostic ID based.
669 switch (DI.getKind()) {
670 case llvm::DK_InlineAsm:
671 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
672 return;
673 ComputeDiagID(Severity, inline_asm, DiagID);
674 break;
675 case llvm::DK_StackSize:
676 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
677 return;
678 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
679 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000680 case DK_Linker:
681 assert(CurLinkModule);
682 // FIXME: stop eating the warnings and notes.
683 if (Severity != DS_Error)
684 return;
685 DiagID = diag::err_fe_cannot_link_module;
686 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000687 case llvm::DK_OptimizationRemark:
688 // Optimization remarks are always handled completely by this
689 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000690 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
Diego Novillo829b1702014-04-16 16:54:24 +0000691 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000692 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000693 // Optimization remarks are always handled completely by this
694 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000695 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
Diego Novillod23ec942014-05-29 19:55:06 +0000696 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000697 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000698 // Optimization remarks are always handled completely by this
699 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000700 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000701 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000702 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
703 // Optimization remarks are always handled completely by this
704 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000705 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000706 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000707 case llvm::DK_OptimizationRemarkAnalysisAliasing:
708 // Optimization remarks are always handled completely by this
709 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000710 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
Tyler Nowicki034baf62015-08-10 23:05:16 +0000711 return;
Adam Nemet7b796f82017-01-26 04:07:11 +0000712 case llvm::DK_MachineOptimizationRemark:
713 // Optimization remarks are always handled completely by this
714 // handler. There is no generic way of emitting them.
715 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
716 return;
717 case llvm::DK_MachineOptimizationRemarkMissed:
718 // Optimization remarks are always handled completely by this
719 // handler. There is no generic way of emitting them.
720 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
721 return;
722 case llvm::DK_MachineOptimizationRemarkAnalysis:
723 // Optimization remarks are always handled completely by this
724 // handler. There is no generic way of emitting them.
725 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
726 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000727 case llvm::DK_OptimizationFailure:
728 // Optimization failures are always handled completely by this
729 // handler.
730 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
731 return;
Oliver Stannard91817852016-02-02 13:52:52 +0000732 case llvm::DK_Unsupported:
733 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
734 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000735 default:
736 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000737 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000738 break;
739 }
740 std::string MsgStorage;
741 {
742 raw_string_ostream Stream(MsgStorage);
743 DiagnosticPrinterRawOStream DP(Stream);
744 DI.print(DP);
745 }
746
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000747 if (DiagID == diag::err_fe_cannot_link_module) {
748 Diags.Report(diag::err_fe_cannot_link_module)
749 << CurLinkModule->getModuleIdentifier() << MsgStorage;
750 return;
751 }
752
Quentin Colombet728c5542014-02-06 18:30:43 +0000753 // Report the backend message using the usual diagnostic mechanism.
754 FullSourceLoc Loc;
755 Diags.Report(Loc, DiagID).AddString(MsgStorage);
756}
757#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000758
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000759CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000760 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
Eric Christopher02e3dd42016-03-12 01:47:11 +0000761 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000762
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000763CodeGenAction::~CodeGenAction() {
764 TheModule.reset();
765 if (OwnsVMContext)
766 delete VMContext;
767}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000768
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000769bool CodeGenAction::hasIRSupport() const { return true; }
770
Daniel Dunbar400a6932010-02-25 04:37:50 +0000771void CodeGenAction::EndSourceFileAction() {
772 // If the consumer creation failed, do nothing.
773 if (!getCompilerInstance().hasASTConsumer())
774 return;
775
776 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000777 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000778}
779
Rafael Espindolae8337302014-08-19 14:36:35 +0000780std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
781 return std::move(TheModule);
782}
783
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000784llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
785 OwnsVMContext = false;
786 return VMContext;
787}
788
Peter Collingbourne03f89072016-07-15 00:55:40 +0000789static std::unique_ptr<raw_pwrite_stream>
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000790GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000791 switch (Action) {
792 case Backend_EmitAssembly:
793 return CI.createDefaultOutputFile(false, InFile, "s");
794 case Backend_EmitLL:
795 return CI.createDefaultOutputFile(false, InFile, "ll");
796 case Backend_EmitBC:
797 return CI.createDefaultOutputFile(true, InFile, "bc");
798 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000799 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000800 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000801 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000802 case Backend_EmitObj:
803 return CI.createDefaultOutputFile(true, InFile, "o");
804 }
805
David Blaikie83d382b2011-09-23 05:06:16 +0000806 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000807}
808
David Blaikie6beb6aa2014-08-10 19:56:51 +0000809std::unique_ptr<ASTConsumer>
810CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000811 BackendAction BA = static_cast<BackendAction>(Act);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000812 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000813 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000814 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000815
Artem Belevich5d40ae32015-10-27 17:56:59 +0000816 // Load bitcode modules to link with, if we need to.
817 if (LinkModules.empty())
Justin Lebarb080b632017-01-25 21:29:48 +0000818 for (const CodeGenOptions::BitcodeFileToLink &F :
819 CI.getCodeGenOpts().LinkBitcodeFiles) {
820 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
Artem Belevich5d40ae32015-10-27 17:56:59 +0000821 if (!BCBuf) {
822 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Justin Lebarb080b632017-01-25 21:29:48 +0000823 << F.Filename << BCBuf.getError().message();
Artem Belevich5d40ae32015-10-27 17:56:59 +0000824 LinkModules.clear();
825 return nullptr;
826 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000827
Peter Collingbourned9445c42016-11-13 07:00:17 +0000828 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000829 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000830 if (!ModuleOrErr) {
831 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
832 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Justin Lebarb080b632017-01-25 21:29:48 +0000833 << F.Filename << EIB.message();
Peter Collingbourned9445c42016-11-13 07:00:17 +0000834 });
Artem Belevich5d40ae32015-10-27 17:56:59 +0000835 LinkModules.clear();
836 return nullptr;
837 }
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000838 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
839 F.Internalize, F.LinkFlags});
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000840 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000841
Alex Lorenzee024992014-08-04 18:41:51 +0000842 CoverageSourceInfo *CoverageInfo = nullptr;
843 // Add the preprocessor callback only when the coverage mapping is generated.
844 if (CI.getCodeGenOpts().CoverageMapping) {
845 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000846 CI.getPreprocessor().addPPCallbacks(
847 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000848 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000849
David Blaikie037e75b2014-08-10 21:06:17 +0000850 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000851 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
852 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Justin Lebarb080b632017-01-25 21:29:48 +0000853 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
854 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000855 BEConsumer = Result.get();
Amjad Aboud546bc112017-02-09 22:07:24 +0000856
857 // Enable generating macro debug info only when debug info is not disabled and
858 // also macro debug info is enabled.
859 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
860 CI.getCodeGenOpts().MacroDebugInfo) {
861 std::unique_ptr<PPCallbacks> Callbacks =
862 llvm::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
863 CI.getPreprocessor());
864 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
865 }
866
David Blaikie6beb6aa2014-08-10 19:56:51 +0000867 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000868}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000869
Tim Northover1390b442016-04-06 19:58:07 +0000870static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
871 void *Context,
872 unsigned LocCookie) {
873 SM.print(nullptr, llvm::errs());
874
875 auto Diags = static_cast<DiagnosticsEngine *>(Context);
876 unsigned DiagID;
877 switch (SM.getKind()) {
878 case llvm::SourceMgr::DK_Error:
879 DiagID = diag::err_fe_inline_asm;
880 break;
881 case llvm::SourceMgr::DK_Warning:
882 DiagID = diag::warn_fe_inline_asm;
883 break;
884 case llvm::SourceMgr::DK_Note:
885 DiagID = diag::note_fe_inline_asm;
886 break;
887 }
888
889 Diags->Report(DiagID).AddString("cannot compile inline asm");
890}
891
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000892std::unique_ptr<llvm::Module> CodeGenAction::loadModule(MemoryBufferRef MBRef) {
893 CompilerInstance &CI = getCompilerInstance();
894 SourceManager &SM = CI.getSourceManager();
895
896 // For ThinLTO backend invocations, ensure that the context
Peter Collingbournef5d17122017-01-26 21:09:48 +0000897 // merges types based on ODR identifiers. We also need to read
898 // the correct module out of a multi-module bitcode file.
899 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000900 VMContext->enableDebugTypeODRUniquing();
901
Peter Collingbournef5d17122017-01-26 21:09:48 +0000902 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
903 unsigned DiagID =
904 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
905 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
906 CI.getDiagnostics().Report(DiagID) << EIB.message();
907 });
908 return {};
909 };
910
911 Expected<llvm::BitcodeModule> BMOrErr = FindThinLTOModule(MBRef);
912 if (!BMOrErr)
913 return DiagErrors(BMOrErr.takeError());
914
915 Expected<std::unique_ptr<llvm::Module>> MOrErr =
916 BMOrErr->parseModule(*VMContext);
917 if (!MOrErr)
918 return DiagErrors(MOrErr.takeError());
919 return std::move(*MOrErr);
920 }
921
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000922 llvm::SMDiagnostic Err;
923 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
924 return M;
925
926 // Translate from the diagnostic info to the SourceManager location if
927 // available.
928 // TODO: Unify this with ConvertBackendLocation()
929 SourceLocation Loc;
930 if (Err.getLineNo() > 0) {
931 assert(Err.getColumnNo() >= 0);
932 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
933 Err.getLineNo(), Err.getColumnNo() + 1);
934 }
935
936 // Strip off a leading diagnostic code if there is one.
937 StringRef Msg = Err.getMessage();
938 if (Msg.startswith("error: "))
939 Msg = Msg.substr(7);
940
941 unsigned DiagID =
942 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
943
944 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
945 return {};
946}
947
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000948void CodeGenAction::ExecuteAction() {
949 // If this is an IR file, we have to treat it specially.
Richard Smith40c0efa2017-04-26 18:57:40 +0000950 if (getCurrentFileKind().getLanguage() == InputKind::LLVM_IR) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000951 BackendAction BA = static_cast<BackendAction>(Act);
952 CompilerInstance &CI = getCompilerInstance();
Peter Collingbourne03f89072016-07-15 00:55:40 +0000953 std::unique_ptr<raw_pwrite_stream> OS =
954 GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000955 if (BA != Backend_EmitNothing && !OS)
956 return;
957
958 bool Invalid;
959 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000960 FileID FID = SM.getMainFileID();
961 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000962 if (Invalid)
963 return;
964
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000965 TheModule = loadModule(*MainFile);
966 if (!TheModule)
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000967 return;
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000968
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000969 const TargetOptions &TargetOpts = CI.getTargetOpts();
970 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000971 CI.getDiagnostics().Report(SourceLocation(),
972 diag::warn_fe_override_module)
973 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000974 TheModule->setTargetTriple(TargetOpts.Triple);
975 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000976
Steven Wu27fb5222016-05-11 16:26:03 +0000977 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
978 MainFile->getMemBufferRef());
979
Tim Northover1390b442016-04-06 19:58:07 +0000980 LLVMContext &Ctx = TheModule->getContext();
981 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
982 &CI.getDiagnostics());
Steven Wu27fb5222016-05-11 16:26:03 +0000983
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000984 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
985 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
986 CI.getTarget().getDataLayout(), TheModule.get(), BA,
987 std::move(OS));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000988 return;
989 }
990
991 // Otherwise follow the normal AST path.
992 this->ASTFrontendAction::ExecuteAction();
993}
994
995//
996
David Blaikie68e081d2011-12-20 02:48:34 +0000997void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000998EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
999 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001000
David Blaikie68e081d2011-12-20 02:48:34 +00001001void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001002EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1003 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001004
David Blaikie68e081d2011-12-20 02:48:34 +00001005void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001006EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1007 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001008
David Blaikie68e081d2011-12-20 02:48:34 +00001009void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001010EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1011 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001012
David Blaikie68e081d2011-12-20 02:48:34 +00001013void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001014EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1015 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +00001016
David Blaikie68e081d2011-12-20 02:48:34 +00001017void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001018EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1019 : CodeGenAction(Backend_EmitObj, _VMContext) {}