blob: 2356f84c05d183713750a2199c96df4838500eec [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbarc13935e2008-10-21 23:49:24 +00006//
7//===----------------------------------------------------------------------===//
8
Justin Lebarb080b632017-01-25 21:29:48 +00009#include "clang/CodeGen/CodeGenAction.h"
10#include "CodeGenModule.h"
Alex Lorenzee024992014-08-04 18:41:51 +000011#include "CoverageMappingGen.h"
Amjad Aboud546bc112017-02-09 22:07:24 +000012#include "MacroPPCallbacks.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"
Rainer Orth09d890d2019-08-05 13:59:26 +000018#include "clang/Basic/LangStandard.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#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"
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +000023#include "clang/Driver/DriverDiagnostic.h"
Daniel Dunbarcea0c702010-02-25 04:37:45 +000024#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbaracadc552009-12-03 09:12:54 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "clang/Lex/Preprocessor.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000027#include "llvm/Bitcode/BitcodeReader.h"
Adam Nemet7b796f82017-01-26 04:07:11 +000028#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
Diego Novillo829b1702014-04-16 16:54:24 +000029#include "llvm/IR/DebugInfo.h"
Quentin Colombet728c5542014-02-06 18:30:43 +000030#include "llvm/IR/DiagnosticInfo.h"
31#include "llvm/IR/DiagnosticPrinter.h"
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +000032#include "llvm/IR/GlobalValue.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Module.h"
Francis Visoiu Mistrihb8a847c2019-03-06 15:20:13 +000035#include "llvm/IR/RemarkStreamer.h"
Chandler Carruthb45836a2013-03-26 02:25:54 +000036#include "llvm/IRReader/IRReader.h"
Chandler Carruth00fa3f72014-03-06 03:46:44 +000037#include "llvm/Linker/Linker.h"
Daniel Dunbar3e111522010-06-07 23:21:04 +000038#include "llvm/Pass.h"
Chris Lattner5ec32e72010-04-06 18:38:50 +000039#include "llvm/Support/MemoryBuffer.h"
40#include "llvm/Support/SourceMgr.h"
Anton Afanasyev3f3a2572019-08-19 22:58:26 +000041#include "llvm/Support/TimeProfiler.h"
Chris Lattner263d64c2009-02-18 01:37:30 +000042#include "llvm/Support/Timer.h"
Hal Finkel8f96e822016-10-11 00:26:09 +000043#include "llvm/Support/ToolOutputFile.h"
44#include "llvm/Support/YAMLTraits.h"
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +000045#include "llvm/Transforms/IPO/Internalize.h"
46
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000047#include <memory>
Daniel Dunbarc13935e2008-10-21 23:49:24 +000048using namespace clang;
49using namespace llvm;
50
Nico Weber2992efa2011-01-25 20:34:14 +000051namespace clang {
Vivek Pandya1dee3be2017-09-15 20:09:55 +000052 class BackendConsumer;
53 class ClangDiagnosticHandler final : public DiagnosticHandler {
54 public:
55 ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
56 : CodeGenOpts(CGOpts), BackendCon(BCon) {}
Fangrui Song6907ce22018-07-30 19:24:48 +000057
Vivek Pandya1dee3be2017-09-15 20:09:55 +000058 bool handleDiagnostics(const DiagnosticInfo &DI) override;
Adam Nemet5d2eb162017-09-19 17:59:40 +000059
60 bool isAnalysisRemarkEnabled(StringRef PassName) const override {
Vivek Pandya1dee3be2017-09-15 20:09:55 +000061 return (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
62 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(PassName));
63 }
Adam Nemet5d2eb162017-09-19 17:59:40 +000064 bool isMissedOptRemarkEnabled(StringRef PassName) const override {
Vivek Pandya1dee3be2017-09-15 20:09:55 +000065 return (CodeGenOpts.OptimizationRemarkMissedPattern &&
66 CodeGenOpts.OptimizationRemarkMissedPattern->match(PassName));
67 }
Adam Nemet5d2eb162017-09-19 17:59:40 +000068 bool isPassedOptRemarkEnabled(StringRef PassName) const override {
Vivek Pandya1dee3be2017-09-15 20:09:55 +000069 return (CodeGenOpts.OptimizationRemarkPattern &&
70 CodeGenOpts.OptimizationRemarkPattern->match(PassName));
71 }
Adam Nemet5d2eb162017-09-19 17:59:40 +000072
Adam Nemet3ac802a2017-09-19 23:00:59 +000073 bool isAnyRemarkEnabled() const override {
74 return (CodeGenOpts.OptimizationRemarkAnalysisPattern ||
75 CodeGenOpts.OptimizationRemarkMissedPattern ||
76 CodeGenOpts.OptimizationRemarkPattern);
77 }
78
Vivek Pandya1dee3be2017-09-15 20:09:55 +000079 private:
80 const CodeGenOptions &CodeGenOpts;
81 BackendConsumer *BackendCon;
82 };
83
Benjamin Kramer16634c22009-11-28 10:07:24 +000084 class BackendConsumer : public ASTConsumer {
Justin Lebarb080b632017-01-25 21:29:48 +000085 using LinkModule = CodeGenAction::LinkModule;
86
David Blaikie68e081d2011-12-20 02:48:34 +000087 virtual void anchor();
David Blaikie9c902b52011-09-25 23:23:43 +000088 DiagnosticsEngine &Diags;
Daniel Dunbarc13935e2008-10-21 23:49:24 +000089 BackendAction Action;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000090 const HeaderSearchOptions &HeaderSearchOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000091 const CodeGenOptions &CodeGenOpts;
Daniel Dunbarde182242009-11-30 08:39:32 +000092 const TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000093 const LangOptions &LangOpts;
Peter Collingbourne03f89072016-07-15 00:55:40 +000094 std::unique_ptr<raw_pwrite_stream> AsmOutStream;
Chris Lattnereae6cb62009-03-05 08:00:35 +000095 ASTContext *Context;
Nico Weberade321e2018-04-10 18:53:28 +000096
97 Timer LLVMIRGeneration;
98 unsigned LLVMIRGenerationRefCount;
Mike Stump11289f42009-09-09 15:08:12 +000099
Reid Kleckner15241ba2016-11-30 00:25:36 +0000100 /// True if we've finished generating IR. This prevents us from generating
101 /// additional LLVM IR after emitting output in HandleTranslationUnit. This
102 /// can happen when Clang plugins trigger additional AST deserialization.
103 bool IRGenFinished = false;
104
Ahmed Charlesb8984322014-03-07 20:03:18 +0000105 std::unique_ptr<CodeGenerator> Gen;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Justin Lebarb080b632017-01-25 21:29:48 +0000107 SmallVector<LinkModule, 4> LinkModules;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000108
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000109 // This is here so that the diagnostic printer knows the module a diagnostic
110 // refers to.
111 llvm::Module *CurLinkModule = nullptr;
112
Mike Stump11289f42009-09-09 15:08:12 +0000113 public:
Justin Lebarb080b632017-01-25 21:29:48 +0000114 BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
115 const HeaderSearchOptions &HeaderSearchOpts,
116 const PreprocessorOptions &PPOpts,
117 const CodeGenOptions &CodeGenOpts,
118 const TargetOptions &TargetOpts,
119 const LangOptions &LangOpts, bool TimePasses,
120 const std::string &InFile,
121 SmallVector<LinkModule, 4> LinkModules,
122 std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
123 CoverageSourceInfo *CoverageInfo = nullptr)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000124 : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
125 CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000126 AsmOutStream(std::move(OS)), Context(nullptr),
Nico Weberade321e2018-04-10 18:53:28 +0000127 LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
128 LLVMIRGenerationRefCount(0),
Adrian Prantle74f5252015-06-30 02:26:03 +0000129 Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
Justin Lebarb080b632017-01-25 21:29:48 +0000130 CodeGenOpts, C, CoverageInfo)),
131 LinkModules(std::move(LinkModules)) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000132 FrontendTimesIsEnabled = TimePasses;
Craig Topper2a92a0e2018-08-08 19:14:23 +0000133 llvm::TimePassesIsEnabled = TimePasses;
Chris Lattnerdeffa132009-02-18 01:23:44 +0000134 }
Serge Pavlov41c1f792016-02-18 16:42:09 +0000135 llvm::Module *getModule() const { return Gen->GetModule(); }
136 std::unique_ptr<llvm::Module> takeModule() {
137 return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
138 }
Daniel Dunbar400a6932010-02-25 04:37:50 +0000139
Amjad Aboud546bc112017-02-09 22:07:24 +0000140 CodeGenerator *getCodeGenerator() { return Gen.get(); }
141
Craig Topper4f12f102014-03-12 06:41:41 +0000142 void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
Rafael Espindoladf88f6f2012-03-08 15:51:03 +0000143 Gen->HandleCXXStaticMemberVarInstantiation(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +0000144 }
145
Craig Topper4f12f102014-03-12 06:41:41 +0000146 void Initialize(ASTContext &Ctx) override {
Richard Smith293534b2015-08-18 20:39:29 +0000147 assert(!Context && "initialized multiple times");
Nico Weberade321e2018-04-10 18:53:28 +0000148
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000149 Context = &Ctx;
Nico Weberade321e2018-04-10 18:53:28 +0000150
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000151 if (FrontendTimesIsEnabled)
Nico Weberade321e2018-04-10 18:53:28 +0000152 LLVMIRGeneration.startTimer();
153
Chris Lattner5cf49fe2009-03-28 02:18:25 +0000154 Gen->Initialize(Ctx);
Nico Weberade321e2018-04-10 18:53:28 +0000155
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000156 if (FrontendTimesIsEnabled)
Nico Weberade321e2018-04-10 18:53:28 +0000157 LLVMIRGeneration.stopTimer();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000158 }
Mike Stump11289f42009-09-09 15:08:12 +0000159
Craig Topper4f12f102014-03-12 06:41:41 +0000160 bool HandleTopLevelDecl(DeclGroupRef D) override {
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000161 PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
Chris Lattnereae6cb62009-03-05 08:00:35 +0000162 Context->getSourceManager(),
163 "LLVM IR generation of declaration");
Nico Weberade321e2018-04-10 18:53:28 +0000164
165 // Recurse.
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000166 if (FrontendTimesIsEnabled) {
Nico Weberade321e2018-04-10 18:53:28 +0000167 LLVMIRGenerationRefCount += 1;
168 if (LLVMIRGenerationRefCount == 1)
169 LLVMIRGeneration.startTimer();
170 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000171
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000172 Gen->HandleTopLevelDecl(D);
Nico Weberade321e2018-04-10 18:53:28 +0000173
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000174 if (FrontendTimesIsEnabled) {
Nico Weberade321e2018-04-10 18:53:28 +0000175 LLVMIRGenerationRefCount -= 1;
176 if (LLVMIRGenerationRefCount == 0)
177 LLVMIRGeneration.stopTimer();
178 }
179
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000180 return true;
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000181 }
Mike Stump11289f42009-09-09 15:08:12 +0000182
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000183 void HandleInlineFunctionDefinition(FunctionDecl *D) override {
Hans Wennborga926d842014-05-23 20:37:38 +0000184 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
185 Context->getSourceManager(),
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000186 "LLVM IR generation of inline function");
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000187 if (FrontendTimesIsEnabled)
Nico Weberade321e2018-04-10 18:53:28 +0000188 LLVMIRGeneration.startTimer();
Hans Wennborga926d842014-05-23 20:37:38 +0000189
Stephan Bergmann17d7d142016-03-30 06:27:31 +0000190 Gen->HandleInlineFunctionDefinition(D);
Nico Weberade321e2018-04-10 18:53:28 +0000191
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000192 if (FrontendTimesIsEnabled)
Nico Weberade321e2018-04-10 18:53:28 +0000193 LLVMIRGeneration.stopTimer();
Hans Wennborga926d842014-05-23 20:37:38 +0000194 }
195
Reid Kleckner68c4bb52016-11-30 01:32:53 +0000196 void HandleInterestingDecl(DeclGroupRef D) override {
Reid Kleckner15241ba2016-11-30 00:25:36 +0000197 // Ignore interesting decls from the AST reader after IRGen is finished.
198 if (!IRGenFinished)
199 HandleTopLevelDecl(D);
200 }
201
Justin Lebarb080b632017-01-25 21:29:48 +0000202 // Links each entry in LinkModules into our module. Returns true on error.
203 bool LinkInModules() {
204 for (auto &LM : LinkModules) {
205 if (LM.PropagateAttrs)
206 for (Function &F : *LM.Module)
207 Gen->CGM().AddDefaultFnAttrs(F);
208
209 CurLinkModule = LM.Module.get();
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000210
211 bool Err;
212 if (LM.Internalize) {
213 Err = Linker::linkModules(
214 *getModule(), std::move(LM.Module), LM.LinkFlags,
215 [](llvm::Module &M, const llvm::StringSet<> &GVS) {
Reid Kleckner987a2812017-03-13 22:33:07 +0000216 internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000217 return !GV.hasName() || (GVS.count(GV.getName()) == 0);
218 });
219 });
220 } else {
221 Err = Linker::linkModules(*getModule(), std::move(LM.Module),
222 LM.LinkFlags);
223 }
224
225 if (Err)
Justin Lebarb080b632017-01-25 21:29:48 +0000226 return true;
227 }
228 return false; // success
229 }
230
Craig Topper4f12f102014-03-12 06:41:41 +0000231 void HandleTranslationUnit(ASTContext &C) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000232 {
Anton Afanasyev3f3a2572019-08-19 22:58:26 +0000233 llvm::TimeTraceScope TimeScope("Frontend", StringRef(""));
Chris Lattnere46de752009-03-06 06:46:31 +0000234 PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000235 if (FrontendTimesIsEnabled) {
Nico Weberade321e2018-04-10 18:53:28 +0000236 LLVMIRGenerationRefCount += 1;
237 if (LLVMIRGenerationRefCount == 1)
238 LLVMIRGeneration.startTimer();
239 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000240
Chris Lattnercf169832009-03-28 04:11:33 +0000241 Gen->HandleTranslationUnit(C);
Nico Weberade321e2018-04-10 18:53:28 +0000242
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000243 if (FrontendTimesIsEnabled) {
Nico Weberade321e2018-04-10 18:53:28 +0000244 LLVMIRGenerationRefCount -= 1;
245 if (LLVMIRGenerationRefCount == 0)
246 LLVMIRGeneration.stopTimer();
247 }
248
Fangrui Song99337e22018-07-20 08:19:20 +0000249 IRGenFinished = true;
Chris Lattnereae6cb62009-03-05 08:00:35 +0000250 }
Chris Lattner263d64c2009-02-18 01:37:30 +0000251
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000252 // Silently ignore if we weren't initialized for some reason.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000253 if (!getModule())
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000254 return;
Mike Stump11289f42009-09-09 15:08:12 +0000255
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000256 // Install an inline asm handler so that diagnostics get printed through
257 // our diagnostics hooks.
Serge Pavlov41c1f792016-02-18 16:42:09 +0000258 LLVMContext &Ctx = getModule()->getContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000259 LLVMContext::InlineAsmDiagHandlerTy OldHandler =
260 Ctx.getInlineAsmDiagnosticHandler();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000261 void *OldContext = Ctx.getInlineAsmDiagnosticContext();
Chris Lattner068f2ab2010-11-17 08:13:04 +0000262 Ctx.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, this);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000263
Vivek Pandya1dee3be2017-09-15 20:09:55 +0000264 std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
Quentin Colombet728c5542014-02-06 18:30:43 +0000265 Ctx.getDiagnosticHandler();
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000266 Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
Vivek Pandya1dee3be2017-09-15 20:09:55 +0000267 CodeGenOpts, this));
Quentin Colombet728c5542014-02-06 18:30:43 +0000268
Francis Visoiu Mistrih7a211132019-06-14 16:20:51 +0000269 Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
270 setupOptimizationRemarks(Ctx, CodeGenOpts.OptRecordFile,
271 CodeGenOpts.OptRecordPasses,
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +0000272 CodeGenOpts.OptRecordFormat,
Francis Visoiu Mistrih7a211132019-06-14 16:20:51 +0000273 CodeGenOpts.DiagnosticsWithHotness,
274 CodeGenOpts.DiagnosticsHotnessThreshold);
Hal Finkel8f96e822016-10-11 00:26:09 +0000275
Francis Visoiu Mistrih7a211132019-06-14 16:20:51 +0000276 if (Error E = OptRecordFileOrErr.takeError()) {
277 handleAllErrors(
278 std::move(E),
279 [&](const RemarkSetupFileError &E) {
280 Diags.Report(diag::err_cannot_open_file)
281 << CodeGenOpts.OptRecordFile << E.message();
282 },
283 [&](const RemarkSetupPatternError &E) {
284 Diags.Report(diag::err_drv_optimization_remark_pattern)
285 << E.message() << CodeGenOpts.OptRecordPasses;
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +0000286 },
287 [&](const RemarkSetupFormatError &E) {
288 Diags.Report(diag::err_drv_optimization_remark_format)
289 << CodeGenOpts.OptRecordFormat;
Francis Visoiu Mistrih7a211132019-06-14 16:20:51 +0000290 });
291 return;
Hal Finkel8f96e822016-10-11 00:26:09 +0000292 }
Francis Visoiu Mistrih7a211132019-06-14 16:20:51 +0000293 std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
294 std::move(*OptRecordFileOrErr);
295
296 if (OptRecordFile &&
297 CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone)
298 Ctx.setDiagnosticsHotnessRequested(true);
Hal Finkel8f96e822016-10-11 00:26:09 +0000299
Justin Lebarb080b632017-01-25 21:29:48 +0000300 // Link each LinkModule into our module.
301 if (LinkInModules())
302 return;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000303
Steven Wu27fb5222016-05-11 16:26:03 +0000304 EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
305
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000306 EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
307 LangOpts, C.getTargetInfo().getDataLayout(),
Peter Collingbourne03f89072016-07-15 00:55:40 +0000308 getModule(), Action, std::move(AsmOutStream));
Rafael Espindola666a2ab2013-12-18 16:38:48 +0000309
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000310 Ctx.setInlineAsmDiagnosticHandler(OldHandler, OldContext);
Quentin Colombet728c5542014-02-06 18:30:43 +0000311
Vivek Pandya1dee3be2017-09-15 20:09:55 +0000312 Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
Hal Finkel8f96e822016-10-11 00:26:09 +0000313
314 if (OptRecordFile)
315 OptRecordFile->keep();
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000316 }
Mike Stump11289f42009-09-09 15:08:12 +0000317
Craig Topper4f12f102014-03-12 06:41:41 +0000318 void HandleTagDeclDefinition(TagDecl *D) override {
Chris Lattnereae6cb62009-03-05 08:00:35 +0000319 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
320 Context->getSourceManager(),
321 "LLVM IR generation of declaration");
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000322 Gen->HandleTagDeclDefinition(D);
323 }
Douglas Gregorbeecd582009-04-21 17:11:58 +0000324
Craig Topper4f12f102014-03-12 06:41:41 +0000325 void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
David Blaikie48ad6dc2013-07-13 21:08:14 +0000326 Gen->HandleTagDeclRequiredDefinition(D);
327 }
328
Craig Topper4f12f102014-03-12 06:41:41 +0000329 void CompleteTentativeDefinition(VarDecl *D) override {
Douglas Gregorbeecd582009-04-21 17:11:58 +0000330 Gen->CompleteTentativeDefinition(D);
331 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000332
David Majnemer929025d2016-01-26 19:30:26 +0000333 void AssignInheritanceModel(CXXRecordDecl *RD) override {
334 Gen->AssignInheritanceModel(RD);
335 }
336
Nico Weberb6a5d052015-01-15 04:07:35 +0000337 void HandleVTable(CXXRecordDecl *RD) override {
338 Gen->HandleVTable(RD);
Douglas Gregor88d292c2010-05-13 16:44:06 +0000339 }
340
Chris Lattner5ec32e72010-04-06 18:38:50 +0000341 static void InlineAsmDiagHandler(const llvm::SMDiagnostic &SM,void *Context,
342 unsigned LocCookie) {
343 SourceLocation Loc = SourceLocation::getFromRawEncoding(LocCookie);
344 ((BackendConsumer*)Context)->InlineAsmDiagHandler2(SM, Loc);
345 }
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000346
Oliver Stannard91817852016-02-02 13:52:52 +0000347 /// Get the best possible source location to represent a diagnostic that
348 /// may have associated debug info.
349 const FullSourceLoc
Justin Bognere91e9dd2017-02-17 17:34:49 +0000350 getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
Oliver Stannard91817852016-02-02 13:52:52 +0000351 bool &BadDebugInfo, StringRef &Filename,
352 unsigned &Line, unsigned &Column) const;
353
Chris Lattner5ec32e72010-04-06 18:38:50 +0000354 void InlineAsmDiagHandler2(const llvm::SMDiagnostic &,
355 SourceLocation LocCookie);
Quentin Colombet728c5542014-02-06 18:30:43 +0000356
357 void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000358 /// Specialized handler for InlineAsm diagnostic.
Quentin Colombet728c5542014-02-06 18:30:43 +0000359 /// \return True if the diagnostic has been successfully reported, false
360 /// otherwise.
361 bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000362 /// Specialized handler for StackSize diagnostic.
Quentin Colombet728c5542014-02-06 18:30:43 +0000363 /// \return True if the diagnostic has been successfully reported, false
364 /// otherwise.
365 bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000366 /// Specialized handler for unsupported backend feature diagnostic.
Oliver Stannard91817852016-02-02 13:52:52 +0000367 void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000368 /// Specialized handlers for optimization remarks.
Diego Novillod23ec942014-05-29 19:55:06 +0000369 /// Note that these handlers only accept remarks and they always handle
Diego Novillo829b1702014-04-16 16:54:24 +0000370 /// them.
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000371 void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
372 unsigned DiagID);
Adam Nemet7b796f82017-01-26 04:07:11 +0000373 void
374 OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000375 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000376 const llvm::OptimizationRemarkAnalysisFPCommute &D);
Diego Novillod23ec942014-05-29 19:55:06 +0000377 void OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000378 const llvm::OptimizationRemarkAnalysisAliasing &D);
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000379 void OptimizationFailureHandler(
380 const llvm::DiagnosticInfoOptimizationFailure &D);
Mike Stump11289f42009-09-09 15:08:12 +0000381 };
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000382
David Blaikie68e081d2011-12-20 02:48:34 +0000383 void BackendConsumer::anchor() {}
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000384}
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000385
Vivek Pandya1dee3be2017-09-15 20:09:55 +0000386bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
387 BackendCon->DiagnosticHandlerImpl(DI);
388 return true;
389}
390
Chris Lattner79f67a72010-04-08 00:23:06 +0000391/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
392/// buffer to be a valid FullSourceLoc.
393static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
394 SourceManager &CSM) {
395 // Get both the clang and llvm source managers. The location is relative to
396 // a memory buffer that the LLVM Source Manager is handling, we need to add
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000397 // a copy to the Clang source manager.
Chris Lattner79f67a72010-04-08 00:23:06 +0000398 const llvm::SourceMgr &LSM = *D.getSourceMgr();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000399
Chris Lattner79f67a72010-04-08 00:23:06 +0000400 // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
401 // already owns its one and clang::SourceManager wants to own its one.
402 const MemoryBuffer *LBuf =
403 LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000404
Chris Lattner79f67a72010-04-08 00:23:06 +0000405 // Create the copy and transfer ownership to clang::SourceManager.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000406 // TODO: Avoid copying files into memory.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000407 std::unique_ptr<llvm::MemoryBuffer> CBuf =
408 llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
409 LBuf->getBufferIdentifier());
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000410 // FIXME: Keep a file ID map instead of creating new IDs for each location.
David Blaikie50a5f972014-08-29 07:59:55 +0000411 FileID FID = CSM.createFileID(std::move(CBuf));
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000412
Chris Lattner79f67a72010-04-08 00:23:06 +0000413 // Translate the offset into the file.
Alp Tokeraa0dd5a2014-06-27 06:02:00 +0000414 unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000415 SourceLocation NewLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000416 CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
Chris Lattner79f67a72010-04-08 00:23:06 +0000417 return FullSourceLoc(NewLoc, CSM);
418}
419
Chris Lattner6d672132010-04-06 17:52:14 +0000420
Chris Lattner5ec32e72010-04-06 18:38:50 +0000421/// InlineAsmDiagHandler2 - This function is invoked when the backend hits an
422/// error parsing inline asm. The SMDiagnostic indicates the error relative to
Daniel Dunbar50aa0a52010-04-29 16:29:09 +0000423/// the temporary memory buffer that the inline asm parser has set up.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000424void BackendConsumer::InlineAsmDiagHandler2(const llvm::SMDiagnostic &D,
425 SourceLocation LocCookie) {
426 // There are a couple of different kinds of errors we could get here. First,
427 // we re-format the SMDiagnostic in terms of a clang diagnostic.
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000428
429 // Strip "error: " off the start of the message string.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000430 StringRef Message = D.getMessage();
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000431 if (Message.startswith("error: "))
432 Message = Message.substr(7);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000433
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000434 // If the SMDiagnostic has an inline asm source location, translate it.
Chris Lattner5ec32e72010-04-06 18:38:50 +0000435 FullSourceLoc Loc;
Chris Lattner79f67a72010-04-08 00:23:06 +0000436 if (D.getLoc() != SMLoc())
437 Loc = ConvertBackendLocation(D, Context->getSourceManager());
Argyrios Kyrtzidisa11b35a2012-02-01 06:36:49 +0000438
Joey Gouly5798b262014-06-05 21:23:42 +0000439 unsigned DiagID;
440 switch (D.getKind()) {
441 case llvm::SourceMgr::DK_Error:
442 DiagID = diag::err_fe_inline_asm;
443 break;
444 case llvm::SourceMgr::DK_Warning:
445 DiagID = diag::warn_fe_inline_asm;
446 break;
447 case llvm::SourceMgr::DK_Note:
448 DiagID = diag::note_fe_inline_asm;
449 break;
Adam Nemet7b1faaa2017-10-12 23:56:54 +0000450 case llvm::SourceMgr::DK_Remark:
451 llvm_unreachable("remarks unexpected");
Joey Gouly5798b262014-06-05 21:23:42 +0000452 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000453 // If this problem has clang-level source location information, report the
Joey Gouly5798b262014-06-05 21:23:42 +0000454 // issue in the source with a note showing the instantiated
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000455 // code.
456 if (LocCookie.isValid()) {
Joey Gouly5798b262014-06-05 21:23:42 +0000457 Diags.Report(LocCookie, DiagID).AddString(Message);
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000458
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000459 if (D.getLoc().isValid()) {
460 DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
461 // Convert the SMDiagnostic ranges into SourceRange and attach them
462 // to the diagnostic.
Yaron Kerenede60302015-08-01 19:11:36 +0000463 for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
Benjamin Kramere06b2b72011-10-16 10:48:28 +0000464 unsigned Column = D.getColumnNo();
465 B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
466 Loc.getLocWithOffset(Range.second - Column));
467 }
468 }
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000469 return;
470 }
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000471
Joey Gouly5798b262014-06-05 21:23:42 +0000472 // Otherwise, report the backend issue as occurring in the generated .s file.
473 // If Loc is invalid, we still need to report the issue, it just gets no
Chris Lattnerc7ed7ea2010-06-15 00:03:12 +0000474 // location info.
Joey Gouly5798b262014-06-05 21:23:42 +0000475 Diags.Report(Loc, DiagID).AddString(Message);
Chris Lattner5ec32e72010-04-06 18:38:50 +0000476}
477
Quentin Colombet728c5542014-02-06 18:30:43 +0000478#define ComputeDiagID(Severity, GroupName, DiagID) \
479 do { \
480 switch (Severity) { \
481 case llvm::DS_Error: \
482 DiagID = diag::err_fe_##GroupName; \
483 break; \
484 case llvm::DS_Warning: \
485 DiagID = diag::warn_fe_##GroupName; \
486 break; \
Tobias Grosser74160242014-02-28 09:11:08 +0000487 case llvm::DS_Remark: \
488 llvm_unreachable("'remark' severity not expected"); \
489 break; \
490 case llvm::DS_Note: \
491 DiagID = diag::note_fe_##GroupName; \
492 break; \
493 } \
494 } while (false)
495
496#define ComputeDiagRemarkID(Severity, GroupName, DiagID) \
497 do { \
498 switch (Severity) { \
499 case llvm::DS_Error: \
500 DiagID = diag::err_fe_##GroupName; \
501 break; \
502 case llvm::DS_Warning: \
503 DiagID = diag::warn_fe_##GroupName; \
504 break; \
505 case llvm::DS_Remark: \
506 DiagID = diag::remark_fe_##GroupName; \
507 break; \
Quentin Colombet728c5542014-02-06 18:30:43 +0000508 case llvm::DS_Note: \
509 DiagID = diag::note_fe_##GroupName; \
510 break; \
511 } \
512 } while (false)
513
514bool
515BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
516 unsigned DiagID;
517 ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
518 std::string Message = D.getMsgStr().str();
519
520 // If this problem has clang-level source location information, report the
Tobias Grosserbd25beb2014-02-26 10:21:56 +0000521 // issue as being a problem in the source with a note showing the instantiated
Quentin Colombet728c5542014-02-06 18:30:43 +0000522 // code.
523 SourceLocation LocCookie =
524 SourceLocation::getFromRawEncoding(D.getLocCookie());
525 if (LocCookie.isValid())
526 Diags.Report(LocCookie, DiagID).AddString(Message);
527 else {
528 // Otherwise, report the backend diagnostic as occurring in the generated
529 // .s file.
530 // If Loc is invalid, we still need to report the diagnostic, it just gets
531 // no location info.
532 FullSourceLoc Loc;
533 Diags.Report(Loc, DiagID).AddString(Message);
534 }
535 // We handled all the possible severities.
536 return true;
537}
538
539bool
540BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
541 if (D.getSeverity() != llvm::DS_Warning)
542 // For now, the only support we have for StackSize diagnostic is warning.
543 // We do not know how to format other severities.
544 return false;
545
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000546 if (const Decl *ND = Gen->GetDeclForMangledName(D.getFunction().getName())) {
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000547 // FIXME: Shouldn't need to truncate to uint32_t
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000548 Diags.Report(ND->getASTContext().getFullLoc(ND->getLocation()),
549 diag::warn_fe_frame_larger_than)
Matt Arsenault4deb4ed22016-06-20 18:13:09 +0000550 << static_cast<uint32_t>(D.getStackSize()) << Decl::castToDeclContext(ND);
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000551 return true;
552 }
553
554 return false;
Quentin Colombet728c5542014-02-06 18:30:43 +0000555}
556
Oliver Stannard91817852016-02-02 13:52:52 +0000557const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
Justin Bognere91e9dd2017-02-17 17:34:49 +0000558 const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
559 StringRef &Filename, unsigned &Line, unsigned &Column) const {
Diego Novillod23ec942014-05-29 19:55:06 +0000560 SourceManager &SourceMgr = Context->getSourceManager();
561 FileManager &FileMgr = SourceMgr.getFileManager();
Alp Toker27506272014-06-05 22:11:12 +0000562 SourceLocation DILoc;
Diego Novillo86f884e2015-05-08 20:59:56 +0000563
564 if (D.isLocationAvailable()) {
Adrian Prantl212c1042018-12-06 18:44:50 +0000565 D.getLocation(Filename, Line, Column);
566 if (Line > 0) {
Harlan Haskins8d323d12019-08-01 21:31:56 +0000567 auto FE = FileMgr.getFile(Filename);
Adrian Prantl212c1042018-12-06 18:44:50 +0000568 if (!FE)
569 FE = FileMgr.getFile(D.getAbsolutePath());
570 if (FE) {
571 // If -gcolumn-info was not used, Column will be 0. This upsets the
572 // source manager, so pass 1 if Column is not set.
Harlan Haskins8d323d12019-08-01 21:31:56 +0000573 DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? Column : 1);
Adrian Prantl212c1042018-12-06 18:44:50 +0000574 }
Diego Novillo86f884e2015-05-08 20:59:56 +0000575 }
Oliver Stannard91817852016-02-02 13:52:52 +0000576 BadDebugInfo = DILoc.isInvalid();
Diego Novillo829b1702014-04-16 16:54:24 +0000577 }
Alp Toker27506272014-06-05 22:11:12 +0000578
579 // If a location isn't available, try to approximate it using the associated
580 // function definition. We use the definition's right brace to differentiate
581 // from diagnostics that genuinely relate to the function itself.
582 FullSourceLoc Loc(DILoc, SourceMgr);
583 if (Loc.isInvalid())
584 if (const Decl *FD = Gen->GetDeclForMangledName(D.getFunction().getName()))
Oliver Stannard91817852016-02-02 13:52:52 +0000585 Loc = FD->getASTContext().getFullLoc(FD->getLocation());
Diego Novillod23ec942014-05-29 19:55:06 +0000586
Diego Novillo86f884e2015-05-08 20:59:56 +0000587 if (DILoc.isInvalid() && D.isLocationAvailable())
Diego Novillod23ec942014-05-29 19:55:06 +0000588 // If we were not able to translate the file:line:col information
589 // back to a SourceLocation, at least emit a note stating that
590 // we could not translate this location. This can happen in the
591 // case of #line directives.
Oliver Stannard91817852016-02-02 13:52:52 +0000592 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Ben Craig6e4695a2016-05-06 13:29:46 +0000593 << Filename << Line << Column;
Oliver Stannard91817852016-02-02 13:52:52 +0000594
595 return Loc;
596}
597
598void BackendConsumer::UnsupportedDiagHandler(
599 const llvm::DiagnosticInfoUnsupported &D) {
600 // We only support errors.
601 assert(D.getSeverity() == llvm::DS_Error);
602
603 StringRef Filename;
604 unsigned Line, Column;
Reid Klecknerf70ee602017-05-12 00:10:49 +0000605 bool BadDebugInfo = false;
606 FullSourceLoc Loc =
607 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
Oliver Stannard91817852016-02-02 13:52:52 +0000608
Zachary Turner41a9ee92017-10-11 23:54:34 +0000609 Diags.Report(Loc, diag::err_fe_backend_unsupported) << D.getMessage().str();
Oliver Stannard91817852016-02-02 13:52:52 +0000610
611 if (BadDebugInfo)
612 // If we were not able to translate the file:line:col information
613 // back to a SourceLocation, at least emit a note stating that
614 // we could not translate this location. This can happen in the
615 // case of #line directives.
616 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
617 << Filename << Line << Column;
618}
619
620void BackendConsumer::EmitOptimizationMessage(
621 const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
622 // We only support warnings and remarks.
623 assert(D.getSeverity() == llvm::DS_Remark ||
624 D.getSeverity() == llvm::DS_Warning);
625
626 StringRef Filename;
627 unsigned Line, Column;
628 bool BadDebugInfo = false;
Reid Klecknerf70ee602017-05-12 00:10:49 +0000629 FullSourceLoc Loc =
630 getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
Oliver Stannard91817852016-02-02 13:52:52 +0000631
Adam Nemet1eea3e52016-09-13 04:32:40 +0000632 std::string Msg;
633 raw_string_ostream MsgStream(Msg);
Adam Nemet699fc5b2016-09-27 20:55:12 +0000634 MsgStream << D.getMsg();
Adam Nemet1eea3e52016-09-13 04:32:40 +0000635
636 if (D.getHotness())
637 MsgStream << " (hotness: " << *D.getHotness() << ")";
638
Oliver Stannard91817852016-02-02 13:52:52 +0000639 Diags.Report(Loc, DiagID)
Mehdi Amini117296c2016-10-01 02:56:57 +0000640 << AddFlagValue(D.getPassName())
Adam Nemet1eea3e52016-09-13 04:32:40 +0000641 << MsgStream.str();
Oliver Stannard91817852016-02-02 13:52:52 +0000642
643 if (BadDebugInfo)
644 // If we were not able to translate the file:line:col information
645 // back to a SourceLocation, at least emit a note stating that
646 // we could not translate this location. This can happen in the
647 // case of #line directives.
648 Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
Diego Novillod23ec942014-05-29 19:55:06 +0000649 << Filename << Line << Column;
650}
651
652void BackendConsumer::OptimizationRemarkHandler(
Adam Nemet7b796f82017-01-26 04:07:11 +0000653 const llvm::DiagnosticInfoOptimizationBase &D) {
Adam Nemet28c2c222017-10-04 04:25:31 +0000654 // Without hotness information, don't show noisy remarks.
655 if (D.isVerbose() && !D.getHotness())
656 return;
657
Adam Nemet7b796f82017-01-26 04:07:11 +0000658 if (D.isPassed()) {
659 // Optimization remarks are active only if the -Rpass flag has a regular
660 // expression that matches the name of the pass name in \p D.
661 if (CodeGenOpts.OptimizationRemarkPattern &&
662 CodeGenOpts.OptimizationRemarkPattern->match(D.getPassName()))
663 EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
664 } else if (D.isMissed()) {
665 // Missed optimization remarks are active only if the -Rpass-missed
666 // flag has a regular expression that matches the name of the pass
667 // name in \p D.
668 if (CodeGenOpts.OptimizationRemarkMissedPattern &&
669 CodeGenOpts.OptimizationRemarkMissedPattern->match(D.getPassName()))
670 EmitOptimizationMessage(
671 D, diag::remark_fe_backend_optimization_remark_missed);
672 } else {
673 assert(D.isAnalysis() && "Unknown remark type");
Diego Novillod23ec942014-05-29 19:55:06 +0000674
Adam Nemet7b796f82017-01-26 04:07:11 +0000675 bool ShouldAlwaysPrint = false;
676 if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
677 ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
Diego Novillod23ec942014-05-29 19:55:06 +0000678
Adam Nemet7b796f82017-01-26 04:07:11 +0000679 if (ShouldAlwaysPrint ||
680 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
681 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
682 EmitOptimizationMessage(
683 D, diag::remark_fe_backend_optimization_remark_analysis);
684 }
Diego Novillo829b1702014-04-16 16:54:24 +0000685}
686
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000687void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000688 const llvm::OptimizationRemarkAnalysisFPCommute &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000689 // Optimization analysis remarks are active if the pass name is set to
690 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
691 // regular expression that matches the name of the pass name in \p D.
692
Adam Nemetb5beb972016-06-29 04:55:31 +0000693 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000694 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
695 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000696 EmitOptimizationMessage(
697 D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
698}
699
Tyler Nowicki034baf62015-08-10 23:05:16 +0000700void BackendConsumer::OptimizationRemarkHandler(
Adam Nemetb4e64a72016-09-27 22:19:29 +0000701 const llvm::OptimizationRemarkAnalysisAliasing &D) {
Tyler Nowicki65061a22015-08-11 01:10:08 +0000702 // Optimization analysis remarks are active if the pass name is set to
703 // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
704 // regular expression that matches the name of the pass name in \p D.
705
Adam Nemetb5beb972016-06-29 04:55:31 +0000706 if (D.shouldAlwaysPrint() ||
Tyler Nowicki65061a22015-08-11 01:10:08 +0000707 (CodeGenOpts.OptimizationRemarkAnalysisPattern &&
708 CodeGenOpts.OptimizationRemarkAnalysisPattern->match(D.getPassName())))
Tyler Nowicki034baf62015-08-10 23:05:16 +0000709 EmitOptimizationMessage(
710 D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
711}
712
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000713void BackendConsumer::OptimizationFailureHandler(
714 const llvm::DiagnosticInfoOptimizationFailure &D) {
715 EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
716}
717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000718/// This function is invoked when the backend needs
Quentin Colombet728c5542014-02-06 18:30:43 +0000719/// to report something to the user.
720void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
721 unsigned DiagID = diag::err_fe_inline_asm;
722 llvm::DiagnosticSeverity Severity = DI.getSeverity();
723 // Get the diagnostic ID based.
724 switch (DI.getKind()) {
725 case llvm::DK_InlineAsm:
726 if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
727 return;
728 ComputeDiagID(Severity, inline_asm, DiagID);
729 break;
730 case llvm::DK_StackSize:
731 if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
732 return;
733 ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
734 break;
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000735 case DK_Linker:
736 assert(CurLinkModule);
737 // FIXME: stop eating the warnings and notes.
738 if (Severity != DS_Error)
739 return;
740 DiagID = diag::err_fe_cannot_link_module;
741 break;
Diego Novillo829b1702014-04-16 16:54:24 +0000742 case llvm::DK_OptimizationRemark:
743 // Optimization remarks are always handled completely by this
744 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000745 OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
Diego Novillo829b1702014-04-16 16:54:24 +0000746 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000747 case llvm::DK_OptimizationRemarkMissed:
Diego Novillod23ec942014-05-29 19:55:06 +0000748 // Optimization remarks are always handled completely by this
749 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000750 OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
Diego Novillod23ec942014-05-29 19:55:06 +0000751 return;
Diego Novillo9c89ff12014-05-29 16:19:27 +0000752 case llvm::DK_OptimizationRemarkAnalysis:
Diego Novillod23ec942014-05-29 19:55:06 +0000753 // Optimization remarks are always handled completely by this
754 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000755 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
Diego Novillo9c89ff12014-05-29 16:19:27 +0000756 return;
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000757 case llvm::DK_OptimizationRemarkAnalysisFPCommute:
758 // Optimization remarks are always handled completely by this
759 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000760 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
Tyler Nowicki8a0925c2015-08-10 19:56:40 +0000761 return;
Tyler Nowicki034baf62015-08-10 23:05:16 +0000762 case llvm::DK_OptimizationRemarkAnalysisAliasing:
763 // Optimization remarks are always handled completely by this
764 // handler. There is no generic way of emitting them.
Adam Nemetb4e64a72016-09-27 22:19:29 +0000765 OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
Tyler Nowicki034baf62015-08-10 23:05:16 +0000766 return;
Adam Nemet7b796f82017-01-26 04:07:11 +0000767 case llvm::DK_MachineOptimizationRemark:
768 // Optimization remarks are always handled completely by this
769 // handler. There is no generic way of emitting them.
770 OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
771 return;
772 case llvm::DK_MachineOptimizationRemarkMissed:
773 // Optimization remarks are always handled completely by this
774 // handler. There is no generic way of emitting them.
775 OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
776 return;
777 case llvm::DK_MachineOptimizationRemarkAnalysis:
778 // Optimization remarks are always handled completely by this
779 // handler. There is no generic way of emitting them.
780 OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
781 return;
Tyler Nowickif8a767d2014-07-18 19:40:19 +0000782 case llvm::DK_OptimizationFailure:
783 // Optimization failures are always handled completely by this
784 // handler.
785 OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
786 return;
Oliver Stannard91817852016-02-02 13:52:52 +0000787 case llvm::DK_Unsupported:
788 UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
789 return;
Quentin Colombet728c5542014-02-06 18:30:43 +0000790 default:
791 // Plugin IDs are not bound to any value as they are set dynamically.
Tobias Grosser74160242014-02-28 09:11:08 +0000792 ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
Quentin Colombet728c5542014-02-06 18:30:43 +0000793 break;
794 }
795 std::string MsgStorage;
796 {
797 raw_string_ostream Stream(MsgStorage);
798 DiagnosticPrinterRawOStream DP(Stream);
799 DI.print(DP);
800 }
801
Rafael Espindola8ce88a52015-12-14 23:17:07 +0000802 if (DiagID == diag::err_fe_cannot_link_module) {
803 Diags.Report(diag::err_fe_cannot_link_module)
804 << CurLinkModule->getModuleIdentifier() << MsgStorage;
805 return;
806 }
807
Quentin Colombet728c5542014-02-06 18:30:43 +0000808 // Report the backend message using the usual diagnostic mechanism.
809 FullSourceLoc Loc;
810 Diags.Report(Loc, DiagID).AddString(MsgStorage);
811}
812#undef ComputeDiagID
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000813
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000814CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
Artem Belevich5d40ae32015-10-27 17:56:59 +0000815 : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
Eric Christopher02e3dd42016-03-12 01:47:11 +0000816 OwnsVMContext(!_VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000817
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000818CodeGenAction::~CodeGenAction() {
819 TheModule.reset();
820 if (OwnsVMContext)
821 delete VMContext;
822}
Daniel Dunbare8ecf9a2010-02-25 20:37:44 +0000823
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000824bool CodeGenAction::hasIRSupport() const { return true; }
825
Daniel Dunbar400a6932010-02-25 04:37:50 +0000826void CodeGenAction::EndSourceFileAction() {
827 // If the consumer creation failed, do nothing.
828 if (!getCompilerInstance().hasASTConsumer())
829 return;
830
831 // Steal the module from the consumer.
David Blaikie780dd3b2014-08-29 05:08:19 +0000832 TheModule = BEConsumer->takeModule();
Daniel Dunbar400a6932010-02-25 04:37:50 +0000833}
834
Rafael Espindolae8337302014-08-19 14:36:35 +0000835std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
836 return std::move(TheModule);
837}
838
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000839llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
840 OwnsVMContext = false;
841 return VMContext;
842}
843
Peter Collingbourne03f89072016-07-15 00:55:40 +0000844static std::unique_ptr<raw_pwrite_stream>
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000845GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000846 switch (Action) {
847 case Backend_EmitAssembly:
848 return CI.createDefaultOutputFile(false, InFile, "s");
849 case Backend_EmitLL:
850 return CI.createDefaultOutputFile(false, InFile, "ll");
851 case Backend_EmitBC:
852 return CI.createDefaultOutputFile(true, InFile, "bc");
853 case Backend_EmitNothing:
Craig Topper8a13c412014-05-21 05:09:00 +0000854 return nullptr;
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000855 case Backend_EmitMCNull:
Alp Tokerea046722014-06-03 17:23:34 +0000856 return CI.createNullOutputFile();
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000857 case Backend_EmitObj:
858 return CI.createDefaultOutputFile(true, InFile, "o");
859 }
860
David Blaikie83d382b2011-09-23 05:06:16 +0000861 llvm_unreachable("Invalid action!");
Daniel Dunbar6f8362c2010-06-07 23:27:59 +0000862}
863
David Blaikie6beb6aa2014-08-10 19:56:51 +0000864std::unique_ptr<ASTConsumer>
865CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000866 BackendAction BA = static_cast<BackendAction>(Act);
Alexey Sotkinaba98fc2018-03-02 12:11:40 +0000867 std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
868 if (!OS)
869 OS = GetOutputStream(CI, InFile, BA);
870
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000871 if (BA != Backend_EmitNothing && !OS)
Craig Topper8a13c412014-05-21 05:09:00 +0000872 return nullptr;
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000873
Artem Belevich5d40ae32015-10-27 17:56:59 +0000874 // Load bitcode modules to link with, if we need to.
875 if (LinkModules.empty())
Justin Lebarb080b632017-01-25 21:29:48 +0000876 for (const CodeGenOptions::BitcodeFileToLink &F :
877 CI.getCodeGenOpts().LinkBitcodeFiles) {
878 auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
Artem Belevich5d40ae32015-10-27 17:56:59 +0000879 if (!BCBuf) {
880 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Justin Lebarb080b632017-01-25 21:29:48 +0000881 << F.Filename << BCBuf.getError().message();
Artem Belevich5d40ae32015-10-27 17:56:59 +0000882 LinkModules.clear();
883 return nullptr;
884 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000885
Peter Collingbourned9445c42016-11-13 07:00:17 +0000886 Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
Peter Collingbournee2dcf7c2016-11-08 06:03:43 +0000887 getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000888 if (!ModuleOrErr) {
889 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
890 CI.getDiagnostics().Report(diag::err_cannot_open_file)
Justin Lebarb080b632017-01-25 21:29:48 +0000891 << F.Filename << EIB.message();
Peter Collingbourned9445c42016-11-13 07:00:17 +0000892 });
Artem Belevich5d40ae32015-10-27 17:56:59 +0000893 LinkModules.clear();
894 return nullptr;
895 }
Jonas Devlieghere5eb9c812017-03-13 18:08:11 +0000896 LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
897 F.Internalize, F.LinkFlags});
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000898 }
Peter Collingbournef1d76db2011-10-30 17:30:44 +0000899
Alex Lorenzee024992014-08-04 18:41:51 +0000900 CoverageSourceInfo *CoverageInfo = nullptr;
901 // Add the preprocessor callback only when the coverage mapping is generated.
902 if (CI.getCodeGenOpts().CoverageMapping) {
903 CoverageInfo = new CoverageSourceInfo;
Craig Topperb8a70532014-09-10 04:53:53 +0000904 CI.getPreprocessor().addPPCallbacks(
905 std::unique_ptr<PPCallbacks>(CoverageInfo));
Alex Lorenzee024992014-08-04 18:41:51 +0000906 }
Artem Belevich5d40ae32015-10-27 17:56:59 +0000907
David Blaikie037e75b2014-08-10 21:06:17 +0000908 std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
Adrian Prantle74f5252015-06-30 02:26:03 +0000909 BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
910 CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
Justin Lebarb080b632017-01-25 21:29:48 +0000911 CI.getLangOpts(), CI.getFrontendOpts().ShowTimers, InFile,
912 std::move(LinkModules), std::move(OS), *VMContext, CoverageInfo));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000913 BEConsumer = Result.get();
Amjad Aboud546bc112017-02-09 22:07:24 +0000914
915 // Enable generating macro debug info only when debug info is not disabled and
916 // also macro debug info is enabled.
917 if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
918 CI.getCodeGenOpts().MacroDebugInfo) {
919 std::unique_ptr<PPCallbacks> Callbacks =
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000920 std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
Amjad Aboud546bc112017-02-09 22:07:24 +0000921 CI.getPreprocessor());
922 CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
923 }
924
David Blaikie6beb6aa2014-08-10 19:56:51 +0000925 return std::move(Result);
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000926}
Daniel Dunbarcea0c702010-02-25 04:37:45 +0000927
Tim Northover1390b442016-04-06 19:58:07 +0000928static void BitcodeInlineAsmDiagHandler(const llvm::SMDiagnostic &SM,
929 void *Context,
930 unsigned LocCookie) {
931 SM.print(nullptr, llvm::errs());
932
933 auto Diags = static_cast<DiagnosticsEngine *>(Context);
934 unsigned DiagID;
935 switch (SM.getKind()) {
936 case llvm::SourceMgr::DK_Error:
937 DiagID = diag::err_fe_inline_asm;
938 break;
939 case llvm::SourceMgr::DK_Warning:
940 DiagID = diag::warn_fe_inline_asm;
941 break;
942 case llvm::SourceMgr::DK_Note:
943 DiagID = diag::note_fe_inline_asm;
944 break;
Adam Nemet7b1faaa2017-10-12 23:56:54 +0000945 case llvm::SourceMgr::DK_Remark:
946 llvm_unreachable("remarks unexpected");
Tim Northover1390b442016-04-06 19:58:07 +0000947 }
948
949 Diags->Report(DiagID).AddString("cannot compile inline asm");
950}
951
Nico Weber04347d82019-04-04 21:06:41 +0000952std::unique_ptr<llvm::Module>
953CodeGenAction::loadModule(MemoryBufferRef MBRef) {
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000954 CompilerInstance &CI = getCompilerInstance();
955 SourceManager &SM = CI.getSourceManager();
956
957 // For ThinLTO backend invocations, ensure that the context
Peter Collingbournef5d17122017-01-26 21:09:48 +0000958 // merges types based on ODR identifiers. We also need to read
959 // the correct module out of a multi-module bitcode file.
960 if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000961 VMContext->enableDebugTypeODRUniquing();
962
Peter Collingbournef5d17122017-01-26 21:09:48 +0000963 auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
964 unsigned DiagID =
965 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
966 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
967 CI.getDiagnostics().Report(DiagID) << EIB.message();
968 });
969 return {};
970 };
971
Vitaly Bukac35ff822018-02-16 23:34:16 +0000972 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
973 if (!BMsOrErr)
974 return DiagErrors(BMsOrErr.takeError());
975 BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr);
976 // We have nothing to do if the file contains no ThinLTO module. This is
977 // possible if ThinLTO compilation was not able to split module. Content of
978 // the file was already processed by indexing and will be passed to the
979 // linker using merged object file.
980 if (!Bm) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000981 auto M = std::make_unique<llvm::Module>("empty", *VMContext);
Vitaly Bukac35ff822018-02-16 23:34:16 +0000982 M->setTargetTriple(CI.getTargetOpts().Triple);
983 return M;
984 }
Peter Collingbournef5d17122017-01-26 21:09:48 +0000985 Expected<std::unique_ptr<llvm::Module>> MOrErr =
Vitaly Bukac35ff822018-02-16 23:34:16 +0000986 Bm->parseModule(*VMContext);
Peter Collingbournef5d17122017-01-26 21:09:48 +0000987 if (!MOrErr)
988 return DiagErrors(MOrErr.takeError());
989 return std::move(*MOrErr);
990 }
991
Peter Collingbourne65cb42c2017-01-24 19:55:38 +0000992 llvm::SMDiagnostic Err;
993 if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
994 return M;
995
996 // Translate from the diagnostic info to the SourceManager location if
997 // available.
998 // TODO: Unify this with ConvertBackendLocation()
999 SourceLocation Loc;
1000 if (Err.getLineNo() > 0) {
1001 assert(Err.getColumnNo() >= 0);
1002 Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1003 Err.getLineNo(), Err.getColumnNo() + 1);
1004 }
1005
1006 // Strip off a leading diagnostic code if there is one.
1007 StringRef Msg = Err.getMessage();
1008 if (Msg.startswith("error: "))
1009 Msg = Msg.substr(7);
1010
1011 unsigned DiagID =
1012 CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1013
1014 CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1015 return {};
1016}
1017
Daniel Dunbar6f8362c2010-06-07 23:27:59 +00001018void CodeGenAction::ExecuteAction() {
1019 // If this is an IR file, we have to treat it specially.
Rainer Orth09d890d2019-08-05 13:59:26 +00001020 if (getCurrentFileKind().getLanguage() == Language::LLVM_IR) {
Daniel Dunbar6f8362c2010-06-07 23:27:59 +00001021 BackendAction BA = static_cast<BackendAction>(Act);
1022 CompilerInstance &CI = getCompilerInstance();
Peter Collingbourne03f89072016-07-15 00:55:40 +00001023 std::unique_ptr<raw_pwrite_stream> OS =
1024 GetOutputStream(CI, getCurrentFile(), BA);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +00001025 if (BA != Backend_EmitNothing && !OS)
1026 return;
1027
1028 bool Invalid;
1029 SourceManager &SM = CI.getSourceManager();
Alp Toker7b463d52014-06-30 01:33:59 +00001030 FileID FID = SM.getMainFileID();
Nico Weber04347d82019-04-04 21:06:41 +00001031 const llvm::MemoryBuffer *MainFile = SM.getBuffer(FID, &Invalid);
Daniel Dunbar6f8362c2010-06-07 23:27:59 +00001032 if (Invalid)
1033 return;
1034
Peter Collingbourne65cb42c2017-01-24 19:55:38 +00001035 TheModule = loadModule(*MainFile);
1036 if (!TheModule)
Daniel Dunbar6f8362c2010-06-07 23:27:59 +00001037 return;
Peter Collingbourne65cb42c2017-01-24 19:55:38 +00001038
Rafael Espindolad5e81e52013-12-20 22:01:25 +00001039 const TargetOptions &TargetOpts = CI.getTargetOpts();
1040 if (TheModule->getTargetTriple() != TargetOpts.Triple) {
Nico Weber6cf2df22015-01-29 06:25:59 +00001041 CI.getDiagnostics().Report(SourceLocation(),
1042 diag::warn_fe_override_module)
1043 << TargetOpts.Triple;
Rafael Espindolad5e81e52013-12-20 22:01:25 +00001044 TheModule->setTargetTriple(TargetOpts.Triple);
1045 }
Daniel Dunbar6f8362c2010-06-07 23:27:59 +00001046
Steven Wu27fb5222016-05-11 16:26:03 +00001047 EmbedBitcode(TheModule.get(), CI.getCodeGenOpts(),
1048 MainFile->getMemBufferRef());
1049
Tim Northover1390b442016-04-06 19:58:07 +00001050 LLVMContext &Ctx = TheModule->getContext();
1051 Ctx.setInlineAsmDiagnosticHandler(BitcodeInlineAsmDiagHandler,
1052 &CI.getDiagnostics());
Steven Wu27fb5222016-05-11 16:26:03 +00001053
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001054 EmitBackendOutput(CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1055 CI.getCodeGenOpts(), TargetOpts, CI.getLangOpts(),
1056 CI.getTarget().getDataLayout(), TheModule.get(), BA,
1057 std::move(OS));
Daniel Dunbar6f8362c2010-06-07 23:27:59 +00001058 return;
1059 }
1060
1061 // Otherwise follow the normal AST path.
1062 this->ASTFrontendAction::ExecuteAction();
1063}
1064
1065//
1066
David Blaikie68e081d2011-12-20 02:48:34 +00001067void EmitAssemblyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001068EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1069 : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001070
David Blaikie68e081d2011-12-20 02:48:34 +00001071void EmitBCAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001072EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1073 : CodeGenAction(Backend_EmitBC, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001074
David Blaikie68e081d2011-12-20 02:48:34 +00001075void EmitLLVMAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001076EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1077 : CodeGenAction(Backend_EmitLL, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001078
David Blaikie68e081d2011-12-20 02:48:34 +00001079void EmitLLVMOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001080EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1081 : CodeGenAction(Backend_EmitNothing, _VMContext) {}
Daniel Dunbarcea0c702010-02-25 04:37:45 +00001082
David Blaikie68e081d2011-12-20 02:48:34 +00001083void EmitCodeGenOnlyAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001084EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1085 : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
Daniel Dunbar4c77a642010-05-25 18:41:01 +00001086
David Blaikie68e081d2011-12-20 02:48:34 +00001087void EmitObjAction::anchor() { }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001088EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1089 : CodeGenAction(Backend_EmitObj, _VMContext) {}