blob: 2023ced655ce05f08c20243333155637b1f64de7 [file] [log] [blame]
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00006//
7//===----------------------------------------------------------------------===//
8
Daniel Dunbarc1b17292010-06-15 17:48:49 +00009#include "clang/CodeGen/BackendUtil.h"
Richard Trieu63688182018-12-11 03:18:39 +000010#include "clang/Basic/CodeGenOptions.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000011#include "clang/Basic/Diagnostic.h"
Dan Gohmanfec0ff82011-07-05 22:02:36 +000012#include "clang/Basic/LangOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/Basic/TargetOptions.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000014#include "clang/Frontend/FrontendDiagnostic.h"
Kostya Serebryanyce2c7262013-12-27 08:11:08 +000015#include "clang/Frontend/Utils.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000016#include "clang/Lex/HeaderSearchOptions.h"
Hal Finkel1a328f52016-12-15 02:19:17 +000017#include "llvm/ADT/SmallSet.h"
Eric Christopher583a1f72015-09-26 01:25:08 +000018#include "llvm/ADT/StringExtras.h"
Saleem Abdulrasool62849c62014-05-08 02:28:32 +000019#include "llvm/ADT/StringSwitch.h"
Steven Wu27fb5222016-05-11 16:26:03 +000020#include "llvm/ADT/Triple.h"
Chandler Carruth418bd1a2015-01-15 02:16:55 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthaab5ec02015-01-31 11:18:46 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000024#include "llvm/Bitcode/BitcodeWriter.h"
25#include "llvm/Bitcode/BitcodeWriterPass.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000026#include "llvm/CodeGen/RegAllocRegistry.h"
27#include "llvm/CodeGen/SchedulerRegistry.h"
David Blaikie7a4f7f52018-01-09 22:03:47 +000028#include "llvm/CodeGen/TargetSubtargetInfo.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
Chandler Carruth0a50c492014-01-12 11:11:50 +000030#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth9828e692015-02-13 09:57:03 +000031#include "llvm/IR/LegacyPassManager.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Module.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000033#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruthca884742014-01-13 09:26:48 +000034#include "llvm/IR/Verifier.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000035#include "llvm/LTO/LTOBackend.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000036#include "llvm/MC/MCAsmInfo.h"
Evan Chengeeb486d2011-06-29 01:14:32 +000037#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000038#include "llvm/Passes/PassBuilder.h"
Philip Pfaffee3f105c2019-02-02 23:19:32 +000039#include "llvm/Passes/PassPlugin.h"
Taewook Ohd4c50f72019-08-14 07:11:09 +000040#include "llvm/Passes/StandardInstrumentations.h"
David Blaikie9941da42018-11-17 18:04:13 +000041#include "llvm/Support/BuryPointer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000042#include "llvm/Support/CommandLine.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000043#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000044#include "llvm/Support/PrettyStackTrace.h"
Evan Cheng494eb062011-08-24 18:09:14 +000045#include "llvm/Support/TargetRegistry.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000046#include "llvm/Support/TimeProfiler.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000047#include "llvm/Support/Timer.h"
48#include "llvm/Support/raw_ostream.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000049#include "llvm/Target/TargetMachine.h"
50#include "llvm/Target/TargetOptions.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000051#include "llvm/Transforms/Coroutines.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000052#include "llvm/Transforms/IPO.h"
Chandler Carruthb72c19f2016-08-17 03:09:11 +000053#include "llvm/Transforms/IPO/AlwaysInliner.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000054#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Tim Shen50fedec2017-06-01 23:27:51 +000055#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
David Blaikied2a572202018-04-24 00:59:22 +000056#include "llvm/Transforms/InstCombine/InstCombine.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000057#include "llvm/Transforms/Instrumentation.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000058#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
Chandler Carruthafce4492017-11-14 01:47:24 +000059#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
David Blaikie4e1ae832018-03-23 22:16:59 +000060#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
Leonard Chan0cdd3b12019-05-14 21:17:21 +000061#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
Rong Xu4059e142019-04-25 17:52:43 +000062#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000063#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
Leonard Chan007f6742019-07-25 20:53:15 +000064#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
Philip Pfaffe685c76d2019-01-16 09:28:01 +000065#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
Michael Gottesman90cae772013-01-28 01:36:00 +000066#include "llvm/Transforms/ObjCARC.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000067#include "llvm/Transforms/Scalar.h"
Chandler Carruth4ddaadc2016-03-11 09:02:43 +000068#include "llvm/Transforms/Scalar/GVN.h"
David Blaikiec133b1e2018-03-28 17:45:10 +000069#include "llvm/Transforms/Utils.h"
Teresa Johnson6ed79132019-01-04 19:05:01 +000070#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
Leonard Chanb2065132019-06-20 19:35:25 +000071#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
Tim Shen66470692017-06-29 23:08:38 +000072#include "llvm/Transforms/Utils/NameAnonGlobals.h"
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +000073#include "llvm/Transforms/Utils/SymbolRewriter.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000074#include <memory>
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000075using namespace clang;
76using namespace llvm;
77
78namespace {
79
Davide Italiano945de432017-02-13 16:07:05 +000080// Default filename used for profile generation.
81static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
82
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000083class EmitAssemblyHelper {
David Blaikie9c902b52011-09-25 23:23:43 +000084 DiagnosticsEngine &Diags;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000085 const HeaderSearchOptions &HSOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000086 const CodeGenOptions &CodeGenOpts;
Nick Lewycky432add52011-12-02 22:17:00 +000087 const clang::TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000088 const LangOptions &LangOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000089 Module *TheModule;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000090
91 Timer CodeGenerationTime;
92
Peter Collingbourne03f89072016-07-15 00:55:40 +000093 std::unique_ptr<raw_pwrite_stream> OS;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000094
Chandler Carruthd294bdb2015-02-01 12:26:23 +000095 TargetIRAnalysis getTargetIRAnalysis() const {
Chandler Carruthaab5ec02015-01-31 11:18:46 +000096 if (TM)
Chandler Carruthd294bdb2015-02-01 12:26:23 +000097 return TM->getTargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +000098
Chandler Carruthd294bdb2015-02-01 12:26:23 +000099 return TargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +0000100 }
101
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000102 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
Nadav Rotemec57ab32012-10-24 00:53:38 +0000103
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000104 /// Generates the TargetMachine.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000105 /// Leaves TM unchanged if it is unable to create the target machine.
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000106 /// Some of our clang tests specify triples which are not built
107 /// into clang. This is okay because these tests check the generated
108 /// IR, and they require DataLayout which depends on the triple.
109 /// In this case, we allow this method to fail and not report an error.
110 /// When MustCreateTM is used, we print an error if we are unable to load
111 /// the requested target.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000112 void CreateTargetMachine(bool MustCreateTM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000113
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000114 /// Add passes necessary to emit assembly or LLVM IR.
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000115 ///
116 /// \return True on success.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000117 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000118 raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
119
120 std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
121 std::error_code EC;
122 auto F = llvm::make_unique<llvm::ToolOutputFile>(Path, EC,
Fangrui Songd9b948b2019-08-05 05:43:48 +0000123 llvm::sys::fs::OF_None);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000124 if (EC) {
125 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
126 F.reset();
127 }
128 return F;
129 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000130
131public:
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000132 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
133 const HeaderSearchOptions &HeaderSearchOpts,
134 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +0000135 const clang::TargetOptions &TOpts,
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000136 const LangOptions &LOpts, Module *M)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000137 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
138 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
139 CodeGenerationTime("codegen", "Code Generation Time") {}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000140
141 ~EmitAssemblyHelper() {
Alp Tokerf4e22382013-12-20 20:26:53 +0000142 if (CodeGenOpts.DisableFree)
David Blaikiea97eaa12014-08-29 16:53:14 +0000143 BuryPointer(std::move(TM));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000144 }
145
Ahmed Charlesb8984322014-03-07 20:03:18 +0000146 std::unique_ptr<TargetMachine> TM;
Alp Tokerf4e22382013-12-20 20:26:53 +0000147
Peter Collingbourne03f89072016-07-15 00:55:40 +0000148 void EmitAssembly(BackendAction Action,
149 std::unique_ptr<raw_pwrite_stream> OS);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000150
151 void EmitAssemblyWithNewPassManager(BackendAction Action,
152 std::unique_ptr<raw_pwrite_stream> OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000153};
154
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000155// We need this wrapper to access LangOpts and CGOpts from extension functions
156// that we add to the PassManagerBuilder.
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000157class PassManagerBuilderWrapper : public PassManagerBuilder {
158public:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000159 PassManagerBuilderWrapper(const Triple &TargetTriple,
160 const CodeGenOptions &CGOpts,
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000161 const LangOptions &LangOpts)
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000162 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
163 LangOpts(LangOpts) {}
164 const Triple &getTargetTriple() const { return TargetTriple; }
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000165 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000166 const LangOptions &getLangOpts() const { return LangOpts; }
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000167
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000168private:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000169 const Triple &TargetTriple;
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000170 const CodeGenOptions &CGOpts;
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000171 const LangOptions &LangOpts;
172};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000173}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000174
Dan Gohman5932ce22012-01-17 20:54:51 +0000175static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
176 if (Builder.OptLevel > 0)
177 PM.add(createObjCARCAPElimPass());
178}
179
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000180static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
181 if (Builder.OptLevel > 0)
182 PM.add(createObjCARCExpandPass());
183}
184
185static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
186 if (Builder.OptLevel > 0)
187 PM.add(createObjCARCOptPass());
188}
189
Diego Novillob56be642014-03-03 20:06:18 +0000190static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000191 legacy::PassManagerBase &PM) {
Diego Novillob56be642014-03-03 20:06:18 +0000192 PM.add(createAddDiscriminatorsPass());
193}
194
Nuno Lopesa4255892012-05-22 17:19:45 +0000195static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000196 legacy::PassManagerBase &PM) {
Chandler Carruth00a301d2017-11-14 01:30:04 +0000197 PM.add(createBoundsCheckingLegacyPass());
Nuno Lopesa4255892012-05-22 17:19:45 +0000198}
199
Leonard Chan007f6742019-07-25 20:53:15 +0000200static SanitizerCoverageOptions
201getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000202 SanitizerCoverageOptions Opts;
203 Opts.CoverageType =
204 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
205 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
206 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
207 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
Kostya Serebryany3b419712016-08-30 01:27:03 +0000208 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
209 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000210 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000211 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000212 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
Kostya Serebryany50fb6182017-05-05 23:28:18 +0000213 Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
Kostya Serebryany2c2fb882017-06-08 22:58:19 +0000214 Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
Kostya Serebryany61457762017-07-28 00:10:10 +0000215 Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
Matt Morehouse5c7fc762017-08-18 18:43:30 +0000216 Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
Leonard Chan007f6742019-07-25 20:53:15 +0000217 return Opts;
218}
219
220static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
221 legacy::PassManagerBase &PM) {
222 const PassManagerBuilderWrapper &BuilderWrapper =
223 static_cast<const PassManagerBuilderWrapper &>(Builder);
224 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
225 auto Opts = getSancovOptsFromCGOpts(CGOpts);
226 PM.add(createModuleSanitizerCoverageLegacyPassPass(Opts));
227 PM.add(createSanitizerCoverageLegacyPassPass(Opts));
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000228}
229
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000230// Check if ASan should use GC-friendly instrumentation for globals.
231// First of all, there is no point if -fdata-sections is off (expect for MachO,
232// where this is not a factor). Also, on ELF this feature requires an assembler
233// extension that only works with -integrated-as at the moment.
234static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000235 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
236 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000237 switch (T.getObjectFormat()) {
238 case Triple::MachO:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000239 case Triple::COFF:
Evgeniy Stepanovc7b90942017-04-26 00:51:06 +0000240 return true;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000241 case Triple::ELF:
242 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
Hubert Tong2711e162019-07-19 08:46:18 +0000243 case Triple::XCOFF:
244 llvm::report_fatal_error("ASan not implemented for XCOFF.");
245 case Triple::Wasm:
246 case Triple::UnknownObjectFormat:
247 break;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000248 }
Hubert Tong2711e162019-07-19 08:46:18 +0000249 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000250}
251
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000252static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000253 legacy::PassManagerBase &PM) {
Yury Gribov5bfeca12015-11-11 10:45:48 +0000254 const PassManagerBuilderWrapper &BuilderWrapper =
255 static_cast<const PassManagerBuilderWrapper&>(Builder);
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000256 const Triple &T = BuilderWrapper.getTargetTriple();
Yury Gribov5bfeca12015-11-11 10:45:48 +0000257 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
258 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000259 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
Vitaly Buka8076c572018-12-05 01:44:31 +0000260 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000261 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000262 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
263 UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000264 PM.add(createModuleAddressSanitizerLegacyPassPass(
265 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000266}
267
268static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
269 legacy::PassManagerBase &PM) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000270 PM.add(createAddressSanitizerFunctionPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000271 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000272 PM.add(createModuleAddressSanitizerLegacyPassPass(
Vitaly Buka8076c572018-12-05 01:44:31 +0000273 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
274 /*UseOdrIndicator*/ false));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000275}
276
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000277static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
278 legacy::PassManagerBase &PM) {
Evgeniy Stepanov3fd1b1a2017-12-20 19:05:44 +0000279 const PassManagerBuilderWrapper &BuilderWrapper =
280 static_cast<const PassManagerBuilderWrapper &>(Builder);
281 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
282 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000283 PM.add(
284 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000285}
286
287static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
288 legacy::PassManagerBase &PM) {
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000289 PM.add(createHWAddressSanitizerLegacyPassPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000290 /*CompileKernel*/ true, /*Recover*/ true));
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000291}
292
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000293static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
294 legacy::PassManagerBase &PM,
295 bool CompileKernel) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000296 const PassManagerBuilderWrapper &BuilderWrapper =
297 static_cast<const PassManagerBuilderWrapper&>(Builder);
298 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Evgeniy Stepanov5b5370a2016-11-07 21:02:11 +0000299 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
300 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
Philip Pfaffe0ee6a932019-02-04 21:02:49 +0000301 PM.add(createMemorySanitizerLegacyPassPass(
302 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000303
304 // MemorySanitizer inserts complex instrumentation that mostly follows
305 // the logic of the original code, but operates on "shadow" values.
306 // It can benefit from re-running some general purpose optimization passes.
307 if (Builder.OptLevel > 0) {
308 PM.add(createEarlyCSEPass());
309 PM.add(createReassociatePass());
310 PM.add(createLICMPass());
311 PM.add(createGVNPass());
312 PM.add(createInstructionCombiningPass());
313 PM.add(createDeadStoreEliminationPass());
314 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000315}
316
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000317static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
318 legacy::PassManagerBase &PM) {
319 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
320}
321
322static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
323 legacy::PassManagerBase &PM) {
324 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
325}
326
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000327static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000328 legacy::PassManagerBase &PM) {
Philip Pfaffe685c76d2019-01-16 09:28:01 +0000329 PM.add(createThreadSanitizerLegacyPassPass());
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000330}
331
Peter Collingbournec3772752013-08-07 22:47:34 +0000332static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000333 legacy::PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000334 const PassManagerBuilderWrapper &BuilderWrapper =
335 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonovae5804f2014-10-15 20:22:54 +0000336 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000337 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
Peter Collingbournec3772752013-08-07 22:47:34 +0000338}
339
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000340static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
341 const CodeGenOptions &CodeGenOpts) {
342 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000343 if (!CodeGenOpts.SimplifyLibCalls)
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000344 TLII->disableAllFunctions();
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000345 else {
346 // Disable individual libc/libm calls in TargetLibraryInfo.
David L. Jones7a7dd032017-01-23 23:16:58 +0000347 LibFunc F;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000348 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
349 if (TLII->getLibFunc(FuncName, F))
350 TLII->setUnavailable(F);
351 }
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000352
353 switch (CodeGenOpts.getVecLib()) {
354 case CodeGenOptions::Accelerate:
355 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
356 break;
Nemanja Ivanovic6321c682019-06-05 01:57:57 +0000357 case CodeGenOptions::MASSV:
358 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
359 break;
Matt Masten6731dea2016-07-29 16:44:24 +0000360 case CodeGenOptions::SVML:
361 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
362 break;
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000363 default:
364 break;
365 }
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000366 return TLII;
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000367}
368
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000369static void addSymbolRewriterPass(const CodeGenOptions &Opts,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000370 legacy::PassManager *MPM) {
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000371 llvm::SymbolRewriter::RewriteDescriptorList DL;
372
373 llvm::SymbolRewriter::RewriteMapParser MapParser;
374 for (const auto &MapFile : Opts.RewriteMapFiles)
375 MapParser.parse(MapFile, &DL);
376
377 MPM->add(createRewriteSymbolsPass(DL));
378}
379
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000380static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
381 switch (CodeGenOpts.OptimizationLevel) {
382 default:
383 llvm_unreachable("Invalid optimization level!");
384 case 0:
385 return CodeGenOpt::None;
386 case 1:
387 return CodeGenOpt::Less;
388 case 2:
389 return CodeGenOpt::Default; // O2/Os/Oz
390 case 3:
391 return CodeGenOpt::Aggressive;
392 }
393}
394
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000395static Optional<llvm::CodeModel::Model>
396getCodeModel(const CodeGenOptions &CodeGenOpts) {
397 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
David Greenecc69872018-08-22 11:34:28 +0000398 .Case("tiny", llvm::CodeModel::Tiny)
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000399 .Case("small", llvm::CodeModel::Small)
400 .Case("kernel", llvm::CodeModel::Kernel)
401 .Case("medium", llvm::CodeModel::Medium)
402 .Case("large", llvm::CodeModel::Large)
403 .Case("default", ~1u)
404 .Default(~0u);
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000405 assert(CodeModel != ~0u && "invalid code model!");
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000406 if (CodeModel == ~1u)
407 return None;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000408 return static_cast<llvm::CodeModel::Model>(CodeModel);
409}
410
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000411static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
412 if (Action == Backend_EmitObj)
413 return TargetMachine::CGFT_ObjectFile;
414 else if (Action == Backend_EmitMCNull)
415 return TargetMachine::CGFT_Null;
416 else {
417 assert(Action == Backend_EmitAssembly && "Invalid action!");
418 return TargetMachine::CGFT_AssemblyFile;
419 }
420}
421
422static void initTargetOptions(llvm::TargetOptions &Options,
423 const CodeGenOptions &CodeGenOpts,
424 const clang::TargetOptions &TargetOpts,
425 const LangOptions &LangOpts,
426 const HeaderSearchOptions &HSOpts) {
427 Options.ThreadModel =
428 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
429 .Case("posix", llvm::ThreadModel::POSIX)
430 .Case("single", llvm::ThreadModel::Single);
431
432 // Set float ABI type.
433 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
434 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
435 "Invalid Floating Point ABI!");
436 Options.FloatABIType =
437 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
438 .Case("soft", llvm::FloatABI::Soft)
439 .Case("softfp", llvm::FloatABI::Soft)
440 .Case("hard", llvm::FloatABI::Hard)
441 .Default(llvm::FloatABI::Default);
442
443 // Set FP fusion mode.
444 switch (LangOpts.getDefaultFPContractMode()) {
445 case LangOptions::FPC_Off:
Adam Nemet03af4242017-04-20 17:09:35 +0000446 // Preserve any contraction performed by the front-end. (Strict performs
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000447 // splitting of the muladd intrinsic in the backend.)
Adam Nemet03af4242017-04-20 17:09:35 +0000448 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000449 break;
450 case LangOptions::FPC_On:
451 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
452 break;
453 case LangOptions::FPC_Fast:
454 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
455 break;
456 }
457
458 Options.UseInitArray = CodeGenOpts.UseInitArray;
459 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
Saleem Abdulrasool54448902017-06-09 00:40:30 +0000460 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000461 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
462
463 // Set EABI version.
Yuka Takahashidc771502017-07-01 07:57:23 +0000464 Options.EABIVersion = TargetOpts.EABIVersion;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000465
466 if (LangOpts.SjLjExceptions)
467 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
Martell Malonec950c652017-11-29 07:25:12 +0000468 if (LangOpts.SEHExceptions)
469 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
470 if (LangOpts.DWARFExceptions)
471 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000472
473 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
474 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
475 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
476 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
477 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
478 Options.FunctionSections = CodeGenOpts.FunctionSections;
479 Options.DataSections = CodeGenOpts.DataSections;
480 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
481 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +0000482 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000483 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
Sean Eveson5110d4f2018-01-08 13:42:26 +0000484 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
Peter Collingbourne14b468b2018-07-18 00:27:07 +0000485 Options.EmitAddrsig = CodeGenOpts.Addrsig;
Djordje Todorovic639d36b2019-06-26 09:38:09 +0000486 Options.EnableDebugEntryValues = CodeGenOpts.EnableDebugEntryValues;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000487
Aaron Puchertb207bae2019-06-26 21:36:35 +0000488 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000489 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
490 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
491 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
492 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
493 Options.MCOptions.MCIncrementalLinkerCompatible =
494 CodeGenOpts.IncrementalLinkerCompatible;
495 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
496 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
Brian Cain7b953b62019-08-08 19:19:20 +0000497 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000498 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
499 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
500 Options.MCOptions.ABIName = TargetOpts.ABI;
501 for (const auto &Entry : HSOpts.UserEntries)
502 if (!Entry.IsFramework &&
503 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
504 Entry.Group == frontend::IncludeDirGroup::Angled ||
505 Entry.Group == frontend::IncludeDirGroup::System))
506 Options.MCOptions.IASSearchPaths.push_back(
507 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
508}
David Blaikie7a4f7f52018-01-09 22:03:47 +0000509static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
510 if (CodeGenOpts.DisableGCov)
511 return None;
512 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
513 return None;
514 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
515 // LLVM's -default-gcov-version flag is set to something invalid.
516 GCOVOptions Options;
517 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
518 Options.EmitData = CodeGenOpts.EmitGcovArcs;
519 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
520 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
521 Options.NoRedZone = CodeGenOpts.DisableRedZone;
522 Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000523 Options.Filter = CodeGenOpts.ProfileFilterFiles;
524 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
David Blaikie7a4f7f52018-01-09 22:03:47 +0000525 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
526 return Options;
527}
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000528
Rong Xu4059e142019-04-25 17:52:43 +0000529static Optional<InstrProfOptions>
530getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
531 const LangOptions &LangOpts) {
532 if (!CodeGenOpts.hasProfileClangInstr())
533 return None;
534 InstrProfOptions Options;
535 Options.NoRedZone = CodeGenOpts.DisableRedZone;
536 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
537
538 // TODO: Surface the option to emit atomic profile counter increments at
539 // the driver level.
540 Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
541 return Options;
542}
543
Peter Collingbourne03f89072016-07-15 00:55:40 +0000544void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000545 legacy::FunctionPassManager &FPM) {
Chandler Carruth93786da2016-12-23 00:23:01 +0000546 // Handle disabling of all LLVM passes, where we want to preserve the
547 // internal module before any optimization.
Steven Wu546a1962015-07-17 20:09:56 +0000548 if (CodeGenOpts.DisableLLVMPasses)
549 return;
550
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000551 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
552 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
553 // are inserted before PMBuilder ones - they'd get the default-constructed
554 // TLI with an unknown target otherwise.
Teresa Johnsonaff22322015-12-07 19:21:34 +0000555 Triple TargetTriple(TheModule->getTargetTriple());
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000556 std::unique_ptr<TargetLibraryInfoImpl> TLII(
557 createTLII(TargetTriple, CodeGenOpts));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000558
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000559 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
560
Chandler Carruthfcd33142016-12-23 01:24:49 +0000561 // At O0 and O1 we only run the always inliner which is more efficient. At
562 // higher optimization levels we run the normal inliner.
563 if (CodeGenOpts.OptimizationLevel <= 1) {
Mehdi Amini7f873072017-01-06 23:18:09 +0000564 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
565 !CodeGenOpts.DisableLifetimeMarkers);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000566 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
567 } else {
Dehao Chence39fdd2017-03-21 19:55:46 +0000568 // We do not want to inline hot callsites for SamplePGO module-summary build
569 // because profile annotation will happen again in ThinLTO backend, and we
570 // want the IR of the hot path to match the profile.
Chandler Carruthfcd33142016-12-23 01:24:49 +0000571 PMBuilder.Inliner = createFunctionInliningPass(
Dehao Chence39fdd2017-03-21 19:55:46 +0000572 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
573 (!CodeGenOpts.SampleProfileFile.empty() &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000574 CodeGenOpts.PrepareForThinLTO));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000575 }
576
Chandler Carruthfcd33142016-12-23 01:24:49 +0000577 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000578 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000579 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
580 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000581
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000582 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Alina Sbirleaa9b9ab82019-04-30 21:29:23 +0000583 // Loop interleaving in the loop vectorizer has historically been set to be
584 // enabled when loop unrolling is enabled.
585 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000586 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000587 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
Teresa Johnson8749d8042015-07-06 16:23:00 +0000588 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
Hal Finkelce0697f2013-11-17 16:03:29 +0000589 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000590
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000591 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
592
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000593 if (TM)
Stanislav Mekhanoshin61da0672017-01-26 16:49:21 +0000594 TM->adjustPassManager(PMBuilder);
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000595
Dehao Chen7810d4f2017-02-21 20:36:21 +0000596 if (CodeGenOpts.DebugInfoForProfiling ||
597 !CodeGenOpts.SampleProfileFile.empty())
598 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
599 addAddDiscriminatorsPass);
Diego Novillob56be642014-03-03 20:06:18 +0000600
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000601 // In ObjC ARC mode, add the main ARC optimization passes.
602 if (LangOpts.ObjCAutoRefCount) {
603 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
604 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000605 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
606 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000607 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
608 addObjCARCOptPass);
609 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000610
Richard Smith10ab78e2019-02-23 21:06:26 +0000611 if (LangOpts.Coroutines)
Brian Gesiak91a4b5a2018-04-01 23:55:21 +0000612 addCoroutinePassesToExtensionPoints(PMBuilder);
613
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000614 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000615 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
616 addBoundsCheckingPass);
617 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
618 addBoundsCheckingPass);
619 }
620
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000621 if (CodeGenOpts.SanitizeCoverageType ||
622 CodeGenOpts.SanitizeCoverageIndirectCalls ||
623 CodeGenOpts.SanitizeCoverageTraceCmp) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000624 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
625 addSanitizerCoveragePass);
626 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
627 addSanitizerCoveragePass);
628 }
629
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000630 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000631 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000632 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000633 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000634 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000635 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000636
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000637 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
638 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
639 addKernelAddressSanitizerPasses);
640 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
641 addKernelAddressSanitizerPasses);
642 }
643
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000644 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
645 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
646 addHWAddressSanitizerPasses);
647 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
648 addHWAddressSanitizerPasses);
649 }
650
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000651 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
652 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
653 addKernelHWAddressSanitizerPasses);
654 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
655 addKernelHWAddressSanitizerPasses);
656 }
657
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000658 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000659 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
660 addMemorySanitizerPass);
661 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
662 addMemorySanitizerPass);
663 }
664
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000665 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
666 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
667 addKernelMemorySanitizerPass);
668 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
669 addKernelMemorySanitizerPass);
670 }
671
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000672 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000673 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000674 addThreadSanitizerPass);
675 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
676 addThreadSanitizerPass);
677 }
678
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000679 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
Peter Collingbournec3772752013-08-07 22:47:34 +0000680 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
681 addDataFlowSanitizerPass);
682 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
683 addDataFlowSanitizerPass);
684 }
685
Chris Lattner5c123672011-05-21 20:40:11 +0000686 // Set up the per-function pass manager.
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000687 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
Chris Lattner5c123672011-05-21 20:40:11 +0000688 if (CodeGenOpts.VerifyModule)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000689 FPM.add(createVerifierPass());
Andrew Trickb2a84722011-04-05 18:49:32 +0000690
Chris Lattner5c123672011-05-21 20:40:11 +0000691 // Set up the per-module pass manager.
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000692 if (!CodeGenOpts.RewriteMapFiles.empty())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000693 addSymbolRewriterPass(CodeGenOpts, &MPM);
Chris Lattnerd98cec52011-02-18 22:20:38 +0000694
David Blaikie7a4f7f52018-01-09 22:03:47 +0000695 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
696 MPM.add(createGCOVProfilerPass(*Options));
Benjamin Kramer8c305922016-02-02 11:06:51 +0000697 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000698 MPM.add(createStripSymbolsPass(true));
Nick Lewycky207bce32011-04-21 23:44:07 +0000699 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000700
Rong Xu4059e142019-04-25 17:52:43 +0000701 if (Optional<InstrProfOptions> Options =
702 getInstrProfOptions(CodeGenOpts, LangOpts))
703 MPM.add(createInstrProfilingLegacyPass(*Options, false));
Vedant Kumaree6c2332018-08-16 22:24:47 +0000704
Rong Xua4a09b22019-03-04 20:21:31 +0000705 bool hasIRInstr = false;
Rong Xu522b5cb2016-02-29 18:54:59 +0000706 if (CodeGenOpts.hasProfileIRInstr()) {
Xinliang David Lib65f8ae2016-07-23 04:28:59 +0000707 PMBuilder.EnablePGOInstrGen = true;
Rong Xua4a09b22019-03-04 20:21:31 +0000708 hasIRInstr = true;
709 }
710 if (CodeGenOpts.hasProfileCSIRInstr()) {
711 assert(!CodeGenOpts.hasProfileCSIRUse() &&
712 "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
713 "same time");
714 assert(!hasIRInstr &&
715 "Cannot have both ProfileGen pass and CSProfileGen pass at the "
716 "same time");
717 PMBuilder.EnablePGOCSInstrGen = true;
718 hasIRInstr = true;
719 }
720 if (hasIRInstr) {
Rong Xu522b5cb2016-02-29 18:54:59 +0000721 if (!CodeGenOpts.InstrProfileOutput.empty())
722 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
723 else
Davide Italiano945de432017-02-13 16:07:05 +0000724 PMBuilder.PGOInstrGen = DefaultProfileGenName;
Rong Xu522b5cb2016-02-29 18:54:59 +0000725 }
Rong Xua4a09b22019-03-04 20:21:31 +0000726 if (CodeGenOpts.hasProfileIRUse()) {
Rong Xu9c6f1532016-03-02 20:59:36 +0000727 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
Rong Xua4a09b22019-03-04 20:21:31 +0000728 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
729 }
Justin Bogner970ac602014-12-08 19:04:51 +0000730
Dehao Chen5717aff2016-12-14 21:41:04 +0000731 if (!CodeGenOpts.SampleProfileFile.empty())
732 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
Diego Novillod3ef1082015-08-25 15:25:13 +0000733
Peter Collingbourne03f89072016-07-15 00:55:40 +0000734 PMBuilder.populateFunctionPassManager(FPM);
735 PMBuilder.populateModulePassManager(MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000736}
737
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000738static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
Yaxun Liub5e80c32016-04-12 20:22:32 +0000739 SmallVector<const char *, 16> BackendArgs;
740 BackendArgs.push_back("clang"); // Fake program name.
741 if (!CodeGenOpts.DebugPass.empty()) {
742 BackendArgs.push_back("-debug-pass");
743 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
744 }
745 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
746 BackendArgs.push_back("-limit-float-precision");
747 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
748 }
Yaxun Liub5e80c32016-04-12 20:22:32 +0000749 BackendArgs.push_back(nullptr);
750 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
751 BackendArgs.data());
752}
753
Peter Collingbourne03f89072016-07-15 00:55:40 +0000754void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000755 // Create the TargetMachine for generating code.
756 std::string Error;
757 std::string Triple = TheModule->getTargetTriple();
758 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
759 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000760 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000761 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000762 return;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000763 }
764
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000765 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
Eric Christopher583a1f72015-09-26 01:25:08 +0000766 std::string FeaturesStr =
767 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
Rafael Espindolae1d70532018-01-18 00:20:03 +0000768 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000769 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
Evan Chengdd286bc2011-11-16 08:38:55 +0000770
Nick Lewycky432add52011-12-02 22:17:00 +0000771 llvm::TargetOptions Options;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000772 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000773 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
774 Options, RM, CM, OptLevel));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000775}
776
Peter Collingbourne03f89072016-07-15 00:55:40 +0000777bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
778 BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000779 raw_pwrite_stream &OS,
780 raw_pwrite_stream *DwoOS) {
Chad Rosierb1cfc682012-02-29 20:14:59 +0000781 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000782 llvm::Triple TargetTriple(TheModule->getTargetTriple());
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000783 std::unique_ptr<TargetLibraryInfoImpl> TLII(
784 createTLII(TargetTriple, CodeGenOpts));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000785 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
Chad Rosierb1cfc682012-02-29 20:14:59 +0000786
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000787 // Normal mode, emit a .s or .o file by running the code generator. Note,
788 // this also adds codegenerator level optimization passes.
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000789 TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000790
791 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
792 // "codegen" passes so that it isn't run multiple times when there is
793 // inlining happening.
Steven Wu1d56be82015-05-02 00:56:15 +0000794 if (CodeGenOpts.OptimizationLevel > 0)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000795 CodeGenPasses.add(createObjCARCContractPass());
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000796
Peter Collingbourne91d02842018-05-22 18:52:37 +0000797 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000798 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
799 Diags.Report(diag::err_fe_unable_to_interface_with_target);
800 return false;
801 }
802
803 return true;
804}
805
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000806void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000807 std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000808 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000809
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000810 setCommandLineOpts(CodeGenOpts);
Yaxun Liub5e80c32016-04-12 20:22:32 +0000811
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000812 bool UsesCodeGen = (Action != Backend_EmitNothing &&
813 Action != Backend_EmitBC &&
814 Action != Backend_EmitLL);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000815 CreateTargetMachine(UsesCodeGen);
Alp Tokerf4e22382013-12-20 20:26:53 +0000816
Rafael Espindolab633d202015-06-23 13:59:36 +0000817 if (UsesCodeGen && !TM)
818 return;
819 if (TM)
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000820 TheModule->setDataLayout(TM->createDataLayout());
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000821
Peter Collingbourne03f89072016-07-15 00:55:40 +0000822 legacy::PassManager PerModulePasses;
823 PerModulePasses.add(
824 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
825
826 legacy::FunctionPassManager PerFunctionPasses(TheModule);
827 PerFunctionPasses.add(
828 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
829
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000830 CreatePasses(PerModulePasses, PerFunctionPasses);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000831
832 legacy::PassManager CodeGenPasses;
833 CodeGenPasses.add(
834 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000835
Peter Collingbourne91d02842018-05-22 18:52:37 +0000836 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000837
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000838 switch (Action) {
839 case Backend_EmitNothing:
840 break;
841
842 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +0000843 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000844 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +0000845 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
846 if (!ThinLinkOS)
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000847 return;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000848 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000849 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
850 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000851 PerModulePasses.add(createWriteThinLTOBitcodePass(
852 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000853 } else {
854 // Emit a module summary by default for Regular LTO except for ld64
855 // targets
856 bool EmitLTOSummary =
857 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +0000858 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000859 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
860 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000861 if (EmitLTOSummary) {
862 if (!TheModule->getModuleFlag("ThinLTO"))
863 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
864 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Teresa Johnson604f8022019-07-19 23:02:58 +0000865 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000866 }
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000867
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000868 PerModulePasses.add(createBitcodeWriterPass(
869 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000870 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000871 break;
872
873 case Backend_EmitLL:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000874 PerModulePasses.add(
Duncan P. N. Exon Smithbb9cadf2015-04-15 02:45:28 +0000875 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000876 break;
877
878 default:
Aaron Puchertb207bae2019-06-26 21:36:35 +0000879 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +0000880 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000881 if (!DwoOS)
882 return;
883 }
884 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
885 DwoOS ? &DwoOS->os() : nullptr))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000886 return;
887 }
888
Andrew Trick15e36e82011-04-05 18:56:55 +0000889 // Before executing passes, print the final values of the LLVM options.
890 cl::PrintOptionValues();
891
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000892 // Run passes. For now we do all passes at once, but eventually we
893 // would like to have the option of streaming code generation.
894
Peter Collingbourne03f89072016-07-15 00:55:40 +0000895 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000896 PrettyStackTraceString CrashInfo("Per-function optimization");
897
Peter Collingbourne03f89072016-07-15 00:55:40 +0000898 PerFunctionPasses.doInitialization();
Yaron Keren10d6d162015-06-05 09:40:53 +0000899 for (Function &F : *TheModule)
900 if (!F.isDeclaration())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000901 PerFunctionPasses.run(F);
902 PerFunctionPasses.doFinalization();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000903 }
904
Peter Collingbourne03f89072016-07-15 00:55:40 +0000905 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000906 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000907 PerModulePasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000908 }
909
Peter Collingbourne03f89072016-07-15 00:55:40 +0000910 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000911 PrettyStackTraceString CrashInfo("Code generation");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000912 CodeGenPasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000913 }
Peter Collingbourne91d02842018-05-22 18:52:37 +0000914
915 if (ThinLinkOS)
916 ThinLinkOS->keep();
917 if (DwoOS)
918 DwoOS->keep();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000919}
920
Chandler Carruth50f9e892016-12-23 20:44:01 +0000921static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
922 switch (Opts.OptimizationLevel) {
923 default:
924 llvm_unreachable("Invalid optimization level!");
925
926 case 1:
927 return PassBuilder::O1;
928
929 case 2:
930 switch (Opts.OptimizeSize) {
931 default:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000932 llvm_unreachable("Invalid optimization level for size!");
Chandler Carruth50f9e892016-12-23 20:44:01 +0000933
934 case 0:
935 return PassBuilder::O2;
936
937 case 1:
938 return PassBuilder::Os;
939
940 case 2:
941 return PassBuilder::Oz;
942 }
943
944 case 3:
945 return PassBuilder::O3;
946 }
947}
948
Benjamin Kramerba2ea932019-03-28 17:18:42 +0000949static void addSanitizersAtO0(ModulePassManager &MPM,
950 const Triple &TargetTriple,
951 const LangOptions &LangOpts,
952 const CodeGenOptions &CodeGenOpts) {
Petr Hosek366cda02019-05-09 06:09:35 +0000953 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
Leonard Chan436fb2b2019-02-13 22:22:48 +0000954 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
Petr Hosek366cda02019-05-09 06:09:35 +0000955 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
956 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
957 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000958 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Petr Hosek366cda02019-05-09 06:09:35 +0000959 MPM.addPass(
960 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
961 CodeGenOpts.SanitizeAddressUseOdrIndicator));
962 };
963
964 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
965 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
966 }
967
968 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
969 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
Leonard Chan436fb2b2019-02-13 22:22:48 +0000970 }
Leonard Chan1a240ed2019-02-20 03:50:11 +0000971
972 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
973 MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
974 }
975
Petr Hosek366cda02019-05-09 06:09:35 +0000976 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
977 MPM.addPass(createModuleToFunctionPassAdaptor(
978 MemorySanitizerPass({0, false, /*Kernel=*/true})));
979 }
980
Leonard Chan1a240ed2019-02-20 03:50:11 +0000981 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
982 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
983 }
Leonard Chan436fb2b2019-02-13 22:22:48 +0000984}
985
Chandler Carruth50f9e892016-12-23 20:44:01 +0000986/// A clean version of `EmitAssembly` that uses the new pass manager.
987///
988/// Not all features are currently supported in this system, but where
989/// necessary it falls back to the legacy pass manager to at least provide
990/// basic functionality.
991///
992/// This API is planned to have its functionality finished and then to replace
993/// `EmitAssembly` at some point in the future when the default switches.
994void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
995 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000996 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000997 setCommandLineOpts(CodeGenOpts);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000998
Petr Hosek5f2e10e2019-05-06 23:24:17 +0000999 bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1000 Action != Backend_EmitBC &&
1001 Action != Backend_EmitLL);
1002 CreateTargetMachine(RequiresCodeGen);
1003
1004 if (RequiresCodeGen && !TM)
Chandler Carruth50f9e892016-12-23 20:44:01 +00001005 return;
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001006 if (TM)
1007 TheModule->setDataLayout(TM->createDataLayout());
Chandler Carruth50f9e892016-12-23 20:44:01 +00001008
Dehao Chenc76a27e2017-07-27 15:29:53 +00001009 Optional<PGOOptions> PGOOpt;
Davide Italiano945de432017-02-13 16:07:05 +00001010
Dehao Chenc76a27e2017-07-27 15:29:53 +00001011 if (CodeGenOpts.hasProfileIRInstr())
1012 // -fprofile-generate.
1013 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1014 ? DefaultProfileGenName
1015 : CodeGenOpts.InstrProfileOutput,
Rong Xua4a09b22019-03-04 20:21:31 +00001016 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
Richard Smith8654ae52018-10-10 23:13:35 +00001017 CodeGenOpts.DebugInfoForProfiling);
Rong Xua4a09b22019-03-04 20:21:31 +00001018 else if (CodeGenOpts.hasProfileIRUse()) {
Dehao Chenc76a27e2017-07-27 15:29:53 +00001019 // -fprofile-use.
Rong Xua4a09b22019-03-04 20:21:31 +00001020 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1021 : PGOOptions::NoCSAction;
1022 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1023 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1024 CSAction, CodeGenOpts.DebugInfoForProfiling);
1025 } else if (!CodeGenOpts.SampleProfileFile.empty())
Dehao Chenc76a27e2017-07-27 15:29:53 +00001026 // -fprofile-sample-use
Rong Xua4a09b22019-03-04 20:21:31 +00001027 PGOOpt =
1028 PGOOptions(CodeGenOpts.SampleProfileFile, "",
1029 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1030 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
Dehao Chenc76a27e2017-07-27 15:29:53 +00001031 else if (CodeGenOpts.DebugInfoForProfiling)
1032 // -fdebug-info-for-profiling
Rong Xua4a09b22019-03-04 20:21:31 +00001033 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1034 PGOOptions::NoCSAction, true);
1035
1036 // Check to see if we want to generate a CS profile.
1037 if (CodeGenOpts.hasProfileCSIRInstr()) {
1038 assert(!CodeGenOpts.hasProfileCSIRUse() &&
1039 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1040 "the same time");
1041 if (PGOOpt.hasValue()) {
1042 assert(PGOOpt->Action != PGOOptions::IRInstr &&
1043 PGOOpt->Action != PGOOptions::SampleUse &&
1044 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1045 " pass");
1046 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1047 ? DefaultProfileGenName
1048 : CodeGenOpts.InstrProfileOutput;
1049 PGOOpt->CSAction = PGOOptions::CSIRInstr;
1050 } else
1051 PGOOpt = PGOOptions("",
1052 CodeGenOpts.InstrProfileOutput.empty()
1053 ? DefaultProfileGenName
1054 : CodeGenOpts.InstrProfileOutput,
1055 "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1056 CodeGenOpts.DebugInfoForProfiling);
1057 }
Davide Italiano945de432017-02-13 16:07:05 +00001058
Alina Sbirlea267ac922019-05-23 18:51:02 +00001059 PipelineTuningOptions PTO;
Alina Sbirlea21efe2a2019-05-24 17:40:52 +00001060 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001061 // For historical reasons, loop interleaving is set to mirror setting for loop
1062 // unrolling.
1063 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1064 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1065 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1066
Taewook Ohd4c50f72019-08-14 07:11:09 +00001067 PassInstrumentationCallbacks PIC;
1068 StandardInstrumentations SI;
1069 SI.registerCallbacks(PIC);
1070 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001071
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001072 // Attempt to load pass plugins and register their callbacks with PB.
1073 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1074 auto PassPlugin = PassPlugin::Load(PluginFN);
1075 if (PassPlugin) {
1076 PassPlugin->registerPassBuilderCallbacks(PB);
1077 } else {
1078 Diags.Report(diag::err_fe_unable_to_load_plugin)
1079 << PluginFN << toString(PassPlugin.takeError());
1080 }
1081 }
1082
Craig Topper926b95c2017-11-14 08:48:28 +00001083 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1084 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1085 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1086 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001087
1088 // Register the AA manager first so that our version is the one used.
1089 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1090
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001091 // Register the target library analysis directly and give it a customized
1092 // preset TLI.
1093 Triple TargetTriple(TheModule->getTargetTriple());
1094 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1095 createTLII(TargetTriple, CodeGenOpts));
1096 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1097 MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1098
Chandler Carruth50f9e892016-12-23 20:44:01 +00001099 // Register all the basic analyses with the managers.
1100 PB.registerModuleAnalyses(MAM);
1101 PB.registerCGSCCAnalyses(CGAM);
1102 PB.registerFunctionAnalyses(FAM);
1103 PB.registerLoopAnalyses(LAM);
1104 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1105
Tim Shenb13eebe2017-06-29 23:10:13 +00001106 ModulePassManager MPM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001107
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001108 if (!CodeGenOpts.DisableLLVMPasses) {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001109 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
Tim Shen66470692017-06-29 23:08:38 +00001110 bool IsLTO = CodeGenOpts.PrepareForLTO;
1111
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001112 if (CodeGenOpts.OptimizationLevel == 0) {
David Blaikieac904d02018-01-23 01:25:24 +00001113 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1114 MPM.addPass(GCOVProfilerPass(*Options));
Rong Xu4059e142019-04-25 17:52:43 +00001115 if (Optional<InstrProfOptions> Options =
1116 getInstrProfOptions(CodeGenOpts, LangOpts))
1117 MPM.addPass(InstrProfiling(*Options, false));
David Blaikieac904d02018-01-23 01:25:24 +00001118
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001119 // Build a minimal pipeline based on the semantics required by Clang,
Leonard Chan587497b2019-06-13 16:45:29 +00001120 // which is just that always inlining occurs. Further, disable generating
1121 // lifetime intrinsics to avoid enabling further optimizations during
1122 // code generation.
1123 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/false));
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001124
Rong Xuca161fa2019-08-01 22:36:34 +00001125 // At -O0, we can still do PGO. Add all the requested passes for
1126 // instrumentation PGO, if requested.
1127 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1128 PGOOpt->Action == PGOOptions::IRUse))
1129 PB.addPGOInstrPassesForO0(
1130 MPM, CodeGenOpts.DebugPassManager,
1131 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1132 /* IsCS */ false, PGOOpt->ProfileFile,
1133 PGOOpt->ProfileRemappingFile);
1134
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001135 // At -O0 we directly run necessary sanitizer passes.
1136 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1137 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1138
Teresa Johnson6ed79132019-01-04 19:05:01 +00001139 // Lastly, add semantically necessary passes for LTO.
1140 if (IsLTO || IsThinLTO) {
1141 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001142 MPM.addPass(NameAnonGlobalPass());
Teresa Johnson6ed79132019-01-04 19:05:01 +00001143 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001144 } else {
Tim Shen66470692017-06-29 23:08:38 +00001145 // Map our optimization levels into one of the distinct levels used to
1146 // configure the pipeline.
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001147 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1148
Leonard Chanb2065132019-06-20 19:35:25 +00001149 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1150 MPM.addPass(createModuleToFunctionPassAdaptor(
1151 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1152 });
1153
Leonard Chan007f6742019-07-25 20:53:15 +00001154 if (CodeGenOpts.SanitizeCoverageType ||
1155 CodeGenOpts.SanitizeCoverageIndirectCalls ||
1156 CodeGenOpts.SanitizeCoverageTraceCmp) {
1157 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1158 PB.registerPipelineStartEPCallback(
1159 [SancovOpts](ModulePassManager &MPM) {
1160 MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1161 });
1162 PB.registerOptimizerLastEPCallback(
1163 [SancovOpts](FunctionPassManager &FPM,
1164 PassBuilder::OptimizationLevel Level) {
1165 FPM.addPass(SanitizerCoveragePass(SancovOpts));
1166 });
1167 }
1168
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001169 // Register callbacks to schedule sanitizer passes at the appropriate part of
1170 // the pipeline.
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001171 // FIXME: either handle asan/the remaining sanitizers or error out
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001172 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1173 PB.registerScalarOptimizerLateEPCallback(
1174 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1175 FPM.addPass(BoundsCheckingPass());
1176 });
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001177 if (LangOpts.Sanitize.has(SanitizerKind::Memory))
1178 PB.registerOptimizerLastEPCallback(
1179 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001180 FPM.addPass(MemorySanitizerPass({}));
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001181 });
1182 if (LangOpts.Sanitize.has(SanitizerKind::Thread))
1183 PB.registerOptimizerLastEPCallback(
1184 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1185 FPM.addPass(ThreadSanitizerPass());
1186 });
Leonard Chan436fb2b2019-02-13 22:22:48 +00001187 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1188 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1189 MPM.addPass(
1190 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1191 });
1192 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
Leonard Chan619b6d52019-02-14 01:07:47 +00001193 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
Leonard Chan436fb2b2019-02-13 22:22:48 +00001194 PB.registerOptimizerLastEPCallback(
Leonard Chan619b6d52019-02-14 01:07:47 +00001195 [Recover, UseAfterScope](FunctionPassManager &FPM,
1196 PassBuilder::OptimizationLevel Level) {
Leonard Chan436fb2b2019-02-13 22:22:48 +00001197 FPM.addPass(AddressSanitizerPass(
Leonard Chan619b6d52019-02-14 01:07:47 +00001198 /*CompileKernel=*/false, Recover, UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +00001199 });
1200 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Leonard Chan619b6d52019-02-14 01:07:47 +00001201 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1202 PB.registerPipelineStartEPCallback(
1203 [Recover, ModuleUseAfterScope,
1204 UseOdrIndicator](ModulePassManager &MPM) {
1205 MPM.addPass(ModuleAddressSanitizerPass(
1206 /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1207 UseOdrIndicator));
1208 });
Leonard Chan436fb2b2019-02-13 22:22:48 +00001209 }
David Blaikieac904d02018-01-23 01:25:24 +00001210 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1211 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1212 MPM.addPass(GCOVProfilerPass(*Options));
1213 });
Rong Xu4059e142019-04-25 17:52:43 +00001214 if (Optional<InstrProfOptions> Options =
1215 getInstrProfOptions(CodeGenOpts, LangOpts))
1216 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1217 MPM.addPass(InstrProfiling(*Options, false));
1218 });
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001219
Tim Shen66470692017-06-29 23:08:38 +00001220 if (IsThinLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001221 MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1222 Level, CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001223 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001224 MPM.addPass(NameAnonGlobalPass());
1225 } else if (IsLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001226 MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1227 CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001228 MPM.addPass(CanonicalizeAliasesPass());
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001229 MPM.addPass(NameAnonGlobalPass());
Tim Shen66470692017-06-29 23:08:38 +00001230 } else {
Tim Shenb13eebe2017-06-29 23:10:13 +00001231 MPM = PB.buildPerModuleDefaultPipeline(Level,
1232 CodeGenOpts.DebugPassManager);
Tim Shen66470692017-06-29 23:08:38 +00001233 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001234 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001235
Peter Collingbourne3b82b922019-07-17 21:45:19 +00001236 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1237 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1238 MPM.addPass(HWAddressSanitizerPass(
1239 /*CompileKernel=*/false, Recover));
1240 }
1241 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1242 MPM.addPass(HWAddressSanitizerPass(
1243 /*CompileKernel=*/true, /*Recover=*/true));
1244 }
1245
Leonard Chan007f6742019-07-25 20:53:15 +00001246 if (CodeGenOpts.OptimizationLevel == 0) {
1247 if (CodeGenOpts.SanitizeCoverageType ||
1248 CodeGenOpts.SanitizeCoverageIndirectCalls ||
1249 CodeGenOpts.SanitizeCoverageTraceCmp) {
1250 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1251 MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1252 MPM.addPass(createModuleToFunctionPassAdaptor(
1253 SanitizerCoveragePass(SancovOpts)));
1254 }
1255
Leonard Chan436fb2b2019-02-13 22:22:48 +00001256 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
Leonard Chan007f6742019-07-25 20:53:15 +00001257 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001258 }
1259
1260 // FIXME: We still use the legacy pass manager to do code generation. We
1261 // create that pass manager here and use it as needed below.
1262 legacy::PassManager CodeGenPasses;
1263 bool NeedCodeGen = false;
Peter Collingbourne91d02842018-05-22 18:52:37 +00001264 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Chandler Carruth50f9e892016-12-23 20:44:01 +00001265
1266 // Append any output we need to the pass manager.
1267 switch (Action) {
1268 case Backend_EmitNothing:
1269 break;
1270
1271 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +00001272 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Tim Shen50fedec2017-06-01 23:27:51 +00001273 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +00001274 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1275 if (!ThinLinkOS)
Tim Shen50fedec2017-06-01 23:27:51 +00001276 return;
Tim Shen50fedec2017-06-01 23:27:51 +00001277 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001278 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1279 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001280 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1281 : nullptr));
Tim Shen50fedec2017-06-01 23:27:51 +00001282 } else {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001283 // Emit a module summary by default for Regular LTO except for ld64
1284 // targets
1285 bool EmitLTOSummary =
1286 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +00001287 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001288 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1289 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001290 if (EmitLTOSummary) {
1291 if (!TheModule->getModuleFlag("ThinLTO"))
1292 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1293 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1294 CodeGenOpts.EnableSplitLTOUnit);
1295 }
1296 MPM.addPass(
1297 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tim Shen50fedec2017-06-01 23:27:51 +00001298 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001299 break;
1300
1301 case Backend_EmitLL:
1302 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1303 break;
1304
1305 case Backend_EmitAssembly:
1306 case Backend_EmitMCNull:
1307 case Backend_EmitObj:
1308 NeedCodeGen = true;
1309 CodeGenPasses.add(
1310 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Aaron Puchertb207bae2019-06-26 21:36:35 +00001311 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00001312 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001313 if (!DwoOS)
1314 return;
1315 }
1316 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1317 DwoOS ? &DwoOS->os() : nullptr))
Chandler Carruth50f9e892016-12-23 20:44:01 +00001318 // FIXME: Should we handle this error differently?
1319 return;
1320 break;
1321 }
1322
1323 // Before executing passes, print the final values of the LLVM options.
1324 cl::PrintOptionValues();
1325
1326 // Now that we have all of the passes ready, run them.
1327 {
1328 PrettyStackTraceString CrashInfo("Optimizer");
1329 MPM.run(*TheModule, MAM);
1330 }
1331
1332 // Now if needed, run the legacy PM for codegen.
1333 if (NeedCodeGen) {
1334 PrettyStackTraceString CrashInfo("Code generation");
1335 CodeGenPasses.run(*TheModule);
1336 }
Peter Collingbourne91d02842018-05-22 18:52:37 +00001337
1338 if (ThinLinkOS)
1339 ThinLinkOS->keep();
1340 if (DwoOS)
1341 DwoOS->keep();
Chandler Carruth50f9e892016-12-23 20:44:01 +00001342}
1343
Peter Collingbourne47d23642017-01-24 19:54:37 +00001344Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1345 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1346 if (!BMsOrErr)
1347 return BMsOrErr.takeError();
1348
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00001349 // The bitcode file may contain multiple modules, we want the one that is
1350 // marked as being the ThinLTO module.
Vitaly Bukac35ff822018-02-16 23:34:16 +00001351 if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1352 return *Bm;
Peter Collingbourne47d23642017-01-24 19:54:37 +00001353
1354 return make_error<StringError>("Could not find module summary",
1355 inconvertibleErrorCode());
1356}
1357
Vitaly Bukac35ff822018-02-16 23:34:16 +00001358BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1359 for (BitcodeModule &BM : BMs) {
1360 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1361 if (LTOInfo && LTOInfo->IsThinLTO)
1362 return &BM;
1363 }
1364 return nullptr;
1365}
1366
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001367static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001368 const HeaderSearchOptions &HeaderOpts,
1369 const CodeGenOptions &CGOpts,
1370 const clang::TargetOptions &TOpts,
1371 const LangOptions &LOpts,
Dehao Chena1bd2d62017-01-13 00:51:55 +00001372 std::unique_ptr<raw_pwrite_stream> OS,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001373 std::string SampleProfile,
Richard Smith8654ae52018-10-10 23:13:35 +00001374 std::string ProfileRemapping,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001375 BackendAction Action) {
Dehao Chen5f83d0e2017-07-10 20:31:37 +00001376 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001377 ModuleToDefinedGVSummaries;
1378 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1379
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001380 setCommandLineOpts(CGOpts);
1381
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001382 // We can simply import the values mentioned in the combined index, since
1383 // we should only invoke this using the individual indexes written out
1384 // via a WriteIndexesThinBackend.
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001385 FunctionImporter::ImportMapTy ImportList;
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001386 for (auto &GlobalList : *CombinedIndex) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001387 // Ignore entries for undefined references.
1388 if (GlobalList.second.SummaryList.empty())
1389 continue;
1390
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001391 auto GUID = GlobalList.first;
Teresa Johnson5ed8b002018-11-29 17:02:59 +00001392 for (auto &Summary : GlobalList.second.SummaryList) {
1393 // Skip the summaries for the importing module. These are included to
1394 // e.g. record required linkage changes.
1395 if (Summary->modulePath() == M->getModuleIdentifier())
1396 continue;
1397 // Add an entry to provoke importing by thinBackend.
1398 ImportList[Summary->modulePath()].insert(GUID);
1399 }
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001400 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001401
1402 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001403 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001404
1405 for (auto &I : ImportList) {
1406 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1407 llvm::MemoryBuffer::getFile(I.first());
1408 if (!MBOrErr) {
1409 errs() << "Error loading imported file '" << I.first()
1410 << "': " << MBOrErr.getError().message() << "\n";
1411 return;
1412 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001413
Peter Collingbourne47d23642017-01-24 19:54:37 +00001414 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1415 if (!BMOrErr) {
1416 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001417 errs() << "Error loading imported file '" << I.first()
1418 << "': " << EIB.message() << '\n';
1419 });
1420 return;
1421 }
Peter Collingbourne47d23642017-01-24 19:54:37 +00001422 ModuleMap.insert({I.first(), *BMOrErr});
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001423
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001424 OwnedImports.push_back(std::move(*MBOrErr));
1425 }
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001426 auto AddStream = [&](size_t Task) {
1427 return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
Mehdi Amini406aa222016-08-17 06:23:08 +00001428 };
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001429 lto::Config Conf;
Teresa Johnson9e4321c2018-04-17 16:39:25 +00001430 if (CGOpts.SaveTempsFilePrefix != "") {
1431 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1432 /* UseInputModulePath */ false)) {
1433 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1434 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1435 << '\n';
1436 });
1437 }
1438 }
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001439 Conf.CPU = TOpts.CPU;
1440 Conf.CodeModel = getCodeModel(CGOpts);
1441 Conf.MAttrs = TOpts.Features;
Rafael Espindolae1d70532018-01-18 00:20:03 +00001442 Conf.RelocModel = CGOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001443 Conf.CGOptLevel = getCGOptLevel(CGOpts);
Teresa Johnson867bc392019-04-23 18:56:19 +00001444 Conf.OptLevel = CGOpts.OptimizationLevel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001445 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001446 Conf.SampleProfile = std::move(SampleProfile);
Rong Xua4a09b22019-03-04 20:21:31 +00001447
1448 // Context sensitive profile.
1449 if (CGOpts.hasProfileCSIRInstr()) {
1450 Conf.RunCSIRInstr = true;
1451 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1452 } else if (CGOpts.hasProfileCSIRUse()) {
1453 Conf.RunCSIRInstr = false;
1454 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1455 }
1456
Richard Smith8654ae52018-10-10 23:13:35 +00001457 Conf.ProfileRemapping = std::move(ProfileRemapping);
Tim Shen50fedec2017-06-01 23:27:51 +00001458 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
Teresa Johnson4cd016ab2017-11-13 15:38:33 +00001459 Conf.DebugPassManager = CGOpts.DebugPassManager;
Teresa Johnson66744f82018-05-05 14:37:29 +00001460 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1461 Conf.RemarksFilename = CGOpts.OptRecordFile;
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00001462 Conf.RemarksPasses = CGOpts.OptRecordPasses;
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00001463 Conf.RemarksFormat = CGOpts.OptRecordFormat;
Aaron Pucherte1dc4952019-06-15 15:38:51 +00001464 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1465 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001466 switch (Action) {
1467 case Backend_EmitNothing:
1468 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1469 return false;
1470 };
1471 break;
1472 case Backend_EmitLL:
1473 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1474 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1475 return false;
1476 };
1477 break;
1478 case Backend_EmitBC:
1479 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
Rafael Espindola76c8f822018-02-14 19:11:37 +00001480 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001481 return false;
1482 };
1483 break;
1484 default:
1485 Conf.CGFileType = getCodeGenFileType(Action);
1486 break;
1487 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001488 if (Error E = thinBackend(
Teresa Johnson66744f82018-05-05 14:37:29 +00001489 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001490 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1491 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1492 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1493 });
1494 }
1495}
1496
David Blaikie9c902b52011-09-25 23:23:43 +00001497void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001498 const HeaderSearchOptions &HeaderOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00001499 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +00001500 const clang::TargetOptions &TOpts,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001501 const LangOptions &LOpts,
1502 const llvm::DataLayout &TDesc, Module *M,
1503 BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +00001504 std::unique_ptr<raw_pwrite_stream> OS) {
Anton Afanasyevd880de22019-03-30 08:42:48 +00001505
1506 llvm::TimeTraceScope TimeScope("Backend", StringRef(""));
1507
Vitaly Buka769134d2018-02-16 23:38:22 +00001508 std::unique_ptr<llvm::Module> EmptyModule;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001509 if (!CGOpts.ThinLTOIndexFile.empty()) {
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001510 // If we are performing a ThinLTO importing compile, load the function index
1511 // into memory and pass it into runThinLTOBackend, which will run the
1512 // function importer and invoke LTO passes.
1513 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
Teresa Johnson517729f2017-05-12 19:32:17 +00001514 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1515 /*IgnoreEmptyThinLTOIndexFile*/true);
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001516 if (!IndexOrErr) {
1517 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1518 "Error loading index file '" +
1519 CGOpts.ThinLTOIndexFile + "': ");
1520 return;
1521 }
1522 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1523 // A null CombinedIndex means we should skip ThinLTO compilation
1524 // (LLVM will optionally ignore empty index files, returning null instead
1525 // of an error).
Vitaly Buka769134d2018-02-16 23:38:22 +00001526 if (CombinedIndex) {
1527 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1528 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1529 LOpts, std::move(OS), CGOpts.SampleProfileFile,
Richard Smith8654ae52018-10-10 23:13:35 +00001530 CGOpts.ProfileRemappingFile, Action);
Vitaly Buka769134d2018-02-16 23:38:22 +00001531 return;
1532 }
1533 // Distributed indexing detected that nothing from the module is needed
1534 // for the final linking. So we can skip the compilation. We sill need to
1535 // output an empty object file to make sure that a linker does not fail
1536 // trying to read it. Also for some features, like CFI, we must skip
1537 // the compilation as CombinedIndex does not contain all required
1538 // information.
1539 EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
1540 EmptyModule->setTargetTriple(M->getTargetTriple());
1541 M = EmptyModule.get();
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001542 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001543 }
1544
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001545 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001546
Chandler Carruth50f9e892016-12-23 20:44:01 +00001547 if (CGOpts.ExperimentalNewPassManager)
1548 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1549 else
1550 AsmHelper.EmitAssembly(Action, std::move(OS));
Alp Tokere83b9062014-01-02 15:08:04 +00001551
James Y Knightb214cbc2016-03-04 19:00:41 +00001552 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1553 // DataLayout.
1554 if (AsmHelper.TM) {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00001555 std::string DLDesc = M->getDataLayout().getStringRepresentation();
James Y Knightb214cbc2016-03-04 19:00:41 +00001556 if (DLDesc != TDesc.getStringRepresentation()) {
Alp Tokere83b9062014-01-02 15:08:04 +00001557 unsigned DiagID = Diags.getCustomDiagID(
1558 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1559 "expected target description '%1'");
James Y Knightb214cbc2016-03-04 19:00:41 +00001560 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
Alp Tokere83b9062014-01-02 15:08:04 +00001561 }
1562 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001563}
Steven Wu27fb5222016-05-11 16:26:03 +00001564
1565static const char* getSectionNameForBitcode(const Triple &T) {
1566 switch (T.getObjectFormat()) {
1567 case Triple::MachO:
1568 return "__LLVM,__bitcode";
1569 case Triple::COFF:
1570 case Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00001571 case Triple::Wasm:
Steven Wu27fb5222016-05-11 16:26:03 +00001572 case Triple::UnknownObjectFormat:
1573 return ".llvmbc";
Jason Liua03ae732019-03-12 22:01:10 +00001574 case Triple::XCOFF:
1575 llvm_unreachable("XCOFF is not yet implemented");
1576 break;
Steven Wu27fb5222016-05-11 16:26:03 +00001577 }
Simon Pilgrimbff9dae2016-05-11 21:55:37 +00001578 llvm_unreachable("Unimplemented ObjectFormatType");
Steven Wu27fb5222016-05-11 16:26:03 +00001579}
1580
1581static const char* getSectionNameForCommandline(const Triple &T) {
1582 switch (T.getObjectFormat()) {
1583 case Triple::MachO:
1584 return "__LLVM,__cmdline";
1585 case Triple::COFF:
1586 case Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00001587 case Triple::Wasm:
Steven Wu27fb5222016-05-11 16:26:03 +00001588 case Triple::UnknownObjectFormat:
1589 return ".llvmcmd";
Jason Liua03ae732019-03-12 22:01:10 +00001590 case Triple::XCOFF:
1591 llvm_unreachable("XCOFF is not yet implemented");
1592 break;
Steven Wu27fb5222016-05-11 16:26:03 +00001593 }
Simon Pilgrimbff9dae2016-05-11 21:55:37 +00001594 llvm_unreachable("Unimplemented ObjectFormatType");
Steven Wu27fb5222016-05-11 16:26:03 +00001595}
1596
1597// With -fembed-bitcode, save a copy of the llvm IR as data in the
1598// __LLVM,__bitcode section.
1599void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1600 llvm::MemoryBufferRef Buf) {
1601 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1602 return;
1603
Steven Wu2c059a52016-05-16 18:54:58 +00001604 // Save llvm.compiler.used and remote it.
1605 SmallVector<Constant*, 2> UsedArray;
Craig Topper7c89d042018-06-09 00:30:45 +00001606 SmallPtrSet<GlobalValue*, 4> UsedGlobals;
Steven Wu2c059a52016-05-16 18:54:58 +00001607 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1608 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1609 for (auto *GV : UsedGlobals) {
1610 if (GV->getName() != "llvm.embedded.module" &&
1611 GV->getName() != "llvm.cmdline")
1612 UsedArray.push_back(
1613 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1614 }
1615 if (Used)
1616 Used->eraseFromParent();
1617
Steven Wu27fb5222016-05-11 16:26:03 +00001618 // Embed the bitcode for the llvm module.
1619 std::string Data;
1620 ArrayRef<uint8_t> ModuleData;
1621 Triple T(M->getTargetTriple());
1622 // Create a constant that contains the bitcode.
1623 // In case of embedding a marker, ignore the input Buf and use the empty
1624 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1625 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1626 if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1627 (const unsigned char *)Buf.getBufferEnd())) {
1628 // If the input is LLVM Assembly, bitcode is produced by serializing
1629 // the module. Use-lists order need to be perserved in this case.
1630 llvm::raw_string_ostream OS(Data);
Rafael Espindola76c8f822018-02-14 19:11:37 +00001631 llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
Steven Wu27fb5222016-05-11 16:26:03 +00001632 ModuleData =
1633 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1634 } else
1635 // If the input is LLVM bitcode, write the input byte stream directly.
1636 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1637 Buf.getBufferSize());
1638 }
1639 llvm::Constant *ModuleConstant =
1640 llvm::ConstantDataArray::get(M->getContext(), ModuleData);
Steven Wu27fb5222016-05-11 16:26:03 +00001641 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
Steven Wu2c059a52016-05-16 18:54:58 +00001642 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
Steven Wu27fb5222016-05-11 16:26:03 +00001643 ModuleConstant);
1644 GV->setSection(getSectionNameForBitcode(T));
Steven Wu2c059a52016-05-16 18:54:58 +00001645 UsedArray.push_back(
1646 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
Steven Wu27fb5222016-05-11 16:26:03 +00001647 if (llvm::GlobalVariable *Old =
Steven Wu2c059a52016-05-16 18:54:58 +00001648 M->getGlobalVariable("llvm.embedded.module", true)) {
1649 assert(Old->hasOneUse() &&
1650 "llvm.embedded.module can only be used once in llvm.compiler.used");
Steven Wu27fb5222016-05-11 16:26:03 +00001651 GV->takeName(Old);
1652 Old->eraseFromParent();
1653 } else {
1654 GV->setName("llvm.embedded.module");
1655 }
1656
Steven Wu2c059a52016-05-16 18:54:58 +00001657 // Skip if only bitcode needs to be embedded.
1658 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1659 // Embed command-line options.
Saleem Abdulrasoolb1d50c12016-05-20 03:58:12 +00001660 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
Steven Wu2c059a52016-05-16 18:54:58 +00001661 CGOpts.CmdArgs.size());
1662 llvm::Constant *CmdConstant =
1663 llvm::ConstantDataArray::get(M->getContext(), CmdData);
1664 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1665 llvm::GlobalValue::PrivateLinkage,
1666 CmdConstant);
1667 GV->setSection(getSectionNameForCommandline(T));
1668 UsedArray.push_back(
1669 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1670 if (llvm::GlobalVariable *Old =
1671 M->getGlobalVariable("llvm.cmdline", true)) {
1672 assert(Old->hasOneUse() &&
1673 "llvm.cmdline can only be used once in llvm.compiler.used");
1674 GV->takeName(Old);
1675 Old->eraseFromParent();
1676 } else {
1677 GV->setName("llvm.cmdline");
1678 }
1679 }
1680
1681 if (UsedArray.empty())
Steven Wu27fb5222016-05-11 16:26:03 +00001682 return;
1683
Steven Wu2c059a52016-05-16 18:54:58 +00001684 // Recreate llvm.compiler.used.
1685 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1686 auto *NewUsed = new GlobalVariable(
1687 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1688 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1689 NewUsed->setSection("llvm.metadata");
Steven Wu27fb5222016-05-11 16:26:03 +00001690}