blob: a125c96fd00e1a24aaf5d543b20bf7ac5829d98e [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"
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -080021#include "llvm/Analysis/StackSafetyAnalysis.h"
Chandler Carruth418bd1a2015-01-15 02:16:55 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthaab5ec02015-01-31 11:18:46 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000024#include "llvm/Bitcode/BitcodeReader.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000025#include "llvm/Bitcode/BitcodeWriter.h"
26#include "llvm/Bitcode/BitcodeWriterPass.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000027#include "llvm/CodeGen/RegAllocRegistry.h"
28#include "llvm/CodeGen/SchedulerRegistry.h"
David Blaikie7a4f7f52018-01-09 22:03:47 +000029#include "llvm/CodeGen/TargetSubtargetInfo.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/DataLayout.h"
Chandler Carruth0a50c492014-01-12 11:11:50 +000031#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth9828e692015-02-13 09:57:03 +000032#include "llvm/IR/LegacyPassManager.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/Module.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000034#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruthca884742014-01-13 09:26:48 +000035#include "llvm/IR/Verifier.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000036#include "llvm/LTO/LTOBackend.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000037#include "llvm/MC/MCAsmInfo.h"
Evan Chengeeb486d2011-06-29 01:14:32 +000038#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000039#include "llvm/Passes/PassBuilder.h"
Philip Pfaffee3f105c2019-02-02 23:19:32 +000040#include "llvm/Passes/PassPlugin.h"
Taewook Ohd4c50f72019-08-14 07:11:09 +000041#include "llvm/Passes/StandardInstrumentations.h"
David Blaikie9941da42018-11-17 18:04:13 +000042#include "llvm/Support/BuryPointer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000043#include "llvm/Support/CommandLine.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000044#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000045#include "llvm/Support/PrettyStackTrace.h"
Evan Cheng494eb062011-08-24 18:09:14 +000046#include "llvm/Support/TargetRegistry.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000047#include "llvm/Support/TimeProfiler.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000048#include "llvm/Support/Timer.h"
49#include "llvm/Support/raw_ostream.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000050#include "llvm/Target/TargetMachine.h"
51#include "llvm/Target/TargetOptions.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000052#include "llvm/Transforms/Coroutines.h"
Brian Gesiak048239e2019-12-26 08:00:00 -050053#include "llvm/Transforms/Coroutines/CoroCleanup.h"
54#include "llvm/Transforms/Coroutines/CoroEarly.h"
55#include "llvm/Transforms/Coroutines/CoroElide.h"
56#include "llvm/Transforms/Coroutines/CoroSplit.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000057#include "llvm/Transforms/IPO.h"
Chandler Carruthb72c19f2016-08-17 03:09:11 +000058#include "llvm/Transforms/IPO/AlwaysInliner.h"
Teresa Johnson2f63d542020-01-24 12:24:18 -080059#include "llvm/Transforms/IPO/LowerTypeTests.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000060#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Tim Shen50fedec2017-06-01 23:27:51 +000061#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
David Blaikied2a572202018-04-24 00:59:22 +000062#include "llvm/Transforms/InstCombine/InstCombine.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000063#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000064#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruthafce4492017-11-14 01:47:24 +000065#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
David Blaikie4e1ae832018-03-23 22:16:59 +000066#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000067#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Rong Xu4059e142019-04-25 17:52:43 +000068#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000069#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
Leonard Chan007f6742019-07-25 20:53:15 +000070#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000071#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Michael Gottesman90cae772013-01-28 01:36:00 +000072#include "llvm/Transforms/ObjCARC.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000073#include "llvm/Transforms/Scalar.h"
Chandler Carruth4ddaadc2016-03-11 09:02:43 +000074#include "llvm/Transforms/Scalar/GVN.h"
David Blaikiec133b1e2018-03-28 17:45:10 +000075#include "llvm/Transforms/Utils.h"
Teresa Johnson6ed79132019-01-04 19:05:01 +000076#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Leonard Chanb2065132019-06-20 19:35:25 +000077#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Tim Shen66470692017-06-29 23:08:38 +000078#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +000079#include "llvm/Transforms/Utils/SymbolRewriter.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000080#include <memory>
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000081using namespace clang;
82using namespace llvm;
83
serge_sans_paille24ab9b52019-06-08 17:37:47 +020084#define HANDLE_EXTENSION(Ext) \
85 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
86#include "llvm/Support/Extension.def"
87
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000088namespace {
89
Davide Italiano945de432017-02-13 16:07:05 +000090// Default filename used for profile generation.
91static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
92
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000093class EmitAssemblyHelper {
David Blaikie9c902b52011-09-25 23:23:43 +000094 DiagnosticsEngine &Diags;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000095 const HeaderSearchOptions &HSOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000096 const CodeGenOptions &CodeGenOpts;
Nick Lewycky432add52011-12-02 22:17:00 +000097 const clang::TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000098 const LangOptions &LangOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000099 Module *TheModule;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000100
101 Timer CodeGenerationTime;
102
Peter Collingbourne03f89072016-07-15 00:55:40 +0000103 std::unique_ptr<raw_pwrite_stream> OS;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000104
Chandler Carruthd294bdb2015-02-01 12:26:23 +0000105 TargetIRAnalysis getTargetIRAnalysis() const {
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000106 if (TM)
Chandler Carruthd294bdb2015-02-01 12:26:23 +0000107 return TM->getTargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000108
Chandler Carruthd294bdb2015-02-01 12:26:23 +0000109 return TargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000110 }
111
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000112 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
Nadav Rotemec57ab32012-10-24 00:53:38 +0000113
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000114 /// Generates the TargetMachine.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000115 /// Leaves TM unchanged if it is unable to create the target machine.
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000116 /// Some of our clang tests specify triples which are not built
117 /// into clang. This is okay because these tests check the generated
118 /// IR, and they require DataLayout which depends on the triple.
119 /// In this case, we allow this method to fail and not report an error.
120 /// When MustCreateTM is used, we print an error if we are unable to load
121 /// the requested target.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000122 void CreateTargetMachine(bool MustCreateTM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000123
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000124 /// Add passes necessary to emit assembly or LLVM IR.
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000125 ///
126 /// \return True on success.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000127 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000128 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
129
130 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
131 std::error_code EC;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000132 auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
Fangrui Songd9b948b2019-08-05 05:43:48 +0000133 llvm::sys::fs::OF_None);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000134 if (EC) {
135 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
136 F.reset();
137 }
138 return F;
139 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000140
141public:
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000142 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
143 const HeaderSearchOptions &HeaderSearchOpts,
144 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +0000145 const clang::TargetOptions &TOpts,
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000146 const LangOptions &LOpts, Module *M)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000147 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
148 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
149 CodeGenerationTime("codegen", "Code Generation Time") {}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000150
151 ~EmitAssemblyHelper() {
Alp Tokerf4e22382013-12-20 20:26:53 +0000152 if (CodeGenOpts.DisableFree)
David Blaikiea97eaa12014-08-29 16:53:14 +0000153 BuryPointer(std::move(TM));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000154 }
155
Ahmed Charlesb8984322014-03-07 20:03:18 +0000156 std::unique_ptr<TargetMachine> TM;
Alp Tokerf4e22382013-12-20 20:26:53 +0000157
Peter Collingbourne03f89072016-07-15 00:55:40 +0000158 void EmitAssembly(BackendAction Action,
159 std::unique_ptr<raw_pwrite_stream> OS);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000160
161 void EmitAssemblyWithNewPassManager(BackendAction Action,
162 std::unique_ptr<raw_pwrite_stream> OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000163};
164
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000165// We need this wrapper to access LangOpts and CGOpts from extension functions
166// that we add to the PassManagerBuilder.
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000167class PassManagerBuilderWrapper : public PassManagerBuilder {
168public:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000169 PassManagerBuilderWrapper(const Triple &TargetTriple,
170 const CodeGenOptions &CGOpts,
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000171 const LangOptions &LangOpts)
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000172 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
173 LangOpts(LangOpts) {}
174 const Triple &getTargetTriple() const { return TargetTriple; }
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000175 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000176 const LangOptions &getLangOpts() const { return LangOpts; }
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000177
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000178private:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000179 const Triple &TargetTriple;
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000180 const CodeGenOptions &CGOpts;
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000181 const LangOptions &LangOpts;
182};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000183}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000184
Dan Gohman5932ce22012-01-17 20:54:51 +0000185static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
186 if (Builder.OptLevel > 0)
187 PM.add(createObjCARCAPElimPass());
188}
189
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000190static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
191 if (Builder.OptLevel > 0)
192 PM.add(createObjCARCExpandPass());
193}
194
195static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
196 if (Builder.OptLevel > 0)
197 PM.add(createObjCARCOptPass());
198}
199
Diego Novillob56be642014-03-03 20:06:18 +0000200static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000201 legacy::PassManagerBase &PM) {
Diego Novillob56be642014-03-03 20:06:18 +0000202 PM.add(createAddDiscriminatorsPass());
203}
204
Nuno Lopesa4255892012-05-22 17:19:45 +0000205static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000206 legacy::PassManagerBase &PM) {
Chandler Carruth00a301d2017-11-14 01:30:04 +0000207 PM.add(createBoundsCheckingLegacyPass());
Nuno Lopesa4255892012-05-22 17:19:45 +0000208}
209
Leonard Chan007f6742019-07-25 20:53:15 +0000210static SanitizerCoverageOptions
211getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000212 SanitizerCoverageOptions Opts;
213 Opts.CoverageType =
214 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
215 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
216 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
217 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
Kostya Serebryany3b419712016-08-30 01:27:03 +0000218 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
219 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000220 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000221 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000222 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000223 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000224 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
Pratyai Mazumderced398f2020-04-09 02:33:36 -0700225 Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
Kostya Serebryany61457762017-07-28 00:10:10 +0000226 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000227 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
Leonard Chan007f6742019-07-25 20:53:15 +0000228 return Opts;
229}
230
231static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
232 legacy::PassManagerBase &PM) {
233 const PassManagerBuilderWrapper &BuilderWrapper =
234 static_cast<const PassManagerBuilderWrapper &>(Builder);
235 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
236 auto Opts = getSancovOptsFromCGOpts(CGOpts);
Matt Morehousebef187c2020-04-10 10:42:41 -0700237 PM.add(createModuleSanitizerCoverageLegacyPassPass(
238 Opts, CGOpts.SanitizeCoverageWhitelistFiles,
239 CGOpts.SanitizeCoverageBlacklistFiles));
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000240}
241
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000242// Check if ASan should use GC-friendly instrumentation for globals.
243// First of all, there is no point if -fdata-sections is off (expect for MachO,
244// where this is not a factor). Also, on ELF this feature requires an assembler
245// extension that only works with -integrated-as at the moment.
246static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000247 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
248 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000249 switch (T.getObjectFormat()) {
250 case Triple::MachO:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000251 case Triple::COFF:
Evgeniy Stepanovc7b90942017-04-26 00:51:06 +0000252 return true;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000253 case Triple::ELF:
254 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
Hubert Tong2711e162019-07-19 08:46:18 +0000255 case Triple::XCOFF:
256 llvm::report_fatal_error("ASan not implemented for XCOFF.");
257 case Triple::Wasm:
258 case Triple::UnknownObjectFormat:
259 break;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000260 }
Hubert Tong2711e162019-07-19 08:46:18 +0000261 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000262}
263
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000264static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000265 legacy::PassManagerBase &PM) {
Yury Gribov5bfeca12015-11-11 10:45:48 +0000266 const PassManagerBuilderWrapper &BuilderWrapper =
267 static_cast<const PassManagerBuilderWrapper&>(Builder);
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000268 const Triple &T = BuilderWrapper.getTargetTriple();
Yury Gribov5bfeca12015-11-11 10:45:48 +0000269 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
270 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000271 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
Vitaly Buka8076c572018-12-05 01:44:31 +0000272 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000273 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000274 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
275 UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000276 PM.add(createModuleAddressSanitizerLegacyPassPass(
277 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000278}
279
280static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
281 legacy::PassManagerBase &PM) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000282 PM.add(createAddressSanitizerFunctionPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000283 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000284 PM.add(createModuleAddressSanitizerLegacyPassPass(
Vitaly Buka8076c572018-12-05 01:44:31 +0000285 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
286 /*UseOdrIndicator*/ false));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000287}
288
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000289static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
290 legacy::PassManagerBase &PM) {
Evgeniy Stepanov3fd1b1a2017-12-20 19:05:44 +0000291 const PassManagerBuilderWrapper &BuilderWrapper =
292 static_cast<const PassManagerBuilderWrapper &>(Builder);
293 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
294 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000295 PM.add(
296 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000297}
298
299static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
300 legacy::PassManagerBase &PM) {
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000301 PM.add(createHWAddressSanitizerLegacyPassPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000302 /*CompileKernel*/ true, /*Recover*/ true));
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000303}
304
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000305static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
306 legacy::PassManagerBase &PM,
307 bool CompileKernel) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000308 const PassManagerBuilderWrapper &BuilderWrapper =
309 static_cast<const PassManagerBuilderWrapper&>(Builder);
310 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Evgeniy Stepanov5b5370a2016-11-07 21:02:11 +0000311 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
312 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
Philip Pfaffe0ee6a932019-02-04 21:02:49 +0000313 PM.add(createMemorySanitizerLegacyPassPass(
314 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000315
316 // MemorySanitizer inserts complex instrumentation that mostly follows
317 // the logic of the original code, but operates on "shadow" values.
318 // It can benefit from re-running some general purpose optimization passes.
319 if (Builder.OptLevel > 0) {
320 PM.add(createEarlyCSEPass());
321 PM.add(createReassociatePass());
322 PM.add(createLICMPass());
323 PM.add(createGVNPass());
324 PM.add(createInstructionCombiningPass());
325 PM.add(createDeadStoreEliminationPass());
326 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000327}
328
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000329static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
330 legacy::PassManagerBase &PM) {
331 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
332}
333
334static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
335 legacy::PassManagerBase &PM) {
336 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
337}
338
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000339static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000340 legacy::PassManagerBase &PM) {
Philip Pfaffe685c76d2019-01-16 09:28:01 +0000341 PM.add(createThreadSanitizerLegacyPassPass());
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000342}
343
Peter Collingbournec3772752013-08-07 22:47:34 +0000344static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000345 legacy::PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000346 const PassManagerBuilderWrapper &BuilderWrapper =
347 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonovae5804f2014-10-15 20:22:54 +0000348 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000349 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
Peter Collingbournec3772752013-08-07 22:47:34 +0000350}
351
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -0800352static void addMemTagOptimizationPasses(const PassManagerBuilder &Builder,
353 legacy::PassManagerBase &PM) {
354 PM.add(createStackSafetyGlobalInfoWrapperPass(/*SetMetadata=*/true));
355}
356
Mehdi Aminied03d942020-04-11 01:00:58 +0000357static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
358 const CodeGenOptions &CodeGenOpts) {
359 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
360
361 switch (CodeGenOpts.getVecLib()) {
362 case CodeGenOptions::Accelerate:
363 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
364 break;
365 case CodeGenOptions::MASSV:
366 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
367 break;
368 case CodeGenOptions::SVML:
369 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
370 break;
371 default:
372 break;
373 }
374 return TLII;
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000375}
376
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000377static void addSymbolRewriterPass(const CodeGenOptions &Opts,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000378 legacy::PassManager *MPM) {
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000379 llvm::SymbolRewriter::RewriteDescriptorList DL;
380
381 llvm::SymbolRewriter::RewriteMapParser MapParser;
382 for (const auto &MapFile : Opts.RewriteMapFiles)
383 MapParser.parse(MapFile, &DL);
384
385 MPM->add(createRewriteSymbolsPass(DL));
386}
387
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000388static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
389 switch (CodeGenOpts.OptimizationLevel) {
390 default:
391 llvm_unreachable("Invalid optimization level!");
392 case 0:
393 return CodeGenOpt::None;
394 case 1:
395 return CodeGenOpt::Less;
396 case 2:
397 return CodeGenOpt::Default; // O2/Os/Oz
398 case 3:
399 return CodeGenOpt::Aggressive;
400 }
401}
402
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000403static Optional<llvm::CodeModel::Model>
404getCodeModel(const CodeGenOptions &CodeGenOpts) {
405 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
David Greenecc69872018-08-22 11:34:28 +0000406 .Case("tiny", llvm::CodeModel::Tiny)
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000407 .Case("small", llvm::CodeModel::Small)
408 .Case("kernel", llvm::CodeModel::Kernel)
409 .Case("medium", llvm::CodeModel::Medium)
410 .Case("large", llvm::CodeModel::Large)
411 .Case("default", ~1u)
412 .Default(~0u);
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000413 assert(CodeModel != ~0u && "invalid code model!");
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000414 if (CodeModel == ~1u)
415 return None;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000416 return static_cast<llvm::CodeModel::Model>(CodeModel);
417}
418
Reid Kleckner1dfede32019-11-13 15:17:46 -0800419static CodeGenFileType getCodeGenFileType(BackendAction Action) {
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000420 if (Action == Backend_EmitObj)
Reid Kleckner1dfede32019-11-13 15:17:46 -0800421 return CGFT_ObjectFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000422 else if (Action == Backend_EmitMCNull)
Reid Kleckner1dfede32019-11-13 15:17:46 -0800423 return CGFT_Null;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000424 else {
425 assert(Action == Backend_EmitAssembly && "Invalid action!");
Reid Kleckner1dfede32019-11-13 15:17:46 -0800426 return CGFT_AssemblyFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000427 }
428}
429
430static void initTargetOptions(llvm::TargetOptions &Options,
431 const CodeGenOptions &CodeGenOpts,
432 const clang::TargetOptions &TargetOpts,
433 const LangOptions &LangOpts,
434 const HeaderSearchOptions &HSOpts) {
435 Options.ThreadModel =
436 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
437 .Case("posix", llvm::ThreadModel::POSIX)
438 .Case("single", llvm::ThreadModel::Single);
439
440 // Set float ABI type.
441 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
442 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
443 "Invalid Floating Point ABI!");
444 Options.FloatABIType =
445 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
446 .Case("soft", llvm::FloatABI::Soft)
447 .Case("softfp", llvm::FloatABI::Soft)
448 .Case("hard", llvm::FloatABI::Hard)
449 .Default(llvm::FloatABI::Default);
450
451 // Set FP fusion mode.
452 switch (LangOpts.getDefaultFPContractMode()) {
Melanie Blowerc355bec2020-05-04 10:48:12 -0700453 case LangOptions::FPM_Off:
Adam Nemet03af4242017-04-20 17:09:35 +0000454 // Preserve any contraction performed by the front-end. (Strict performs
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000455 // splitting of the muladd intrinsic in the backend.)
Adam Nemet03af4242017-04-20 17:09:35 +0000456 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000457 break;
Melanie Blowerc355bec2020-05-04 10:48:12 -0700458 case LangOptions::FPM_On:
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000459 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
460 break;
Melanie Blowerc355bec2020-05-04 10:48:12 -0700461 case LangOptions::FPM_Fast:
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000462 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
463 break;
464 }
465
466 Options.UseInitArray = CodeGenOpts.UseInitArray;
467 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
Saleem Abdulrasool54448902017-06-09 00:40:30 +0000468 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000469 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
470
471 // Set EABI version.
Yuka Takahashidc771502017-07-01 07:57:23 +0000472 Options.EABIVersion = TargetOpts.EABIVersion;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000473
474 if (LangOpts.SjLjExceptions)
475 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
Martell Malonec950c652017-11-29 07:25:12 +0000476 if (LangOpts.SEHExceptions)
477 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
478 if (LangOpts.DWARFExceptions)
479 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
Heejin Ahne8b2b882019-09-12 04:01:37 +0000480 if (LangOpts.WasmExceptions)
481 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000482
483 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
484 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
485 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
486 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
487 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
488 Options.FunctionSections = CodeGenOpts.FunctionSections;
489 Options.DataSections = CodeGenOpts.DataSections;
490 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
KAWASHIMA Takahiro10c11e42020-01-13 09:28:02 +0000491 Options.TLSSize = CodeGenOpts.TLSSize;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000492 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +0000493 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000494 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
Sean Eveson5110d4f2018-01-08 13:42:26 +0000495 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
Peter Collingbourne14b468b2018-07-18 00:27:07 +0000496 Options.EmitAddrsig = CodeGenOpts.Addrsig;
David Candler92aa0c22019-10-31 08:55:57 +0000497 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
Djordje Todorovicc15c68a2020-03-09 11:02:35 +0100498 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000499
Aaron Puchertb207bae2019-06-26 21:36:35 +0000500 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000501 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
502 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
503 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
504 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
505 Options.MCOptions.MCIncrementalLinkerCompatible =
506 CodeGenOpts.IncrementalLinkerCompatible;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000507 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
Brian Cain7b953b62019-08-08 19:19:20 +0000508 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000509 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
510 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
511 Options.MCOptions.ABIName = TargetOpts.ABI;
512 for (const auto &Entry : HSOpts.UserEntries)
513 if (!Entry.IsFramework &&
514 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
515 Entry.Group == frontend::IncludeDirGroup::Angled ||
516 Entry.Group == frontend::IncludeDirGroup::System))
517 Options.MCOptions.IASSearchPaths.push_back(
518 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
519}
David Blaikie7a4f7f52018-01-09 22:03:47 +0000520static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
521 if (CodeGenOpts.DisableGCov)
522 return None;
523 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
524 return None;
525 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
526 // LLVM's -default-gcov-version flag is set to something invalid.
527 GCOVOptions Options;
528 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
529 Options.EmitData = CodeGenOpts.EmitGcovArcs;
530 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
531 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
532 Options.NoRedZone = CodeGenOpts.DisableRedZone;
533 Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000534 Options.Filter = CodeGenOpts.ProfileFilterFiles;
535 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
David Blaikie7a4f7f52018-01-09 22:03:47 +0000536 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
537 return Options;
538}
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000539
Rong Xu4059e142019-04-25 17:52:43 +0000540static Optional<InstrProfOptions>
541getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
542 const LangOptions &LangOpts) {
543 if (!CodeGenOpts.hasProfileClangInstr())
544 return None;
545 InstrProfOptions Options;
546 Options.NoRedZone = CodeGenOpts.DisableRedZone;
547 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
548
549 // TODO: Surface the option to emit atomic profile counter increments at
550 // the driver level.
551 Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
552 return Options;
553}
554
Peter Collingbourne03f89072016-07-15 00:55:40 +0000555void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000556 legacy::FunctionPassManager &FPM) {
Chandler Carruth93786da2016-12-23 00:23:01 +0000557 // Handle disabling of all LLVM passes, where we want to preserve the
558 // internal module before any optimization.
Steven Wu546a1962015-07-17 20:09:56 +0000559 if (CodeGenOpts.DisableLLVMPasses)
560 return;
561
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000562 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
563 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
564 // are inserted before PMBuilder ones - they'd get the default-constructed
565 // TLI with an unknown target otherwise.
Teresa Johnsonaff22322015-12-07 19:21:34 +0000566 Triple TargetTriple(TheModule->getTargetTriple());
Mehdi Aminied03d942020-04-11 01:00:58 +0000567 std::unique_ptr<TargetLibraryInfoImpl> TLII(
568 createTLII(TargetTriple, CodeGenOpts));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000569
Teresa Johnson2f63d542020-01-24 12:24:18 -0800570 // If we reached here with a non-empty index file name, then the index file
571 // was empty and we are not performing ThinLTO backend compilation (used in
572 // testing in a distributed build environment). Drop any the type test
573 // assume sequences inserted for whole program vtables so that codegen doesn't
574 // complain.
575 if (!CodeGenOpts.ThinLTOIndexFile.empty())
576 MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
577 /*ImportSummary=*/nullptr,
578 /*DropTypeTests=*/true));
579
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000580 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
581
Chandler Carruthfcd33142016-12-23 01:24:49 +0000582 // At O0 and O1 we only run the always inliner which is more efficient. At
583 // higher optimization levels we run the normal inliner.
584 if (CodeGenOpts.OptimizationLevel <= 1) {
Jun Mad0f4af82020-03-13 15:27:45 +0800585 bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
586 !CodeGenOpts.DisableLifetimeMarkers) ||
587 LangOpts.Coroutines);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000588 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
589 } else {
Dehao Chence39fdd2017-03-21 19:55:46 +0000590 // We do not want to inline hot callsites for SamplePGO module-summary build
591 // because profile annotation will happen again in ThinLTO backend, and we
592 // want the IR of the hot path to match the profile.
Chandler Carruthfcd33142016-12-23 01:24:49 +0000593 PMBuilder.Inliner = createFunctionInliningPass(
Dehao Chence39fdd2017-03-21 19:55:46 +0000594 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
595 (!CodeGenOpts.SampleProfileFile.empty() &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000596 CodeGenOpts.PrepareForThinLTO));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000597 }
598
Chandler Carruthfcd33142016-12-23 01:24:49 +0000599 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000600 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000601 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
602 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000603
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000604 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Alina Sbirleaa9b9ab82019-04-30 21:29:23 +0000605 // Loop interleaving in the loop vectorizer has historically been set to be
606 // enabled when loop unrolling is enabled.
607 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000608 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000609 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
Teresa Johnson8749d8042015-07-06 16:23:00 +0000610 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
Hal Finkelce0697f2013-11-17 16:03:29 +0000611 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000612
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000613 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
614
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000615 if (TM)
Stanislav Mekhanoshin61da0672017-01-26 16:49:21 +0000616 TM->adjustPassManager(PMBuilder);
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000617
Dehao Chen7810d4f2017-02-21 20:36:21 +0000618 if (CodeGenOpts.DebugInfoForProfiling ||
619 !CodeGenOpts.SampleProfileFile.empty())
620 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
621 addAddDiscriminatorsPass);
Diego Novillob56be642014-03-03 20:06:18 +0000622
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000623 // In ObjC ARC mode, add the main ARC optimization passes.
624 if (LangOpts.ObjCAutoRefCount) {
625 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
626 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000627 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
628 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000629 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
630 addObjCARCOptPass);
631 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000632
Richard Smith10ab78e2019-02-23 21:06:26 +0000633 if (LangOpts.Coroutines)
Brian Gesiak91a4b5a2018-04-01 23:55:21 +0000634 addCoroutinePassesToExtensionPoints(PMBuilder);
635
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000636 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000637 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
638 addBoundsCheckingPass);
639 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
640 addBoundsCheckingPass);
641 }
642
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000643 if (CodeGenOpts.SanitizeCoverageType ||
644 CodeGenOpts.SanitizeCoverageIndirectCalls ||
645 CodeGenOpts.SanitizeCoverageTraceCmp) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000646 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
647 addSanitizerCoveragePass);
648 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
649 addSanitizerCoveragePass);
650 }
651
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000652 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000653 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000654 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000655 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000656 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000657 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000658
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000659 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
660 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
661 addKernelAddressSanitizerPasses);
662 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
663 addKernelAddressSanitizerPasses);
664 }
665
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000666 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
667 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
668 addHWAddressSanitizerPasses);
669 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
670 addHWAddressSanitizerPasses);
671 }
672
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000673 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
674 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
675 addKernelHWAddressSanitizerPasses);
676 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
677 addKernelHWAddressSanitizerPasses);
678 }
679
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000680 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000681 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
682 addMemorySanitizerPass);
683 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
684 addMemorySanitizerPass);
685 }
686
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000687 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
688 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
689 addKernelMemorySanitizerPass);
690 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
691 addKernelMemorySanitizerPass);
692 }
693
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000694 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000695 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000696 addThreadSanitizerPass);
697 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
698 addThreadSanitizerPass);
699 }
700
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000701 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
Peter Collingbournec3772752013-08-07 22:47:34 +0000702 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
703 addDataFlowSanitizerPass);
704 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
705 addDataFlowSanitizerPass);
706 }
707
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -0800708 if (LangOpts.Sanitize.has(SanitizerKind::MemTag)) {
709 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
710 addMemTagOptimizationPasses);
711 }
712
Chris Lattner5c123672011-05-21 20:40:11 +0000713 // Set up the per-function pass manager.
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000714 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
Chris Lattner5c123672011-05-21 20:40:11 +0000715 if (CodeGenOpts.VerifyModule)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000716 FPM.add(createVerifierPass());
Andrew Trickb2a84722011-04-05 18:49:32 +0000717
Chris Lattner5c123672011-05-21 20:40:11 +0000718 // Set up the per-module pass manager.
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000719 if (!CodeGenOpts.RewriteMapFiles.empty())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000720 addSymbolRewriterPass(CodeGenOpts, &MPM);
Chris Lattnerd98cec52011-02-18 22:20:38 +0000721
David Blaikie7a4f7f52018-01-09 22:03:47 +0000722 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
723 MPM.add(createGCOVProfilerPass(*Options));
Benjamin Kramer8c305922016-02-02 11:06:51 +0000724 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000725 MPM.add(createStripSymbolsPass(true));
Nick Lewycky207bce32011-04-21 23:44:07 +0000726 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000727
Rong Xu4059e142019-04-25 17:52:43 +0000728 if (Optional<InstrProfOptions> Options =
729 getInstrProfOptions(CodeGenOpts, LangOpts))
730 MPM.add(createInstrProfilingLegacyPass(*Options, false));
Vedant Kumaree6c2332018-08-16 22:24:47 +0000731
Rong Xua4a09b22019-03-04 20:21:31 +0000732 bool hasIRInstr = false;
Rong Xu522b5cb2016-02-29 18:54:59 +0000733 if (CodeGenOpts.hasProfileIRInstr()) {
Xinliang David Lib65f8ae2016-07-23 04:28:59 +0000734 PMBuilder.EnablePGOInstrGen = true;
Rong Xua4a09b22019-03-04 20:21:31 +0000735 hasIRInstr = true;
736 }
737 if (CodeGenOpts.hasProfileCSIRInstr()) {
738 assert(!CodeGenOpts.hasProfileCSIRUse() &&
739 "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
740 "same time");
741 assert(!hasIRInstr &&
742 "Cannot have both ProfileGen pass and CSProfileGen pass at the "
743 "same time");
744 PMBuilder.EnablePGOCSInstrGen = true;
745 hasIRInstr = true;
746 }
747 if (hasIRInstr) {
Rong Xu522b5cb2016-02-29 18:54:59 +0000748 if (!CodeGenOpts.InstrProfileOutput.empty())
749 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
750 else
Benjamin Krameradcd0262020-01-28 20:23:46 +0100751 PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
Rong Xu522b5cb2016-02-29 18:54:59 +0000752 }
Rong Xua4a09b22019-03-04 20:21:31 +0000753 if (CodeGenOpts.hasProfileIRUse()) {
Rong Xu9c6f1532016-03-02 20:59:36 +0000754 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
Rong Xua4a09b22019-03-04 20:21:31 +0000755 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
756 }
Justin Bogner970ac602014-12-08 19:04:51 +0000757
Dehao Chen5717aff2016-12-14 21:41:04 +0000758 if (!CodeGenOpts.SampleProfileFile.empty())
759 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
Diego Novillod3ef1082015-08-25 15:25:13 +0000760
Peter Collingbourne03f89072016-07-15 00:55:40 +0000761 PMBuilder.populateFunctionPassManager(FPM);
762 PMBuilder.populateModulePassManager(MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000763}
764
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000765static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
Yaxun Liub5e80c32016-04-12 20:22:32 +0000766 SmallVector<const char *, 16> BackendArgs;
767 BackendArgs.push_back("clang"); // Fake program name.
768 if (!CodeGenOpts.DebugPass.empty()) {
769 BackendArgs.push_back("-debug-pass");
770 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
771 }
772 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
773 BackendArgs.push_back("-limit-float-precision");
774 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
775 }
Yaxun Liub5e80c32016-04-12 20:22:32 +0000776 BackendArgs.push_back(nullptr);
777 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
778 BackendArgs.data());
779}
780
Peter Collingbourne03f89072016-07-15 00:55:40 +0000781void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000782 // Create the TargetMachine for generating code.
783 std::string Error;
784 std::string Triple = TheModule->getTargetTriple();
785 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
786 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000787 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000788 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000789 return;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000790 }
791
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000792 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
Eric Christopher583a1f72015-09-26 01:25:08 +0000793 std::string FeaturesStr =
794 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
Rafael Espindolae1d70532018-01-18 00:20:03 +0000795 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000796 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
Evan Chengdd286bc2011-11-16 08:38:55 +0000797
Nick Lewycky432add52011-12-02 22:17:00 +0000798 llvm::TargetOptions Options;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000799 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000800 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
801 Options, RM, CM, OptLevel));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000802}
803
Peter Collingbourne03f89072016-07-15 00:55:40 +0000804bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
805 BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000806 raw_pwrite_stream &OS,
807 raw_pwrite_stream *DwoOS) {
Chad Rosierb1cfc682012-02-29 20:14:59 +0000808 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000809 llvm::Triple TargetTriple(TheModule->getTargetTriple());
Mehdi Aminied03d942020-04-11 01:00:58 +0000810 std::unique_ptr<TargetLibraryInfoImpl> TLII(
811 createTLII(TargetTriple, CodeGenOpts));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000812 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
Chad Rosierb1cfc682012-02-29 20:14:59 +0000813
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000814 // Normal mode, emit a .s or .o file by running the code generator. Note,
815 // this also adds codegenerator level optimization passes.
Reid Kleckner1dfede32019-11-13 15:17:46 -0800816 CodeGenFileType CGFT = getCodeGenFileType(Action);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000817
818 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
819 // "codegen" passes so that it isn't run multiple times when there is
820 // inlining happening.
Steven Wu1d56be82015-05-02 00:56:15 +0000821 if (CodeGenOpts.OptimizationLevel > 0)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000822 CodeGenPasses.add(createObjCARCContractPass());
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000823
Peter Collingbourne91d02842018-05-22 18:52:37 +0000824 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000825 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
826 Diags.Report(diag::err_fe_unable_to_interface_with_target);
827 return false;
828 }
829
830 return true;
831}
832
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000833void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000834 std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000835 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000836
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000837 setCommandLineOpts(CodeGenOpts);
Yaxun Liub5e80c32016-04-12 20:22:32 +0000838
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000839 bool UsesCodeGen = (Action != Backend_EmitNothing &&
840 Action != Backend_EmitBC &&
841 Action != Backend_EmitLL);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000842 CreateTargetMachine(UsesCodeGen);
Alp Tokerf4e22382013-12-20 20:26:53 +0000843
Rafael Espindolab633d202015-06-23 13:59:36 +0000844 if (UsesCodeGen && !TM)
845 return;
846 if (TM)
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000847 TheModule->setDataLayout(TM->createDataLayout());
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000848
Peter Collingbourne03f89072016-07-15 00:55:40 +0000849 legacy::PassManager PerModulePasses;
850 PerModulePasses.add(
851 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
852
853 legacy::FunctionPassManager PerFunctionPasses(TheModule);
854 PerFunctionPasses.add(
855 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
856
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000857 CreatePasses(PerModulePasses, PerFunctionPasses);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000858
859 legacy::PassManager CodeGenPasses;
860 CodeGenPasses.add(
861 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000862
Peter Collingbourne91d02842018-05-22 18:52:37 +0000863 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000864
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000865 switch (Action) {
866 case Backend_EmitNothing:
867 break;
868
869 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +0000870 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000871 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +0000872 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
873 if (!ThinLinkOS)
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000874 return;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000875 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000876 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
877 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000878 PerModulePasses.add(createWriteThinLTOBitcodePass(
879 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000880 } else {
881 // Emit a module summary by default for Regular LTO except for ld64
882 // targets
883 bool EmitLTOSummary =
884 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +0000885 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000886 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
887 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000888 if (EmitLTOSummary) {
889 if (!TheModule->getModuleFlag("ThinLTO"))
890 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
891 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Teresa Johnson604f8022019-07-19 23:02:58 +0000892 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000893 }
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000894
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000895 PerModulePasses.add(createBitcodeWriterPass(
896 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000897 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000898 break;
899
900 case Backend_EmitLL:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000901 PerModulePasses.add(
Duncan P. N. Exon Smithbb9cadf2015-04-15 02:45:28 +0000902 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000903 break;
904
905 default:
Aaron Puchertb207bae2019-06-26 21:36:35 +0000906 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +0000907 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000908 if (!DwoOS)
909 return;
910 }
911 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
912 DwoOS ? &DwoOS->os() : nullptr))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000913 return;
914 }
915
Andrew Trick15e36e82011-04-05 18:56:55 +0000916 // Before executing passes, print the final values of the LLVM options.
917 cl::PrintOptionValues();
918
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000919 // Run passes. For now we do all passes at once, but eventually we
920 // would like to have the option of streaming code generation.
921
Peter Collingbourne03f89072016-07-15 00:55:40 +0000922 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000923 PrettyStackTraceString CrashInfo("Per-function optimization");
Russell Gallopdf494f72019-12-11 11:49:42 +0000924 llvm::TimeTraceScope TimeScope("PerFunctionPasses");
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000925
Peter Collingbourne03f89072016-07-15 00:55:40 +0000926 PerFunctionPasses.doInitialization();
Yaron Keren10d6d162015-06-05 09:40:53 +0000927 for (Function &F : *TheModule)
928 if (!F.isDeclaration())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000929 PerFunctionPasses.run(F);
930 PerFunctionPasses.doFinalization();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000931 }
932
Peter Collingbourne03f89072016-07-15 00:55:40 +0000933 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000934 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Russell Gallopdf494f72019-12-11 11:49:42 +0000935 llvm::TimeTraceScope TimeScope("PerModulePasses");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000936 PerModulePasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000937 }
938
Peter Collingbourne03f89072016-07-15 00:55:40 +0000939 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000940 PrettyStackTraceString CrashInfo("Code generation");
Russell Gallopdf494f72019-12-11 11:49:42 +0000941 llvm::TimeTraceScope TimeScope("CodeGenPasses");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000942 CodeGenPasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000943 }
Peter Collingbourne91d02842018-05-22 18:52:37 +0000944
945 if (ThinLinkOS)
946 ThinLinkOS->keep();
947 if (DwoOS)
948 DwoOS->keep();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000949}
950
Chandler Carruth50f9e892016-12-23 20:44:01 +0000951static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
952 switch (Opts.OptimizationLevel) {
953 default:
954 llvm_unreachable("Invalid optimization level!");
955
956 case 1:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800957 return PassBuilder::OptimizationLevel::O1;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000958
959 case 2:
960 switch (Opts.OptimizeSize) {
961 default:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000962 llvm_unreachable("Invalid optimization level for size!");
Chandler Carruth50f9e892016-12-23 20:44:01 +0000963
964 case 0:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800965 return PassBuilder::OptimizationLevel::O2;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000966
967 case 1:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800968 return PassBuilder::OptimizationLevel::Os;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000969
970 case 2:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800971 return PassBuilder::OptimizationLevel::Oz;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000972 }
973
974 case 3:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800975 return PassBuilder::OptimizationLevel::O3;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000976 }
977}
978
Brian Gesiak048239e2019-12-26 08:00:00 -0500979static void addCoroutinePassesAtO0(ModulePassManager &MPM,
980 const LangOptions &LangOpts,
981 const CodeGenOptions &CodeGenOpts) {
982 if (!LangOpts.Coroutines)
983 return;
984
985 MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
986
987 CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
988 CGPM.addPass(CoroSplitPass());
989 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
990 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
991
992 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
993}
994
Benjamin Kramerba2ea932019-03-28 17:18:42 +0000995static void addSanitizersAtO0(ModulePassManager &MPM,
996 const Triple &TargetTriple,
997 const LangOptions &LangOpts,
998 const CodeGenOptions &CodeGenOpts) {
Petr Hosek366cda02019-05-09 06:09:35 +0000999 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
Leonard Chan436fb2b2019-02-13 22:22:48 +00001000 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
Petr Hosek366cda02019-05-09 06:09:35 +00001001 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1002 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1003 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
Leonard Chan436fb2b2019-02-13 22:22:48 +00001004 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Petr Hosek366cda02019-05-09 06:09:35 +00001005 MPM.addPass(
1006 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
1007 CodeGenOpts.SanitizeAddressUseOdrIndicator));
1008 };
1009
1010 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1011 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
1012 }
1013
1014 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1015 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001016 }
Leonard Chan1a240ed2019-02-20 03:50:11 +00001017
1018 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Arthur Eubanks48451ee2020-05-05 13:33:13 -07001019 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1020 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1021 MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1022 MPM.addPass(createModuleToFunctionPassAdaptor(
1023 MemorySanitizerPass({TrackOrigins, Recover, false})));
Leonard Chan1a240ed2019-02-20 03:50:11 +00001024 }
1025
Petr Hosek366cda02019-05-09 06:09:35 +00001026 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1027 MPM.addPass(createModuleToFunctionPassAdaptor(
1028 MemorySanitizerPass({0, false, /*Kernel=*/true})));
1029 }
1030
Leonard Chan1a240ed2019-02-20 03:50:11 +00001031 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001032 MPM.addPass(ThreadSanitizerPass());
Leonard Chan1a240ed2019-02-20 03:50:11 +00001033 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1034 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001035}
1036
Chandler Carruth50f9e892016-12-23 20:44:01 +00001037/// A clean version of `EmitAssembly` that uses the new pass manager.
1038///
1039/// Not all features are currently supported in this system, but where
1040/// necessary it falls back to the legacy pass manager to at least provide
1041/// basic functionality.
1042///
1043/// This API is planned to have its functionality finished and then to replace
1044/// `EmitAssembly` at some point in the future when the default switches.
1045void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1046 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +00001047 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001048 setCommandLineOpts(CodeGenOpts);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001049
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001050 bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1051 Action != Backend_EmitBC &&
1052 Action != Backend_EmitLL);
1053 CreateTargetMachine(RequiresCodeGen);
1054
1055 if (RequiresCodeGen && !TM)
Chandler Carruth50f9e892016-12-23 20:44:01 +00001056 return;
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001057 if (TM)
1058 TheModule->setDataLayout(TM->createDataLayout());
Chandler Carruth50f9e892016-12-23 20:44:01 +00001059
Dehao Chenc76a27e2017-07-27 15:29:53 +00001060 Optional<PGOOptions> PGOOpt;
Davide Italiano945de432017-02-13 16:07:05 +00001061
Dehao Chenc76a27e2017-07-27 15:29:53 +00001062 if (CodeGenOpts.hasProfileIRInstr())
1063 // -fprofile-generate.
1064 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001065 ? std::string(DefaultProfileGenName)
Dehao Chenc76a27e2017-07-27 15:29:53 +00001066 : CodeGenOpts.InstrProfileOutput,
Rong Xua4a09b22019-03-04 20:21:31 +00001067 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
Richard Smith8654ae52018-10-10 23:13:35 +00001068 CodeGenOpts.DebugInfoForProfiling);
Rong Xua4a09b22019-03-04 20:21:31 +00001069 else if (CodeGenOpts.hasProfileIRUse()) {
Dehao Chenc76a27e2017-07-27 15:29:53 +00001070 // -fprofile-use.
Rong Xua4a09b22019-03-04 20:21:31 +00001071 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1072 : PGOOptions::NoCSAction;
1073 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1074 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1075 CSAction, CodeGenOpts.DebugInfoForProfiling);
1076 } else if (!CodeGenOpts.SampleProfileFile.empty())
Dehao Chenc76a27e2017-07-27 15:29:53 +00001077 // -fprofile-sample-use
Rong Xua4a09b22019-03-04 20:21:31 +00001078 PGOOpt =
1079 PGOOptions(CodeGenOpts.SampleProfileFile, "",
1080 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1081 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
Dehao Chenc76a27e2017-07-27 15:29:53 +00001082 else if (CodeGenOpts.DebugInfoForProfiling)
1083 // -fdebug-info-for-profiling
Rong Xua4a09b22019-03-04 20:21:31 +00001084 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1085 PGOOptions::NoCSAction, true);
1086
1087 // Check to see if we want to generate a CS profile.
1088 if (CodeGenOpts.hasProfileCSIRInstr()) {
1089 assert(!CodeGenOpts.hasProfileCSIRUse() &&
1090 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1091 "the same time");
1092 if (PGOOpt.hasValue()) {
1093 assert(PGOOpt->Action != PGOOptions::IRInstr &&
1094 PGOOpt->Action != PGOOptions::SampleUse &&
1095 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1096 " pass");
1097 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001098 ? std::string(DefaultProfileGenName)
Rong Xua4a09b22019-03-04 20:21:31 +00001099 : CodeGenOpts.InstrProfileOutput;
1100 PGOOpt->CSAction = PGOOptions::CSIRInstr;
1101 } else
1102 PGOOpt = PGOOptions("",
1103 CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001104 ? std::string(DefaultProfileGenName)
Rong Xua4a09b22019-03-04 20:21:31 +00001105 : CodeGenOpts.InstrProfileOutput,
1106 "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1107 CodeGenOpts.DebugInfoForProfiling);
1108 }
Davide Italiano945de432017-02-13 16:07:05 +00001109
Alina Sbirlea267ac922019-05-23 18:51:02 +00001110 PipelineTuningOptions PTO;
Alina Sbirlea21efe2a2019-05-24 17:40:52 +00001111 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001112 // For historical reasons, loop interleaving is set to mirror setting for loop
1113 // unrolling.
1114 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1115 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1116 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
zhizhouy94d91222020-03-31 10:23:17 -07001117 PTO.CallGraphProfile = CodeGenOpts.CallGraphProfile;
Brian Gesiak048239e2019-12-26 08:00:00 -05001118 PTO.Coroutines = LangOpts.Coroutines;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001119
Taewook Ohd4c50f72019-08-14 07:11:09 +00001120 PassInstrumentationCallbacks PIC;
1121 StandardInstrumentations SI;
1122 SI.registerCallbacks(PIC);
1123 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001124
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001125 // Attempt to load pass plugins and register their callbacks with PB.
1126 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1127 auto PassPlugin = PassPlugin::Load(PluginFN);
1128 if (PassPlugin) {
1129 PassPlugin->registerPassBuilderCallbacks(PB);
1130 } else {
1131 Diags.Report(diag::err_fe_unable_to_load_plugin)
1132 << PluginFN << toString(PassPlugin.takeError());
1133 }
1134 }
serge_sans_paille24ab9b52019-06-08 17:37:47 +02001135#define HANDLE_EXTENSION(Ext) \
1136 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1137#include "llvm/Support/Extension.def"
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001138
Craig Topper926b95c2017-11-14 08:48:28 +00001139 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1140 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1141 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1142 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001143
1144 // Register the AA manager first so that our version is the one used.
1145 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1146
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001147 // Register the target library analysis directly and give it a customized
1148 // preset TLI.
1149 Triple TargetTriple(TheModule->getTargetTriple());
Mehdi Aminied03d942020-04-11 01:00:58 +00001150 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1151 createTLII(TargetTriple, CodeGenOpts));
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001152 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001153
Chandler Carruth50f9e892016-12-23 20:44:01 +00001154 // Register all the basic analyses with the managers.
1155 PB.registerModuleAnalyses(MAM);
1156 PB.registerCGSCCAnalyses(CGAM);
1157 PB.registerFunctionAnalyses(FAM);
1158 PB.registerLoopAnalyses(LAM);
1159 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1160
Tim Shenb13eebe2017-06-29 23:10:13 +00001161 ModulePassManager MPM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001162
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001163 if (!CodeGenOpts.DisableLLVMPasses) {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001164 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
Tim Shen66470692017-06-29 23:08:38 +00001165 bool IsLTO = CodeGenOpts.PrepareForLTO;
1166
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001167 if (CodeGenOpts.OptimizationLevel == 0) {
Teresa Johnson2f63d542020-01-24 12:24:18 -08001168 // If we reached here with a non-empty index file name, then the index
1169 // file was empty and we are not performing ThinLTO backend compilation
1170 // (used in testing in a distributed build environment). Drop any the type
1171 // test assume sequences inserted for whole program vtables so that
1172 // codegen doesn't complain.
1173 if (!CodeGenOpts.ThinLTOIndexFile.empty())
1174 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1175 /*ImportSummary=*/nullptr,
1176 /*DropTypeTests=*/true));
David Blaikieac904d02018-01-23 01:25:24 +00001177 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1178 MPM.addPass(GCOVProfilerPass(*Options));
Rong Xu4059e142019-04-25 17:52:43 +00001179 if (Optional<InstrProfOptions> Options =
1180 getInstrProfOptions(CodeGenOpts, LangOpts))
1181 MPM.addPass(InstrProfiling(*Options, false));
David Blaikieac904d02018-01-23 01:25:24 +00001182
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001183 // Build a minimal pipeline based on the semantics required by Clang,
Leonard Chan587497b2019-06-13 16:45:29 +00001184 // which is just that always inlining occurs. Further, disable generating
1185 // lifetime intrinsics to avoid enabling further optimizations during
1186 // code generation.
Jun Mad0f4af82020-03-13 15:27:45 +08001187 // However, we need to insert lifetime intrinsics to avoid invalid access
1188 // caused by multithreaded coroutines.
1189 MPM.addPass(
1190 AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001191
Rong Xuca161fa2019-08-01 22:36:34 +00001192 // At -O0, we can still do PGO. Add all the requested passes for
1193 // instrumentation PGO, if requested.
1194 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1195 PGOOpt->Action == PGOOptions::IRUse))
1196 PB.addPGOInstrPassesForO0(
1197 MPM, CodeGenOpts.DebugPassManager,
1198 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1199 /* IsCS */ false, PGOOpt->ProfileFile,
1200 PGOOpt->ProfileRemappingFile);
1201
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001202 // At -O0 we directly run necessary sanitizer passes.
1203 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1204 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1205
Teresa Johnson6ed79132019-01-04 19:05:01 +00001206 // Lastly, add semantically necessary passes for LTO.
1207 if (IsLTO || IsThinLTO) {
1208 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001209 MPM.addPass(NameAnonGlobalPass());
Teresa Johnson6ed79132019-01-04 19:05:01 +00001210 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001211 } else {
Tim Shen66470692017-06-29 23:08:38 +00001212 // Map our optimization levels into one of the distinct levels used to
1213 // configure the pipeline.
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001214 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1215
Teresa Johnson2f63d542020-01-24 12:24:18 -08001216 // If we reached here with a non-empty index file name, then the index
1217 // file was empty and we are not performing ThinLTO backend compilation
1218 // (used in testing in a distributed build environment). Drop any the type
1219 // test assume sequences inserted for whole program vtables so that
1220 // codegen doesn't complain.
1221 if (!CodeGenOpts.ThinLTOIndexFile.empty())
1222 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1223 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1224 /*ImportSummary=*/nullptr,
1225 /*DropTypeTests=*/true));
1226 });
1227
Leonard Chanb2065132019-06-20 19:35:25 +00001228 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1229 MPM.addPass(createModuleToFunctionPassAdaptor(
1230 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1231 });
1232
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001233 // Register callbacks to schedule sanitizer passes at the appropriate part of
1234 // the pipeline.
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001235 // FIXME: either handle asan/the remaining sanitizers or error out
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001236 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1237 PB.registerScalarOptimizerLateEPCallback(
1238 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1239 FPM.addPass(BoundsCheckingPass());
1240 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001241 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Arthur Eubanks48451ee2020-05-05 13:33:13 -07001242 int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1243 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1244 PB.registerPipelineStartEPCallback(
1245 [TrackOrigins, Recover](ModulePassManager &MPM) {
1246 MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1247 });
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001248 PB.registerOptimizerLastEPCallback(
Arthur Eubanks48451ee2020-05-05 13:33:13 -07001249 [TrackOrigins, Recover](FunctionPassManager &FPM,
1250 PassBuilder::OptimizationLevel Level) {
1251 FPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001252 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001253 }
1254 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1255 PB.registerPipelineStartEPCallback(
1256 [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); });
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001257 PB.registerOptimizerLastEPCallback(
1258 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1259 FPM.addPass(ThreadSanitizerPass());
1260 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001261 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001262 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1263 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1264 MPM.addPass(
1265 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1266 });
1267 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
Leonard Chan619b6d52019-02-14 01:07:47 +00001268 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
Leonard Chan436fb2b2019-02-13 22:22:48 +00001269 PB.registerOptimizerLastEPCallback(
Leonard Chan619b6d52019-02-14 01:07:47 +00001270 [Recover, UseAfterScope](FunctionPassManager &FPM,
1271 PassBuilder::OptimizationLevel Level) {
Leonard Chan436fb2b2019-02-13 22:22:48 +00001272 FPM.addPass(AddressSanitizerPass(
Leonard Chan619b6d52019-02-14 01:07:47 +00001273 /*CompileKernel=*/false, Recover, UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +00001274 });
1275 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Leonard Chan619b6d52019-02-14 01:07:47 +00001276 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1277 PB.registerPipelineStartEPCallback(
1278 [Recover, ModuleUseAfterScope,
1279 UseOdrIndicator](ModulePassManager &MPM) {
1280 MPM.addPass(ModuleAddressSanitizerPass(
1281 /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1282 UseOdrIndicator));
1283 });
Leonard Chan436fb2b2019-02-13 22:22:48 +00001284 }
David Blaikieac904d02018-01-23 01:25:24 +00001285 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1286 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1287 MPM.addPass(GCOVProfilerPass(*Options));
1288 });
Rong Xu4059e142019-04-25 17:52:43 +00001289 if (Optional<InstrProfOptions> Options =
1290 getInstrProfOptions(CodeGenOpts, LangOpts))
1291 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1292 MPM.addPass(InstrProfiling(*Options, false));
1293 });
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001294
Tim Shen66470692017-06-29 23:08:38 +00001295 if (IsThinLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001296 MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1297 Level, CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001298 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001299 MPM.addPass(NameAnonGlobalPass());
1300 } else if (IsLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001301 MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1302 CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001303 MPM.addPass(CanonicalizeAliasesPass());
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001304 MPM.addPass(NameAnonGlobalPass());
Tim Shen66470692017-06-29 23:08:38 +00001305 } else {
Tim Shenb13eebe2017-06-29 23:10:13 +00001306 MPM = PB.buildPerModuleDefaultPipeline(Level,
1307 CodeGenOpts.DebugPassManager);
Tim Shen66470692017-06-29 23:08:38 +00001308 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001309 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001310
Leonard Chan486b1732019-09-08 07:30:17 +00001311 if (CodeGenOpts.SanitizeCoverageType ||
1312 CodeGenOpts.SanitizeCoverageIndirectCalls ||
1313 CodeGenOpts.SanitizeCoverageTraceCmp) {
1314 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1315 MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1316 }
1317
Peter Collingbourne3b82b922019-07-17 21:45:19 +00001318 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1319 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1320 MPM.addPass(HWAddressSanitizerPass(
1321 /*CompileKernel=*/false, Recover));
1322 }
1323 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1324 MPM.addPass(HWAddressSanitizerPass(
1325 /*CompileKernel=*/true, /*Recover=*/true));
1326 }
1327
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -08001328 if (CodeGenOpts.OptimizationLevel > 0 &&
1329 LangOpts.Sanitize.has(SanitizerKind::MemTag)) {
1330 MPM.addPass(StackSafetyGlobalAnnotatorPass());
1331 }
1332
Leonard Chan007f6742019-07-25 20:53:15 +00001333 if (CodeGenOpts.OptimizationLevel == 0) {
Brian Gesiak048239e2019-12-26 08:00:00 -05001334 addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001335 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
Leonard Chan007f6742019-07-25 20:53:15 +00001336 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001337 }
1338
1339 // FIXME: We still use the legacy pass manager to do code generation. We
1340 // create that pass manager here and use it as needed below.
1341 legacy::PassManager CodeGenPasses;
1342 bool NeedCodeGen = false;
Peter Collingbourne91d02842018-05-22 18:52:37 +00001343 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Chandler Carruth50f9e892016-12-23 20:44:01 +00001344
1345 // Append any output we need to the pass manager.
1346 switch (Action) {
1347 case Backend_EmitNothing:
1348 break;
1349
1350 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +00001351 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Tim Shen50fedec2017-06-01 23:27:51 +00001352 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +00001353 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1354 if (!ThinLinkOS)
Tim Shen50fedec2017-06-01 23:27:51 +00001355 return;
Tim Shen50fedec2017-06-01 23:27:51 +00001356 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001357 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1358 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001359 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1360 : nullptr));
Tim Shen50fedec2017-06-01 23:27:51 +00001361 } else {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001362 // Emit a module summary by default for Regular LTO except for ld64
1363 // targets
1364 bool EmitLTOSummary =
1365 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +00001366 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001367 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1368 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001369 if (EmitLTOSummary) {
1370 if (!TheModule->getModuleFlag("ThinLTO"))
1371 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1372 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Leonard Chan19ec31d2019-08-21 17:24:14 +00001373 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001374 }
1375 MPM.addPass(
1376 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tim Shen50fedec2017-06-01 23:27:51 +00001377 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001378 break;
1379
1380 case Backend_EmitLL:
1381 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1382 break;
1383
1384 case Backend_EmitAssembly:
1385 case Backend_EmitMCNull:
1386 case Backend_EmitObj:
1387 NeedCodeGen = true;
1388 CodeGenPasses.add(
1389 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Aaron Puchertb207bae2019-06-26 21:36:35 +00001390 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00001391 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001392 if (!DwoOS)
1393 return;
1394 }
1395 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1396 DwoOS ? &DwoOS->os() : nullptr))
Chandler Carruth50f9e892016-12-23 20:44:01 +00001397 // FIXME: Should we handle this error differently?
1398 return;
1399 break;
1400 }
1401
1402 // Before executing passes, print the final values of the LLVM options.
1403 cl::PrintOptionValues();
1404
1405 // Now that we have all of the passes ready, run them.
1406 {
1407 PrettyStackTraceString CrashInfo("Optimizer");
1408 MPM.run(*TheModule, MAM);
1409 }
1410
1411 // Now if needed, run the legacy PM for codegen.
1412 if (NeedCodeGen) {
1413 PrettyStackTraceString CrashInfo("Code generation");
1414 CodeGenPasses.run(*TheModule);
1415 }
Peter Collingbourne91d02842018-05-22 18:52:37 +00001416
1417 if (ThinLinkOS)
1418 ThinLinkOS->keep();
1419 if (DwoOS)
1420 DwoOS->keep();
Chandler Carruth50f9e892016-12-23 20:44:01 +00001421}
1422
Peter Collingbourne47d23642017-01-24 19:54:37 +00001423Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1424 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1425 if (!BMsOrErr)
1426 return BMsOrErr.takeError();
1427
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00001428 // The bitcode file may contain multiple modules, we want the one that is
1429 // marked as being the ThinLTO module.
Vitaly Bukac35ff822018-02-16 23:34:16 +00001430 if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1431 return *Bm;
Peter Collingbourne47d23642017-01-24 19:54:37 +00001432
1433 return make_error<StringError>("Could not find module summary",
1434 inconvertibleErrorCode());
1435}
1436
Vitaly Bukac35ff822018-02-16 23:34:16 +00001437BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1438 for (BitcodeModule &BM : BMs) {
1439 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1440 if (LTOInfo && LTOInfo->IsThinLTO)
1441 return &BM;
1442 }
1443 return nullptr;
1444}
1445
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001446static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001447 const HeaderSearchOptions &HeaderOpts,
1448 const CodeGenOptions &CGOpts,
1449 const clang::TargetOptions &TOpts,
1450 const LangOptions &LOpts,
Dehao Chena1bd2d62017-01-13 00:51:55 +00001451 std::unique_ptr<raw_pwrite_stream> OS,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001452 std::string SampleProfile,
Richard Smith8654ae52018-10-10 23:13:35 +00001453 std::string ProfileRemapping,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001454 BackendAction Action) {
Dehao Chen5f83d0e2017-07-10 20:31:37 +00001455 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001456 ModuleToDefinedGVSummaries;
1457 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1458
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001459 setCommandLineOpts(CGOpts);
1460
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001461 // We can simply import the values mentioned in the combined index, since
1462 // we should only invoke this using the individual indexes written out
1463 // via a WriteIndexesThinBackend.
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001464 FunctionImporter::ImportMapTy ImportList;
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001465 for (auto &GlobalList : *CombinedIndex) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001466 // Ignore entries for undefined references.
1467 if (GlobalList.second.SummaryList.empty())
1468 continue;
1469
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001470 auto GUID = GlobalList.first;
Teresa Johnson5ed8b002018-11-29 17:02:59 +00001471 for (auto &Summary : GlobalList.second.SummaryList) {
1472 // Skip the summaries for the importing module. These are included to
1473 // e.g. record required linkage changes.
1474 if (Summary->modulePath() == M->getModuleIdentifier())
1475 continue;
1476 // Add an entry to provoke importing by thinBackend.
1477 ImportList[Summary->modulePath()].insert(GUID);
1478 }
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001479 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001480
1481 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001482 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001483
1484 for (auto &I : ImportList) {
1485 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1486 llvm::MemoryBuffer::getFile(I.first());
1487 if (!MBOrErr) {
1488 errs() << "Error loading imported file '" << I.first()
1489 << "': " << MBOrErr.getError().message() << "\n";
1490 return;
1491 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001492
Peter Collingbourne47d23642017-01-24 19:54:37 +00001493 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1494 if (!BMOrErr) {
1495 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001496 errs() << "Error loading imported file '" << I.first()
1497 << "': " << EIB.message() << '\n';
1498 });
1499 return;
1500 }
Peter Collingbourne47d23642017-01-24 19:54:37 +00001501 ModuleMap.insert({I.first(), *BMOrErr});
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001502
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001503 OwnedImports.push_back(std::move(*MBOrErr));
1504 }
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001505 auto AddStream = [&](size_t Task) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001506 return std::make_unique<lto::NativeObjectStream>(std::move(OS));
Mehdi Amini406aa222016-08-17 06:23:08 +00001507 };
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001508 lto::Config Conf;
Teresa Johnson9e4321c2018-04-17 16:39:25 +00001509 if (CGOpts.SaveTempsFilePrefix != "") {
1510 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1511 /* UseInputModulePath */ false)) {
1512 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1513 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1514 << '\n';
1515 });
1516 }
1517 }
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001518 Conf.CPU = TOpts.CPU;
1519 Conf.CodeModel = getCodeModel(CGOpts);
1520 Conf.MAttrs = TOpts.Features;
Rafael Espindolae1d70532018-01-18 00:20:03 +00001521 Conf.RelocModel = CGOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001522 Conf.CGOptLevel = getCGOptLevel(CGOpts);
Teresa Johnson867bc392019-04-23 18:56:19 +00001523 Conf.OptLevel = CGOpts.OptimizationLevel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001524 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001525 Conf.SampleProfile = std::move(SampleProfile);
Wei Mi21a47102020-01-09 20:58:31 -08001526 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1527 // For historical reasons, loop interleaving is set to mirror setting for loop
1528 // unrolling.
1529 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1530 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1531 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
zhizhouy94d91222020-03-31 10:23:17 -07001532 Conf.PTO.CallGraphProfile = CGOpts.CallGraphProfile;
Rong Xua4a09b22019-03-04 20:21:31 +00001533
1534 // Context sensitive profile.
1535 if (CGOpts.hasProfileCSIRInstr()) {
1536 Conf.RunCSIRInstr = true;
1537 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1538 } else if (CGOpts.hasProfileCSIRUse()) {
1539 Conf.RunCSIRInstr = false;
1540 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1541 }
1542
Richard Smith8654ae52018-10-10 23:13:35 +00001543 Conf.ProfileRemapping = std::move(ProfileRemapping);
Tim Shen50fedec2017-06-01 23:27:51 +00001544 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
Teresa Johnson4cd016ab2017-11-13 15:38:33 +00001545 Conf.DebugPassManager = CGOpts.DebugPassManager;
Teresa Johnson66744f82018-05-05 14:37:29 +00001546 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1547 Conf.RemarksFilename = CGOpts.OptRecordFile;
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00001548 Conf.RemarksPasses = CGOpts.OptRecordPasses;
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00001549 Conf.RemarksFormat = CGOpts.OptRecordFormat;
Aaron Pucherte1dc4952019-06-15 15:38:51 +00001550 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1551 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001552 switch (Action) {
1553 case Backend_EmitNothing:
1554 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1555 return false;
1556 };
1557 break;
1558 case Backend_EmitLL:
1559 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1560 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1561 return false;
1562 };
1563 break;
1564 case Backend_EmitBC:
1565 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
Rafael Espindola76c8f822018-02-14 19:11:37 +00001566 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001567 return false;
1568 };
1569 break;
1570 default:
1571 Conf.CGFileType = getCodeGenFileType(Action);
1572 break;
1573 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001574 if (Error E = thinBackend(
Teresa Johnson66744f82018-05-05 14:37:29 +00001575 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001576 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1577 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1578 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1579 });
1580 }
1581}
1582
David Blaikie9c902b52011-09-25 23:23:43 +00001583void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001584 const HeaderSearchOptions &HeaderOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00001585 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +00001586 const clang::TargetOptions &TOpts,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001587 const LangOptions &LOpts,
1588 const llvm::DataLayout &TDesc, Module *M,
1589 BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +00001590 std::unique_ptr<raw_pwrite_stream> OS) {
Anton Afanasyevd880de22019-03-30 08:42:48 +00001591
Russell Gallopdf494f72019-12-11 11:49:42 +00001592 llvm::TimeTraceScope TimeScope("Backend");
Anton Afanasyevd880de22019-03-30 08:42:48 +00001593
Vitaly Buka769134d2018-02-16 23:38:22 +00001594 std::unique_ptr<llvm::Module> EmptyModule;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001595 if (!CGOpts.ThinLTOIndexFile.empty()) {
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001596 // If we are performing a ThinLTO importing compile, load the function index
1597 // into memory and pass it into runThinLTOBackend, which will run the
1598 // function importer and invoke LTO passes.
1599 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
Teresa Johnson517729f2017-05-12 19:32:17 +00001600 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1601 /*IgnoreEmptyThinLTOIndexFile*/true);
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001602 if (!IndexOrErr) {
1603 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1604 "Error loading index file '" +
1605 CGOpts.ThinLTOIndexFile + "': ");
1606 return;
1607 }
1608 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1609 // A null CombinedIndex means we should skip ThinLTO compilation
1610 // (LLVM will optionally ignore empty index files, returning null instead
1611 // of an error).
Vitaly Buka769134d2018-02-16 23:38:22 +00001612 if (CombinedIndex) {
1613 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1614 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1615 LOpts, std::move(OS), CGOpts.SampleProfileFile,
Richard Smith8654ae52018-10-10 23:13:35 +00001616 CGOpts.ProfileRemappingFile, Action);
Vitaly Buka769134d2018-02-16 23:38:22 +00001617 return;
1618 }
1619 // Distributed indexing detected that nothing from the module is needed
1620 // for the final linking. So we can skip the compilation. We sill need to
1621 // output an empty object file to make sure that a linker does not fail
1622 // trying to read it. Also for some features, like CFI, we must skip
1623 // the compilation as CombinedIndex does not contain all required
1624 // information.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001625 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
Vitaly Buka769134d2018-02-16 23:38:22 +00001626 EmptyModule->setTargetTriple(M->getTargetTriple());
1627 M = EmptyModule.get();
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001628 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001629 }
1630
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001631 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001632
Chandler Carruth50f9e892016-12-23 20:44:01 +00001633 if (CGOpts.ExperimentalNewPassManager)
1634 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1635 else
1636 AsmHelper.EmitAssembly(Action, std::move(OS));
Alp Tokere83b9062014-01-02 15:08:04 +00001637
James Y Knightb214cbc2016-03-04 19:00:41 +00001638 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1639 // DataLayout.
1640 if (AsmHelper.TM) {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00001641 std::string DLDesc = M->getDataLayout().getStringRepresentation();
James Y Knightb214cbc2016-03-04 19:00:41 +00001642 if (DLDesc != TDesc.getStringRepresentation()) {
Alp Tokere83b9062014-01-02 15:08:04 +00001643 unsigned DiagID = Diags.getCustomDiagID(
1644 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1645 "expected target description '%1'");
James Y Knightb214cbc2016-03-04 19:00:41 +00001646 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
Alp Tokere83b9062014-01-02 15:08:04 +00001647 }
1648 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001649}
Steven Wu27fb5222016-05-11 16:26:03 +00001650
Steven Wu27fb5222016-05-11 16:26:03 +00001651// With -fembed-bitcode, save a copy of the llvm IR as data in the
1652// __LLVM,__bitcode section.
1653void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1654 llvm::MemoryBufferRef Buf) {
1655 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1656 return;
Teresa Johnsonc8e0bb32019-12-12 11:59:36 -08001657 llvm::EmbedBitcodeInModule(
1658 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1659 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1660 &CGOpts.CmdArgs);
Steven Wu27fb5222016-05-11 16:26:03 +00001661}