blob: 4e8b722eea34c87cd7f5ba66cf3b29f4ae59f6a2 [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;
Kostya Serebryany61457762017-07-28 00:10:10 +0000225 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000226 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
Leonard Chan007f6742019-07-25 20:53:15 +0000227 return Opts;
228}
229
230static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
231 legacy::PassManagerBase &PM) {
232 const PassManagerBuilderWrapper &BuilderWrapper =
233 static_cast<const PassManagerBuilderWrapper &>(Builder);
234 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
235 auto Opts = getSancovOptsFromCGOpts(CGOpts);
236 PM.add(createModuleSanitizerCoverageLegacyPassPass(Opts));
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000237}
238
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000239// Check if ASan should use GC-friendly instrumentation for globals.
240// First of all, there is no point if -fdata-sections is off (expect for MachO,
241// where this is not a factor). Also, on ELF this feature requires an assembler
242// extension that only works with -integrated-as at the moment.
243static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000244 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
245 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000246 switch (T.getObjectFormat()) {
247 case Triple::MachO:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000248 case Triple::COFF:
Evgeniy Stepanovc7b90942017-04-26 00:51:06 +0000249 return true;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000250 case Triple::ELF:
251 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
Hubert Tong2711e162019-07-19 08:46:18 +0000252 case Triple::XCOFF:
253 llvm::report_fatal_error("ASan not implemented for XCOFF.");
254 case Triple::Wasm:
255 case Triple::UnknownObjectFormat:
256 break;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000257 }
Hubert Tong2711e162019-07-19 08:46:18 +0000258 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000259}
260
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000261static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000262 legacy::PassManagerBase &PM) {
Yury Gribov5bfeca12015-11-11 10:45:48 +0000263 const PassManagerBuilderWrapper &BuilderWrapper =
264 static_cast<const PassManagerBuilderWrapper&>(Builder);
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000265 const Triple &T = BuilderWrapper.getTargetTriple();
Yury Gribov5bfeca12015-11-11 10:45:48 +0000266 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
267 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000268 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
Vitaly Buka8076c572018-12-05 01:44:31 +0000269 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000270 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000271 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
272 UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000273 PM.add(createModuleAddressSanitizerLegacyPassPass(
274 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000275}
276
277static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
278 legacy::PassManagerBase &PM) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000279 PM.add(createAddressSanitizerFunctionPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000280 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000281 PM.add(createModuleAddressSanitizerLegacyPassPass(
Vitaly Buka8076c572018-12-05 01:44:31 +0000282 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
283 /*UseOdrIndicator*/ false));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000284}
285
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000286static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
287 legacy::PassManagerBase &PM) {
Evgeniy Stepanov3fd1b1a2017-12-20 19:05:44 +0000288 const PassManagerBuilderWrapper &BuilderWrapper =
289 static_cast<const PassManagerBuilderWrapper &>(Builder);
290 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
291 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000292 PM.add(
293 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000294}
295
296static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
297 legacy::PassManagerBase &PM) {
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000298 PM.add(createHWAddressSanitizerLegacyPassPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000299 /*CompileKernel*/ true, /*Recover*/ true));
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000300}
301
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000302static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
303 legacy::PassManagerBase &PM,
304 bool CompileKernel) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000305 const PassManagerBuilderWrapper &BuilderWrapper =
306 static_cast<const PassManagerBuilderWrapper&>(Builder);
307 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Evgeniy Stepanov5b5370a2016-11-07 21:02:11 +0000308 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
309 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
Philip Pfaffe0ee6a932019-02-04 21:02:49 +0000310 PM.add(createMemorySanitizerLegacyPassPass(
311 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000312
313 // MemorySanitizer inserts complex instrumentation that mostly follows
314 // the logic of the original code, but operates on "shadow" values.
315 // It can benefit from re-running some general purpose optimization passes.
316 if (Builder.OptLevel > 0) {
317 PM.add(createEarlyCSEPass());
318 PM.add(createReassociatePass());
319 PM.add(createLICMPass());
320 PM.add(createGVNPass());
321 PM.add(createInstructionCombiningPass());
322 PM.add(createDeadStoreEliminationPass());
323 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000324}
325
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000326static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
327 legacy::PassManagerBase &PM) {
328 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
329}
330
331static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
332 legacy::PassManagerBase &PM) {
333 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
334}
335
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000336static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000337 legacy::PassManagerBase &PM) {
Philip Pfaffe685c76d2019-01-16 09:28:01 +0000338 PM.add(createThreadSanitizerLegacyPassPass());
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000339}
340
Peter Collingbournec3772752013-08-07 22:47:34 +0000341static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000342 legacy::PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000343 const PassManagerBuilderWrapper &BuilderWrapper =
344 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonovae5804f2014-10-15 20:22:54 +0000345 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000346 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
Peter Collingbournec3772752013-08-07 22:47:34 +0000347}
348
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -0800349static void addMemTagOptimizationPasses(const PassManagerBuilder &Builder,
350 legacy::PassManagerBase &PM) {
351 PM.add(createStackSafetyGlobalInfoWrapperPass(/*SetMetadata=*/true));
352}
353
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000354static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
355 const CodeGenOptions &CodeGenOpts) {
356 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000357
358 switch (CodeGenOpts.getVecLib()) {
359 case CodeGenOptions::Accelerate:
360 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
361 break;
Nemanja Ivanovic6321c682019-06-05 01:57:57 +0000362 case CodeGenOptions::MASSV:
363 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
Jim Lin466f8842020-02-18 10:48:38 +0800364 break;
Matt Masten6731dea2016-07-29 16:44:24 +0000365 case CodeGenOptions::SVML:
366 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
367 break;
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000368 default:
369 break;
370 }
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000371 return TLII;
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000372}
373
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000374static void addSymbolRewriterPass(const CodeGenOptions &Opts,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000375 legacy::PassManager *MPM) {
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000376 llvm::SymbolRewriter::RewriteDescriptorList DL;
377
378 llvm::SymbolRewriter::RewriteMapParser MapParser;
379 for (const auto &MapFile : Opts.RewriteMapFiles)
380 MapParser.parse(MapFile, &DL);
381
382 MPM->add(createRewriteSymbolsPass(DL));
383}
384
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000385static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
386 switch (CodeGenOpts.OptimizationLevel) {
387 default:
388 llvm_unreachable("Invalid optimization level!");
389 case 0:
390 return CodeGenOpt::None;
391 case 1:
392 return CodeGenOpt::Less;
393 case 2:
394 return CodeGenOpt::Default; // O2/Os/Oz
395 case 3:
396 return CodeGenOpt::Aggressive;
397 }
398}
399
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000400static Optional<llvm::CodeModel::Model>
401getCodeModel(const CodeGenOptions &CodeGenOpts) {
402 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
David Greenecc69872018-08-22 11:34:28 +0000403 .Case("tiny", llvm::CodeModel::Tiny)
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000404 .Case("small", llvm::CodeModel::Small)
405 .Case("kernel", llvm::CodeModel::Kernel)
406 .Case("medium", llvm::CodeModel::Medium)
407 .Case("large", llvm::CodeModel::Large)
408 .Case("default", ~1u)
409 .Default(~0u);
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000410 assert(CodeModel != ~0u && "invalid code model!");
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000411 if (CodeModel == ~1u)
412 return None;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000413 return static_cast<llvm::CodeModel::Model>(CodeModel);
414}
415
Reid Kleckner1dfede32019-11-13 15:17:46 -0800416static CodeGenFileType getCodeGenFileType(BackendAction Action) {
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000417 if (Action == Backend_EmitObj)
Reid Kleckner1dfede32019-11-13 15:17:46 -0800418 return CGFT_ObjectFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000419 else if (Action == Backend_EmitMCNull)
Reid Kleckner1dfede32019-11-13 15:17:46 -0800420 return CGFT_Null;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000421 else {
422 assert(Action == Backend_EmitAssembly && "Invalid action!");
Reid Kleckner1dfede32019-11-13 15:17:46 -0800423 return CGFT_AssemblyFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000424 }
425}
426
427static void initTargetOptions(llvm::TargetOptions &Options,
428 const CodeGenOptions &CodeGenOpts,
429 const clang::TargetOptions &TargetOpts,
430 const LangOptions &LangOpts,
431 const HeaderSearchOptions &HSOpts) {
432 Options.ThreadModel =
433 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
434 .Case("posix", llvm::ThreadModel::POSIX)
435 .Case("single", llvm::ThreadModel::Single);
436
437 // Set float ABI type.
438 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
439 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
440 "Invalid Floating Point ABI!");
441 Options.FloatABIType =
442 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
443 .Case("soft", llvm::FloatABI::Soft)
444 .Case("softfp", llvm::FloatABI::Soft)
445 .Case("hard", llvm::FloatABI::Hard)
446 .Default(llvm::FloatABI::Default);
447
448 // Set FP fusion mode.
449 switch (LangOpts.getDefaultFPContractMode()) {
450 case LangOptions::FPC_Off:
Adam Nemet03af4242017-04-20 17:09:35 +0000451 // Preserve any contraction performed by the front-end. (Strict performs
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000452 // splitting of the muladd intrinsic in the backend.)
Adam Nemet03af4242017-04-20 17:09:35 +0000453 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000454 break;
455 case LangOptions::FPC_On:
456 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
457 break;
458 case LangOptions::FPC_Fast:
459 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
460 break;
461 }
462
463 Options.UseInitArray = CodeGenOpts.UseInitArray;
464 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
Saleem Abdulrasool54448902017-06-09 00:40:30 +0000465 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000466 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
467
468 // Set EABI version.
Yuka Takahashidc771502017-07-01 07:57:23 +0000469 Options.EABIVersion = TargetOpts.EABIVersion;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000470
471 if (LangOpts.SjLjExceptions)
472 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
Martell Malonec950c652017-11-29 07:25:12 +0000473 if (LangOpts.SEHExceptions)
474 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
475 if (LangOpts.DWARFExceptions)
476 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
Heejin Ahne8b2b882019-09-12 04:01:37 +0000477 if (LangOpts.WasmExceptions)
478 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000479
480 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
481 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
482 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
483 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
484 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
485 Options.FunctionSections = CodeGenOpts.FunctionSections;
486 Options.DataSections = CodeGenOpts.DataSections;
487 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
KAWASHIMA Takahiro10c11e42020-01-13 09:28:02 +0000488 Options.TLSSize = CodeGenOpts.TLSSize;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000489 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +0000490 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000491 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
Sean Eveson5110d4f2018-01-08 13:42:26 +0000492 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
Peter Collingbourne14b468b2018-07-18 00:27:07 +0000493 Options.EmitAddrsig = CodeGenOpts.Addrsig;
David Candler92aa0c22019-10-31 08:55:57 +0000494 Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
Djordje Todorovicc15c68a2020-03-09 11:02:35 +0100495 Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000496
Aaron Puchertb207bae2019-06-26 21:36:35 +0000497 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000498 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
499 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
500 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
501 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
502 Options.MCOptions.MCIncrementalLinkerCompatible =
503 CodeGenOpts.IncrementalLinkerCompatible;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000504 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
Brian Cain7b953b62019-08-08 19:19:20 +0000505 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000506 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
507 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
508 Options.MCOptions.ABIName = TargetOpts.ABI;
509 for (const auto &Entry : HSOpts.UserEntries)
510 if (!Entry.IsFramework &&
511 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
512 Entry.Group == frontend::IncludeDirGroup::Angled ||
513 Entry.Group == frontend::IncludeDirGroup::System))
514 Options.MCOptions.IASSearchPaths.push_back(
515 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
516}
David Blaikie7a4f7f52018-01-09 22:03:47 +0000517static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
518 if (CodeGenOpts.DisableGCov)
519 return None;
520 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
521 return None;
522 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
523 // LLVM's -default-gcov-version flag is set to something invalid.
524 GCOVOptions Options;
525 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
526 Options.EmitData = CodeGenOpts.EmitGcovArcs;
527 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
528 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
529 Options.NoRedZone = CodeGenOpts.DisableRedZone;
530 Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000531 Options.Filter = CodeGenOpts.ProfileFilterFiles;
532 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
David Blaikie7a4f7f52018-01-09 22:03:47 +0000533 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
534 return Options;
535}
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000536
Rong Xu4059e142019-04-25 17:52:43 +0000537static Optional<InstrProfOptions>
538getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
539 const LangOptions &LangOpts) {
540 if (!CodeGenOpts.hasProfileClangInstr())
541 return None;
542 InstrProfOptions Options;
543 Options.NoRedZone = CodeGenOpts.DisableRedZone;
544 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
545
546 // TODO: Surface the option to emit atomic profile counter increments at
547 // the driver level.
548 Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
549 return Options;
550}
551
Peter Collingbourne03f89072016-07-15 00:55:40 +0000552void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000553 legacy::FunctionPassManager &FPM) {
Chandler Carruth93786da2016-12-23 00:23:01 +0000554 // Handle disabling of all LLVM passes, where we want to preserve the
555 // internal module before any optimization.
Steven Wu546a1962015-07-17 20:09:56 +0000556 if (CodeGenOpts.DisableLLVMPasses)
557 return;
558
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000559 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
560 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
561 // are inserted before PMBuilder ones - they'd get the default-constructed
562 // TLI with an unknown target otherwise.
Teresa Johnsonaff22322015-12-07 19:21:34 +0000563 Triple TargetTriple(TheModule->getTargetTriple());
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000564 std::unique_ptr<TargetLibraryInfoImpl> TLII(
565 createTLII(TargetTriple, CodeGenOpts));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000566
Teresa Johnson2f63d542020-01-24 12:24:18 -0800567 // If we reached here with a non-empty index file name, then the index file
568 // was empty and we are not performing ThinLTO backend compilation (used in
569 // testing in a distributed build environment). Drop any the type test
570 // assume sequences inserted for whole program vtables so that codegen doesn't
571 // complain.
572 if (!CodeGenOpts.ThinLTOIndexFile.empty())
573 MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
574 /*ImportSummary=*/nullptr,
575 /*DropTypeTests=*/true));
576
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000577 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
578
Chandler Carruthfcd33142016-12-23 01:24:49 +0000579 // At O0 and O1 we only run the always inliner which is more efficient. At
580 // higher optimization levels we run the normal inliner.
581 if (CodeGenOpts.OptimizationLevel <= 1) {
Jun Mad0f4af82020-03-13 15:27:45 +0800582 bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
583 !CodeGenOpts.DisableLifetimeMarkers) ||
584 LangOpts.Coroutines);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000585 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
586 } else {
Dehao Chence39fdd2017-03-21 19:55:46 +0000587 // We do not want to inline hot callsites for SamplePGO module-summary build
588 // because profile annotation will happen again in ThinLTO backend, and we
589 // want the IR of the hot path to match the profile.
Chandler Carruthfcd33142016-12-23 01:24:49 +0000590 PMBuilder.Inliner = createFunctionInliningPass(
Dehao Chence39fdd2017-03-21 19:55:46 +0000591 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
592 (!CodeGenOpts.SampleProfileFile.empty() &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000593 CodeGenOpts.PrepareForThinLTO));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000594 }
595
Chandler Carruthfcd33142016-12-23 01:24:49 +0000596 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000597 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000598 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
599 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000600
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000601 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Alina Sbirleaa9b9ab82019-04-30 21:29:23 +0000602 // Loop interleaving in the loop vectorizer has historically been set to be
603 // enabled when loop unrolling is enabled.
604 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000605 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000606 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
Teresa Johnson8749d8042015-07-06 16:23:00 +0000607 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
Hal Finkelce0697f2013-11-17 16:03:29 +0000608 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000609
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000610 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
611
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000612 if (TM)
Stanislav Mekhanoshin61da0672017-01-26 16:49:21 +0000613 TM->adjustPassManager(PMBuilder);
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000614
Dehao Chen7810d4f2017-02-21 20:36:21 +0000615 if (CodeGenOpts.DebugInfoForProfiling ||
616 !CodeGenOpts.SampleProfileFile.empty())
617 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
618 addAddDiscriminatorsPass);
Diego Novillob56be642014-03-03 20:06:18 +0000619
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000620 // In ObjC ARC mode, add the main ARC optimization passes.
621 if (LangOpts.ObjCAutoRefCount) {
622 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
623 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000624 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
625 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000626 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
627 addObjCARCOptPass);
628 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000629
Richard Smith10ab78e2019-02-23 21:06:26 +0000630 if (LangOpts.Coroutines)
Brian Gesiak91a4b5a2018-04-01 23:55:21 +0000631 addCoroutinePassesToExtensionPoints(PMBuilder);
632
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000633 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000634 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
635 addBoundsCheckingPass);
636 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
637 addBoundsCheckingPass);
638 }
639
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000640 if (CodeGenOpts.SanitizeCoverageType ||
641 CodeGenOpts.SanitizeCoverageIndirectCalls ||
642 CodeGenOpts.SanitizeCoverageTraceCmp) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000643 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
644 addSanitizerCoveragePass);
645 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
646 addSanitizerCoveragePass);
647 }
648
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000649 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000650 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000651 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000652 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000653 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000654 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000655
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000656 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
657 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
658 addKernelAddressSanitizerPasses);
659 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
660 addKernelAddressSanitizerPasses);
661 }
662
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000663 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
664 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
665 addHWAddressSanitizerPasses);
666 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
667 addHWAddressSanitizerPasses);
668 }
669
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000670 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
671 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
672 addKernelHWAddressSanitizerPasses);
673 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
674 addKernelHWAddressSanitizerPasses);
675 }
676
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000677 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000678 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
679 addMemorySanitizerPass);
680 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
681 addMemorySanitizerPass);
682 }
683
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000684 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
685 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
686 addKernelMemorySanitizerPass);
687 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
688 addKernelMemorySanitizerPass);
689 }
690
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000691 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000692 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000693 addThreadSanitizerPass);
694 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
695 addThreadSanitizerPass);
696 }
697
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000698 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
Peter Collingbournec3772752013-08-07 22:47:34 +0000699 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
700 addDataFlowSanitizerPass);
701 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
702 addDataFlowSanitizerPass);
703 }
704
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -0800705 if (LangOpts.Sanitize.has(SanitizerKind::MemTag)) {
706 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
707 addMemTagOptimizationPasses);
708 }
709
Chris Lattner5c123672011-05-21 20:40:11 +0000710 // Set up the per-function pass manager.
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000711 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
Chris Lattner5c123672011-05-21 20:40:11 +0000712 if (CodeGenOpts.VerifyModule)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000713 FPM.add(createVerifierPass());
Andrew Trickb2a84722011-04-05 18:49:32 +0000714
Chris Lattner5c123672011-05-21 20:40:11 +0000715 // Set up the per-module pass manager.
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000716 if (!CodeGenOpts.RewriteMapFiles.empty())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000717 addSymbolRewriterPass(CodeGenOpts, &MPM);
Chris Lattnerd98cec52011-02-18 22:20:38 +0000718
David Blaikie7a4f7f52018-01-09 22:03:47 +0000719 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
720 MPM.add(createGCOVProfilerPass(*Options));
Benjamin Kramer8c305922016-02-02 11:06:51 +0000721 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000722 MPM.add(createStripSymbolsPass(true));
Nick Lewycky207bce32011-04-21 23:44:07 +0000723 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000724
Rong Xu4059e142019-04-25 17:52:43 +0000725 if (Optional<InstrProfOptions> Options =
726 getInstrProfOptions(CodeGenOpts, LangOpts))
727 MPM.add(createInstrProfilingLegacyPass(*Options, false));
Vedant Kumaree6c2332018-08-16 22:24:47 +0000728
Rong Xua4a09b22019-03-04 20:21:31 +0000729 bool hasIRInstr = false;
Rong Xu522b5cb2016-02-29 18:54:59 +0000730 if (CodeGenOpts.hasProfileIRInstr()) {
Xinliang David Lib65f8ae2016-07-23 04:28:59 +0000731 PMBuilder.EnablePGOInstrGen = true;
Rong Xua4a09b22019-03-04 20:21:31 +0000732 hasIRInstr = true;
733 }
734 if (CodeGenOpts.hasProfileCSIRInstr()) {
735 assert(!CodeGenOpts.hasProfileCSIRUse() &&
736 "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
737 "same time");
738 assert(!hasIRInstr &&
739 "Cannot have both ProfileGen pass and CSProfileGen pass at the "
740 "same time");
741 PMBuilder.EnablePGOCSInstrGen = true;
742 hasIRInstr = true;
743 }
744 if (hasIRInstr) {
Rong Xu522b5cb2016-02-29 18:54:59 +0000745 if (!CodeGenOpts.InstrProfileOutput.empty())
746 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
747 else
Benjamin Krameradcd0262020-01-28 20:23:46 +0100748 PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
Rong Xu522b5cb2016-02-29 18:54:59 +0000749 }
Rong Xua4a09b22019-03-04 20:21:31 +0000750 if (CodeGenOpts.hasProfileIRUse()) {
Rong Xu9c6f1532016-03-02 20:59:36 +0000751 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
Rong Xua4a09b22019-03-04 20:21:31 +0000752 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
753 }
Justin Bogner970ac602014-12-08 19:04:51 +0000754
Dehao Chen5717aff2016-12-14 21:41:04 +0000755 if (!CodeGenOpts.SampleProfileFile.empty())
756 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
Diego Novillod3ef1082015-08-25 15:25:13 +0000757
Peter Collingbourne03f89072016-07-15 00:55:40 +0000758 PMBuilder.populateFunctionPassManager(FPM);
759 PMBuilder.populateModulePassManager(MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000760}
761
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000762static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
Yaxun Liub5e80c32016-04-12 20:22:32 +0000763 SmallVector<const char *, 16> BackendArgs;
764 BackendArgs.push_back("clang"); // Fake program name.
765 if (!CodeGenOpts.DebugPass.empty()) {
766 BackendArgs.push_back("-debug-pass");
767 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
768 }
769 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
770 BackendArgs.push_back("-limit-float-precision");
771 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
772 }
Yaxun Liub5e80c32016-04-12 20:22:32 +0000773 BackendArgs.push_back(nullptr);
774 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
775 BackendArgs.data());
776}
777
Peter Collingbourne03f89072016-07-15 00:55:40 +0000778void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000779 // Create the TargetMachine for generating code.
780 std::string Error;
781 std::string Triple = TheModule->getTargetTriple();
782 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
783 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000784 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000785 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000786 return;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000787 }
788
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000789 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
Eric Christopher583a1f72015-09-26 01:25:08 +0000790 std::string FeaturesStr =
791 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
Rafael Espindolae1d70532018-01-18 00:20:03 +0000792 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000793 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
Evan Chengdd286bc2011-11-16 08:38:55 +0000794
Nick Lewycky432add52011-12-02 22:17:00 +0000795 llvm::TargetOptions Options;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000796 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000797 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
798 Options, RM, CM, OptLevel));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000799}
800
Peter Collingbourne03f89072016-07-15 00:55:40 +0000801bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
802 BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000803 raw_pwrite_stream &OS,
804 raw_pwrite_stream *DwoOS) {
Chad Rosierb1cfc682012-02-29 20:14:59 +0000805 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000806 llvm::Triple TargetTriple(TheModule->getTargetTriple());
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000807 std::unique_ptr<TargetLibraryInfoImpl> TLII(
808 createTLII(TargetTriple, CodeGenOpts));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000809 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
Chad Rosierb1cfc682012-02-29 20:14:59 +0000810
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000811 // Normal mode, emit a .s or .o file by running the code generator. Note,
812 // this also adds codegenerator level optimization passes.
Reid Kleckner1dfede32019-11-13 15:17:46 -0800813 CodeGenFileType CGFT = getCodeGenFileType(Action);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000814
815 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
816 // "codegen" passes so that it isn't run multiple times when there is
817 // inlining happening.
Steven Wu1d56be82015-05-02 00:56:15 +0000818 if (CodeGenOpts.OptimizationLevel > 0)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000819 CodeGenPasses.add(createObjCARCContractPass());
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000820
Peter Collingbourne91d02842018-05-22 18:52:37 +0000821 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000822 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
823 Diags.Report(diag::err_fe_unable_to_interface_with_target);
824 return false;
825 }
826
827 return true;
828}
829
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000830void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000831 std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000832 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000833
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000834 setCommandLineOpts(CodeGenOpts);
Yaxun Liub5e80c32016-04-12 20:22:32 +0000835
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000836 bool UsesCodeGen = (Action != Backend_EmitNothing &&
837 Action != Backend_EmitBC &&
838 Action != Backend_EmitLL);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000839 CreateTargetMachine(UsesCodeGen);
Alp Tokerf4e22382013-12-20 20:26:53 +0000840
Rafael Espindolab633d202015-06-23 13:59:36 +0000841 if (UsesCodeGen && !TM)
842 return;
843 if (TM)
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000844 TheModule->setDataLayout(TM->createDataLayout());
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000845
Peter Collingbourne03f89072016-07-15 00:55:40 +0000846 legacy::PassManager PerModulePasses;
847 PerModulePasses.add(
848 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
849
850 legacy::FunctionPassManager PerFunctionPasses(TheModule);
851 PerFunctionPasses.add(
852 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
853
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000854 CreatePasses(PerModulePasses, PerFunctionPasses);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000855
856 legacy::PassManager CodeGenPasses;
857 CodeGenPasses.add(
858 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000859
Peter Collingbourne91d02842018-05-22 18:52:37 +0000860 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000861
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000862 switch (Action) {
863 case Backend_EmitNothing:
864 break;
865
866 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +0000867 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000868 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +0000869 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
870 if (!ThinLinkOS)
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000871 return;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000872 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000873 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
874 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000875 PerModulePasses.add(createWriteThinLTOBitcodePass(
876 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000877 } else {
878 // Emit a module summary by default for Regular LTO except for ld64
879 // targets
880 bool EmitLTOSummary =
881 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +0000882 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000883 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
884 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000885 if (EmitLTOSummary) {
886 if (!TheModule->getModuleFlag("ThinLTO"))
887 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
888 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Teresa Johnson604f8022019-07-19 23:02:58 +0000889 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000890 }
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000891
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000892 PerModulePasses.add(createBitcodeWriterPass(
893 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000894 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000895 break;
896
897 case Backend_EmitLL:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000898 PerModulePasses.add(
Duncan P. N. Exon Smithbb9cadf2015-04-15 02:45:28 +0000899 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000900 break;
901
902 default:
Aaron Puchertb207bae2019-06-26 21:36:35 +0000903 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +0000904 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000905 if (!DwoOS)
906 return;
907 }
908 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
909 DwoOS ? &DwoOS->os() : nullptr))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000910 return;
911 }
912
Andrew Trick15e36e82011-04-05 18:56:55 +0000913 // Before executing passes, print the final values of the LLVM options.
914 cl::PrintOptionValues();
915
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000916 // Run passes. For now we do all passes at once, but eventually we
917 // would like to have the option of streaming code generation.
918
Peter Collingbourne03f89072016-07-15 00:55:40 +0000919 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000920 PrettyStackTraceString CrashInfo("Per-function optimization");
Russell Gallopdf494f72019-12-11 11:49:42 +0000921 llvm::TimeTraceScope TimeScope("PerFunctionPasses");
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000922
Peter Collingbourne03f89072016-07-15 00:55:40 +0000923 PerFunctionPasses.doInitialization();
Yaron Keren10d6d162015-06-05 09:40:53 +0000924 for (Function &F : *TheModule)
925 if (!F.isDeclaration())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000926 PerFunctionPasses.run(F);
927 PerFunctionPasses.doFinalization();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000928 }
929
Peter Collingbourne03f89072016-07-15 00:55:40 +0000930 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000931 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Russell Gallopdf494f72019-12-11 11:49:42 +0000932 llvm::TimeTraceScope TimeScope("PerModulePasses");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000933 PerModulePasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000934 }
935
Peter Collingbourne03f89072016-07-15 00:55:40 +0000936 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000937 PrettyStackTraceString CrashInfo("Code generation");
Russell Gallopdf494f72019-12-11 11:49:42 +0000938 llvm::TimeTraceScope TimeScope("CodeGenPasses");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000939 CodeGenPasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000940 }
Peter Collingbourne91d02842018-05-22 18:52:37 +0000941
942 if (ThinLinkOS)
943 ThinLinkOS->keep();
944 if (DwoOS)
945 DwoOS->keep();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000946}
947
Chandler Carruth50f9e892016-12-23 20:44:01 +0000948static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
949 switch (Opts.OptimizationLevel) {
950 default:
951 llvm_unreachable("Invalid optimization level!");
952
953 case 1:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800954 return PassBuilder::OptimizationLevel::O1;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000955
956 case 2:
957 switch (Opts.OptimizeSize) {
958 default:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000959 llvm_unreachable("Invalid optimization level for size!");
Chandler Carruth50f9e892016-12-23 20:44:01 +0000960
961 case 0:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800962 return PassBuilder::OptimizationLevel::O2;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000963
964 case 1:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800965 return PassBuilder::OptimizationLevel::Os;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000966
967 case 2:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800968 return PassBuilder::OptimizationLevel::Oz;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000969 }
970
971 case 3:
Mircea Trofin7acfda62020-01-16 08:51:50 -0800972 return PassBuilder::OptimizationLevel::O3;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000973 }
974}
975
Brian Gesiak048239e2019-12-26 08:00:00 -0500976static void addCoroutinePassesAtO0(ModulePassManager &MPM,
977 const LangOptions &LangOpts,
978 const CodeGenOptions &CodeGenOpts) {
979 if (!LangOpts.Coroutines)
980 return;
981
982 MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
983
984 CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
985 CGPM.addPass(CoroSplitPass());
986 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
987 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
988
989 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
990}
991
Benjamin Kramerba2ea932019-03-28 17:18:42 +0000992static void addSanitizersAtO0(ModulePassManager &MPM,
993 const Triple &TargetTriple,
994 const LangOptions &LangOpts,
995 const CodeGenOptions &CodeGenOpts) {
Petr Hosek366cda02019-05-09 06:09:35 +0000996 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
Leonard Chan436fb2b2019-02-13 22:22:48 +0000997 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
Petr Hosek366cda02019-05-09 06:09:35 +0000998 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
999 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1000 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
Leonard Chan436fb2b2019-02-13 22:22:48 +00001001 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Petr Hosek366cda02019-05-09 06:09:35 +00001002 MPM.addPass(
1003 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
1004 CodeGenOpts.SanitizeAddressUseOdrIndicator));
1005 };
1006
1007 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1008 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
1009 }
1010
1011 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1012 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001013 }
Leonard Chan1a240ed2019-02-20 03:50:11 +00001014
1015 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001016 MPM.addPass(MemorySanitizerPass({}));
Leonard Chan1a240ed2019-02-20 03:50:11 +00001017 MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
1018 }
1019
Petr Hosek366cda02019-05-09 06:09:35 +00001020 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1021 MPM.addPass(createModuleToFunctionPassAdaptor(
1022 MemorySanitizerPass({0, false, /*Kernel=*/true})));
1023 }
1024
Leonard Chan1a240ed2019-02-20 03:50:11 +00001025 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001026 MPM.addPass(ThreadSanitizerPass());
Leonard Chan1a240ed2019-02-20 03:50:11 +00001027 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1028 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001029}
1030
Chandler Carruth50f9e892016-12-23 20:44:01 +00001031/// A clean version of `EmitAssembly` that uses the new pass manager.
1032///
1033/// Not all features are currently supported in this system, but where
1034/// necessary it falls back to the legacy pass manager to at least provide
1035/// basic functionality.
1036///
1037/// This API is planned to have its functionality finished and then to replace
1038/// `EmitAssembly` at some point in the future when the default switches.
1039void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1040 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +00001041 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001042 setCommandLineOpts(CodeGenOpts);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001043
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001044 bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1045 Action != Backend_EmitBC &&
1046 Action != Backend_EmitLL);
1047 CreateTargetMachine(RequiresCodeGen);
1048
1049 if (RequiresCodeGen && !TM)
Chandler Carruth50f9e892016-12-23 20:44:01 +00001050 return;
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001051 if (TM)
1052 TheModule->setDataLayout(TM->createDataLayout());
Chandler Carruth50f9e892016-12-23 20:44:01 +00001053
Dehao Chenc76a27e2017-07-27 15:29:53 +00001054 Optional<PGOOptions> PGOOpt;
Davide Italiano945de432017-02-13 16:07:05 +00001055
Dehao Chenc76a27e2017-07-27 15:29:53 +00001056 if (CodeGenOpts.hasProfileIRInstr())
1057 // -fprofile-generate.
1058 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001059 ? std::string(DefaultProfileGenName)
Dehao Chenc76a27e2017-07-27 15:29:53 +00001060 : CodeGenOpts.InstrProfileOutput,
Rong Xua4a09b22019-03-04 20:21:31 +00001061 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
Richard Smith8654ae52018-10-10 23:13:35 +00001062 CodeGenOpts.DebugInfoForProfiling);
Rong Xua4a09b22019-03-04 20:21:31 +00001063 else if (CodeGenOpts.hasProfileIRUse()) {
Dehao Chenc76a27e2017-07-27 15:29:53 +00001064 // -fprofile-use.
Rong Xua4a09b22019-03-04 20:21:31 +00001065 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1066 : PGOOptions::NoCSAction;
1067 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1068 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1069 CSAction, CodeGenOpts.DebugInfoForProfiling);
1070 } else if (!CodeGenOpts.SampleProfileFile.empty())
Dehao Chenc76a27e2017-07-27 15:29:53 +00001071 // -fprofile-sample-use
Rong Xua4a09b22019-03-04 20:21:31 +00001072 PGOOpt =
1073 PGOOptions(CodeGenOpts.SampleProfileFile, "",
1074 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1075 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
Dehao Chenc76a27e2017-07-27 15:29:53 +00001076 else if (CodeGenOpts.DebugInfoForProfiling)
1077 // -fdebug-info-for-profiling
Rong Xua4a09b22019-03-04 20:21:31 +00001078 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1079 PGOOptions::NoCSAction, true);
1080
1081 // Check to see if we want to generate a CS profile.
1082 if (CodeGenOpts.hasProfileCSIRInstr()) {
1083 assert(!CodeGenOpts.hasProfileCSIRUse() &&
1084 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1085 "the same time");
1086 if (PGOOpt.hasValue()) {
1087 assert(PGOOpt->Action != PGOOptions::IRInstr &&
1088 PGOOpt->Action != PGOOptions::SampleUse &&
1089 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1090 " pass");
1091 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
Benjamin Krameradcd0262020-01-28 20:23:46 +01001092 ? std::string(DefaultProfileGenName)
Rong Xua4a09b22019-03-04 20:21:31 +00001093 : CodeGenOpts.InstrProfileOutput;
1094 PGOOpt->CSAction = PGOOptions::CSIRInstr;
1095 } else
1096 PGOOpt = PGOOptions("",
1097 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 "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1101 CodeGenOpts.DebugInfoForProfiling);
1102 }
Davide Italiano945de432017-02-13 16:07:05 +00001103
Alina Sbirlea267ac922019-05-23 18:51:02 +00001104 PipelineTuningOptions PTO;
Alina Sbirlea21efe2a2019-05-24 17:40:52 +00001105 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001106 // For historical reasons, loop interleaving is set to mirror setting for loop
1107 // unrolling.
1108 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1109 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1110 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
zhizhouy94d91222020-03-31 10:23:17 -07001111 PTO.CallGraphProfile = CodeGenOpts.CallGraphProfile;
Brian Gesiak048239e2019-12-26 08:00:00 -05001112 PTO.Coroutines = LangOpts.Coroutines;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001113
Taewook Ohd4c50f72019-08-14 07:11:09 +00001114 PassInstrumentationCallbacks PIC;
1115 StandardInstrumentations SI;
1116 SI.registerCallbacks(PIC);
1117 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001118
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001119 // Attempt to load pass plugins and register their callbacks with PB.
1120 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1121 auto PassPlugin = PassPlugin::Load(PluginFN);
1122 if (PassPlugin) {
1123 PassPlugin->registerPassBuilderCallbacks(PB);
1124 } else {
1125 Diags.Report(diag::err_fe_unable_to_load_plugin)
1126 << PluginFN << toString(PassPlugin.takeError());
1127 }
1128 }
serge_sans_paille24ab9b52019-06-08 17:37:47 +02001129#define HANDLE_EXTENSION(Ext) \
1130 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1131#include "llvm/Support/Extension.def"
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001132
Craig Topper926b95c2017-11-14 08:48:28 +00001133 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1134 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1135 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1136 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001137
1138 // Register the AA manager first so that our version is the one used.
1139 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1140
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001141 // Register the target library analysis directly and give it a customized
1142 // preset TLI.
1143 Triple TargetTriple(TheModule->getTargetTriple());
1144 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1145 createTLII(TargetTriple, CodeGenOpts));
1146 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001147
Chandler Carruth50f9e892016-12-23 20:44:01 +00001148 // Register all the basic analyses with the managers.
1149 PB.registerModuleAnalyses(MAM);
1150 PB.registerCGSCCAnalyses(CGAM);
1151 PB.registerFunctionAnalyses(FAM);
1152 PB.registerLoopAnalyses(LAM);
1153 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1154
Tim Shenb13eebe2017-06-29 23:10:13 +00001155 ModulePassManager MPM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001156
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001157 if (!CodeGenOpts.DisableLLVMPasses) {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001158 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
Tim Shen66470692017-06-29 23:08:38 +00001159 bool IsLTO = CodeGenOpts.PrepareForLTO;
1160
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001161 if (CodeGenOpts.OptimizationLevel == 0) {
Teresa Johnson2f63d542020-01-24 12:24:18 -08001162 // If we reached here with a non-empty index file name, then the index
1163 // file was empty and we are not performing ThinLTO backend compilation
1164 // (used in testing in a distributed build environment). Drop any the type
1165 // test assume sequences inserted for whole program vtables so that
1166 // codegen doesn't complain.
1167 if (!CodeGenOpts.ThinLTOIndexFile.empty())
1168 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1169 /*ImportSummary=*/nullptr,
1170 /*DropTypeTests=*/true));
David Blaikieac904d02018-01-23 01:25:24 +00001171 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1172 MPM.addPass(GCOVProfilerPass(*Options));
Rong Xu4059e142019-04-25 17:52:43 +00001173 if (Optional<InstrProfOptions> Options =
1174 getInstrProfOptions(CodeGenOpts, LangOpts))
1175 MPM.addPass(InstrProfiling(*Options, false));
David Blaikieac904d02018-01-23 01:25:24 +00001176
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001177 // Build a minimal pipeline based on the semantics required by Clang,
Leonard Chan587497b2019-06-13 16:45:29 +00001178 // which is just that always inlining occurs. Further, disable generating
1179 // lifetime intrinsics to avoid enabling further optimizations during
1180 // code generation.
Jun Mad0f4af82020-03-13 15:27:45 +08001181 // However, we need to insert lifetime intrinsics to avoid invalid access
1182 // caused by multithreaded coroutines.
1183 MPM.addPass(
1184 AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001185
Rong Xuca161fa2019-08-01 22:36:34 +00001186 // At -O0, we can still do PGO. Add all the requested passes for
1187 // instrumentation PGO, if requested.
1188 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1189 PGOOpt->Action == PGOOptions::IRUse))
1190 PB.addPGOInstrPassesForO0(
1191 MPM, CodeGenOpts.DebugPassManager,
1192 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1193 /* IsCS */ false, PGOOpt->ProfileFile,
1194 PGOOpt->ProfileRemappingFile);
1195
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001196 // At -O0 we directly run necessary sanitizer passes.
1197 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1198 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1199
Teresa Johnson6ed79132019-01-04 19:05:01 +00001200 // Lastly, add semantically necessary passes for LTO.
1201 if (IsLTO || IsThinLTO) {
1202 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001203 MPM.addPass(NameAnonGlobalPass());
Teresa Johnson6ed79132019-01-04 19:05:01 +00001204 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001205 } else {
Tim Shen66470692017-06-29 23:08:38 +00001206 // Map our optimization levels into one of the distinct levels used to
1207 // configure the pipeline.
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001208 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1209
Teresa Johnson2f63d542020-01-24 12:24:18 -08001210 // If we reached here with a non-empty index file name, then the index
1211 // file was empty and we are not performing ThinLTO backend compilation
1212 // (used in testing in a distributed build environment). Drop any the type
1213 // test assume sequences inserted for whole program vtables so that
1214 // codegen doesn't complain.
1215 if (!CodeGenOpts.ThinLTOIndexFile.empty())
1216 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1217 MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1218 /*ImportSummary=*/nullptr,
1219 /*DropTypeTests=*/true));
1220 });
1221
Leonard Chanb2065132019-06-20 19:35:25 +00001222 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1223 MPM.addPass(createModuleToFunctionPassAdaptor(
1224 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1225 });
1226
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001227 // Register callbacks to schedule sanitizer passes at the appropriate part of
1228 // the pipeline.
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001229 // FIXME: either handle asan/the remaining sanitizers or error out
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001230 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1231 PB.registerScalarOptimizerLateEPCallback(
1232 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1233 FPM.addPass(BoundsCheckingPass());
1234 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001235 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1236 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1237 MPM.addPass(MemorySanitizerPass({}));
1238 });
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001239 PB.registerOptimizerLastEPCallback(
1240 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001241 FPM.addPass(MemorySanitizerPass({}));
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001242 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001243 }
1244 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1245 PB.registerPipelineStartEPCallback(
1246 [](ModulePassManager &MPM) { MPM.addPass(ThreadSanitizerPass()); });
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001247 PB.registerOptimizerLastEPCallback(
1248 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1249 FPM.addPass(ThreadSanitizerPass());
1250 });
Vitaly Bukab46dd6e2019-10-11 08:47:03 +00001251 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001252 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1253 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1254 MPM.addPass(
1255 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1256 });
1257 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
Leonard Chan619b6d52019-02-14 01:07:47 +00001258 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
Leonard Chan436fb2b2019-02-13 22:22:48 +00001259 PB.registerOptimizerLastEPCallback(
Leonard Chan619b6d52019-02-14 01:07:47 +00001260 [Recover, UseAfterScope](FunctionPassManager &FPM,
1261 PassBuilder::OptimizationLevel Level) {
Leonard Chan436fb2b2019-02-13 22:22:48 +00001262 FPM.addPass(AddressSanitizerPass(
Leonard Chan619b6d52019-02-14 01:07:47 +00001263 /*CompileKernel=*/false, Recover, UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +00001264 });
1265 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Leonard Chan619b6d52019-02-14 01:07:47 +00001266 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1267 PB.registerPipelineStartEPCallback(
1268 [Recover, ModuleUseAfterScope,
1269 UseOdrIndicator](ModulePassManager &MPM) {
1270 MPM.addPass(ModuleAddressSanitizerPass(
1271 /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1272 UseOdrIndicator));
1273 });
Leonard Chan436fb2b2019-02-13 22:22:48 +00001274 }
David Blaikieac904d02018-01-23 01:25:24 +00001275 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1276 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1277 MPM.addPass(GCOVProfilerPass(*Options));
1278 });
Rong Xu4059e142019-04-25 17:52:43 +00001279 if (Optional<InstrProfOptions> Options =
1280 getInstrProfOptions(CodeGenOpts, LangOpts))
1281 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1282 MPM.addPass(InstrProfiling(*Options, false));
1283 });
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001284
Tim Shen66470692017-06-29 23:08:38 +00001285 if (IsThinLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001286 MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1287 Level, CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001288 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001289 MPM.addPass(NameAnonGlobalPass());
1290 } else if (IsLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001291 MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1292 CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001293 MPM.addPass(CanonicalizeAliasesPass());
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001294 MPM.addPass(NameAnonGlobalPass());
Tim Shen66470692017-06-29 23:08:38 +00001295 } else {
Tim Shenb13eebe2017-06-29 23:10:13 +00001296 MPM = PB.buildPerModuleDefaultPipeline(Level,
1297 CodeGenOpts.DebugPassManager);
Tim Shen66470692017-06-29 23:08:38 +00001298 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001299 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001300
Leonard Chan486b1732019-09-08 07:30:17 +00001301 if (CodeGenOpts.SanitizeCoverageType ||
1302 CodeGenOpts.SanitizeCoverageIndirectCalls ||
1303 CodeGenOpts.SanitizeCoverageTraceCmp) {
1304 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1305 MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1306 }
1307
Peter Collingbourne3b82b922019-07-17 21:45:19 +00001308 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1309 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1310 MPM.addPass(HWAddressSanitizerPass(
1311 /*CompileKernel=*/false, Recover));
1312 }
1313 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1314 MPM.addPass(HWAddressSanitizerPass(
1315 /*CompileKernel=*/true, /*Recover=*/true));
1316 }
1317
Evgenii Stepanov2a3723e2020-02-27 15:43:53 -08001318 if (CodeGenOpts.OptimizationLevel > 0 &&
1319 LangOpts.Sanitize.has(SanitizerKind::MemTag)) {
1320 MPM.addPass(StackSafetyGlobalAnnotatorPass());
1321 }
1322
Leonard Chan007f6742019-07-25 20:53:15 +00001323 if (CodeGenOpts.OptimizationLevel == 0) {
Brian Gesiak048239e2019-12-26 08:00:00 -05001324 addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001325 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
Leonard Chan007f6742019-07-25 20:53:15 +00001326 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001327 }
1328
1329 // FIXME: We still use the legacy pass manager to do code generation. We
1330 // create that pass manager here and use it as needed below.
1331 legacy::PassManager CodeGenPasses;
1332 bool NeedCodeGen = false;
Peter Collingbourne91d02842018-05-22 18:52:37 +00001333 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Chandler Carruth50f9e892016-12-23 20:44:01 +00001334
1335 // Append any output we need to the pass manager.
1336 switch (Action) {
1337 case Backend_EmitNothing:
1338 break;
1339
1340 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +00001341 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Tim Shen50fedec2017-06-01 23:27:51 +00001342 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +00001343 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1344 if (!ThinLinkOS)
Tim Shen50fedec2017-06-01 23:27:51 +00001345 return;
Tim Shen50fedec2017-06-01 23:27:51 +00001346 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001347 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1348 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001349 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1350 : nullptr));
Tim Shen50fedec2017-06-01 23:27:51 +00001351 } else {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001352 // Emit a module summary by default for Regular LTO except for ld64
1353 // targets
1354 bool EmitLTOSummary =
1355 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +00001356 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001357 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1358 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001359 if (EmitLTOSummary) {
1360 if (!TheModule->getModuleFlag("ThinLTO"))
1361 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1362 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Leonard Chan19ec31d2019-08-21 17:24:14 +00001363 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001364 }
1365 MPM.addPass(
1366 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tim Shen50fedec2017-06-01 23:27:51 +00001367 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001368 break;
1369
1370 case Backend_EmitLL:
1371 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1372 break;
1373
1374 case Backend_EmitAssembly:
1375 case Backend_EmitMCNull:
1376 case Backend_EmitObj:
1377 NeedCodeGen = true;
1378 CodeGenPasses.add(
1379 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Aaron Puchertb207bae2019-06-26 21:36:35 +00001380 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00001381 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001382 if (!DwoOS)
1383 return;
1384 }
1385 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1386 DwoOS ? &DwoOS->os() : nullptr))
Chandler Carruth50f9e892016-12-23 20:44:01 +00001387 // FIXME: Should we handle this error differently?
1388 return;
1389 break;
1390 }
1391
1392 // Before executing passes, print the final values of the LLVM options.
1393 cl::PrintOptionValues();
1394
1395 // Now that we have all of the passes ready, run them.
1396 {
1397 PrettyStackTraceString CrashInfo("Optimizer");
1398 MPM.run(*TheModule, MAM);
1399 }
1400
1401 // Now if needed, run the legacy PM for codegen.
1402 if (NeedCodeGen) {
1403 PrettyStackTraceString CrashInfo("Code generation");
1404 CodeGenPasses.run(*TheModule);
1405 }
Peter Collingbourne91d02842018-05-22 18:52:37 +00001406
1407 if (ThinLinkOS)
1408 ThinLinkOS->keep();
1409 if (DwoOS)
1410 DwoOS->keep();
Chandler Carruth50f9e892016-12-23 20:44:01 +00001411}
1412
Peter Collingbourne47d23642017-01-24 19:54:37 +00001413Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1414 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1415 if (!BMsOrErr)
1416 return BMsOrErr.takeError();
1417
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00001418 // The bitcode file may contain multiple modules, we want the one that is
1419 // marked as being the ThinLTO module.
Vitaly Bukac35ff822018-02-16 23:34:16 +00001420 if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1421 return *Bm;
Peter Collingbourne47d23642017-01-24 19:54:37 +00001422
1423 return make_error<StringError>("Could not find module summary",
1424 inconvertibleErrorCode());
1425}
1426
Vitaly Bukac35ff822018-02-16 23:34:16 +00001427BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1428 for (BitcodeModule &BM : BMs) {
1429 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1430 if (LTOInfo && LTOInfo->IsThinLTO)
1431 return &BM;
1432 }
1433 return nullptr;
1434}
1435
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001436static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001437 const HeaderSearchOptions &HeaderOpts,
1438 const CodeGenOptions &CGOpts,
1439 const clang::TargetOptions &TOpts,
1440 const LangOptions &LOpts,
Dehao Chena1bd2d62017-01-13 00:51:55 +00001441 std::unique_ptr<raw_pwrite_stream> OS,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001442 std::string SampleProfile,
Richard Smith8654ae52018-10-10 23:13:35 +00001443 std::string ProfileRemapping,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001444 BackendAction Action) {
Dehao Chen5f83d0e2017-07-10 20:31:37 +00001445 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001446 ModuleToDefinedGVSummaries;
1447 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1448
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001449 setCommandLineOpts(CGOpts);
1450
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001451 // We can simply import the values mentioned in the combined index, since
1452 // we should only invoke this using the individual indexes written out
1453 // via a WriteIndexesThinBackend.
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001454 FunctionImporter::ImportMapTy ImportList;
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001455 for (auto &GlobalList : *CombinedIndex) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001456 // Ignore entries for undefined references.
1457 if (GlobalList.second.SummaryList.empty())
1458 continue;
1459
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001460 auto GUID = GlobalList.first;
Teresa Johnson5ed8b002018-11-29 17:02:59 +00001461 for (auto &Summary : GlobalList.second.SummaryList) {
1462 // Skip the summaries for the importing module. These are included to
1463 // e.g. record required linkage changes.
1464 if (Summary->modulePath() == M->getModuleIdentifier())
1465 continue;
1466 // Add an entry to provoke importing by thinBackend.
1467 ImportList[Summary->modulePath()].insert(GUID);
1468 }
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001469 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001470
1471 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001472 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001473
1474 for (auto &I : ImportList) {
1475 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1476 llvm::MemoryBuffer::getFile(I.first());
1477 if (!MBOrErr) {
1478 errs() << "Error loading imported file '" << I.first()
1479 << "': " << MBOrErr.getError().message() << "\n";
1480 return;
1481 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001482
Peter Collingbourne47d23642017-01-24 19:54:37 +00001483 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1484 if (!BMOrErr) {
1485 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001486 errs() << "Error loading imported file '" << I.first()
1487 << "': " << EIB.message() << '\n';
1488 });
1489 return;
1490 }
Peter Collingbourne47d23642017-01-24 19:54:37 +00001491 ModuleMap.insert({I.first(), *BMOrErr});
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001492
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001493 OwnedImports.push_back(std::move(*MBOrErr));
1494 }
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001495 auto AddStream = [&](size_t Task) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001496 return std::make_unique<lto::NativeObjectStream>(std::move(OS));
Mehdi Amini406aa222016-08-17 06:23:08 +00001497 };
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001498 lto::Config Conf;
Teresa Johnson9e4321c2018-04-17 16:39:25 +00001499 if (CGOpts.SaveTempsFilePrefix != "") {
1500 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1501 /* UseInputModulePath */ false)) {
1502 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1503 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1504 << '\n';
1505 });
1506 }
1507 }
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001508 Conf.CPU = TOpts.CPU;
1509 Conf.CodeModel = getCodeModel(CGOpts);
1510 Conf.MAttrs = TOpts.Features;
Rafael Espindolae1d70532018-01-18 00:20:03 +00001511 Conf.RelocModel = CGOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001512 Conf.CGOptLevel = getCGOptLevel(CGOpts);
Teresa Johnson867bc392019-04-23 18:56:19 +00001513 Conf.OptLevel = CGOpts.OptimizationLevel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001514 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001515 Conf.SampleProfile = std::move(SampleProfile);
Wei Mi21a47102020-01-09 20:58:31 -08001516 Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1517 // For historical reasons, loop interleaving is set to mirror setting for loop
1518 // unrolling.
1519 Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1520 Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1521 Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
zhizhouy94d91222020-03-31 10:23:17 -07001522 Conf.PTO.CallGraphProfile = CGOpts.CallGraphProfile;
Rong Xua4a09b22019-03-04 20:21:31 +00001523
1524 // Context sensitive profile.
1525 if (CGOpts.hasProfileCSIRInstr()) {
1526 Conf.RunCSIRInstr = true;
1527 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1528 } else if (CGOpts.hasProfileCSIRUse()) {
1529 Conf.RunCSIRInstr = false;
1530 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1531 }
1532
Richard Smith8654ae52018-10-10 23:13:35 +00001533 Conf.ProfileRemapping = std::move(ProfileRemapping);
Tim Shen50fedec2017-06-01 23:27:51 +00001534 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
Teresa Johnson4cd016ab2017-11-13 15:38:33 +00001535 Conf.DebugPassManager = CGOpts.DebugPassManager;
Teresa Johnson66744f82018-05-05 14:37:29 +00001536 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1537 Conf.RemarksFilename = CGOpts.OptRecordFile;
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00001538 Conf.RemarksPasses = CGOpts.OptRecordPasses;
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00001539 Conf.RemarksFormat = CGOpts.OptRecordFormat;
Aaron Pucherte1dc4952019-06-15 15:38:51 +00001540 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1541 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001542 switch (Action) {
1543 case Backend_EmitNothing:
1544 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1545 return false;
1546 };
1547 break;
1548 case Backend_EmitLL:
1549 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1550 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1551 return false;
1552 };
1553 break;
1554 case Backend_EmitBC:
1555 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
Rafael Espindola76c8f822018-02-14 19:11:37 +00001556 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001557 return false;
1558 };
1559 break;
1560 default:
1561 Conf.CGFileType = getCodeGenFileType(Action);
1562 break;
1563 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001564 if (Error E = thinBackend(
Teresa Johnson66744f82018-05-05 14:37:29 +00001565 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001566 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1567 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1568 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1569 });
1570 }
1571}
1572
David Blaikie9c902b52011-09-25 23:23:43 +00001573void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001574 const HeaderSearchOptions &HeaderOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00001575 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +00001576 const clang::TargetOptions &TOpts,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001577 const LangOptions &LOpts,
1578 const llvm::DataLayout &TDesc, Module *M,
1579 BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +00001580 std::unique_ptr<raw_pwrite_stream> OS) {
Anton Afanasyevd880de22019-03-30 08:42:48 +00001581
Russell Gallopdf494f72019-12-11 11:49:42 +00001582 llvm::TimeTraceScope TimeScope("Backend");
Anton Afanasyevd880de22019-03-30 08:42:48 +00001583
Vitaly Buka769134d2018-02-16 23:38:22 +00001584 std::unique_ptr<llvm::Module> EmptyModule;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001585 if (!CGOpts.ThinLTOIndexFile.empty()) {
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001586 // If we are performing a ThinLTO importing compile, load the function index
1587 // into memory and pass it into runThinLTOBackend, which will run the
1588 // function importer and invoke LTO passes.
1589 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
Teresa Johnson517729f2017-05-12 19:32:17 +00001590 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1591 /*IgnoreEmptyThinLTOIndexFile*/true);
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001592 if (!IndexOrErr) {
1593 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1594 "Error loading index file '" +
1595 CGOpts.ThinLTOIndexFile + "': ");
1596 return;
1597 }
1598 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1599 // A null CombinedIndex means we should skip ThinLTO compilation
1600 // (LLVM will optionally ignore empty index files, returning null instead
1601 // of an error).
Vitaly Buka769134d2018-02-16 23:38:22 +00001602 if (CombinedIndex) {
1603 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1604 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1605 LOpts, std::move(OS), CGOpts.SampleProfileFile,
Richard Smith8654ae52018-10-10 23:13:35 +00001606 CGOpts.ProfileRemappingFile, Action);
Vitaly Buka769134d2018-02-16 23:38:22 +00001607 return;
1608 }
1609 // Distributed indexing detected that nothing from the module is needed
1610 // for the final linking. So we can skip the compilation. We sill need to
1611 // output an empty object file to make sure that a linker does not fail
1612 // trying to read it. Also for some features, like CFI, we must skip
1613 // the compilation as CombinedIndex does not contain all required
1614 // information.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001615 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
Vitaly Buka769134d2018-02-16 23:38:22 +00001616 EmptyModule->setTargetTriple(M->getTargetTriple());
1617 M = EmptyModule.get();
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001618 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001619 }
1620
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001621 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001622
Chandler Carruth50f9e892016-12-23 20:44:01 +00001623 if (CGOpts.ExperimentalNewPassManager)
1624 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1625 else
1626 AsmHelper.EmitAssembly(Action, std::move(OS));
Alp Tokere83b9062014-01-02 15:08:04 +00001627
James Y Knightb214cbc2016-03-04 19:00:41 +00001628 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1629 // DataLayout.
1630 if (AsmHelper.TM) {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00001631 std::string DLDesc = M->getDataLayout().getStringRepresentation();
James Y Knightb214cbc2016-03-04 19:00:41 +00001632 if (DLDesc != TDesc.getStringRepresentation()) {
Alp Tokere83b9062014-01-02 15:08:04 +00001633 unsigned DiagID = Diags.getCustomDiagID(
1634 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1635 "expected target description '%1'");
James Y Knightb214cbc2016-03-04 19:00:41 +00001636 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
Alp Tokere83b9062014-01-02 15:08:04 +00001637 }
1638 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001639}
Steven Wu27fb5222016-05-11 16:26:03 +00001640
Steven Wu27fb5222016-05-11 16:26:03 +00001641// With -fembed-bitcode, save a copy of the llvm IR as data in the
1642// __LLVM,__bitcode section.
1643void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1644 llvm::MemoryBufferRef Buf) {
1645 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1646 return;
Teresa Johnsonc8e0bb32019-12-12 11:59:36 -08001647 llvm::EmbedBitcodeInModule(
1648 *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1649 CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1650 &CGOpts.CmdArgs);
Steven Wu27fb5222016-05-11 16:26:03 +00001651}