blob: b6ca46e7e83511a95297e6570f5f2641b4bd1895 [file] [log] [blame]
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2//
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 Dunbarf976d1b2010-06-07 23:20:08 +00006//
7//===----------------------------------------------------------------------===//
8
Daniel Dunbarc1b17292010-06-15 17:48:49 +00009#include "clang/CodeGen/BackendUtil.h"
Richard Trieu63688182018-12-11 03:18:39 +000010#include "clang/Basic/CodeGenOptions.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000011#include "clang/Basic/Diagnostic.h"
Dan Gohmanfec0ff82011-07-05 22:02:36 +000012#include "clang/Basic/LangOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/Basic/TargetOptions.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000014#include "clang/Frontend/FrontendDiagnostic.h"
Kostya Serebryanyce2c7262013-12-27 08:11:08 +000015#include "clang/Frontend/Utils.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000016#include "clang/Lex/HeaderSearchOptions.h"
Hal Finkel1a328f52016-12-15 02:19:17 +000017#include "llvm/ADT/SmallSet.h"
Eric Christopher583a1f72015-09-26 01:25:08 +000018#include "llvm/ADT/StringExtras.h"
Saleem Abdulrasool62849c62014-05-08 02:28:32 +000019#include "llvm/ADT/StringSwitch.h"
Steven Wu27fb5222016-05-11 16:26:03 +000020#include "llvm/ADT/Triple.h"
Chandler Carruth418bd1a2015-01-15 02:16:55 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthaab5ec02015-01-31 11:18:46 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000024#include "llvm/Bitcode/BitcodeWriter.h"
25#include "llvm/Bitcode/BitcodeWriterPass.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000026#include "llvm/CodeGen/RegAllocRegistry.h"
27#include "llvm/CodeGen/SchedulerRegistry.h"
David Blaikie7a4f7f52018-01-09 22:03:47 +000028#include "llvm/CodeGen/TargetSubtargetInfo.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
Chandler Carruth0a50c492014-01-12 11:11:50 +000030#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth9828e692015-02-13 09:57:03 +000031#include "llvm/IR/LegacyPassManager.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Module.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000033#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruthca884742014-01-13 09:26:48 +000034#include "llvm/IR/Verifier.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000035#include "llvm/LTO/LTOBackend.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000036#include "llvm/MC/MCAsmInfo.h"
Evan Chengeeb486d2011-06-29 01:14:32 +000037#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000038#include "llvm/Passes/PassBuilder.h"
Philip Pfaffee3f105c2019-02-02 23:19:32 +000039#include "llvm/Passes/PassPlugin.h"
Taewook Ohd4c50f72019-08-14 07:11:09 +000040#include "llvm/Passes/StandardInstrumentations.h"
David Blaikie9941da42018-11-17 18:04:13 +000041#include "llvm/Support/BuryPointer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000042#include "llvm/Support/CommandLine.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000043#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000044#include "llvm/Support/PrettyStackTrace.h"
Evan Cheng494eb062011-08-24 18:09:14 +000045#include "llvm/Support/TargetRegistry.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000046#include "llvm/Support/TimeProfiler.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000047#include "llvm/Support/Timer.h"
48#include "llvm/Support/raw_ostream.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000049#include "llvm/Target/TargetMachine.h"
50#include "llvm/Target/TargetOptions.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000051#include "llvm/Transforms/Coroutines.h"
Brian Gesiak048239e2019-12-26 08:00:00 -050052#include "llvm/Transforms/Coroutines/CoroCleanup.h"
53#include "llvm/Transforms/Coroutines/CoroEarly.h"
54#include "llvm/Transforms/Coroutines/CoroElide.h"
55#include "llvm/Transforms/Coroutines/CoroSplit.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000056#include "llvm/Transforms/IPO.h"
Chandler Carruthb72c19f2016-08-17 03:09:11 +000057#include "llvm/Transforms/IPO/AlwaysInliner.h"
Teresa Johnson2f63d542020-01-24 12:24:18 -080058#include "llvm/Transforms/IPO/LowerTypeTests.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000059#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Tim Shen50fedec2017-06-01 23:27:51 +000060#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
David Blaikied2a572202018-04-24 00:59:22 +000061#include "llvm/Transforms/InstCombine/InstCombine.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000062#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000063#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruthafce4492017-11-14 01:47:24 +000064#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
David Blaikie4e1ae832018-03-23 22:16:59 +000065#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000066#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Rong Xu4059e142019-04-25 17:52:43 +000067#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000068#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
Leonard Chan007f6742019-07-25 20:53:15 +000069#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000070#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Michael Gottesman90cae772013-01-28 01:36:00 +000071#include "llvm/Transforms/ObjCARC.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000072#include "llvm/Transforms/Scalar.h"
Chandler Carruth4ddaadc2016-03-11 09:02:43 +000073#include "llvm/Transforms/Scalar/GVN.h"
David Blaikiec133b1e2018-03-28 17:45:10 +000074#include "llvm/Transforms/Utils.h"
Teresa Johnson6ed79132019-01-04 19:05:01 +000075#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Leonard Chanb2065132019-06-20 19:35:25 +000076#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Tim Shen66470692017-06-29 23:08:38 +000077#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +000078#include "llvm/Transforms/Utils/SymbolRewriter.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000079#include <memory>
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000080using namespace clang;
81using namespace llvm;
82
serge_sans_paille24ab9b52019-06-08 17:37:47 +020083#define HANDLE_EXTENSION(Ext) \
84 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
85#include "llvm/Support/Extension.def"
86
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000087namespace {
88
Davide Italiano945de432017-02-13 16:07:05 +000089// Default filename used for profile generation.
90static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
91
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000092class EmitAssemblyHelper {
David Blaikie9c902b52011-09-25 23:23:43 +000093 DiagnosticsEngine &Diags;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000094 const HeaderSearchOptions &HSOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000095 const CodeGenOptions &CodeGenOpts;
Nick Lewycky432add52011-12-02 22:17:00 +000096 const clang::TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000097 const LangOptions &LangOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000098 Module *TheModule;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000099
100 Timer CodeGenerationTime;
101
Peter Collingbourne03f89072016-07-15 00:55:40 +0000102 std::unique_ptr<raw_pwrite_stream> OS;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000103
Chandler Carruthd294bdb2015-02-01 12:26:23 +0000104 TargetIRAnalysis getTargetIRAnalysis() const {
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000105 if (TM)
Chandler Carruthd294bdb2015-02-01 12:26:23 +0000106 return TM->getTargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000107
Chandler Carruthd294bdb2015-02-01 12:26:23 +0000108 return TargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000109 }
110
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000111 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
Nadav Rotemec57ab32012-10-24 00:53:38 +0000112
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000113 /// Generates the TargetMachine.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000114 /// Leaves TM unchanged if it is unable to create the target machine.
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000115 /// Some of our clang tests specify triples which are not built
116 /// into clang. This is okay because these tests check the generated
117 /// IR, and they require DataLayout which depends on the triple.
118 /// In this case, we allow this method to fail and not report an error.
119 /// When MustCreateTM is used, we print an error if we are unable to load
120 /// the requested target.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000121 void CreateTargetMachine(bool MustCreateTM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000122
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000123 /// Add passes necessary to emit assembly or LLVM IR.
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000124 ///
125 /// \return True on success.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000126 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000127 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
128
129 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
130 std::error_code EC;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000131 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
Fangrui Songd9b948b2019-08-05 05:43:48 +0000132 llvm::sys::fs::OF_None);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000133 if (EC) {
134 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
135 F.reset();
136 }
137 return F;
138 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000139
140public:
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000141 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
142 const HeaderSearchOptions &HeaderSearchOpts,
143 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +0000144 const clang::TargetOptions &TOpts,
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000145 const LangOptions &LOpts, Module *M)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000146 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
147 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
148 CodeGenerationTime("codegen", "Code Generation Time") {}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000149
150 ~EmitAssemblyHelper() {
Alp Tokerf4e22382013-12-20 20:26:53 +0000151 if (CodeGenOpts.DisableFree)
David Blaikiea97eaa12014-08-29 16:53:14 +0000152 BuryPointer(std::move(TM));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000153 }
154
Ahmed Charlesb8984322014-03-07 20:03:18 +0000155 std::unique_ptr<TargetMachine> TM;
Alp Tokerf4e22382013-12-20 20:26:53 +0000156
Peter Collingbourne03f89072016-07-15 00:55:40 +0000157 void EmitAssembly(BackendAction Action,
158 std::unique_ptr<raw_pwrite_stream> OS);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000159
160 void EmitAssemblyWithNewPassManager(BackendAction Action,
161 std::unique_ptr<raw_pwrite_stream> OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000162};
163
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000164// We need this wrapper to access LangOpts and CGOpts from extension functions
165// that we add to the PassManagerBuilder.
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000166class PassManagerBuilderWrapper : public PassManagerBuilder {
167public:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000168 PassManagerBuilderWrapper(const Triple &TargetTriple,
169 const CodeGenOptions &CGOpts,
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000170 const LangOptions &LangOpts)
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000171 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
172 LangOpts(LangOpts) {}
173 const Triple &getTargetTriple() const { return TargetTriple; }
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000174 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000175 const LangOptions &getLangOpts() const { return LangOpts; }
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000176
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000177private:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000178 const Triple &TargetTriple;
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000179 const CodeGenOptions &CGOpts;
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000180 const LangOptions &LangOpts;
181};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000182}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000183
Dan Gohman5932ce22012-01-17 20:54:51 +0000184static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
185 if (Builder.OptLevel > 0)
186 PM.add(createObjCARCAPElimPass());
187}
188
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000189static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
190 if (Builder.OptLevel > 0)
191 PM.add(createObjCARCExpandPass());
192}
193
194static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
195 if (Builder.OptLevel > 0)
196 PM.add(createObjCARCOptPass());
197}
198
Diego Novillob56be642014-03-03 20:06:18 +0000199static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000200 legacy::PassManagerBase &PM) {
Diego Novillob56be642014-03-03 20:06:18 +0000201 PM.add(createAddDiscriminatorsPass());
202}
203
Nuno Lopesa4255892012-05-22 17:19:45 +0000204static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000205 legacy::PassManagerBase &PM) {
Chandler Carruth00a301d2017-11-14 01:30:04 +0000206 PM.add(createBoundsCheckingLegacyPass());
Nuno Lopesa4255892012-05-22 17:19:45 +0000207}
208
Leonard Chan007f6742019-07-25 20:53:15 +0000209static SanitizerCoverageOptions
210getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000211 SanitizerCoverageOptions Opts;
212 Opts.CoverageType =
213 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
214 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
215 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
216 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
Kostya Serebryany3b419712016-08-30 01:27:03 +0000217 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
218 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000219 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000220 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000221 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000222 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000223 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
Kostya Serebryany61457762017-07-28 00:10:10 +0000224 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000225 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
Leonard Chan007f6742019-07-25 20:53:15 +0000226 return Opts;
227}
228
229static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
230 legacy::PassManagerBase &PM) {
231 const PassManagerBuilderWrapper &BuilderWrapper =
232 static_cast<const PassManagerBuilderWrapper &>(Builder);
233 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
234 auto Opts = getSancovOptsFromCGOpts(CGOpts);
235 PM.add(createModuleSanitizerCoverageLegacyPassPass(Opts));
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000236}
237
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000238// Check if ASan should use GC-friendly instrumentation for globals.
239// First of all, there is no point if -fdata-sections is off (expect for MachO,
240// where this is not a factor). Also, on ELF this feature requires an assembler
241// extension that only works with -integrated-as at the moment.
242static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000243 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
244 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000245 switch (T.getObjectFormat()) {
246 case Triple::MachO:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000247 case Triple::COFF:
Evgeniy Stepanovc7b90942017-04-26 00:51:06 +0000248 return true;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000249 case Triple::ELF:
250 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
Hubert Tong2711e162019-07-19 08:46:18 +0000251 case Triple::XCOFF:
252 llvm::report_fatal_error("ASan not implemented for XCOFF.");
253 case Triple::Wasm:
254 case Triple::UnknownObjectFormat:
255 break;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000256 }
Hubert Tong2711e162019-07-19 08:46:18 +0000257 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000258}
259
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000260static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000261 legacy::PassManagerBase &PM) {
Yury Gribov5bfeca12015-11-11 10:45:48 +0000262 const PassManagerBuilderWrapper &BuilderWrapper =
263 static_cast<const PassManagerBuilderWrapper&>(Builder);
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000264 const Triple &T = BuilderWrapper.getTargetTriple();
Yury Gribov5bfeca12015-11-11 10:45:48 +0000265 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
266 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000267 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
Vitaly Buka8076c572018-12-05 01:44:31 +0000268 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000269 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000270 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
271 UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000272 PM.add(createModuleAddressSanitizerLegacyPassPass(
273 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000274}
275
276static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
277 legacy::PassManagerBase &PM) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000278 PM.add(createAddressSanitizerFunctionPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000279 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000280 PM.add(createModuleAddressSanitizerLegacyPassPass(
Vitaly Buka8076c572018-12-05 01:44:31 +0000281 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
282 /*UseOdrIndicator*/ false));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000283}
284
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000285static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
286 legacy::PassManagerBase &PM) {
Evgeniy Stepanov3fd1b1a2017-12-20 19:05:44 +0000287 const PassManagerBuilderWrapper &BuilderWrapper =
288 static_cast<const PassManagerBuilderWrapper &>(Builder);
289 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
290 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000291 PM.add(
292 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000293}
294
295static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
296 legacy::PassManagerBase &PM) {
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000297 PM.add(createHWAddressSanitizerLegacyPassPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000298 /*CompileKernel*/ true, /*Recover*/ true));
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000299}
300
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000301static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
302 legacy::PassManagerBase &PM,
303 bool CompileKernel) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000304 const PassManagerBuilderWrapper &BuilderWrapper =
305 static_cast<const PassManagerBuilderWrapper&>(Builder);
306 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Evgeniy Stepanov5b5370a2016-11-07 21:02:11 +0000307 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
308 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
Philip Pfaffe0ee6a932019-02-04 21:02:49 +0000309 PM.add(createMemorySanitizerLegacyPassPass(
310 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000311
312 // MemorySanitizer inserts complex instrumentation that mostly follows
313 // the logic of the original code, but operates on "shadow" values.
314 // It can benefit from re-running some general purpose optimization passes.
315 if (Builder.OptLevel > 0) {
316 PM.add(createEarlyCSEPass());
317 PM.add(createReassociatePass());
318 PM.add(createLICMPass());
319 PM.add(createGVNPass());
320 PM.add(createInstructionCombiningPass());
321 PM.add(createDeadStoreEliminationPass());
322 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000323}
324
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000325static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
326 legacy::PassManagerBase &PM) {
327 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
328}
329
330static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
331 legacy::PassManagerBase &PM) {
332 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
333}
334
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000335static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000336 legacy::PassManagerBase &PM) {
Philip Pfaffe685c76d2019-01-16 09:28:01 +0000337 PM.add(createThreadSanitizerLegacyPassPass());
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000338}
339
Peter Collingbournec3772752013-08-07 22:47:34 +0000340static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000341 legacy::PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000342 const PassManagerBuilderWrapper &BuilderWrapper =
343 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonovae5804f2014-10-15 20:22:54 +0000344 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000345 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
Peter Collingbournec3772752013-08-07 22:47:34 +0000346}
347
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000348static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
349 const CodeGenOptions &CodeGenOpts) {
350 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000351
352 switch (CodeGenOpts.getVecLib()) {
353 case CodeGenOptions::Accelerate:
354 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
355 break;
Nemanja Ivanovic6321c682019-06-05 01:57:57 +0000356 case CodeGenOptions::MASSV:
357 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
Jim Lin466f8842020-02-18 10:48:38 +0800358 break;
Matt Masten6731dea2016-07-29 16:44:24 +0000359 case CodeGenOptions::SVML:
360 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
361 break;
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000362 default:
363 break;
364 }
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000365 return TLII;
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000366}
367
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000368static void addSymbolRewriterPass(const CodeGenOptions &Opts,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000369 legacy::PassManager *MPM) {
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000370 llvm::SymbolRewriter::RewriteDescriptorList DL;
371
372 llvm::SymbolRewriter::RewriteMapParser MapParser;
373 for (const auto &MapFile : Opts.RewriteMapFiles)
374 MapParser.parse(MapFile, &DL);
375
376 MPM->add(createRewriteSymbolsPass(DL));
377}
378
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000379static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
380 switch (CodeGenOpts.OptimizationLevel) {
381 default:
382 llvm_unreachable("Invalid optimization level!");
383 case 0:
384 return CodeGenOpt::None;
385 case 1:
386 return CodeGenOpt::Less;
387 case 2:
388 return CodeGenOpt::Default; // O2/Os/Oz
389 case 3:
390 return CodeGenOpt::Aggressive;
391 }
392}
393
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000394static Optional<llvm::CodeModel::Model>
395getCodeModel(const CodeGenOptions &CodeGenOpts) {
396 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
David Greenecc69872018-08-22 11:34:28 +0000397 .Case("tiny", llvm::CodeModel::Tiny)
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000398 .Case("small", llvm::CodeModel::Small)
399 .Case("kernel", llvm::CodeModel::Kernel)
400 .Case("medium", llvm::CodeModel::Medium)
401 .Case("large", llvm::CodeModel::Large)
402 .Case("default", ~1u)
403 .Default(~0u);
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000404 assert(CodeModel != ~0u && "invalid code model!");
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000405 if (CodeModel == ~1u)
406 return None;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000407 return static_cast<llvm::CodeModel::Model>(CodeModel);
408}
409
Reid Kleckner1dfede32019-11-13 15:17:46 -0800410static CodeGenFileType getCodeGenFileType(BackendAction Action) {
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000411 if (Action == Backend_EmitObj)
Reid Kleckner1dfede32019-11-13 15:17:46 -0800412 return CGFT_ObjectFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000413 else if (Action == Backend_EmitMCNull)
Reid Kleckner1dfede32019-11-13 15:17:46 -0800414 return CGFT_Null;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000415 else {
416 assert(Action == Backend_EmitAssembly && "Invalid action!");
Reid Kleckner1dfede32019-11-13 15:17:46 -0800417 return CGFT_AssemblyFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000418 }
419}
420
421static void initTargetOptions(llvm::TargetOptions &Options,
422 const CodeGenOptions &CodeGenOpts,
423 const clang::TargetOptions &TargetOpts,
424 const LangOptions &LangOpts,
425 const HeaderSearchOptions &HSOpts) {
426 Options.ThreadModel =
427 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
428 .Case("posix", llvm::ThreadModel::POSIX)
429 .Case("single", llvm::ThreadModel::Single);
430
431 // Set float ABI type.
432 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
433 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
434 "Invalid Floating Point ABI!");
435 Options.FloatABIType =
436 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
437 .Case("soft", llvm::FloatABI::Soft)
438 .Case("softfp", llvm::FloatABI::Soft)
439 .Case("hard", llvm::FloatABI::Hard)
440 .Default(llvm::FloatABI::Default);
441
442 // Set FP fusion mode.
443 switch (LangOpts.getDefaultFPContractMode()) {
444 case LangOptions::FPC_Off:
Adam Nemet03af4242017-04-20 17:09:35 +0000445 // Preserve any contraction performed by the front-end. (Strict performs
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000446 // splitting of the muladd intrinsic in the backend.)
Adam Nemet03af4242017-04-20 17:09:35 +0000447 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000448 break;
449 case LangOptions::FPC_On:
450 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
451 break;
452 case LangOptions::FPC_Fast:
453 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
454 break;
455 }
456
457 Options.UseInitArray = CodeGenOpts.UseInitArray;
458 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
Saleem Abdulrasool54448902017-06-09 00:40:30 +0000459 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000460 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
461
462 // Set EABI version.
Yuka Takahashidc771502017-07-01 07:57:23 +0000463 Options.EABIVersion = TargetOpts.EABIVersion;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000464
465 if (LangOpts.SjLjExceptions)
466 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
Martell Malonec950c652017-11-29 07:25:12 +0000467 if (LangOpts.SEHExceptions)
468 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
469 if (LangOpts.DWARFExceptions)
470 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
Heejin Ahne8b2b882019-09-12 04:01:37 +0000471 if (LangOpts.WasmExceptions)
472 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000473
474 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
475 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
476 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
477 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
478 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
479 Options.FunctionSections = CodeGenOpts.FunctionSections;
480 Options.DataSections = CodeGenOpts.DataSections;
481 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
KAWASHIMA Takahiro10c11e42020-01-13 09:28:02 +0000482 Options.TLSSize = CodeGenOpts.TLSSize;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000483 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +0000484 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000485 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
Sean Eveson5110d4f2018-01-08 13:42:26 +0000486 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
Peter Collingbourne14b468b2018-07-18 00:27:07 +0000487 Options.EmitAddrsig = CodeGenOpts.Addrsig;
Djordje Todorovic2f215cf2020-02-20 13:43:01 +0100488 Options.EnableDebugEntryValues = CodeGenOpts.EnableDebugEntryValues;
David Candler92aa0c22019-10-31 08:55:57 +0000489 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
Djordje Todorovicc15c68a2020-03-09 11:02:35 +0100490 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000491
Aaron Puchertb207bae2019-06-26 21:36:35 +0000492 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000493 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
494 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
495 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
496 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
497 Options.MCOptions.MCIncrementalLinkerCompatible =
498 CodeGenOpts.IncrementalLinkerCompatible;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000499 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
Brian Cain7b953b62019-08-08 19:19:20 +0000500 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000501 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
502 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
503 Options.MCOptions.ABIName = TargetOpts.ABI;
504 for (const auto &Entry : HSOpts.UserEntries)
505 if (!Entry.IsFramework &&
506 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
507 Entry.Group == frontend::IncludeDirGroup::Angled ||
508 Entry.Group == frontend::IncludeDirGroup::System))
509 Options.MCOptions.IASSearchPaths.push_back(
510 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
511}
David Blaikie7a4f7f52018-01-09 22:03:47 +0000512static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
513 if (CodeGenOpts.DisableGCov)
514 return None;
515 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
516 return None;
517 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
518 // LLVM's -default-gcov-version flag is set to something invalid.
519 GCOVOptions Options;
520 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
521 Options.EmitData = CodeGenOpts.EmitGcovArcs;
522 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
523 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
524 Options.NoRedZone = CodeGenOpts.DisableRedZone;
525 Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000526 Options.Filter = CodeGenOpts.ProfileFilterFiles;
527 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
David Blaikie7a4f7f52018-01-09 22:03:47 +0000528 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
529 return Options;
530}
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000531
Rong Xu4059e142019-04-25 17:52:43 +0000532static Optional<InstrProfOptions>
533getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
534 const LangOptions &LangOpts) {
535 if (!CodeGenOpts.hasProfileClangInstr())
536 return None;
537 InstrProfOptions Options;
538 Options.NoRedZone = CodeGenOpts.DisableRedZone;
539 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
540
541 // TODO: Surface the option to emit atomic profile counter increments at
542 // the driver level.
543 Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
544 return Options;
545}
546
Peter Collingbourne03f89072016-07-15 00:55:40 +0000547void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000548 legacy::FunctionPassManager &FPM) {
Chandler Carruth93786da2016-12-23 00:23:01 +0000549 // Handle disabling of all LLVM passes, where we want to preserve the
550 // internal module before any optimization.
Steven Wu546a1962015-07-17 20:09:56 +0000551 if (CodeGenOpts.DisableLLVMPasses)
552 return;
553
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000554 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
555 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
556 // are inserted before PMBuilder ones - they'd get the default-constructed
557 // TLI with an unknown target otherwise.
Teresa Johnsonaff22322015-12-07 19:21:34 +0000558 Triple TargetTriple(TheModule->getTargetTriple());
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000559 std::unique_ptr<TargetLibraryInfoImpl> TLII(
560 createTLII(TargetTriple, CodeGenOpts));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000561
Teresa Johnson2f63d542020-01-24 12:24:18 -0800562 // If we reached here with a non-empty index file name, then the index file
563 // was empty and we are not performing ThinLTO backend compilation (used in
564 // testing in a distributed build environment). Drop any the type test
565 // assume sequences inserted for whole program vtables so that codegen doesn't
566 // complain.
567 if (!CodeGenOpts.ThinLTOIndexFile.empty())
568 MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
569 /*ImportSummary=*/nullptr,
570 /*DropTypeTests=*/true));
571
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000572 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
573
Chandler Carruthfcd33142016-12-23 01:24:49 +0000574 // At O0 and O1 we only run the always inliner which is more efficient. At
575 // higher optimization levels we run the normal inliner.
576 if (CodeGenOpts.OptimizationLevel <= 1) {
Mehdi Amini7f873072017-01-06 23:18:09 +0000577 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
578 !CodeGenOpts.DisableLifetimeMarkers);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000579 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
580 } else {
Dehao Chence39fdd2017-03-21 19:55:46 +0000581 // We do not want to inline hot callsites for SamplePGO module-summary build
582 // because profile annotation will happen again in ThinLTO backend, and we
583 // want the IR of the hot path to match the profile.
Chandler Carruthfcd33142016-12-23 01:24:49 +0000584 PMBuilder.Inliner = createFunctionInliningPass(
Dehao Chence39fdd2017-03-21 19:55:46 +0000585 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
586 (!CodeGenOpts.SampleProfileFile.empty() &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000587 CodeGenOpts.PrepareForThinLTO));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000588 }
589
Chandler Carruthfcd33142016-12-23 01:24:49 +0000590 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000591 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000592 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
593 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000594
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000595 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Alina Sbirleaa9b9ab82019-04-30 21:29:23 +0000596 // Loop interleaving in the loop vectorizer has historically been set to be
597 // enabled when loop unrolling is enabled.
598 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000599 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000600 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
Teresa Johnson8749d8042015-07-06 16:23:00 +0000601 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
Hal Finkelce0697f2013-11-17 16:03:29 +0000602 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000603
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000604 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
605
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000606 if (TM)
Stanislav Mekhanoshin61da0672017-01-26 16:49:21 +0000607 TM->adjustPassManager(PMBuilder);
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000608
Dehao Chen7810d4f2017-02-21 20:36:21 +0000609 if (CodeGenOpts.DebugInfoForProfiling ||
610 !CodeGenOpts.SampleProfileFile.empty())
611 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
612 addAddDiscriminatorsPass);
Diego Novillob56be642014-03-03 20:06:18 +0000613
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000614 // In ObjC ARC mode, add the main ARC optimization passes.
615 if (LangOpts.ObjCAutoRefCount) {
616 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
617 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000618 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
619 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000620 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
621 addObjCARCOptPass);
622 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000623
Richard Smith10ab78e2019-02-23 21:06:26 +0000624 if (LangOpts.Coroutines)
Brian Gesiak91a4b5a2018-04-01 23:55:21 +0000625 addCoroutinePassesToExtensionPoints(PMBuilder);
626
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000627 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000628 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
629 addBoundsCheckingPass);
630 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
631 addBoundsCheckingPass);
632 }
633
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000634 if (CodeGenOpts.SanitizeCoverageType ||
635 CodeGenOpts.SanitizeCoverageIndirectCalls ||
636 CodeGenOpts.SanitizeCoverageTraceCmp) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000637 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
638 addSanitizerCoveragePass);
639 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
640 addSanitizerCoveragePass);
641 }
642
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000643 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000644 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000645 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000646 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000647 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000648 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000649
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000650 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
651 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
652 addKernelAddressSanitizerPasses);
653 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
654 addKernelAddressSanitizerPasses);
655 }
656
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000657 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
658 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
659 addHWAddressSanitizerPasses);
660 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
661 addHWAddressSanitizerPasses);
662 }
663
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000664 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
665 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
666 addKernelHWAddressSanitizerPasses);
667 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
668 addKernelHWAddressSanitizerPasses);
669 }
670
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000671 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000672 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
673 addMemorySanitizerPass);
674 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
675 addMemorySanitizerPass);
676 }
677
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000678 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
679 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
680 addKernelMemorySanitizerPass);
681 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
682 addKernelMemorySanitizerPass);
683 }
684
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000685 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000686 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000687 addThreadSanitizerPass);
688 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
689 addThreadSanitizerPass);
690 }
691
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000692 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
Peter Collingbournec3772752013-08-07 22:47:34 +0000693 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
694 addDataFlowSanitizerPass);
695 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
696 addDataFlowSanitizerPass);
697 }
698
Chris Lattner5c123672011-05-21 20:40:11 +0000699 // Set up the per-function pass manager.
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000700 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
Chris Lattner5c123672011-05-21 20:40:11 +0000701 if (CodeGenOpts.VerifyModule)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000702 FPM.add(createVerifierPass());
Andrew Trickb2a84722011-04-05 18:49:32 +0000703
Chris Lattner5c123672011-05-21 20:40:11 +0000704 // Set up the per-module pass manager.
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000705 if (!CodeGenOpts.RewriteMapFiles.empty())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000706 addSymbolRewriterPass(CodeGenOpts, &MPM);
Chris Lattnerd98cec52011-02-18 22:20:38 +0000707
David Blaikie7a4f7f52018-01-09 22:03:47 +0000708 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
709 MPM.add(createGCOVProfilerPass(*Options));
Benjamin Kramer8c305922016-02-02 11:06:51 +0000710 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000711 MPM.add(createStripSymbolsPass(true));
Nick Lewycky207bce32011-04-21 23:44:07 +0000712 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000713
Rong Xu4059e142019-04-25 17:52:43 +0000714 if (Optional<InstrProfOptions> Options =
715 getInstrProfOptions(CodeGenOpts, LangOpts))
716 MPM.add(createInstrProfilingLegacyPass(*Options, false));
Vedant Kumaree6c2332018-08-16 22:24:47 +0000717
Rong Xua4a09b22019-03-04 20:21:31 +0000718 bool hasIRInstr = false;
Rong Xu522b5cb2016-02-29 18:54:59 +0000719 if (CodeGenOpts.hasProfileIRInstr()) {
Xinliang David Lib65f8ae2016-07-23 04:28:59 +0000720 PMBuilder.EnablePGOInstrGen = true;
Rong Xua4a09b22019-03-04 20:21:31 +0000721 hasIRInstr = true;
722 }
723 if (CodeGenOpts.hasProfileCSIRInstr()) {
724 assert(!CodeGenOpts.hasProfileCSIRUse() &&
725 "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
726 "same time");
727 assert(!hasIRInstr &&
728 "Cannot have both ProfileGen pass and CSProfileGen pass at the "
729 "same time");
730 PMBuilder.EnablePGOCSInstrGen = true;
731 hasIRInstr = true;
732 }
733 if (hasIRInstr) {
Rong Xu522b5cb2016-02-29 18:54:59 +0000734 if (!CodeGenOpts.InstrProfileOutput.empty())
735 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
736 else
Benjamin Krameradcd0262020-01-28 20:23:46 +0100737 PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
Rong Xu522b5cb2016-02-29 18:54:59 +0000738 }
Rong Xua4a09b22019-03-04 20:21:31 +0000739 if (CodeGenOpts.hasProfileIRUse()) {
Rong Xu9c6f1532016-03-02 20:59:36 +0000740 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
Rong Xua4a09b22019-03-04 20:21:31 +0000741 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
742 }
Justin Bogner970ac602014-12-08 19:04:51 +0000743
Dehao Chen5717aff2016-12-14 21:41:04 +0000744 if (!CodeGenOpts.SampleProfileFile.empty())
745 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
Diego Novillod3ef1082015-08-25 15:25:13 +0000746
Peter Collingbourne03f89072016-07-15 00:55:40 +0000747 PMBuilder.populateFunctionPassManager(FPM);
748 PMBuilder.populateModulePassManager(MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000749}
750
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000751static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
Yaxun Liub5e80c32016-04-12 20:22:32 +0000752 SmallVector<const char *, 16> BackendArgs;
753 BackendArgs.push_back("clang"); // Fake program name.
754 if (!CodeGenOpts.DebugPass.empty()) {
755 BackendArgs.push_back("-debug-pass");
756 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
757 }
758 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
759 BackendArgs.push_back("-limit-float-precision");
760 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
761 }
Yaxun Liub5e80c32016-04-12 20:22:32 +0000762 BackendArgs.push_back(nullptr);
763 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
764 BackendArgs.data());
765}
766
Peter Collingbourne03f89072016-07-15 00:55:40 +0000767void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000768 // Create the TargetMachine for generating code.
769 std::string Error;
770 std::string Triple = TheModule->getTargetTriple();
771 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
772 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000773 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000774 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000775 return;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000776 }
777
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000778 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
Eric Christopher583a1f72015-09-26 01:25:08 +0000779 std::string FeaturesStr =
780 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
Rafael Espindolae1d70532018-01-18 00:20:03 +0000781 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000782 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
Evan Chengdd286bc2011-11-16 08:38:55 +0000783
Nick Lewycky432add52011-12-02 22:17:00 +0000784 llvm::TargetOptions Options;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000785 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000786 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
787 Options, RM, CM, OptLevel));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000788}
789
Peter Collingbourne03f89072016-07-15 00:55:40 +0000790bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
791 BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000792 raw_pwrite_stream &OS,
793 raw_pwrite_stream *DwoOS) {
Chad Rosierb1cfc682012-02-29 20:14:59 +0000794 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000795 llvm::Triple TargetTriple(TheModule->getTargetTriple());
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000796 std::unique_ptr<TargetLibraryInfoImpl> TLII(
797 createTLII(TargetTriple, CodeGenOpts));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000798 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
Chad Rosierb1cfc682012-02-29 20:14:59 +0000799
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000800 // Normal mode, emit a .s or .o file by running the code generator. Note,
801 // this also adds codegenerator level optimization passes.
Reid Kleckner1dfede32019-11-13 15:17:46 -0800802 CodeGenFileType CGFT = getCodeGenFileType(Action);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000803
804 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
805 // "codegen" passes so that it isn't run multiple times when there is
806 // inlining happening.
Steven Wu1d56be82015-05-02 00:56:15 +0000807 if (CodeGenOpts.OptimizationLevel > 0)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000808 CodeGenPasses.add(createObjCARCContractPass());
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000809
Peter Collingbourne91d02842018-05-22 18:52:37 +0000810 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000811 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
812 Diags.Report(diag::err_fe_unable_to_interface_with_target);
813 return false;
814 }
815
816 return true;
817}
818
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000819void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000820 std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000821 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000822
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000823 setCommandLineOpts(CodeGenOpts);
Yaxun Liub5e80c32016-04-12 20:22:32 +0000824
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000825 bool UsesCodeGen = (Action != Backend_EmitNothing &&
826 Action != Backend_EmitBC &&
827 Action != Backend_EmitLL);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000828 CreateTargetMachine(UsesCodeGen);
Alp Tokerf4e22382013-12-20 20:26:53 +0000829
Rafael Espindolab633d202015-06-23 13:59:36 +0000830 if (UsesCodeGen && !TM)
831 return;
832 if (TM)
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000833 TheModule->setDataLayout(TM->createDataLayout());
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000834
Peter Collingbourne03f89072016-07-15 00:55:40 +0000835 legacy::PassManager PerModulePasses;
836 PerModulePasses.add(
837 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
838
839 legacy::FunctionPassManager PerFunctionPasses(TheModule);
840 PerFunctionPasses.add(
841 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
842
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000843 CreatePasses(PerModulePasses, PerFunctionPasses);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000844
845 legacy::PassManager CodeGenPasses;
846 CodeGenPasses.add(
847 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000848
Peter Collingbourne91d02842018-05-22 18:52:37 +0000849 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000850
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000851 switch (Action) {
852 case Backend_EmitNothing:
853 break;
854
855 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +0000856 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000857 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +0000858 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
859 if (!ThinLinkOS)
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000860 return;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000861 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000862 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
863 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000864 PerModulePasses.add(createWriteThinLTOBitcodePass(
865 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000866 } else {
867 // Emit a module summary by default for Regular LTO except for ld64
868 // targets
869 bool EmitLTOSummary =
870 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +0000871 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000872 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
873 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000874 if (EmitLTOSummary) {
875 if (!TheModule->getModuleFlag("ThinLTO"))
876 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
877 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Teresa Johnson604f8022019-07-19 23:02:58 +0000878 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000879 }
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000880
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000881 PerModulePasses.add(createBitcodeWriterPass(
882 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000883 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000884 break;
885
886 case Backend_EmitLL:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000887 PerModulePasses.add(
Duncan P. N. Exon Smithbb9cadf2015-04-15 02:45:28 +0000888 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000889 break;
890
891 default:
Aaron Puchertb207bae2019-06-26 21:36:35 +0000892 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +0000893 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000894 if (!DwoOS)
895 return;
896 }
897 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
898 DwoOS ? &DwoOS->os() : nullptr))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000899 return;
900 }
901
Andrew Trick15e36e82011-04-05 18:56:55 +0000902 // Before executing passes, print the final values of the LLVM options.
903 cl::PrintOptionValues();
904
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000905 // Run passes. For now we do all passes at once, but eventually we
906 // would like to have the option of streaming code generation.
907
Peter Collingbourne03f89072016-07-15 00:55:40 +0000908 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000909 PrettyStackTraceString CrashInfo("Per-function optimization");
Russell Gallopdf494f72019-12-11 11:49:42 +0000910 llvm::TimeTraceScope TimeScope("PerFunctionPasses");
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000911
Peter Collingbourne03f89072016-07-15 00:55:40 +0000912 PerFunctionPasses.doInitialization();
Yaron Keren10d6d162015-06-05 09:40:53 +0000913 for (Function &F : *TheModule)
914 if (!F.isDeclaration())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000915 PerFunctionPasses.run(F);
916 PerFunctionPasses.doFinalization();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000917 }
918
Peter Collingbourne03f89072016-07-15 00:55:40 +0000919 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000920 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Russell Gallopdf494f72019-12-11 11:49:42 +0000921 llvm::TimeTraceScope TimeScope("PerModulePasses");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000922 PerModulePasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000923 }
924
Peter Collingbourne03f89072016-07-15 00:55:40 +0000925 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000926 PrettyStackTraceString CrashInfo("Code generation");
Russell Gallopdf494f72019-12-11 11:49:42 +0000927 llvm::TimeTraceScope TimeScope("CodeGenPasses");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000928 CodeGenPasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000929 }
Peter Collingbourne91d02842018-05-22 18:52:37 +0000930
931 if (ThinLinkOS)
932 ThinLinkOS->keep();
933 if (DwoOS)
934 DwoOS->keep();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000935}
936
Chandler Carruth50f9e892016-12-23 20:44:01 +0000937static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
938 switch (Opts.OptimizationLevel) {
939 default:
940 llvm_unreachable("Invalid optimization level!");
941
942 case 1:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800943 return PassBuilder::OptimizationLevel::O1;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000944
945 case 2:
946 switch (Opts.OptimizeSize) {
947 default:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000948 llvm_unreachable("Invalid optimization level for size!");
Chandler Carruth50f9e892016-12-23 20:44:01 +0000949
950 case 0:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800951 return PassBuilder::OptimizationLevel::O2;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000952
953 case 1:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800954 return PassBuilder::OptimizationLevel::Os;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000955
956 case 2:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800957 return PassBuilder::OptimizationLevel::Oz;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000958 }
959
960 case 3:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800961 return PassBuilder::OptimizationLevel::O3;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000962 }
963}
964
Brian Gesiak048239e2019-12-26 08:00:00 -0500965static void addCoroutinePassesAtO0(ModulePassManager &MPM,
966 const LangOptions &LangOpts,
967 const CodeGenOptions &CodeGenOpts) {
968 if (!LangOpts.Coroutines)
969 return;
970
971 MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
972
973 CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
974 CGPM.addPass(CoroSplitPass());
975 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
976 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
977
978 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
979}
980
Benjamin Kramerba2ea932019-03-28 17:18:42 +0000981static void addSanitizersAtO0(ModulePassManager &MPM,
982 const Triple &TargetTriple,
983 const LangOptions &LangOpts,
984 const CodeGenOptions &CodeGenOpts) {
Petr Hosek366cda02019-05-09 06:09:35 +0000985 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
Leonard Chan436fb2b2019-02-13 22:22:48 +0000986 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
Petr Hosek366cda02019-05-09 06:09:35 +0000987 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
988 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
989 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000990 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Petr Hosek366cda02019-05-09 06:09:35 +0000991 MPM.addPass(
992 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
993 CodeGenOpts.SanitizeAddressUseOdrIndicator));
994 };
995
996 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
997 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
998 }
999
1000 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1001 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001002 }
Leonard Chan1a240ed2019-02-20 03:50:11 +00001003
1004 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001005 MPM.addPass(MemorySanitizerPass({}));
Leonard Chan1a240ed2019-02-20 03:50:11 +00001006 MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
1007 }
1008
Petr Hosek366cda02019-05-09 06:09:35 +00001009 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1010 MPM.addPass(createModuleToFunctionPassAdaptor(
1011 MemorySanitizerPass({0, false, /*Kernel=*/true})));
1012 }
1013
Leonard Chan1a240ed2019-02-20 03:50:11 +00001014 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001015 MPM.addPass(ThreadSanitizerPass());
Leonard Chan1a240ed2019-02-20 03:50:11 +00001016 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1017 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001018}
1019
Chandler Carruth50f9e892016-12-23 20:44:01 +00001020/// A clean version of `EmitAssembly` that uses the new pass manager.
1021///
1022/// Not all features are currently supported in this system, but where
1023/// necessary it falls back to the legacy pass manager to at least provide
1024/// basic functionality.
1025///
1026/// This API is planned to have its functionality finished and then to replace
1027/// `EmitAssembly` at some point in the future when the default switches.
1028void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1029 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +00001030 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001031 setCommandLineOpts(CodeGenOpts);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001032
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001033 bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1034 Action != Backend_EmitBC &&
1035 Action != Backend_EmitLL);
1036 CreateTargetMachine(RequiresCodeGen);
1037
1038 if (RequiresCodeGen && !TM)
Chandler Carruth50f9e892016-12-23 20:44:01 +00001039 return;
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001040 if (TM)
1041 TheModule->setDataLayout(TM->createDataLayout());
Chandler Carruth50f9e892016-12-23 20:44:01 +00001042
Dehao Chenc76a27e2017-07-27 15:29:53 +00001043 Optional<PGOOptions> PGOOpt;
Davide Italiano945de432017-02-13 16:07:05 +00001044
Dehao Chenc76a27e2017-07-27 15:29:53 +00001045 if (CodeGenOpts.hasProfileIRInstr())
1046 // -fprofile-generate.
1047 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001048 ? std::string(DefaultProfileGenName)
Dehao Chenc76a27e2017-07-27 15:29:53 +00001049 : CodeGenOpts.InstrProfileOutput,
Rong Xua4a09b22019-03-04 20:21:31 +00001050 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
Richard Smith8654ae52018-10-10 23:13:35 +00001051 CodeGenOpts.DebugInfoForProfiling);
Rong Xua4a09b22019-03-04 20:21:31 +00001052 else if (CodeGenOpts.hasProfileIRUse()) {
Dehao Chenc76a27e2017-07-27 15:29:53 +00001053 // -fprofile-use.
Rong Xua4a09b22019-03-04 20:21:31 +00001054 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1055 : PGOOptions::NoCSAction;
1056 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1057 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1058 CSAction, CodeGenOpts.DebugInfoForProfiling);
1059 } else if (!CodeGenOpts.SampleProfileFile.empty())
Dehao Chenc76a27e2017-07-27 15:29:53 +00001060 // -fprofile-sample-use
Rong Xua4a09b22019-03-04 20:21:31 +00001061 PGOOpt =
1062 PGOOptions(CodeGenOpts.SampleProfileFile, "",
1063 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1064 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
Dehao Chenc76a27e2017-07-27 15:29:53 +00001065 else if (CodeGenOpts.DebugInfoForProfiling)
1066 // -fdebug-info-for-profiling
Rong Xua4a09b22019-03-04 20:21:31 +00001067 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1068 PGOOptions::NoCSAction, true);
1069
1070 // Check to see if we want to generate a CS profile.
1071 if (CodeGenOpts.hasProfileCSIRInstr()) {
1072 assert(!CodeGenOpts.hasProfileCSIRUse() &&
1073 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1074 "the same time");
1075 if (PGOOpt.hasValue()) {
1076 assert(PGOOpt->Action != PGOOptions::IRInstr &&
1077 PGOOpt->Action != PGOOptions::SampleUse &&
1078 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1079 " pass");
1080 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001081 ? std::string(DefaultProfileGenName)
Rong Xua4a09b22019-03-04 20:21:31 +00001082 : CodeGenOpts.InstrProfileOutput;
1083 PGOOpt->CSAction = PGOOptions::CSIRInstr;
1084 } else
1085 PGOOpt = PGOOptions("",
1086 CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001087 ? std::string(DefaultProfileGenName)
Rong Xua4a09b22019-03-04 20:21:31 +00001088 : CodeGenOpts.InstrProfileOutput,
1089 "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1090 CodeGenOpts.DebugInfoForProfiling);
1091 }
Davide Italiano945de432017-02-13 16:07:05 +00001092
Alina Sbirlea267ac922019-05-23 18:51:02 +00001093 PipelineTuningOptions PTO;
Alina Sbirlea21efe2a2019-05-24 17:40:52 +00001094 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001095 // For historical reasons, loop interleaving is set to mirror setting for loop
1096 // unrolling.
1097 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1098 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1099 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
Brian Gesiak048239e2019-12-26 08:00:00 -05001100 PTO.Coroutines = LangOpts.Coroutines;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001101
Taewook Ohd4c50f72019-08-14 07:11:09 +00001102 PassInstrumentationCallbacks PIC;
1103 StandardInstrumentations SI;
1104 SI.registerCallbacks(PIC);
1105 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001106
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001107 // Attempt to load pass plugins and register their callbacks with PB.
1108 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1109 auto PassPlugin = PassPlugin::Load(PluginFN);
1110 if (PassPlugin) {
1111 PassPlugin->registerPassBuilderCallbacks(PB);
1112 } else {
1113 Diags.Report(diag::err_fe_unable_to_load_plugin)
1114 << PluginFN << toString(PassPlugin.takeError());
1115 }
1116 }
serge_sans_paille24ab9b52019-06-08 17:37:47 +02001117#define HANDLE_EXTENSION(Ext) \
1118 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1119#include "llvm/Support/Extension.def"
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001120
Craig Topper926b95c2017-11-14 08:48:28 +00001121 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1122 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1123 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1124 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001125
1126 // Register the AA manager first so that our version is the one used.
1127 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1128
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001129 // Register the target library analysis directly and give it a customized
1130 // preset TLI.
1131 Triple TargetTriple(TheModule->getTargetTriple());
1132 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1133 createTLII(TargetTriple, CodeGenOpts));
1134 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001135
Chandler Carruth50f9e892016-12-23 20:44:01 +00001136 // Register all the basic analyses with the managers.
1137 PB.registerModuleAnalyses(MAM);
1138 PB.registerCGSCCAnalyses(CGAM);
1139 PB.registerFunctionAnalyses(FAM);
1140 PB.registerLoopAnalyses(LAM);
1141 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1142
Tim Shenb13eebe2017-06-29 23:10:13 +00001143 ModulePassManager MPM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001144
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001145 if (!CodeGenOpts.DisableLLVMPasses) {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001146 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
Tim Shen66470692017-06-29 23:08:38 +00001147 bool IsLTO = CodeGenOpts.PrepareForLTO;
1148
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001149 if (CodeGenOpts.OptimizationLevel == 0) {
Teresa Johnson2f63d542020-01-24 12:24:18 -08001150 // If we reached here with a non-empty index file name, then the index
1151 // file was empty and we are not performing ThinLTO backend compilation
1152 // (used in testing in a distributed build environment). Drop any the type
1153 // test assume sequences inserted for whole program vtables so that
1154 // codegen doesn't complain.
1155 if (!CodeGenOpts.ThinLTOIndexFile.empty())
1156 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1157 /*ImportSummary=*/nullptr,
1158 /*DropTypeTests=*/true));
David Blaikieac904d02018-01-23 01:25:24 +00001159 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1160 MPM.addPass(GCOVProfilerPass(*Options));
Rong Xu4059e142019-04-25 17:52:43 +00001161 if (Optional<InstrProfOptions> Options =
1162 getInstrProfOptions(CodeGenOpts, LangOpts))
1163 MPM.addPass(InstrProfiling(*Options, false));
David Blaikieac904d02018-01-23 01:25:24 +00001164
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001165 // Build a minimal pipeline based on the semantics required by Clang,
Leonard Chan587497b2019-06-13 16:45:29 +00001166 // which is just that always inlining occurs. Further, disable generating
1167 // lifetime intrinsics to avoid enabling further optimizations during
1168 // code generation.
1169 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/false));
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001170
Rong Xuca161fa2019-08-01 22:36:34 +00001171 // At -O0, we can still do PGO. Add all the requested passes for
1172 // instrumentation PGO, if requested.
1173 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1174 PGOOpt->Action == PGOOptions::IRUse))
1175 PB.addPGOInstrPassesForO0(
1176 MPM, CodeGenOpts.DebugPassManager,
1177 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1178 /* IsCS */ false, PGOOpt->ProfileFile,
1179 PGOOpt->ProfileRemappingFile);
1180
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001181 // At -O0 we directly run necessary sanitizer passes.
1182 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1183 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1184
Teresa Johnson6ed79132019-01-04 19:05:01 +00001185 // Lastly, add semantically necessary passes for LTO.
1186 if (IsLTO || IsThinLTO) {
1187 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001188 MPM.addPass(NameAnonGlobalPass());
Teresa Johnson6ed79132019-01-04 19:05:01 +00001189 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001190 } else {
Tim Shen66470692017-06-29 23:08:38 +00001191 // Map our optimization levels into one of the distinct levels used to
1192 // configure the pipeline.
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001193 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1194
Teresa Johnson2f63d542020-01-24 12:24:18 -08001195 // If we reached here with a non-empty index file name, then the index
1196 // file was empty and we are not performing ThinLTO backend compilation
1197 // (used in testing in a distributed build environment). Drop any the type
1198 // test assume sequences inserted for whole program vtables so that
1199 // codegen doesn't complain.
1200 if (!CodeGenOpts.ThinLTOIndexFile.empty())
1201 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1202 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1203 /*ImportSummary=*/nullptr,
1204 /*DropTypeTests=*/true));
1205 });
1206
Leonard Chanb2065132019-06-20 19:35:25 +00001207 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1208 MPM.addPass(createModuleToFunctionPassAdaptor(
1209 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1210 });
1211
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001212 // Register callbacks to schedule sanitizer passes at the appropriate part of
1213 // the pipeline.
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001214 // FIXME: either handle asan/the remaining sanitizers or error out
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001215 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1216 PB.registerScalarOptimizerLateEPCallback(
1217 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1218 FPM.addPass(BoundsCheckingPass());
1219 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001220 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1221 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1222 MPM.addPass(MemorySanitizerPass({}));
1223 });
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001224 PB.registerOptimizerLastEPCallback(
1225 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001226 FPM.addPass(MemorySanitizerPass({}));
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001227 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001228 }
1229 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1230 PB.registerPipelineStartEPCallback(
1231 [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); });
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001232 PB.registerOptimizerLastEPCallback(
1233 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1234 FPM.addPass(ThreadSanitizerPass());
1235 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001236 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001237 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1238 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1239 MPM.addPass(
1240 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1241 });
1242 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
Leonard Chan619b6d52019-02-14 01:07:47 +00001243 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
Leonard Chan436fb2b2019-02-13 22:22:48 +00001244 PB.registerOptimizerLastEPCallback(
Leonard Chan619b6d52019-02-14 01:07:47 +00001245 [Recover, UseAfterScope](FunctionPassManager &FPM,
1246 PassBuilder::OptimizationLevel Level) {
Leonard Chan436fb2b2019-02-13 22:22:48 +00001247 FPM.addPass(AddressSanitizerPass(
Leonard Chan619b6d52019-02-14 01:07:47 +00001248 /*CompileKernel=*/false, Recover, UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +00001249 });
1250 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Leonard Chan619b6d52019-02-14 01:07:47 +00001251 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1252 PB.registerPipelineStartEPCallback(
1253 [Recover, ModuleUseAfterScope,
1254 UseOdrIndicator](ModulePassManager &MPM) {
1255 MPM.addPass(ModuleAddressSanitizerPass(
1256 /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1257 UseOdrIndicator));
1258 });
Leonard Chan436fb2b2019-02-13 22:22:48 +00001259 }
David Blaikieac904d02018-01-23 01:25:24 +00001260 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1261 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1262 MPM.addPass(GCOVProfilerPass(*Options));
1263 });
Rong Xu4059e142019-04-25 17:52:43 +00001264 if (Optional<InstrProfOptions> Options =
1265 getInstrProfOptions(CodeGenOpts, LangOpts))
1266 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1267 MPM.addPass(InstrProfiling(*Options, false));
1268 });
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001269
Tim Shen66470692017-06-29 23:08:38 +00001270 if (IsThinLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001271 MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1272 Level, CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001273 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001274 MPM.addPass(NameAnonGlobalPass());
1275 } else if (IsLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001276 MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1277 CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001278 MPM.addPass(CanonicalizeAliasesPass());
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001279 MPM.addPass(NameAnonGlobalPass());
Tim Shen66470692017-06-29 23:08:38 +00001280 } else {
Tim Shenb13eebe2017-06-29 23:10:13 +00001281 MPM = PB.buildPerModuleDefaultPipeline(Level,
1282 CodeGenOpts.DebugPassManager);
Tim Shen66470692017-06-29 23:08:38 +00001283 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001284 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001285
Leonard Chan486b1732019-09-08 07:30:17 +00001286 if (CodeGenOpts.SanitizeCoverageType ||
1287 CodeGenOpts.SanitizeCoverageIndirectCalls ||
1288 CodeGenOpts.SanitizeCoverageTraceCmp) {
1289 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1290 MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1291 }
1292
Peter Collingbourne3b82b922019-07-17 21:45:19 +00001293 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1294 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1295 MPM.addPass(HWAddressSanitizerPass(
1296 /*CompileKernel=*/false, Recover));
1297 }
1298 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1299 MPM.addPass(HWAddressSanitizerPass(
1300 /*CompileKernel=*/true, /*Recover=*/true));
1301 }
1302
Leonard Chan007f6742019-07-25 20:53:15 +00001303 if (CodeGenOpts.OptimizationLevel == 0) {
Brian Gesiak048239e2019-12-26 08:00:00 -05001304 addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001305 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
Leonard Chan007f6742019-07-25 20:53:15 +00001306 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001307 }
1308
1309 // FIXME: We still use the legacy pass manager to do code generation. We
1310 // create that pass manager here and use it as needed below.
1311 legacy::PassManager CodeGenPasses;
1312 bool NeedCodeGen = false;
Peter Collingbourne91d02842018-05-22 18:52:37 +00001313 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Chandler Carruth50f9e892016-12-23 20:44:01 +00001314
1315 // Append any output we need to the pass manager.
1316 switch (Action) {
1317 case Backend_EmitNothing:
1318 break;
1319
1320 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +00001321 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Tim Shen50fedec2017-06-01 23:27:51 +00001322 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +00001323 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1324 if (!ThinLinkOS)
Tim Shen50fedec2017-06-01 23:27:51 +00001325 return;
Tim Shen50fedec2017-06-01 23:27:51 +00001326 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001327 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1328 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001329 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1330 : nullptr));
Tim Shen50fedec2017-06-01 23:27:51 +00001331 } else {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001332 // Emit a module summary by default for Regular LTO except for ld64
1333 // targets
1334 bool EmitLTOSummary =
1335 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +00001336 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001337 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1338 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001339 if (EmitLTOSummary) {
1340 if (!TheModule->getModuleFlag("ThinLTO"))
1341 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1342 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Leonard Chan19ec31d2019-08-21 17:24:14 +00001343 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001344 }
1345 MPM.addPass(
1346 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tim Shen50fedec2017-06-01 23:27:51 +00001347 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001348 break;
1349
1350 case Backend_EmitLL:
1351 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1352 break;
1353
1354 case Backend_EmitAssembly:
1355 case Backend_EmitMCNull:
1356 case Backend_EmitObj:
1357 NeedCodeGen = true;
1358 CodeGenPasses.add(
1359 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Aaron Puchertb207bae2019-06-26 21:36:35 +00001360 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00001361 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001362 if (!DwoOS)
1363 return;
1364 }
1365 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1366 DwoOS ? &DwoOS->os() : nullptr))
Chandler Carruth50f9e892016-12-23 20:44:01 +00001367 // FIXME: Should we handle this error differently?
1368 return;
1369 break;
1370 }
1371
1372 // Before executing passes, print the final values of the LLVM options.
1373 cl::PrintOptionValues();
1374
1375 // Now that we have all of the passes ready, run them.
1376 {
1377 PrettyStackTraceString CrashInfo("Optimizer");
1378 MPM.run(*TheModule, MAM);
1379 }
1380
1381 // Now if needed, run the legacy PM for codegen.
1382 if (NeedCodeGen) {
1383 PrettyStackTraceString CrashInfo("Code generation");
1384 CodeGenPasses.run(*TheModule);
1385 }
Peter Collingbourne91d02842018-05-22 18:52:37 +00001386
1387 if (ThinLinkOS)
1388 ThinLinkOS->keep();
1389 if (DwoOS)
1390 DwoOS->keep();
Chandler Carruth50f9e892016-12-23 20:44:01 +00001391}
1392
Peter Collingbourne47d23642017-01-24 19:54:37 +00001393Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1394 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1395 if (!BMsOrErr)
1396 return BMsOrErr.takeError();
1397
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00001398 // The bitcode file may contain multiple modules, we want the one that is
1399 // marked as being the ThinLTO module.
Vitaly Bukac35ff822018-02-16 23:34:16 +00001400 if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1401 return *Bm;
Peter Collingbourne47d23642017-01-24 19:54:37 +00001402
1403 return make_error<StringError>("Could not find module summary",
1404 inconvertibleErrorCode());
1405}
1406
Vitaly Bukac35ff822018-02-16 23:34:16 +00001407BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1408 for (BitcodeModule &BM : BMs) {
1409 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1410 if (LTOInfo && LTOInfo->IsThinLTO)
1411 return &BM;
1412 }
1413 return nullptr;
1414}
1415
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001416static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001417 const HeaderSearchOptions &HeaderOpts,
1418 const CodeGenOptions &CGOpts,
1419 const clang::TargetOptions &TOpts,
1420 const LangOptions &LOpts,
Dehao Chena1bd2d62017-01-13 00:51:55 +00001421 std::unique_ptr<raw_pwrite_stream> OS,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001422 std::string SampleProfile,
Richard Smith8654ae52018-10-10 23:13:35 +00001423 std::string ProfileRemapping,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001424 BackendAction Action) {
Dehao Chen5f83d0e2017-07-10 20:31:37 +00001425 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001426 ModuleToDefinedGVSummaries;
1427 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1428
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001429 setCommandLineOpts(CGOpts);
1430
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001431 // We can simply import the values mentioned in the combined index, since
1432 // we should only invoke this using the individual indexes written out
1433 // via a WriteIndexesThinBackend.
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001434 FunctionImporter::ImportMapTy ImportList;
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001435 for (auto &GlobalList : *CombinedIndex) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001436 // Ignore entries for undefined references.
1437 if (GlobalList.second.SummaryList.empty())
1438 continue;
1439
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001440 auto GUID = GlobalList.first;
Teresa Johnson5ed8b002018-11-29 17:02:59 +00001441 for (auto &Summary : GlobalList.second.SummaryList) {
1442 // Skip the summaries for the importing module. These are included to
1443 // e.g. record required linkage changes.
1444 if (Summary->modulePath() == M->getModuleIdentifier())
1445 continue;
1446 // Add an entry to provoke importing by thinBackend.
1447 ImportList[Summary->modulePath()].insert(GUID);
1448 }
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001449 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001450
1451 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001452 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001453
1454 for (auto &I : ImportList) {
1455 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1456 llvm::MemoryBuffer::getFile(I.first());
1457 if (!MBOrErr) {
1458 errs() << "Error loading imported file '" << I.first()
1459 << "': " << MBOrErr.getError().message() << "\n";
1460 return;
1461 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001462
Peter Collingbourne47d23642017-01-24 19:54:37 +00001463 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1464 if (!BMOrErr) {
1465 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001466 errs() << "Error loading imported file '" << I.first()
1467 << "': " << EIB.message() << '\n';
1468 });
1469 return;
1470 }
Peter Collingbourne47d23642017-01-24 19:54:37 +00001471 ModuleMap.insert({I.first(), *BMOrErr});
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001472
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001473 OwnedImports.push_back(std::move(*MBOrErr));
1474 }
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001475 auto AddStream = [&](size_t Task) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001476 return std::make_unique<lto::NativeObjectStream>(std::move(OS));
Mehdi Amini406aa222016-08-17 06:23:08 +00001477 };
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001478 lto::Config Conf;
Teresa Johnson9e4321c2018-04-17 16:39:25 +00001479 if (CGOpts.SaveTempsFilePrefix != "") {
1480 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1481 /* UseInputModulePath */ false)) {
1482 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1483 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1484 << '\n';
1485 });
1486 }
1487 }
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001488 Conf.CPU = TOpts.CPU;
1489 Conf.CodeModel = getCodeModel(CGOpts);
1490 Conf.MAttrs = TOpts.Features;
Rafael Espindolae1d70532018-01-18 00:20:03 +00001491 Conf.RelocModel = CGOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001492 Conf.CGOptLevel = getCGOptLevel(CGOpts);
Teresa Johnson867bc392019-04-23 18:56:19 +00001493 Conf.OptLevel = CGOpts.OptimizationLevel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001494 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001495 Conf.SampleProfile = std::move(SampleProfile);
Wei Mi21a47102020-01-09 20:58:31 -08001496 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1497 // For historical reasons, loop interleaving is set to mirror setting for loop
1498 // unrolling.
1499 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1500 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1501 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
Rong Xua4a09b22019-03-04 20:21:31 +00001502
1503 // Context sensitive profile.
1504 if (CGOpts.hasProfileCSIRInstr()) {
1505 Conf.RunCSIRInstr = true;
1506 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1507 } else if (CGOpts.hasProfileCSIRUse()) {
1508 Conf.RunCSIRInstr = false;
1509 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1510 }
1511
Richard Smith8654ae52018-10-10 23:13:35 +00001512 Conf.ProfileRemapping = std::move(ProfileRemapping);
Tim Shen50fedec2017-06-01 23:27:51 +00001513 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
Teresa Johnson4cd016ab2017-11-13 15:38:33 +00001514 Conf.DebugPassManager = CGOpts.DebugPassManager;
Teresa Johnson66744f82018-05-05 14:37:29 +00001515 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1516 Conf.RemarksFilename = CGOpts.OptRecordFile;
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00001517 Conf.RemarksPasses = CGOpts.OptRecordPasses;
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00001518 Conf.RemarksFormat = CGOpts.OptRecordFormat;
Aaron Pucherte1dc4952019-06-15 15:38:51 +00001519 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1520 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001521 switch (Action) {
1522 case Backend_EmitNothing:
1523 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1524 return false;
1525 };
1526 break;
1527 case Backend_EmitLL:
1528 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1529 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1530 return false;
1531 };
1532 break;
1533 case Backend_EmitBC:
1534 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
Rafael Espindola76c8f822018-02-14 19:11:37 +00001535 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001536 return false;
1537 };
1538 break;
1539 default:
1540 Conf.CGFileType = getCodeGenFileType(Action);
1541 break;
1542 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001543 if (Error E = thinBackend(
Teresa Johnson66744f82018-05-05 14:37:29 +00001544 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001545 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1546 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1547 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1548 });
1549 }
1550}
1551
David Blaikie9c902b52011-09-25 23:23:43 +00001552void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001553 const HeaderSearchOptions &HeaderOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00001554 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +00001555 const clang::TargetOptions &TOpts,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001556 const LangOptions &LOpts,
1557 const llvm::DataLayout &TDesc, Module *M,
1558 BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +00001559 std::unique_ptr<raw_pwrite_stream> OS) {
Anton Afanasyevd880de22019-03-30 08:42:48 +00001560
Russell Gallopdf494f72019-12-11 11:49:42 +00001561 llvm::TimeTraceScope TimeScope("Backend");
Anton Afanasyevd880de22019-03-30 08:42:48 +00001562
Vitaly Buka769134d2018-02-16 23:38:22 +00001563 std::unique_ptr<llvm::Module> EmptyModule;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001564 if (!CGOpts.ThinLTOIndexFile.empty()) {
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001565 // If we are performing a ThinLTO importing compile, load the function index
1566 // into memory and pass it into runThinLTOBackend, which will run the
1567 // function importer and invoke LTO passes.
1568 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
Teresa Johnson517729f2017-05-12 19:32:17 +00001569 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1570 /*IgnoreEmptyThinLTOIndexFile*/true);
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001571 if (!IndexOrErr) {
1572 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1573 "Error loading index file '" +
1574 CGOpts.ThinLTOIndexFile + "': ");
1575 return;
1576 }
1577 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1578 // A null CombinedIndex means we should skip ThinLTO compilation
1579 // (LLVM will optionally ignore empty index files, returning null instead
1580 // of an error).
Vitaly Buka769134d2018-02-16 23:38:22 +00001581 if (CombinedIndex) {
1582 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1583 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1584 LOpts, std::move(OS), CGOpts.SampleProfileFile,
Richard Smith8654ae52018-10-10 23:13:35 +00001585 CGOpts.ProfileRemappingFile, Action);
Vitaly Buka769134d2018-02-16 23:38:22 +00001586 return;
1587 }
1588 // Distributed indexing detected that nothing from the module is needed
1589 // for the final linking. So we can skip the compilation. We sill need to
1590 // output an empty object file to make sure that a linker does not fail
1591 // trying to read it. Also for some features, like CFI, we must skip
1592 // the compilation as CombinedIndex does not contain all required
1593 // information.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001594 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
Vitaly Buka769134d2018-02-16 23:38:22 +00001595 EmptyModule->setTargetTriple(M->getTargetTriple());
1596 M = EmptyModule.get();
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001597 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001598 }
1599
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001600 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001601
Chandler Carruth50f9e892016-12-23 20:44:01 +00001602 if (CGOpts.ExperimentalNewPassManager)
1603 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1604 else
1605 AsmHelper.EmitAssembly(Action, std::move(OS));
Alp Tokere83b9062014-01-02 15:08:04 +00001606
James Y Knightb214cbc2016-03-04 19:00:41 +00001607 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1608 // DataLayout.
1609 if (AsmHelper.TM) {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00001610 std::string DLDesc = M->getDataLayout().getStringRepresentation();
James Y Knightb214cbc2016-03-04 19:00:41 +00001611 if (DLDesc != TDesc.getStringRepresentation()) {
Alp Tokere83b9062014-01-02 15:08:04 +00001612 unsigned DiagID = Diags.getCustomDiagID(
1613 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1614 "expected target description '%1'");
James Y Knightb214cbc2016-03-04 19:00:41 +00001615 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
Alp Tokere83b9062014-01-02 15:08:04 +00001616 }
1617 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001618}
Steven Wu27fb5222016-05-11 16:26:03 +00001619
Steven Wu27fb5222016-05-11 16:26:03 +00001620// With -fembed-bitcode, save a copy of the llvm IR as data in the
1621// __LLVM,__bitcode section.
1622void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1623 llvm::MemoryBufferRef Buf) {
1624 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1625 return;
Teresa Johnsonc8e0bb32019-12-12 11:59:36 -08001626 llvm::EmbedBitcodeInModule(
1627 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1628 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1629 &CGOpts.CmdArgs);
Steven Wu27fb5222016-05-11 16:26:03 +00001630}