blob: 27b0d0b673f98d92fed7f553c6ded2285fdc8fef [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"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000013#include "clang/AST/ASTConsumer.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000014#include "clang/AST/ASTContext.h"
Hans Wennborga926d842014-05-23 20:37:38 +000015#include "clang/AST/DeclCXX.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000016#include "clang/AST/DeclGroup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Basic/FileManager.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/TargetInfo.h"
Daniel Dunbarc1b17292010-06-15 17:48:49 +000020#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbarb9bbd542009-11-15 06:48:46 +000021#include "clang/CodeGen/ModuleBuilder.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000022#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbaracadc552009-12-03 09:12:54 +000023#include "clang/Frontend/FrontendDiagnostic.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "clang/Lex/Preprocessor.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000025#include "llvm/Bitcode/BitcodeReader.h"
Adam Nemet7b796f82017-01-26 04:07:11 +000026#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Diego Novillo829b1702014-04-16 16:54:24 +000027#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000028#include "llvm/IR/DiagnosticInfo.h"
29#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/Module.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000032#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000033#include "llvm/Linker/Linker.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000034#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000035#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/SourceMgr.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000037#include "llvm/Support/Timer.h"
Hal Finkel8f96e822016-10-11 00:26:09 +000038#include "llvm/Support/ToolOutputFile.h"
39#include "llvm/Support/YAMLTraits.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000040#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000041using namespace clang;
42using namespace llvm;
43
Nico Weber2992efa2011-01-25 20:34:14 +000044namespace clang {
Benjamin Kramer16634c22009-11-28 10:07:24 +000045 class BackendConsumer : public ASTConsumer {
Justin Lebarb080b632017-01-25 21:29:48 +000046 using LinkModule = CodeGenAction::LinkModule;
47
David Blaikie68e081d2011-12-20 02:48:34 +000048 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000049 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000050 BackendAction Action;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000051 const HeaderSearchOptions &HeaderSearchOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000052 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000053 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000054 const LangOptions &LangOpts;
Peter Collingbourne03f89072016-07-15 00:55:40 +000055 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000056 ASTContext *Context;
Daniel Dunbarb3a36cf2008-10-29 08:50:02 +000057
Chris Lattner263d64c2009-02-18 01:37:30 +000058 Timer LLVMIRGeneration;
Davide Italianob99fabd2016-07-21 06:28:48 +000059 unsigned LLVMIRGenerationRefCount;
Mike Stump11289f42009-09-09 15:08:12 +000060
Reid Kleckner15241ba2016-11-30 00:25:36 +000061 /// True if we've finished generating IR. This prevents us from generating
62 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
63 /// can happen when Clang plugins trigger additional AST deserialization.
64 bool IRGenFinished = false;
65
Ahmed Charlesb8984322014-03-07 20:03:18 +000066 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +000067
Justin Lebarb080b632017-01-25 21:29:48 +000068 SmallVector<LinkModule, 4> LinkModules;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000069
Rafael Espindola8ce88a52015-12-14 23:17:07 +000070 // This is here so that the diagnostic printer knows the module a diagnostic
71 // refers to.
72 llvm::Module *CurLinkModule = nullptr;
73
Mike Stump11289f42009-09-09 15:08:12 +000074 public:
Justin Lebarb080b632017-01-25 21:29:48 +000075 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
76 const HeaderSearchOptions &HeaderSearchOpts,
77 const PreprocessorOptions &PPOpts,
78 const CodeGenOptions &CodeGenOpts,
79 const TargetOptions &TargetOpts,
80 const LangOptions &LangOpts, bool TimePasses,
81 const std::string &InFile,
82 SmallVector<LinkModule, 4> LinkModules,
83 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
84 CoverageSourceInfo *CoverageInfo = nullptr)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000085 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
86 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
Peter Collingbourne03f89072016-07-15 00:55:40 +000087 AsmOutStream(std::move(OS)), Context(nullptr),
Matthias Braunae032b62016-11-18 19:43:25 +000088 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
Davide Italianob99fabd2016-07-21 06:28:48 +000089 LLVMIRGenerationRefCount(0),
Adrian Prantle74f5252015-06-30 02:26:03 +000090 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
Justin Lebarb080b632017-01-25 21:29:48 +000091 CodeGenOpts, C, CoverageInfo)),
92 LinkModules(std::move(LinkModules)) {
Daniel Dunbar8e705052009-11-30 08:39:52 +000093 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattnerdeffa132009-02-18 01:23:44 +000094 }
Serge Pavlov41c1f792016-02-18 16:42:09 +000095 llvm::Module *getModule() const { return Gen->GetModule(); }
96 std::unique_ptr<llvm::Module> takeModule() {
97 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
98 }
Daniel Dunbar400a6932010-02-25 04:37:50 +000099
Craig Topper4f12f102014-03-12 06:41:41 +0000100 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +0000101 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +0000102 }
103
Craig Topper4f12f102014-03-12 06:41:41 +0000104 void Initialize(ASTContext &Ctx) override {
Richard Smith293534b2015-08-18 20:39:29 +0000105 assert(!Context && "initialized multiple times");
106
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000107 Context = &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +0000108
Daniel Dunbar8e705052009-11-30 08:39:52 +0000109 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000110 LLVMIRGeneration.startTimer();
Mike Stump11289f42009-09-09 15:08:12 +0000111
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000112 Gen->Initialize(Ctx);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000113
Daniel Dunbar8e705052009-11-30 08:39:52 +0000114 if (llvm::TimePassesIsEnabled)
Chris Lattner263d64c2009-02-18 01:37:30 +0000115 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000116 }
Mike Stump11289f42009-09-09 15:08:12 +0000117
Craig Topper4f12f102014-03-12 06:41:41 +0000118 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000119 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +0000120 Context->getSourceManager(),
121 "LLVM IR generation of declaration");
Mike Stump11289f42009-09-09 15:08:12 +0000122
Davide Italianob99fabd2016-07-21 06:28:48 +0000123 // Recurse.
124 if (llvm::TimePassesIsEnabled) {
125 LLVMIRGenerationRefCount += 1;
126 if (LLVMIRGenerationRefCount == 1)
127 LLVMIRGeneration.startTimer();
128 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000129
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000130 Gen->HandleTopLevelDecl(D);
Chris Lattner263d64c2009-02-18 01:37:30 +0000131
Davide Italianob99fabd2016-07-21 06:28:48 +0000132 if (llvm::TimePassesIsEnabled) {
133 LLVMIRGenerationRefCount -= 1;
134 if (LLVMIRGenerationRefCount == 0)
135 LLVMIRGeneration.stopTimer();
136 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000137
138 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000139 }
Mike Stump11289f42009-09-09 15:08:12 +0000140
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000141 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000142 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
143 Context->getSourceManager(),
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000144 "LLVM IR generation of inline function");
Hans Wennborga926d842014-05-23 20:37:38 +0000145 if (llvm::TimePassesIsEnabled)
146 LLVMIRGeneration.startTimer();
147
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000148 Gen->HandleInlineFunctionDefinition(D);
Hans Wennborga926d842014-05-23 20:37:38 +0000149
150 if (llvm::TimePassesIsEnabled)
151 LLVMIRGeneration.stopTimer();
152 }
153
Reid Kleckner68c4bb52016-11-30 01:32:53 +0000154 void HandleInterestingDecl(DeclGroupRef D) override {
Reid Kleckner15241ba2016-11-30 00:25:36 +0000155 // Ignore interesting decls from the AST reader after IRGen is finished.
156 if (!IRGenFinished)
157 HandleTopLevelDecl(D);
158 }
159
Justin Lebarb080b632017-01-25 21:29:48 +0000160 // Links each entry in LinkModules into our module. Returns true on error.
161 bool LinkInModules() {
162 for (auto &LM : LinkModules) {
163 if (LM.PropagateAttrs)
164 for (Function &F : *LM.Module)
165 Gen->CGM().AddDefaultFnAttrs(F);
166
167 CurLinkModule = LM.Module.get();
168 if (Linker::linkModules(*getModule(), std::move(LM.Module),
169 LM.LinkFlags))
170 return true;
171 }
172 return false; // success
173 }
174
Craig Topper4f12f102014-03-12 06:41:41 +0000175 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000176 {
Chris Lattnere46de752009-03-06 06:46:31 +0000177 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Davide Italianob99fabd2016-07-21 06:28:48 +0000178 if (llvm::TimePassesIsEnabled) {
179 LLVMIRGenerationRefCount += 1;
180 if (LLVMIRGenerationRefCount == 1)
181 LLVMIRGeneration.startTimer();
182 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000183
Chris Lattnercf169832009-03-28 04:11:33 +0000184 Gen->HandleTranslationUnit(C);
Daniel Dunbara94d8732008-11-11 06:35:39 +0000185
Davide Italianob99fabd2016-07-21 06:28:48 +0000186 if (llvm::TimePassesIsEnabled) {
187 LLVMIRGenerationRefCount -= 1;
188 if (LLVMIRGenerationRefCount == 0)
189 LLVMIRGeneration.stopTimer();
190 }
Reid Kleckner15241ba2016-11-30 00:25:36 +0000191
192 IRGenFinished = true;
Chris Lattnereae6cb62009-03-05 08:00:35 +0000193 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000194
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000195 // Silently ignore if we weren't initialized for some reason.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000196 if (!getModule())
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000197 return;
Mike Stump11289f42009-09-09 15:08:12 +0000198
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000199 // Install an inline asm handler so that diagnostics get printed through
200 // our diagnostics hooks.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000201 LLVMContext &Ctx = getModule()->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000202 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
203 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000204 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000205 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000206
Quentin Colombet728c5542014-02-06 18:30:43 +0000207 LLVMContext::DiagnosticHandlerTy OldDiagnosticHandler =
208 Ctx.getDiagnosticHandler();
209 void *OldDiagnosticContext = Ctx.getDiagnosticContext();
210 Ctx.setDiagnosticHandler(DiagnosticHandler, this);
Adam Nemet1eea3e52016-09-13 04:32:40 +0000211 Ctx.setDiagnosticHotnessRequested(CodeGenOpts.DiagnosticsWithHotness);
Quentin Colombet728c5542014-02-06 18:30:43 +0000212
Hal Finkel8f96e822016-10-11 00:26:09 +0000213 std::unique_ptr<llvm::tool_output_file> OptRecordFile;
214 if (!CodeGenOpts.OptRecordFile.empty()) {
215 std::error_code EC;
216 OptRecordFile =
217 llvm::make_unique<llvm::tool_output_file>(CodeGenOpts.OptRecordFile,
218 EC, sys::fs::F_None);
219 if (EC) {
220 Diags.Report(diag::err_cannot_open_file) <<
221 CodeGenOpts.OptRecordFile << EC.message();
222 return;
223 }
224
Mehdi Amini6f408362016-11-19 18:19:41 +0000225 Ctx.setDiagnosticsOutputFile(
226 llvm::make_unique<yaml::Output>(OptRecordFile->os()));
Hal Finkel8f96e822016-10-11 00:26:09 +0000227
228 if (CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
229 Ctx.setDiagnosticHotnessRequested(true);
230 }
231
Justin Lebarb080b632017-01-25 21:29:48 +0000232 // Link each LinkModule into our module.
233 if (LinkInModules())
234 return;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000235
Steven Wu27fb5222016-05-11 16:26:03 +0000236 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
237
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000238 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
239 LangOpts, C.getTargetInfo().getDataLayout(),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000240 getModule(), Action, std::move(AsmOutStream));
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000241
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000242 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000243
244 Ctx.setDiagnosticHandler(OldDiagnosticHandler, OldDiagnosticContext);
Hal Finkel8f96e822016-10-11 00:26:09 +0000245
246 if (OptRecordFile)
247 OptRecordFile->keep();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000248 }
Mike Stump11289f42009-09-09 15:08:12 +0000249
Craig Topper4f12f102014-03-12 06:41:41 +0000250 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000251 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
252 Context->getSourceManager(),
253 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000254 Gen->HandleTagDeclDefinition(D);
255 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000256
Craig Topper4f12f102014-03-12 06:41:41 +0000257 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000258 Gen->HandleTagDeclRequiredDefinition(D);
259 }
260
Craig Topper4f12f102014-03-12 06:41:41 +0000261 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000262 Gen->CompleteTentativeDefinition(D);
263 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000264
David Majnemer929025d2016-01-26 19:30:26 +0000265 void AssignInheritanceModel(CXXRecordDecl *RD) override {
266 Gen->AssignInheritanceModel(RD);
267 }
268
Nico Weberb6a5d052015-01-15 04:07:35 +0000269 void HandleVTable(CXXRecordDecl *RD) override {
270 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000271 }
272
Chris Lattner5ec32e72010-04-06 18:38:50 +0000273 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
274 unsigned LocCookie) {
275 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
276 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
277 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000278
Quentin Colombet728c5542014-02-06 18:30:43 +0000279 static void DiagnosticHandler(const llvm::DiagnosticInfo &DI,
280 void *Context) {
281 ((BackendConsumer *)Context)->DiagnosticHandlerImpl(DI);
282 }
283
Oliver Stannard91817852016-02-02 13:52:52 +0000284 /// Get the best possible source location to represent a diagnostic that
285 /// may have associated debug info.
286 const FullSourceLoc
287 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithDebugLocBase &D,
288 bool &BadDebugInfo, StringRef &Filename,
289 unsigned &Line, unsigned &Column) const;
290
Chris Lattner5ec32e72010-04-06 18:38:50 +0000291 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
292 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000293
294 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
295 /// \brief Specialized handler for InlineAsm diagnostic.
296 /// \return True if the diagnostic has been successfully reported, false
297 /// otherwise.
298 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
299 /// \brief Specialized handler for StackSize diagnostic.
300 /// \return True if the diagnostic has been successfully reported, false
301 /// otherwise.
302 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Oliver Stannard91817852016-02-02 13:52:52 +0000303 /// \brief Specialized handler for unsupported backend feature diagnostic.
304 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000305 /// \brief Specialized handlers for optimization remarks.
306 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000307 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000308 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
309 unsigned DiagID);
Adam Nemet7b796f82017-01-26 04:07:11 +0000310 void
311 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000312 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000313 const llvm::OptimizationRemarkAnalysisFPCommute &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000314 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000315 const llvm::OptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000316 void OptimizationFailureHandler(
317 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000318 };
David Blaikie68e081d2011-12-20 02:48:34 +0000319
320 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000321}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000322
Chris Lattner79f67a72010-04-08 00:23:06 +0000323/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
324/// buffer to be a valid FullSourceLoc.
325static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
326 SourceManager &CSM) {
327 // Get both the clang and llvm source managers. The location is relative to
328 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000329 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000330 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000331
Chris Lattner79f67a72010-04-08 00:23:06 +0000332 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
333 // already owns its one and clang::SourceManager wants to own its one.
334 const MemoryBuffer *LBuf =
335 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000336
Chris Lattner79f67a72010-04-08 00:23:06 +0000337 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000338 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000339 std::unique_ptr<llvm::MemoryBuffer> CBuf =
340 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
341 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000342 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000343 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000344
Chris Lattner79f67a72010-04-08 00:23:06 +0000345 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000346 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000347 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000348 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000349 return FullSourceLoc(NewLoc, CSM);
350}
351
Chris Lattner6d672132010-04-06 17:52:14 +0000352
Chris Lattner5ec32e72010-04-06 18:38:50 +0000353/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
354/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000355/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000356void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
357 SourceLocation LocCookie) {
358 // There are a couple of different kinds of errors we could get here. First,
359 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000360
361 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000362 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000363 if (Message.startswith("error: "))
364 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000365
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000366 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000367 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000368 if (D.getLoc() != SMLoc())
369 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000370
Joey Gouly5798b262014-06-05 21:23:42 +0000371 unsigned DiagID;
372 switch (D.getKind()) {
373 case llvm::SourceMgr::DK_Error:
374 DiagID = diag::err_fe_inline_asm;
375 break;
376 case llvm::SourceMgr::DK_Warning:
377 DiagID = diag::warn_fe_inline_asm;
378 break;
379 case llvm::SourceMgr::DK_Note:
380 DiagID = diag::note_fe_inline_asm;
381 break;
382 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000383 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000384 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000385 // code.
386 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000387 Diags.Report(LocCookie, DiagID).AddString(Message);
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000388
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000389 if (D.getLoc().isValid()) {
390 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
391 // Convert the SMDiagnostic ranges into SourceRange and attach them
392 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000393 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000394 unsigned Column = D.getColumnNo();
395 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
396 Loc.getLocWithOffset(Range.second - Column));
397 }
398 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000399 return;
400 }
401
Joey Gouly5798b262014-06-05 21:23:42 +0000402 // Otherwise, report the backend issue as occurring in the generated .s file.
403 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000404 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000405 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000406}
407
Quentin Colombet728c5542014-02-06 18:30:43 +0000408#define ComputeDiagID(Severity, GroupName, DiagID) \
409 do { \
410 switch (Severity) { \
411 case llvm::DS_Error: \
412 DiagID = diag::err_fe_##GroupName; \
413 break; \
414 case llvm::DS_Warning: \
415 DiagID = diag::warn_fe_##GroupName; \
416 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000417 case llvm::DS_Remark: \
418 llvm_unreachable("'remark' severity not expected"); \
419 break; \
420 case llvm::DS_Note: \
421 DiagID = diag::note_fe_##GroupName; \
422 break; \
423 } \
424 } while (false)
425
426#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
427 do { \
428 switch (Severity) { \
429 case llvm::DS_Error: \
430 DiagID = diag::err_fe_##GroupName; \
431 break; \
432 case llvm::DS_Warning: \
433 DiagID = diag::warn_fe_##GroupName; \
434 break; \
435 case llvm::DS_Remark: \
436 DiagID = diag::remark_fe_##GroupName; \
437 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000438 case llvm::DS_Note: \
439 DiagID = diag::note_fe_##GroupName; \
440 break; \
441 } \
442 } while (false)
443
444bool
445BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
446 unsigned DiagID;
447 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
448 std::string Message = D.getMsgStr().str();
449
450 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000451 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000452 // code.
453 SourceLocation LocCookie =
454 SourceLocation::getFromRawEncoding(D.getLocCookie());
455 if (LocCookie.isValid())
456 Diags.Report(LocCookie, DiagID).AddString(Message);
457 else {
458 // Otherwise, report the backend diagnostic as occurring in the generated
459 // .s file.
460 // If Loc is invalid, we still need to report the diagnostic, it just gets
461 // no location info.
462 FullSourceLoc Loc;
463 Diags.Report(Loc, DiagID).AddString(Message);
464 }
465 // We handled all the possible severities.
466 return true;
467}
468
469bool
470BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
471 if (D.getSeverity() != llvm::DS_Warning)
472 // For now, the only support we have for StackSize diagnostic is warning.
473 // We do not know how to format other severities.
474 return false;
475
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000476 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000477 // FIXME: Shouldn't need to truncate to uint32_t
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000478 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
479 diag::warn_fe_frame_larger_than)
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000480 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000481 return true;
482 }
483
484 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000485}
486
Oliver Stannard91817852016-02-02 13:52:52 +0000487const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
488 const llvm::DiagnosticInfoWithDebugLocBase &D, bool &BadDebugInfo, StringRef &Filename,
489 unsigned &Line, unsigned &Column) const {
Diego Novillod23ec942014-05-29 19:55:06 +0000490 SourceManager &SourceMgr = Context->getSourceManager();
491 FileManager &FileMgr = SourceMgr.getFileManager();
Alp Toker27506272014-06-05 22:11:12 +0000492 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000493
494 if (D.isLocationAvailable()) {
495 D.getLocation(&Filename, &Line, &Column);
496 const FileEntry *FE = FileMgr.getFile(Filename);
497 if (FE && Line > 0) {
498 // If -gcolumn-info was not used, Column will be 0. This upsets the
499 // source manager, so pass 1 if Column is not set.
500 DILoc = SourceMgr.translateFileLineCol(FE, Line, Column ? Column : 1);
501 }
Oliver Stannard91817852016-02-02 13:52:52 +0000502 BadDebugInfo = DILoc.isInvalid();
Diego Novillo829b1702014-04-16 16:54:24 +0000503 }
Alp Toker27506272014-06-05 22:11:12 +0000504
505 // If a location isn't available, try to approximate it using the associated
506 // function definition. We use the definition's right brace to differentiate
507 // from diagnostics that genuinely relate to the function itself.
508 FullSourceLoc Loc(DILoc, SourceMgr);
509 if (Loc.isInvalid())
510 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Oliver Stannard91817852016-02-02 13:52:52 +0000511 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
Diego Novillod23ec942014-05-29 19:55:06 +0000512
Diego Novillo86f884e2015-05-08 20:59:56 +0000513 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000514 // If we were not able to translate the file:line:col information
515 // back to a SourceLocation, at least emit a note stating that
516 // we could not translate this location. This can happen in the
517 // case of #line directives.
Oliver Stannard91817852016-02-02 13:52:52 +0000518 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Ben Craig6e4695a2016-05-06 13:29:46 +0000519 << Filename << Line << Column;
Oliver Stannard91817852016-02-02 13:52:52 +0000520
521 return Loc;
522}
523
524void BackendConsumer::UnsupportedDiagHandler(
525 const llvm::DiagnosticInfoUnsupported &D) {
526 // We only support errors.
527 assert(D.getSeverity() == llvm::DS_Error);
528
529 StringRef Filename;
530 unsigned Line, Column;
531 bool BadDebugInfo;
532 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
533 Line, Column);
534
535 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
536
537 if (BadDebugInfo)
538 // If we were not able to translate the file:line:col information
539 // back to a SourceLocation, at least emit a note stating that
540 // we could not translate this location. This can happen in the
541 // case of #line directives.
542 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
543 << Filename << Line << Column;
544}
545
546void BackendConsumer::EmitOptimizationMessage(
547 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
548 // We only support warnings and remarks.
549 assert(D.getSeverity() == llvm::DS_Remark ||
550 D.getSeverity() == llvm::DS_Warning);
551
552 StringRef Filename;
553 unsigned Line, Column;
554 bool BadDebugInfo = false;
555 FullSourceLoc Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename,
556 Line, Column);
557
Adam Nemet1eea3e52016-09-13 04:32:40 +0000558 std::string Msg;
559 raw_string_ostream MsgStream(Msg);
Adam Nemet699fc5b2016-09-27 20:55:12 +0000560 MsgStream << D.getMsg();
Adam Nemet1eea3e52016-09-13 04:32:40 +0000561
562 if (D.getHotness())
563 MsgStream << " (hotness: " << *D.getHotness() << ")";
564
Oliver Stannard91817852016-02-02 13:52:52 +0000565 Diags.Report(Loc, DiagID)
Mehdi Amini117296c2016-10-01 02:56:57 +0000566 << AddFlagValue(D.getPassName())
Adam Nemet1eea3e52016-09-13 04:32:40 +0000567 << MsgStream.str();
Oliver Stannard91817852016-02-02 13:52:52 +0000568
569 if (BadDebugInfo)
570 // If we were not able to translate the file:line:col information
571 // back to a SourceLocation, at least emit a note stating that
572 // we could not translate this location. This can happen in the
573 // case of #line directives.
574 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000575 << Filename << Line << Column;
576}
577
578void BackendConsumer::OptimizationRemarkHandler(
Adam Nemet7b796f82017-01-26 04:07:11 +0000579 const llvm::DiagnosticInfoOptimizationBase &D) {
580 if (D.isPassed()) {
581 // Optimization remarks are active only if the -Rpass flag has a regular
582 // expression that matches the name of the pass name in \p D.
583 if (CodeGenOpts.OptimizationRemarkPattern &&
584 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
585 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
586 } else if (D.isMissed()) {
587 // Missed optimization remarks are active only if the -Rpass-missed
588 // flag has a regular expression that matches the name of the pass
589 // name in \p D.
590 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
591 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
592 EmitOptimizationMessage(
593 D, diag::remark_fe_backend_optimization_remark_missed);
594 } else {
595 assert(D.isAnalysis() && "Unknown remark type");
Diego Novillod23ec942014-05-29 19:55:06 +0000596
Adam Nemet7b796f82017-01-26 04:07:11 +0000597 bool ShouldAlwaysPrint = false;
598 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
599 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
Diego Novillod23ec942014-05-29 19:55:06 +0000600
Adam Nemet7b796f82017-01-26 04:07:11 +0000601 if (ShouldAlwaysPrint ||
602 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
603 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
604 EmitOptimizationMessage(
605 D, diag::remark_fe_backend_optimization_remark_analysis);
606 }
Diego Novillo829b1702014-04-16 16:54:24 +0000607}
608
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000609void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000610 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000611 // Optimization analysis remarks are active if the pass name is set to
612 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
613 // regular expression that matches the name of the pass name in \p D.
614
Adam Nemetb5beb972016-06-29 04:55:31 +0000615 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000616 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
617 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000618 EmitOptimizationMessage(
619 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
620}
621
Tyler Nowicki034baf62015-08-10 23:05:16 +0000622void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000623 const llvm::OptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000624 // Optimization analysis remarks are active if the pass name is set to
625 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
626 // regular expression that matches the name of the pass name in \p D.
627
Adam Nemetb5beb972016-06-29 04:55:31 +0000628 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000629 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
630 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000631 EmitOptimizationMessage(
632 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
633}
634
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000635void BackendConsumer::OptimizationFailureHandler(
636 const llvm::DiagnosticInfoOptimizationFailure &D) {
637 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
638}
639
Quentin Colombet728c5542014-02-06 18:30:43 +0000640/// \brief This function is invoked when the backend needs
641/// to report something to the user.
642void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
643 unsigned DiagID = diag::err_fe_inline_asm;
644 llvm::DiagnosticSeverity Severity = DI.getSeverity();
645 // Get the diagnostic ID based.
646 switch (DI.getKind()) {
647 case llvm::DK_InlineAsm:
648 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
649 return;
650 ComputeDiagID(Severity, inline_asm, DiagID);
651 break;
652 case llvm::DK_StackSize:
653 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
654 return;
655 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
656 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000657 case DK_Linker:
658 assert(CurLinkModule);
659 // FIXME: stop eating the warnings and notes.
660 if (Severity != DS_Error)
661 return;
662 DiagID = diag::err_fe_cannot_link_module;
663 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000664 case llvm::DK_OptimizationRemark:
665 // Optimization remarks are always handled completely by this
666 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000667 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
Diego Novillo829b1702014-04-16 16:54:24 +0000668 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000669 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000670 // Optimization remarks are always handled completely by this
671 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000672 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
Diego Novillod23ec942014-05-29 19:55:06 +0000673 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000674 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000675 // Optimization remarks are always handled completely by this
676 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000677 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000678 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000679 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
680 // Optimization remarks are always handled completely by this
681 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000682 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000683 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000684 case llvm::DK_OptimizationRemarkAnalysisAliasing:
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<OptimizationRemarkAnalysisAliasing>(DI));
Tyler Nowicki034baf62015-08-10 23:05:16 +0000688 return;
Adam Nemet7b796f82017-01-26 04:07:11 +0000689 case llvm::DK_MachineOptimizationRemark:
690 // Optimization remarks are always handled completely by this
691 // handler. There is no generic way of emitting them.
692 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
693 return;
694 case llvm::DK_MachineOptimizationRemarkMissed:
695 // Optimization remarks are always handled completely by this
696 // handler. There is no generic way of emitting them.
697 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
698 return;
699 case llvm::DK_MachineOptimizationRemarkAnalysis:
700 // Optimization remarks are always handled completely by this
701 // handler. There is no generic way of emitting them.
702 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
703 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000704 case llvm::DK_OptimizationFailure:
705 // Optimization failures are always handled completely by this
706 // handler.
707 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
708 return;
Oliver Stannard91817852016-02-02 13:52:52 +0000709 case llvm::DK_Unsupported:
710 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
711 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000712 default:
713 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000714 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000715 break;
716 }
717 std::string MsgStorage;
718 {
719 raw_string_ostream Stream(MsgStorage);
720 DiagnosticPrinterRawOStream DP(Stream);
721 DI.print(DP);
722 }
723
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000724 if (DiagID == diag::err_fe_cannot_link_module) {
725 Diags.Report(diag::err_fe_cannot_link_module)
726 << CurLinkModule->getModuleIdentifier() << MsgStorage;
727 return;
728 }
729
Quentin Colombet728c5542014-02-06 18:30:43 +0000730 // Report the backend message using the usual diagnostic mechanism.
731 FullSourceLoc Loc;
732 Diags.Report(Loc, DiagID).AddString(MsgStorage);
733}
734#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000735
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000736CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000737 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
Eric Christopher02e3dd42016-03-12 01:47:11 +0000738 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000739
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000740CodeGenAction::~CodeGenAction() {
741 TheModule.reset();
742 if (OwnsVMContext)
743 delete VMContext;
744}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000745
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000746bool CodeGenAction::hasIRSupport() const { return true; }
747
Daniel Dunbar400a6932010-02-25 04:37:50 +0000748void CodeGenAction::EndSourceFileAction() {
749 // If the consumer creation failed, do nothing.
750 if (!getCompilerInstance().hasASTConsumer())
751 return;
752
753 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000754 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000755}
756
Rafael Espindolae8337302014-08-19 14:36:35 +0000757std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
758 return std::move(TheModule);
759}
760
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000761llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
762 OwnsVMContext = false;
763 return VMContext;
764}
765
Peter Collingbourne03f89072016-07-15 00:55:40 +0000766static std::unique_ptr<raw_pwrite_stream>
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000767GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000768 switch (Action) {
769 case Backend_EmitAssembly:
770 return CI.createDefaultOutputFile(false, InFile, "s");
771 case Backend_EmitLL:
772 return CI.createDefaultOutputFile(false, InFile, "ll");
773 case Backend_EmitBC:
774 return CI.createDefaultOutputFile(true, InFile, "bc");
775 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000776 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000777 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000778 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000779 case Backend_EmitObj:
780 return CI.createDefaultOutputFile(true, InFile, "o");
781 }
782
David Blaikie83d382b2011-09-23 05:06:16 +0000783 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000784}
785
David Blaikie6beb6aa2014-08-10 19:56:51 +0000786std::unique_ptr<ASTConsumer>
787CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000788 BackendAction BA = static_cast<BackendAction>(Act);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000789 std::unique_ptr<raw_pwrite_stream> OS = GetOutputStream(CI, InFile, BA);
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000790 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000791 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000792
Artem Belevich5d40ae32015-10-27 17:56:59 +0000793 // Load bitcode modules to link with, if we need to.
794 if (LinkModules.empty())
Justin Lebarb080b632017-01-25 21:29:48 +0000795 for (const CodeGenOptions::BitcodeFileToLink &F :
796 CI.getCodeGenOpts().LinkBitcodeFiles) {
797 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
Artem Belevich5d40ae32015-10-27 17:56:59 +0000798 if (!BCBuf) {
799 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Justin Lebarb080b632017-01-25 21:29:48 +0000800 << F.Filename << BCBuf.getError().message();
Artem Belevich5d40ae32015-10-27 17:56:59 +0000801 LinkModules.clear();
802 return nullptr;
803 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000804
Peter Collingbourned9445c42016-11-13 07:00:17 +0000805 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000806 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000807 if (!ModuleOrErr) {
808 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
809 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Justin Lebarb080b632017-01-25 21:29:48 +0000810 << F.Filename << EIB.message();
Peter Collingbourned9445c42016-11-13 07:00:17 +0000811 });
Artem Belevich5d40ae32015-10-27 17:56:59 +0000812 LinkModules.clear();
813 return nullptr;
814 }
Justin Lebarb080b632017-01-25 21:29:48 +0000815 LinkModules.push_back(
816 {std::move(ModuleOrErr.get()), F.PropagateAttrs, F.LinkFlags});
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000817 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000818
Alex Lorenzee024992014-08-04 18:41:51 +0000819 CoverageSourceInfo *CoverageInfo = nullptr;
820 // Add the preprocessor callback only when the coverage mapping is generated.
821 if (CI.getCodeGenOpts().CoverageMapping) {
822 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000823 CI.getPreprocessor().addPPCallbacks(
824 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000825 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000826
David Blaikie037e75b2014-08-10 21:06:17 +0000827 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000828 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
829 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Justin Lebarb080b632017-01-25 21:29:48 +0000830 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
831 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000832 BEConsumer = Result.get();
833 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000834}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000835
Tim Northover1390b442016-04-06 19:58:07 +0000836static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
837 void *Context,
838 unsigned LocCookie) {
839 SM.print(nullptr, llvm::errs());
840
841 auto Diags = static_cast<DiagnosticsEngine *>(Context);
842 unsigned DiagID;
843 switch (SM.getKind()) {
844 case llvm::SourceMgr::DK_Error:
845 DiagID = diag::err_fe_inline_asm;
846 break;
847 case llvm::SourceMgr::DK_Warning:
848 DiagID = diag::warn_fe_inline_asm;
849 break;
850 case llvm::SourceMgr::DK_Note:
851 DiagID = diag::note_fe_inline_asm;
852 break;
853 }
854
855 Diags->Report(DiagID).AddString("cannot compile inline asm");
856}
857
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000858std::unique_ptr<llvm::Module> CodeGenAction::loadModule(MemoryBufferRef MBRef) {
859 CompilerInstance &CI = getCompilerInstance();
860 SourceManager &SM = CI.getSourceManager();
861
862 // For ThinLTO backend invocations, ensure that the context
863 // merges types based on ODR identifiers.
864 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty())
865 VMContext->enableDebugTypeODRUniquing();
866
867 llvm::SMDiagnostic Err;
868 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
869 return M;
870
871 // Translate from the diagnostic info to the SourceManager location if
872 // available.
873 // TODO: Unify this with ConvertBackendLocation()
874 SourceLocation Loc;
875 if (Err.getLineNo() > 0) {
876 assert(Err.getColumnNo() >= 0);
877 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
878 Err.getLineNo(), Err.getColumnNo() + 1);
879 }
880
881 // Strip off a leading diagnostic code if there is one.
882 StringRef Msg = Err.getMessage();
883 if (Msg.startswith("error: "))
884 Msg = Msg.substr(7);
885
886 unsigned DiagID =
887 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
888
889 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
890 return {};
891}
892
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000893void CodeGenAction::ExecuteAction() {
894 // If this is an IR file, we have to treat it specially.
895 if (getCurrentFileKind() == IK_LLVM_IR) {
896 BackendAction BA = static_cast<BackendAction>(Act);
897 CompilerInstance &CI = getCompilerInstance();
Peter Collingbourne03f89072016-07-15 00:55:40 +0000898 std::unique_ptr<raw_pwrite_stream> OS =
899 GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000900 if (BA != Backend_EmitNothing && !OS)
901 return;
902
903 bool Invalid;
904 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +0000905 FileID FID = SM.getMainFileID();
906 llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000907 if (Invalid)
908 return;
909
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000910 TheModule = loadModule(*MainFile);
911 if (!TheModule)
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000912 return;
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000913
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000914 const TargetOptions &TargetOpts = CI.getTargetOpts();
915 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +0000916 CI.getDiagnostics().Report(SourceLocation(),
917 diag::warn_fe_override_module)
918 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +0000919 TheModule->setTargetTriple(TargetOpts.Triple);
920 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000921
Steven Wu27fb5222016-05-11 16:26:03 +0000922 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
923 MainFile->getMemBufferRef());
924
Tim Northover1390b442016-04-06 19:58:07 +0000925 LLVMContext &Ctx = TheModule->getContext();
926 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
927 &CI.getDiagnostics());
Steven Wu27fb5222016-05-11 16:26:03 +0000928
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000929 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
930 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
931 CI.getTarget().getDataLayout(), TheModule.get(), BA,
932 std::move(OS));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000933 return;
934 }
935
936 // Otherwise follow the normal AST path.
937 this->ASTFrontendAction::ExecuteAction();
938}
939
940//
941
David Blaikie68e081d2011-12-20 02:48:34 +0000942void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000943EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
944 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000945
David Blaikie68e081d2011-12-20 02:48:34 +0000946void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000947EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
948 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000949
David Blaikie68e081d2011-12-20 02:48:34 +0000950void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000951EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
952 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000953
David Blaikie68e081d2011-12-20 02:48:34 +0000954void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000955EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
956 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000957
David Blaikie68e081d2011-12-20 02:48:34 +0000958void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000959EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
960 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +0000961
David Blaikie68e081d2011-12-20 02:48:34 +0000962void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000963EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
964 : CodeGenAction(Backend_EmitObj, _VMContext) {}