blob: 469aa0c9e0fb2aa8a911a945d957c9939bc74b2f [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;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000122 auto F = std::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));
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000227}
228
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000229// Check if ASan should use GC-friendly instrumentation for globals.
230// First of all, there is no point if -fdata-sections is off (expect for MachO,
231// where this is not a factor). Also, on ELF this feature requires an assembler
232// extension that only works with -integrated-as at the moment.
233static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
Evgeniy Stepanovd991cdd2017-05-09 21:57:43 +0000234 if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
235 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000236 switch (T.getObjectFormat()) {
237 case Triple::MachO:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000238 case Triple::COFF:
Evgeniy Stepanovc7b90942017-04-26 00:51:06 +0000239 return true;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000240 case Triple::ELF:
241 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
Hubert Tong2711e162019-07-19 08:46:18 +0000242 case Triple::XCOFF:
243 llvm::report_fatal_error("ASan not implemented for XCOFF.");
244 case Triple::Wasm:
245 case Triple::UnknownObjectFormat:
246 break;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000247 }
Hubert Tong2711e162019-07-19 08:46:18 +0000248 return false;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000249}
250
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000251static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000252 legacy::PassManagerBase &PM) {
Yury Gribov5bfeca12015-11-11 10:45:48 +0000253 const PassManagerBuilderWrapper &BuilderWrapper =
254 static_cast<const PassManagerBuilderWrapper&>(Builder);
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000255 const Triple &T = BuilderWrapper.getTargetTriple();
Yury Gribov5bfeca12015-11-11 10:45:48 +0000256 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
257 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000258 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
Vitaly Buka8076c572018-12-05 01:44:31 +0000259 bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000260 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000261 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
262 UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000263 PM.add(createModuleAddressSanitizerLegacyPassPass(
264 /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000265}
266
267static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
268 legacy::PassManagerBase &PM) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000269 PM.add(createAddressSanitizerFunctionPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000270 /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000271 PM.add(createModuleAddressSanitizerLegacyPassPass(
Vitaly Buka8076c572018-12-05 01:44:31 +0000272 /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
273 /*UseOdrIndicator*/ false));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000274}
275
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000276static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
277 legacy::PassManagerBase &PM) {
Evgeniy Stepanov3fd1b1a2017-12-20 19:05:44 +0000278 const PassManagerBuilderWrapper &BuilderWrapper =
279 static_cast<const PassManagerBuilderWrapper &>(Builder);
280 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
281 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000282 PM.add(
283 createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000284}
285
286static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
287 legacy::PassManagerBase &PM) {
Leonard Chan0cdd3b12019-05-14 21:17:21 +0000288 PM.add(createHWAddressSanitizerLegacyPassPass(
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000289 /*CompileKernel*/ true, /*Recover*/ true));
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000290}
291
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000292static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
293 legacy::PassManagerBase &PM,
294 bool CompileKernel) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000295 const PassManagerBuilderWrapper &BuilderWrapper =
296 static_cast<const PassManagerBuilderWrapper&>(Builder);
297 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Evgeniy Stepanov5b5370a2016-11-07 21:02:11 +0000298 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
299 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
Philip Pfaffe0ee6a932019-02-04 21:02:49 +0000300 PM.add(createMemorySanitizerLegacyPassPass(
301 MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000302
303 // MemorySanitizer inserts complex instrumentation that mostly follows
304 // the logic of the original code, but operates on "shadow" values.
305 // It can benefit from re-running some general purpose optimization passes.
306 if (Builder.OptLevel > 0) {
307 PM.add(createEarlyCSEPass());
308 PM.add(createReassociatePass());
309 PM.add(createLICMPass());
310 PM.add(createGVNPass());
311 PM.add(createInstructionCombiningPass());
312 PM.add(createDeadStoreEliminationPass());
313 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000314}
315
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000316static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
317 legacy::PassManagerBase &PM) {
318 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
319}
320
321static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
322 legacy::PassManagerBase &PM) {
323 addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
324}
325
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000326static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000327 legacy::PassManagerBase &PM) {
Philip Pfaffe685c76d2019-01-16 09:28:01 +0000328 PM.add(createThreadSanitizerLegacyPassPass());
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000329}
330
Peter Collingbournec3772752013-08-07 22:47:34 +0000331static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000332 legacy::PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000333 const PassManagerBuilderWrapper &BuilderWrapper =
334 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonovae5804f2014-10-15 20:22:54 +0000335 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000336 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
Peter Collingbournec3772752013-08-07 22:47:34 +0000337}
338
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000339static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
340 const CodeGenOptions &CodeGenOpts) {
341 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000342 if (!CodeGenOpts.SimplifyLibCalls)
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000343 TLII->disableAllFunctions();
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000344 else {
345 // Disable individual libc/libm calls in TargetLibraryInfo.
David L. Jones7a7dd032017-01-23 23:16:58 +0000346 LibFunc F;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000347 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
348 if (TLII->getLibFunc(FuncName, F))
349 TLII->setUnavailable(F);
350 }
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000351
352 switch (CodeGenOpts.getVecLib()) {
353 case CodeGenOptions::Accelerate:
354 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
355 break;
Nemanja Ivanovic6321c682019-06-05 01:57:57 +0000356 case CodeGenOptions::MASSV:
357 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
358 break;
Matt Masten6731dea2016-07-29 16:44:24 +0000359 case CodeGenOptions::SVML:
360 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
361 break;
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000362 default:
363 break;
364 }
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000365 return TLII;
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000366}
367
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000368static void addSymbolRewriterPass(const CodeGenOptions &Opts,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000369 legacy::PassManager *MPM) {
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000370 llvm::SymbolRewriter::RewriteDescriptorList DL;
371
372 llvm::SymbolRewriter::RewriteMapParser MapParser;
373 for (const auto &MapFile : Opts.RewriteMapFiles)
374 MapParser.parse(MapFile, &DL);
375
376 MPM->add(createRewriteSymbolsPass(DL));
377}
378
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000379static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
380 switch (CodeGenOpts.OptimizationLevel) {
381 default:
382 llvm_unreachable("Invalid optimization level!");
383 case 0:
384 return CodeGenOpt::None;
385 case 1:
386 return CodeGenOpt::Less;
387 case 2:
388 return CodeGenOpt::Default; // O2/Os/Oz
389 case 3:
390 return CodeGenOpt::Aggressive;
391 }
392}
393
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000394static Optional<llvm::CodeModel::Model>
395getCodeModel(const CodeGenOptions &CodeGenOpts) {
396 unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
David Greenecc69872018-08-22 11:34:28 +0000397 .Case("tiny", llvm::CodeModel::Tiny)
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000398 .Case("small", llvm::CodeModel::Small)
399 .Case("kernel", llvm::CodeModel::Kernel)
400 .Case("medium", llvm::CodeModel::Medium)
401 .Case("large", llvm::CodeModel::Large)
402 .Case("default", ~1u)
403 .Default(~0u);
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000404 assert(CodeModel != ~0u && "invalid code model!");
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000405 if (CodeModel == ~1u)
406 return None;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000407 return static_cast<llvm::CodeModel::Model>(CodeModel);
408}
409
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000410static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
411 if (Action == Backend_EmitObj)
412 return TargetMachine::CGFT_ObjectFile;
413 else if (Action == Backend_EmitMCNull)
414 return TargetMachine::CGFT_Null;
415 else {
416 assert(Action == Backend_EmitAssembly && "Invalid action!");
417 return TargetMachine::CGFT_AssemblyFile;
418 }
419}
420
421static void initTargetOptions(llvm::TargetOptions &Options,
422 const CodeGenOptions &CodeGenOpts,
423 const clang::TargetOptions &TargetOpts,
424 const LangOptions &LangOpts,
425 const HeaderSearchOptions &HSOpts) {
426 Options.ThreadModel =
427 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
428 .Case("posix", llvm::ThreadModel::POSIX)
429 .Case("single", llvm::ThreadModel::Single);
430
431 // Set float ABI type.
432 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
433 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
434 "Invalid Floating Point ABI!");
435 Options.FloatABIType =
436 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
437 .Case("soft", llvm::FloatABI::Soft)
438 .Case("softfp", llvm::FloatABI::Soft)
439 .Case("hard", llvm::FloatABI::Hard)
440 .Default(llvm::FloatABI::Default);
441
442 // Set FP fusion mode.
443 switch (LangOpts.getDefaultFPContractMode()) {
444 case LangOptions::FPC_Off:
Adam Nemet03af4242017-04-20 17:09:35 +0000445 // Preserve any contraction performed by the front-end. (Strict performs
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000446 // splitting of the muladd intrinsic in the backend.)
Adam Nemet03af4242017-04-20 17:09:35 +0000447 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000448 break;
449 case LangOptions::FPC_On:
450 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
451 break;
452 case LangOptions::FPC_Fast:
453 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
454 break;
455 }
456
457 Options.UseInitArray = CodeGenOpts.UseInitArray;
458 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
Saleem Abdulrasool54448902017-06-09 00:40:30 +0000459 Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000460 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
461
462 // Set EABI version.
Yuka Takahashidc771502017-07-01 07:57:23 +0000463 Options.EABIVersion = TargetOpts.EABIVersion;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000464
465 if (LangOpts.SjLjExceptions)
466 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
Martell Malonec950c652017-11-29 07:25:12 +0000467 if (LangOpts.SEHExceptions)
468 Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
469 if (LangOpts.DWARFExceptions)
470 Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
Heejin Ahne8b2b882019-09-12 04:01:37 +0000471 if (LangOpts.WasmExceptions)
472 Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000473
474 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
475 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
476 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
477 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
478 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
479 Options.FunctionSections = CodeGenOpts.FunctionSections;
480 Options.DataSections = CodeGenOpts.DataSections;
481 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
482 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
Chih-Hung Hsiehca552b82018-03-01 22:26:19 +0000483 Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000484 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
Sean Eveson5110d4f2018-01-08 13:42:26 +0000485 Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
Peter Collingbourne14b468b2018-07-18 00:27:07 +0000486 Options.EmitAddrsig = CodeGenOpts.Addrsig;
Djordje Todorovic639d36b2019-06-26 09:38:09 +0000487 Options.EnableDebugEntryValues = CodeGenOpts.EnableDebugEntryValues;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000488
Aaron Puchertb207bae2019-06-26 21:36:35 +0000489 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000490 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
491 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
492 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
493 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
494 Options.MCOptions.MCIncrementalLinkerCompatible =
495 CodeGenOpts.IncrementalLinkerCompatible;
496 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
497 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
Brian Cain7b953b62019-08-08 19:19:20 +0000498 Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000499 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
500 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
501 Options.MCOptions.ABIName = TargetOpts.ABI;
502 for (const auto &Entry : HSOpts.UserEntries)
503 if (!Entry.IsFramework &&
504 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
505 Entry.Group == frontend::IncludeDirGroup::Angled ||
506 Entry.Group == frontend::IncludeDirGroup::System))
507 Options.MCOptions.IASSearchPaths.push_back(
508 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
509}
David Blaikie7a4f7f52018-01-09 22:03:47 +0000510static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
511 if (CodeGenOpts.DisableGCov)
512 return None;
513 if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
514 return None;
515 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
516 // LLVM's -default-gcov-version flag is set to something invalid.
517 GCOVOptions Options;
518 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
519 Options.EmitData = CodeGenOpts.EmitGcovArcs;
520 llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
521 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
522 Options.NoRedZone = CodeGenOpts.DisableRedZone;
523 Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
Calixte Denizetf4bf6712018-11-17 19:41:39 +0000524 Options.Filter = CodeGenOpts.ProfileFilterFiles;
525 Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
David Blaikie7a4f7f52018-01-09 22:03:47 +0000526 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
527 return Options;
528}
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000529
Rong Xu4059e142019-04-25 17:52:43 +0000530static Optional<InstrProfOptions>
531getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
532 const LangOptions &LangOpts) {
533 if (!CodeGenOpts.hasProfileClangInstr())
534 return None;
535 InstrProfOptions Options;
536 Options.NoRedZone = CodeGenOpts.DisableRedZone;
537 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
538
539 // TODO: Surface the option to emit atomic profile counter increments at
540 // the driver level.
541 Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
542 return Options;
543}
544
Peter Collingbourne03f89072016-07-15 00:55:40 +0000545void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000546 legacy::FunctionPassManager &FPM) {
Chandler Carruth93786da2016-12-23 00:23:01 +0000547 // Handle disabling of all LLVM passes, where we want to preserve the
548 // internal module before any optimization.
Steven Wu546a1962015-07-17 20:09:56 +0000549 if (CodeGenOpts.DisableLLVMPasses)
550 return;
551
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000552 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
553 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
554 // are inserted before PMBuilder ones - they'd get the default-constructed
555 // TLI with an unknown target otherwise.
Teresa Johnsonaff22322015-12-07 19:21:34 +0000556 Triple TargetTriple(TheModule->getTargetTriple());
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000557 std::unique_ptr<TargetLibraryInfoImpl> TLII(
558 createTLII(TargetTriple, CodeGenOpts));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000559
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000560 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
561
Chandler Carruthfcd33142016-12-23 01:24:49 +0000562 // At O0 and O1 we only run the always inliner which is more efficient. At
563 // higher optimization levels we run the normal inliner.
564 if (CodeGenOpts.OptimizationLevel <= 1) {
Mehdi Amini7f873072017-01-06 23:18:09 +0000565 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
566 !CodeGenOpts.DisableLifetimeMarkers);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000567 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
568 } else {
Dehao Chence39fdd2017-03-21 19:55:46 +0000569 // We do not want to inline hot callsites for SamplePGO module-summary build
570 // because profile annotation will happen again in ThinLTO backend, and we
571 // want the IR of the hot path to match the profile.
Chandler Carruthfcd33142016-12-23 01:24:49 +0000572 PMBuilder.Inliner = createFunctionInliningPass(
Dehao Chence39fdd2017-03-21 19:55:46 +0000573 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
574 (!CodeGenOpts.SampleProfileFile.empty() &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000575 CodeGenOpts.PrepareForThinLTO));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000576 }
577
Chandler Carruthfcd33142016-12-23 01:24:49 +0000578 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000579 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000580 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
581 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000582
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000583 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Alina Sbirleaa9b9ab82019-04-30 21:29:23 +0000584 // Loop interleaving in the loop vectorizer has historically been set to be
585 // enabled when loop unrolling is enabled.
586 PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000587 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000588 PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
Teresa Johnson8749d8042015-07-06 16:23:00 +0000589 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
Hal Finkelce0697f2013-11-17 16:03:29 +0000590 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000591
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000592 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
593
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000594 if (TM)
Stanislav Mekhanoshin61da0672017-01-26 16:49:21 +0000595 TM->adjustPassManager(PMBuilder);
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000596
Dehao Chen7810d4f2017-02-21 20:36:21 +0000597 if (CodeGenOpts.DebugInfoForProfiling ||
598 !CodeGenOpts.SampleProfileFile.empty())
599 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
600 addAddDiscriminatorsPass);
Diego Novillob56be642014-03-03 20:06:18 +0000601
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000602 // In ObjC ARC mode, add the main ARC optimization passes.
603 if (LangOpts.ObjCAutoRefCount) {
604 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
605 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000606 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
607 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000608 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
609 addObjCARCOptPass);
610 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000611
Richard Smith10ab78e2019-02-23 21:06:26 +0000612 if (LangOpts.Coroutines)
Brian Gesiak91a4b5a2018-04-01 23:55:21 +0000613 addCoroutinePassesToExtensionPoints(PMBuilder);
614
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000615 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000616 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
617 addBoundsCheckingPass);
618 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
619 addBoundsCheckingPass);
620 }
621
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000622 if (CodeGenOpts.SanitizeCoverageType ||
623 CodeGenOpts.SanitizeCoverageIndirectCalls ||
624 CodeGenOpts.SanitizeCoverageTraceCmp) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000625 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
626 addSanitizerCoveragePass);
627 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
628 addSanitizerCoveragePass);
629 }
630
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000631 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000632 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000633 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000634 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000635 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000636 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000637
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000638 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
639 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
640 addKernelAddressSanitizerPasses);
641 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
642 addKernelAddressSanitizerPasses);
643 }
644
Evgeniy Stepanov12817e52017-12-09 01:32:07 +0000645 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
646 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
647 addHWAddressSanitizerPasses);
648 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
649 addHWAddressSanitizerPasses);
650 }
651
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000652 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
653 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
654 addKernelHWAddressSanitizerPasses);
655 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
656 addKernelHWAddressSanitizerPasses);
657 }
658
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000659 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000660 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
661 addMemorySanitizerPass);
662 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
663 addMemorySanitizerPass);
664 }
665
Alexander Potapenkod49c32c2018-09-07 09:21:09 +0000666 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
667 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
668 addKernelMemorySanitizerPass);
669 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
670 addKernelMemorySanitizerPass);
671 }
672
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000673 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000674 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000675 addThreadSanitizerPass);
676 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
677 addThreadSanitizerPass);
678 }
679
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000680 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
Peter Collingbournec3772752013-08-07 22:47:34 +0000681 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
682 addDataFlowSanitizerPass);
683 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
684 addDataFlowSanitizerPass);
685 }
686
Chris Lattner5c123672011-05-21 20:40:11 +0000687 // Set up the per-function pass manager.
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000688 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
Chris Lattner5c123672011-05-21 20:40:11 +0000689 if (CodeGenOpts.VerifyModule)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000690 FPM.add(createVerifierPass());
Andrew Trickb2a84722011-04-05 18:49:32 +0000691
Chris Lattner5c123672011-05-21 20:40:11 +0000692 // Set up the per-module pass manager.
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000693 if (!CodeGenOpts.RewriteMapFiles.empty())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000694 addSymbolRewriterPass(CodeGenOpts, &MPM);
Chris Lattnerd98cec52011-02-18 22:20:38 +0000695
David Blaikie7a4f7f52018-01-09 22:03:47 +0000696 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
697 MPM.add(createGCOVProfilerPass(*Options));
Benjamin Kramer8c305922016-02-02 11:06:51 +0000698 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000699 MPM.add(createStripSymbolsPass(true));
Nick Lewycky207bce32011-04-21 23:44:07 +0000700 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000701
Rong Xu4059e142019-04-25 17:52:43 +0000702 if (Optional<InstrProfOptions> Options =
703 getInstrProfOptions(CodeGenOpts, LangOpts))
704 MPM.add(createInstrProfilingLegacyPass(*Options, false));
Vedant Kumaree6c2332018-08-16 22:24:47 +0000705
Rong Xua4a09b22019-03-04 20:21:31 +0000706 bool hasIRInstr = false;
Rong Xu522b5cb2016-02-29 18:54:59 +0000707 if (CodeGenOpts.hasProfileIRInstr()) {
Xinliang David Lib65f8ae2016-07-23 04:28:59 +0000708 PMBuilder.EnablePGOInstrGen = true;
Rong Xua4a09b22019-03-04 20:21:31 +0000709 hasIRInstr = true;
710 }
711 if (CodeGenOpts.hasProfileCSIRInstr()) {
712 assert(!CodeGenOpts.hasProfileCSIRUse() &&
713 "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
714 "same time");
715 assert(!hasIRInstr &&
716 "Cannot have both ProfileGen pass and CSProfileGen pass at the "
717 "same time");
718 PMBuilder.EnablePGOCSInstrGen = true;
719 hasIRInstr = true;
720 }
721 if (hasIRInstr) {
Rong Xu522b5cb2016-02-29 18:54:59 +0000722 if (!CodeGenOpts.InstrProfileOutput.empty())
723 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
724 else
Davide Italiano945de432017-02-13 16:07:05 +0000725 PMBuilder.PGOInstrGen = DefaultProfileGenName;
Rong Xu522b5cb2016-02-29 18:54:59 +0000726 }
Rong Xua4a09b22019-03-04 20:21:31 +0000727 if (CodeGenOpts.hasProfileIRUse()) {
Rong Xu9c6f1532016-03-02 20:59:36 +0000728 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
Rong Xua4a09b22019-03-04 20:21:31 +0000729 PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
730 }
Justin Bogner970ac602014-12-08 19:04:51 +0000731
Dehao Chen5717aff2016-12-14 21:41:04 +0000732 if (!CodeGenOpts.SampleProfileFile.empty())
733 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
Diego Novillod3ef1082015-08-25 15:25:13 +0000734
Peter Collingbourne03f89072016-07-15 00:55:40 +0000735 PMBuilder.populateFunctionPassManager(FPM);
736 PMBuilder.populateModulePassManager(MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000737}
738
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000739static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
Yaxun Liub5e80c32016-04-12 20:22:32 +0000740 SmallVector<const char *, 16> BackendArgs;
741 BackendArgs.push_back("clang"); // Fake program name.
742 if (!CodeGenOpts.DebugPass.empty()) {
743 BackendArgs.push_back("-debug-pass");
744 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
745 }
746 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
747 BackendArgs.push_back("-limit-float-precision");
748 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
749 }
Yaxun Liub5e80c32016-04-12 20:22:32 +0000750 BackendArgs.push_back(nullptr);
751 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
752 BackendArgs.data());
753}
754
Peter Collingbourne03f89072016-07-15 00:55:40 +0000755void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000756 // Create the TargetMachine for generating code.
757 std::string Error;
758 std::string Triple = TheModule->getTargetTriple();
759 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
760 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000761 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000762 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000763 return;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000764 }
765
Rafael Espindolaaa0226e2017-08-03 02:16:28 +0000766 Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
Eric Christopher583a1f72015-09-26 01:25:08 +0000767 std::string FeaturesStr =
768 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
Rafael Espindolae1d70532018-01-18 00:20:03 +0000769 llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000770 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
Evan Chengdd286bc2011-11-16 08:38:55 +0000771
Nick Lewycky432add52011-12-02 22:17:00 +0000772 llvm::TargetOptions Options;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000773 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000774 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
775 Options, RM, CM, OptLevel));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000776}
777
Peter Collingbourne03f89072016-07-15 00:55:40 +0000778bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
779 BackendAction Action,
Peter Collingbourne91d02842018-05-22 18:52:37 +0000780 raw_pwrite_stream &OS,
781 raw_pwrite_stream *DwoOS) {
Chad Rosierb1cfc682012-02-29 20:14:59 +0000782 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000783 llvm::Triple TargetTriple(TheModule->getTargetTriple());
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000784 std::unique_ptr<TargetLibraryInfoImpl> TLII(
785 createTLII(TargetTriple, CodeGenOpts));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000786 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
Chad Rosierb1cfc682012-02-29 20:14:59 +0000787
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000788 // Normal mode, emit a .s or .o file by running the code generator. Note,
789 // this also adds codegenerator level optimization passes.
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000790 TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000791
792 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
793 // "codegen" passes so that it isn't run multiple times when there is
794 // inlining happening.
Steven Wu1d56be82015-05-02 00:56:15 +0000795 if (CodeGenOpts.OptimizationLevel > 0)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000796 CodeGenPasses.add(createObjCARCContractPass());
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000797
Peter Collingbourne91d02842018-05-22 18:52:37 +0000798 if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000799 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
800 Diags.Report(diag::err_fe_unable_to_interface_with_target);
801 return false;
802 }
803
804 return true;
805}
806
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000807void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000808 std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +0000809 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000810
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000811 setCommandLineOpts(CodeGenOpts);
Yaxun Liub5e80c32016-04-12 20:22:32 +0000812
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000813 bool UsesCodeGen = (Action != Backend_EmitNothing &&
814 Action != Backend_EmitBC &&
815 Action != Backend_EmitLL);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000816 CreateTargetMachine(UsesCodeGen);
Alp Tokerf4e22382013-12-20 20:26:53 +0000817
Rafael Espindolab633d202015-06-23 13:59:36 +0000818 if (UsesCodeGen && !TM)
819 return;
820 if (TM)
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000821 TheModule->setDataLayout(TM->createDataLayout());
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000822
Peter Collingbourne03f89072016-07-15 00:55:40 +0000823 legacy::PassManager PerModulePasses;
824 PerModulePasses.add(
825 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
826
827 legacy::FunctionPassManager PerFunctionPasses(TheModule);
828 PerFunctionPasses.add(
829 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
830
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000831 CreatePasses(PerModulePasses, PerFunctionPasses);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000832
833 legacy::PassManager CodeGenPasses;
834 CodeGenPasses.add(
835 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000836
Peter Collingbourne91d02842018-05-22 18:52:37 +0000837 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000838
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000839 switch (Action) {
840 case Backend_EmitNothing:
841 break;
842
843 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +0000844 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000845 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +0000846 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
847 if (!ThinLinkOS)
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000848 return;
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000849 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000850 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
851 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000852 PerModulePasses.add(createWriteThinLTOBitcodePass(
853 *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000854 } else {
855 // Emit a module summary by default for Regular LTO except for ld64
856 // targets
857 bool EmitLTOSummary =
858 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +0000859 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000860 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
861 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000862 if (EmitLTOSummary) {
863 if (!TheModule->getModuleFlag("ThinLTO"))
864 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
865 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Teresa Johnson604f8022019-07-19 23:02:58 +0000866 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000867 }
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000868
Teresa Johnson84cecfc2019-01-11 18:32:07 +0000869 PerModulePasses.add(createBitcodeWriterPass(
870 *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +0000871 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000872 break;
873
874 case Backend_EmitLL:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000875 PerModulePasses.add(
Duncan P. N. Exon Smithbb9cadf2015-04-15 02:45:28 +0000876 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000877 break;
878
879 default:
Aaron Puchertb207bae2019-06-26 21:36:35 +0000880 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +0000881 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +0000882 if (!DwoOS)
883 return;
884 }
885 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
886 DwoOS ? &DwoOS->os() : nullptr))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000887 return;
888 }
889
Andrew Trick15e36e82011-04-05 18:56:55 +0000890 // Before executing passes, print the final values of the LLVM options.
891 cl::PrintOptionValues();
892
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000893 // Run passes. For now we do all passes at once, but eventually we
894 // would like to have the option of streaming code generation.
895
Peter Collingbourne03f89072016-07-15 00:55:40 +0000896 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000897 PrettyStackTraceString CrashInfo("Per-function optimization");
Anton Afanasyevf7a428e2019-09-28 07:14:12 +0000898 llvm::TimeTraceScope TimeScope("PerFunctionPasses", StringRef(""));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000899
Peter Collingbourne03f89072016-07-15 00:55:40 +0000900 PerFunctionPasses.doInitialization();
Yaron Keren10d6d162015-06-05 09:40:53 +0000901 for (Function &F : *TheModule)
902 if (!F.isDeclaration())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000903 PerFunctionPasses.run(F);
904 PerFunctionPasses.doFinalization();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000905 }
906
Peter Collingbourne03f89072016-07-15 00:55:40 +0000907 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000908 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Anton Afanasyevf7a428e2019-09-28 07:14:12 +0000909 llvm::TimeTraceScope TimeScope("PerModulePasses", StringRef(""));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000910 PerModulePasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000911 }
912
Peter Collingbourne03f89072016-07-15 00:55:40 +0000913 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000914 PrettyStackTraceString CrashInfo("Code generation");
Anton Afanasyevf7a428e2019-09-28 07:14:12 +0000915 llvm::TimeTraceScope TimeScope("CodeGenPasses", StringRef(""));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000916 CodeGenPasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000917 }
Peter Collingbourne91d02842018-05-22 18:52:37 +0000918
919 if (ThinLinkOS)
920 ThinLinkOS->keep();
921 if (DwoOS)
922 DwoOS->keep();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000923}
924
Chandler Carruth50f9e892016-12-23 20:44:01 +0000925static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
926 switch (Opts.OptimizationLevel) {
927 default:
928 llvm_unreachable("Invalid optimization level!");
929
930 case 1:
931 return PassBuilder::O1;
932
933 case 2:
934 switch (Opts.OptimizeSize) {
935 default:
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000936 llvm_unreachable("Invalid optimization level for size!");
Chandler Carruth50f9e892016-12-23 20:44:01 +0000937
938 case 0:
939 return PassBuilder::O2;
940
941 case 1:
942 return PassBuilder::Os;
943
944 case 2:
945 return PassBuilder::Oz;
946 }
947
948 case 3:
949 return PassBuilder::O3;
950 }
951}
952
Benjamin Kramerba2ea932019-03-28 17:18:42 +0000953static void addSanitizersAtO0(ModulePassManager &MPM,
954 const Triple &TargetTriple,
955 const LangOptions &LangOpts,
956 const CodeGenOptions &CodeGenOpts) {
Petr Hosek366cda02019-05-09 06:09:35 +0000957 auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
Leonard Chan436fb2b2019-02-13 22:22:48 +0000958 MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
Petr Hosek366cda02019-05-09 06:09:35 +0000959 bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
960 MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
961 CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
Leonard Chan436fb2b2019-02-13 22:22:48 +0000962 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Petr Hosek366cda02019-05-09 06:09:35 +0000963 MPM.addPass(
964 ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
965 CodeGenOpts.SanitizeAddressUseOdrIndicator));
966 };
967
968 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
969 ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
970 }
971
972 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
973 ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
Leonard Chan436fb2b2019-02-13 22:22:48 +0000974 }
Leonard Chan1a240ed2019-02-20 03:50:11 +0000975
976 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
977 MPM.addPass(createModuleToFunctionPassAdaptor(MemorySanitizerPass({})));
978 }
979
Petr Hosek366cda02019-05-09 06:09:35 +0000980 if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
981 MPM.addPass(createModuleToFunctionPassAdaptor(
982 MemorySanitizerPass({0, false, /*Kernel=*/true})));
983 }
984
Leonard Chan1a240ed2019-02-20 03:50:11 +0000985 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
986 MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
987 }
Leonard Chan436fb2b2019-02-13 22:22:48 +0000988}
989
Chandler Carruth50f9e892016-12-23 20:44:01 +0000990/// A clean version of `EmitAssembly` that uses the new pass manager.
991///
992/// Not all features are currently supported in this system, but where
993/// necessary it falls back to the legacy pass manager to at least provide
994/// basic functionality.
995///
996/// This API is planned to have its functionality finished and then to replace
997/// `EmitAssembly` at some point in the future when the default switches.
998void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
999 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
Andrew V. Tischenko8ab2c9c2018-04-23 09:22:30 +00001000 TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001001 setCommandLineOpts(CodeGenOpts);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001002
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001003 bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1004 Action != Backend_EmitBC &&
1005 Action != Backend_EmitLL);
1006 CreateTargetMachine(RequiresCodeGen);
1007
1008 if (RequiresCodeGen && !TM)
Chandler Carruth50f9e892016-12-23 20:44:01 +00001009 return;
Petr Hosek5f2e10e2019-05-06 23:24:17 +00001010 if (TM)
1011 TheModule->setDataLayout(TM->createDataLayout());
Chandler Carruth50f9e892016-12-23 20:44:01 +00001012
Dehao Chenc76a27e2017-07-27 15:29:53 +00001013 Optional<PGOOptions> PGOOpt;
Davide Italiano945de432017-02-13 16:07:05 +00001014
Dehao Chenc76a27e2017-07-27 15:29:53 +00001015 if (CodeGenOpts.hasProfileIRInstr())
1016 // -fprofile-generate.
1017 PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1018 ? DefaultProfileGenName
1019 : CodeGenOpts.InstrProfileOutput,
Rong Xua4a09b22019-03-04 20:21:31 +00001020 "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
Richard Smith8654ae52018-10-10 23:13:35 +00001021 CodeGenOpts.DebugInfoForProfiling);
Rong Xua4a09b22019-03-04 20:21:31 +00001022 else if (CodeGenOpts.hasProfileIRUse()) {
Dehao Chenc76a27e2017-07-27 15:29:53 +00001023 // -fprofile-use.
Rong Xua4a09b22019-03-04 20:21:31 +00001024 auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1025 : PGOOptions::NoCSAction;
1026 PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1027 CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1028 CSAction, CodeGenOpts.DebugInfoForProfiling);
1029 } else if (!CodeGenOpts.SampleProfileFile.empty())
Dehao Chenc76a27e2017-07-27 15:29:53 +00001030 // -fprofile-sample-use
Rong Xua4a09b22019-03-04 20:21:31 +00001031 PGOOpt =
1032 PGOOptions(CodeGenOpts.SampleProfileFile, "",
1033 CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1034 PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
Dehao Chenc76a27e2017-07-27 15:29:53 +00001035 else if (CodeGenOpts.DebugInfoForProfiling)
1036 // -fdebug-info-for-profiling
Rong Xua4a09b22019-03-04 20:21:31 +00001037 PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1038 PGOOptions::NoCSAction, true);
1039
1040 // Check to see if we want to generate a CS profile.
1041 if (CodeGenOpts.hasProfileCSIRInstr()) {
1042 assert(!CodeGenOpts.hasProfileCSIRUse() &&
1043 "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1044 "the same time");
1045 if (PGOOpt.hasValue()) {
1046 assert(PGOOpt->Action != PGOOptions::IRInstr &&
1047 PGOOpt->Action != PGOOptions::SampleUse &&
1048 "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1049 " pass");
1050 PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1051 ? DefaultProfileGenName
1052 : CodeGenOpts.InstrProfileOutput;
1053 PGOOpt->CSAction = PGOOptions::CSIRInstr;
1054 } else
1055 PGOOpt = PGOOptions("",
1056 CodeGenOpts.InstrProfileOutput.empty()
1057 ? DefaultProfileGenName
1058 : CodeGenOpts.InstrProfileOutput,
1059 "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1060 CodeGenOpts.DebugInfoForProfiling);
1061 }
Davide Italiano945de432017-02-13 16:07:05 +00001062
Alina Sbirlea267ac922019-05-23 18:51:02 +00001063 PipelineTuningOptions PTO;
Alina Sbirlea21efe2a2019-05-24 17:40:52 +00001064 PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
Alina Sbirlea267ac922019-05-23 18:51:02 +00001065 // For historical reasons, loop interleaving is set to mirror setting for loop
1066 // unrolling.
1067 PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1068 PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1069 PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1070
Taewook Ohd4c50f72019-08-14 07:11:09 +00001071 PassInstrumentationCallbacks PIC;
1072 StandardInstrumentations SI;
1073 SI.registerCallbacks(PIC);
1074 PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001075
Philip Pfaffee3f105c2019-02-02 23:19:32 +00001076 // Attempt to load pass plugins and register their callbacks with PB.
1077 for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1078 auto PassPlugin = PassPlugin::Load(PluginFN);
1079 if (PassPlugin) {
1080 PassPlugin->registerPassBuilderCallbacks(PB);
1081 } else {
1082 Diags.Report(diag::err_fe_unable_to_load_plugin)
1083 << PluginFN << toString(PassPlugin.takeError());
1084 }
1085 }
1086
Craig Topper926b95c2017-11-14 08:48:28 +00001087 LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1088 FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1089 CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1090 ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001091
1092 // Register the AA manager first so that our version is the one used.
1093 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1094
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001095 // Register the target library analysis directly and give it a customized
1096 // preset TLI.
1097 Triple TargetTriple(TheModule->getTargetTriple());
1098 std::unique_ptr<TargetLibraryInfoImpl> TLII(
1099 createTLII(TargetTriple, CodeGenOpts));
1100 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
Chandler Carruth9fdd5fa2017-07-25 10:46:07 +00001101
Chandler Carruth50f9e892016-12-23 20:44:01 +00001102 // Register all the basic analyses with the managers.
1103 PB.registerModuleAnalyses(MAM);
1104 PB.registerCGSCCAnalyses(CGAM);
1105 PB.registerFunctionAnalyses(FAM);
1106 PB.registerLoopAnalyses(LAM);
1107 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1108
Tim Shenb13eebe2017-06-29 23:10:13 +00001109 ModulePassManager MPM(CodeGenOpts.DebugPassManager);
Chandler Carruth50f9e892016-12-23 20:44:01 +00001110
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001111 if (!CodeGenOpts.DisableLLVMPasses) {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001112 bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
Tim Shen66470692017-06-29 23:08:38 +00001113 bool IsLTO = CodeGenOpts.PrepareForLTO;
1114
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001115 if (CodeGenOpts.OptimizationLevel == 0) {
David Blaikieac904d02018-01-23 01:25:24 +00001116 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1117 MPM.addPass(GCOVProfilerPass(*Options));
Rong Xu4059e142019-04-25 17:52:43 +00001118 if (Optional<InstrProfOptions> Options =
1119 getInstrProfOptions(CodeGenOpts, LangOpts))
1120 MPM.addPass(InstrProfiling(*Options, false));
David Blaikieac904d02018-01-23 01:25:24 +00001121
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001122 // Build a minimal pipeline based on the semantics required by Clang,
Leonard Chan587497b2019-06-13 16:45:29 +00001123 // which is just that always inlining occurs. Further, disable generating
1124 // lifetime intrinsics to avoid enabling further optimizations during
1125 // code generation.
1126 MPM.addPass(AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/false));
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001127
Rong Xuca161fa2019-08-01 22:36:34 +00001128 // At -O0, we can still do PGO. Add all the requested passes for
1129 // instrumentation PGO, if requested.
1130 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1131 PGOOpt->Action == PGOOptions::IRUse))
1132 PB.addPGOInstrPassesForO0(
1133 MPM, CodeGenOpts.DebugPassManager,
1134 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1135 /* IsCS */ false, PGOOpt->ProfileFile,
1136 PGOOpt->ProfileRemappingFile);
1137
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001138 // At -O0 we directly run necessary sanitizer passes.
1139 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1140 MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1141
Teresa Johnson6ed79132019-01-04 19:05:01 +00001142 // Lastly, add semantically necessary passes for LTO.
1143 if (IsLTO || IsThinLTO) {
1144 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001145 MPM.addPass(NameAnonGlobalPass());
Teresa Johnson6ed79132019-01-04 19:05:01 +00001146 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001147 } else {
Tim Shen66470692017-06-29 23:08:38 +00001148 // Map our optimization levels into one of the distinct levels used to
1149 // configure the pipeline.
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001150 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1151
Leonard Chanb2065132019-06-20 19:35:25 +00001152 PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1153 MPM.addPass(createModuleToFunctionPassAdaptor(
1154 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1155 });
1156
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001157 // Register callbacks to schedule sanitizer passes at the appropriate part of
1158 // the pipeline.
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001159 // FIXME: either handle asan/the remaining sanitizers or error out
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001160 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1161 PB.registerScalarOptimizerLateEPCallback(
1162 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1163 FPM.addPass(BoundsCheckingPass());
1164 });
Nico Weberd3833292019-10-11 02:44:20 +00001165 if (LangOpts.Sanitize.has(SanitizerKind::Memory))
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001166 PB.registerOptimizerLastEPCallback(
1167 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
Philip Pfaffe0ee6a932019-02-04 21:02:49 +00001168 FPM.addPass(MemorySanitizerPass({}));
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001169 });
Nico Weberd3833292019-10-11 02:44:20 +00001170 if (LangOpts.Sanitize.has(SanitizerKind::Thread))
Philip Pfaffe88a13b92019-01-17 10:10:47 +00001171 PB.registerOptimizerLastEPCallback(
1172 [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1173 FPM.addPass(ThreadSanitizerPass());
1174 });
Leonard Chan436fb2b2019-02-13 22:22:48 +00001175 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1176 PB.registerPipelineStartEPCallback([&](ModulePassManager &MPM) {
1177 MPM.addPass(
1178 RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1179 });
1180 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
Leonard Chan619b6d52019-02-14 01:07:47 +00001181 bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
Leonard Chan436fb2b2019-02-13 22:22:48 +00001182 PB.registerOptimizerLastEPCallback(
Leonard Chan619b6d52019-02-14 01:07:47 +00001183 [Recover, UseAfterScope](FunctionPassManager &FPM,
1184 PassBuilder::OptimizationLevel Level) {
Leonard Chan436fb2b2019-02-13 22:22:48 +00001185 FPM.addPass(AddressSanitizerPass(
Leonard Chan619b6d52019-02-14 01:07:47 +00001186 /*CompileKernel=*/false, Recover, UseAfterScope));
Leonard Chan436fb2b2019-02-13 22:22:48 +00001187 });
1188 bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
Leonard Chan619b6d52019-02-14 01:07:47 +00001189 bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1190 PB.registerPipelineStartEPCallback(
1191 [Recover, ModuleUseAfterScope,
1192 UseOdrIndicator](ModulePassManager &MPM) {
1193 MPM.addPass(ModuleAddressSanitizerPass(
1194 /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1195 UseOdrIndicator));
1196 });
Leonard Chan436fb2b2019-02-13 22:22:48 +00001197 }
David Blaikieac904d02018-01-23 01:25:24 +00001198 if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1199 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1200 MPM.addPass(GCOVProfilerPass(*Options));
1201 });
Rong Xu4059e142019-04-25 17:52:43 +00001202 if (Optional<InstrProfOptions> Options =
1203 getInstrProfOptions(CodeGenOpts, LangOpts))
1204 PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1205 MPM.addPass(InstrProfiling(*Options, false));
1206 });
Chandler Carrutha8bd4e32017-11-14 01:59:18 +00001207
Tim Shen66470692017-06-29 23:08:38 +00001208 if (IsThinLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001209 MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1210 Level, CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001211 MPM.addPass(CanonicalizeAliasesPass());
Tim Shen66470692017-06-29 23:08:38 +00001212 MPM.addPass(NameAnonGlobalPass());
1213 } else if (IsLTO) {
Tim Shenb13eebe2017-06-29 23:10:13 +00001214 MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1215 CodeGenOpts.DebugPassManager);
Teresa Johnson6ed79132019-01-04 19:05:01 +00001216 MPM.addPass(CanonicalizeAliasesPass());
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001217 MPM.addPass(NameAnonGlobalPass());
Tim Shen66470692017-06-29 23:08:38 +00001218 } else {
Tim Shenb13eebe2017-06-29 23:10:13 +00001219 MPM = PB.buildPerModuleDefaultPipeline(Level,
1220 CodeGenOpts.DebugPassManager);
Tim Shen66470692017-06-29 23:08:38 +00001221 }
Chandler Carruth6d1b83e2016-12-27 00:13:09 +00001222 }
Leonard Chan436fb2b2019-02-13 22:22:48 +00001223
Leonard Chan486b1732019-09-08 07:30:17 +00001224 if (CodeGenOpts.SanitizeCoverageType ||
1225 CodeGenOpts.SanitizeCoverageIndirectCalls ||
1226 CodeGenOpts.SanitizeCoverageTraceCmp) {
1227 auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1228 MPM.addPass(ModuleSanitizerCoveragePass(SancovOpts));
1229 }
1230
Peter Collingbourne3b82b922019-07-17 21:45:19 +00001231 if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1232 bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1233 MPM.addPass(HWAddressSanitizerPass(
1234 /*CompileKernel=*/false, Recover));
1235 }
1236 if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1237 MPM.addPass(HWAddressSanitizerPass(
1238 /*CompileKernel=*/true, /*Recover=*/true));
1239 }
1240
Leonard Chan007f6742019-07-25 20:53:15 +00001241 if (CodeGenOpts.OptimizationLevel == 0) {
Leonard Chan436fb2b2019-02-13 22:22:48 +00001242 addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
Leonard Chan007f6742019-07-25 20:53:15 +00001243 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001244 }
1245
1246 // FIXME: We still use the legacy pass manager to do code generation. We
1247 // create that pass manager here and use it as needed below.
1248 legacy::PassManager CodeGenPasses;
1249 bool NeedCodeGen = false;
Peter Collingbourne91d02842018-05-22 18:52:37 +00001250 std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
Chandler Carruth50f9e892016-12-23 20:44:01 +00001251
1252 // Append any output we need to the pass manager.
1253 switch (Action) {
1254 case Backend_EmitNothing:
1255 break;
1256
1257 case Backend_EmitBC:
Eli Friedman53591232018-08-24 19:31:52 +00001258 if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
Tim Shen50fedec2017-06-01 23:27:51 +00001259 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
Peter Collingbourne91d02842018-05-22 18:52:37 +00001260 ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1261 if (!ThinLinkOS)
Tim Shen50fedec2017-06-01 23:27:51 +00001262 return;
Tim Shen50fedec2017-06-01 23:27:51 +00001263 }
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001264 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1265 CodeGenOpts.EnableSplitLTOUnit);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001266 MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1267 : nullptr));
Tim Shen50fedec2017-06-01 23:27:51 +00001268 } else {
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001269 // Emit a module summary by default for Regular LTO except for ld64
1270 // targets
1271 bool EmitLTOSummary =
1272 (CodeGenOpts.PrepareForLTO &&
Eli Friedman53591232018-08-24 19:31:52 +00001273 !CodeGenOpts.DisableLLVMPasses &&
Tobias Edler von Koch7609cb82018-06-22 20:23:21 +00001274 llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1275 llvm::Triple::Apple);
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001276 if (EmitLTOSummary) {
1277 if (!TheModule->getModuleFlag("ThinLTO"))
1278 TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1279 TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
Leonard Chan19ec31d2019-08-21 17:24:14 +00001280 uint32_t(1));
Teresa Johnson84cecfc2019-01-11 18:32:07 +00001281 }
1282 MPM.addPass(
1283 BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
Tim Shen50fedec2017-06-01 23:27:51 +00001284 }
Chandler Carruth50f9e892016-12-23 20:44:01 +00001285 break;
1286
1287 case Backend_EmitLL:
1288 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1289 break;
1290
1291 case Backend_EmitAssembly:
1292 case Backend_EmitMCNull:
1293 case Backend_EmitObj:
1294 NeedCodeGen = true;
1295 CodeGenPasses.add(
1296 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Aaron Puchertb207bae2019-06-26 21:36:35 +00001297 if (!CodeGenOpts.SplitDwarfOutput.empty()) {
Aaron Puchert922759a2019-06-15 14:07:43 +00001298 DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
Peter Collingbourne91d02842018-05-22 18:52:37 +00001299 if (!DwoOS)
1300 return;
1301 }
1302 if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1303 DwoOS ? &DwoOS->os() : nullptr))
Chandler Carruth50f9e892016-12-23 20:44:01 +00001304 // FIXME: Should we handle this error differently?
1305 return;
1306 break;
1307 }
1308
1309 // Before executing passes, print the final values of the LLVM options.
1310 cl::PrintOptionValues();
1311
1312 // Now that we have all of the passes ready, run them.
1313 {
1314 PrettyStackTraceString CrashInfo("Optimizer");
1315 MPM.run(*TheModule, MAM);
1316 }
1317
1318 // Now if needed, run the legacy PM for codegen.
1319 if (NeedCodeGen) {
1320 PrettyStackTraceString CrashInfo("Code generation");
1321 CodeGenPasses.run(*TheModule);
1322 }
Peter Collingbourne91d02842018-05-22 18:52:37 +00001323
1324 if (ThinLinkOS)
1325 ThinLinkOS->keep();
1326 if (DwoOS)
1327 DwoOS->keep();
Chandler Carruth50f9e892016-12-23 20:44:01 +00001328}
1329
Peter Collingbourne47d23642017-01-24 19:54:37 +00001330Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1331 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1332 if (!BMsOrErr)
1333 return BMsOrErr.takeError();
1334
Peter Collingbournedbd2fed2017-06-15 17:26:13 +00001335 // The bitcode file may contain multiple modules, we want the one that is
1336 // marked as being the ThinLTO module.
Vitaly Bukac35ff822018-02-16 23:34:16 +00001337 if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1338 return *Bm;
Peter Collingbourne47d23642017-01-24 19:54:37 +00001339
1340 return make_error<StringError>("Could not find module summary",
1341 inconvertibleErrorCode());
1342}
1343
Vitaly Bukac35ff822018-02-16 23:34:16 +00001344BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1345 for (BitcodeModule &BM : BMs) {
1346 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1347 if (LTOInfo && LTOInfo->IsThinLTO)
1348 return &BM;
1349 }
1350 return nullptr;
1351}
1352
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001353static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001354 const HeaderSearchOptions &HeaderOpts,
1355 const CodeGenOptions &CGOpts,
1356 const clang::TargetOptions &TOpts,
1357 const LangOptions &LOpts,
Dehao Chena1bd2d62017-01-13 00:51:55 +00001358 std::unique_ptr<raw_pwrite_stream> OS,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001359 std::string SampleProfile,
Richard Smith8654ae52018-10-10 23:13:35 +00001360 std::string ProfileRemapping,
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001361 BackendAction Action) {
Dehao Chen5f83d0e2017-07-10 20:31:37 +00001362 StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001363 ModuleToDefinedGVSummaries;
1364 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1365
David Blaikie6e2ec5f2017-04-19 20:08:21 +00001366 setCommandLineOpts(CGOpts);
1367
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001368 // We can simply import the values mentioned in the combined index, since
1369 // we should only invoke this using the individual indexes written out
1370 // via a WriteIndexesThinBackend.
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001371 FunctionImporter::ImportMapTy ImportList;
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001372 for (auto &GlobalList : *CombinedIndex) {
Peter Collingbourne9667b912017-05-04 18:03:25 +00001373 // Ignore entries for undefined references.
1374 if (GlobalList.second.SummaryList.empty())
1375 continue;
1376
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001377 auto GUID = GlobalList.first;
Teresa Johnson5ed8b002018-11-29 17:02:59 +00001378 for (auto &Summary : GlobalList.second.SummaryList) {
1379 // Skip the summaries for the importing module. These are included to
1380 // e.g. record required linkage changes.
1381 if (Summary->modulePath() == M->getModuleIdentifier())
1382 continue;
1383 // Add an entry to provoke importing by thinBackend.
1384 ImportList[Summary->modulePath()].insert(GUID);
1385 }
Teresa Johnsonf9b17d42016-12-28 18:00:08 +00001386 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001387
1388 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001389 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001390
1391 for (auto &I : ImportList) {
1392 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1393 llvm::MemoryBuffer::getFile(I.first());
1394 if (!MBOrErr) {
1395 errs() << "Error loading imported file '" << I.first()
1396 << "': " << MBOrErr.getError().message() << "\n";
1397 return;
1398 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001399
Peter Collingbourne47d23642017-01-24 19:54:37 +00001400 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1401 if (!BMOrErr) {
1402 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001403 errs() << "Error loading imported file '" << I.first()
1404 << "': " << EIB.message() << '\n';
1405 });
1406 return;
1407 }
Peter Collingbourne47d23642017-01-24 19:54:37 +00001408 ModuleMap.insert({I.first(), *BMOrErr});
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001409
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001410 OwnedImports.push_back(std::move(*MBOrErr));
1411 }
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001412 auto AddStream = [&](size_t Task) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001413 return std::make_unique<lto::NativeObjectStream>(std::move(OS));
Mehdi Amini406aa222016-08-17 06:23:08 +00001414 };
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001415 lto::Config Conf;
Teresa Johnson9e4321c2018-04-17 16:39:25 +00001416 if (CGOpts.SaveTempsFilePrefix != "") {
1417 if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1418 /* UseInputModulePath */ false)) {
1419 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1420 errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1421 << '\n';
1422 });
1423 }
1424 }
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001425 Conf.CPU = TOpts.CPU;
1426 Conf.CodeModel = getCodeModel(CGOpts);
1427 Conf.MAttrs = TOpts.Features;
Rafael Espindolae1d70532018-01-18 00:20:03 +00001428 Conf.RelocModel = CGOpts.RelocationModel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001429 Conf.CGOptLevel = getCGOptLevel(CGOpts);
Teresa Johnson867bc392019-04-23 18:56:19 +00001430 Conf.OptLevel = CGOpts.OptimizationLevel;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001431 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001432 Conf.SampleProfile = std::move(SampleProfile);
Rong Xua4a09b22019-03-04 20:21:31 +00001433
1434 // Context sensitive profile.
1435 if (CGOpts.hasProfileCSIRInstr()) {
1436 Conf.RunCSIRInstr = true;
1437 Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1438 } else if (CGOpts.hasProfileCSIRUse()) {
1439 Conf.RunCSIRInstr = false;
1440 Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1441 }
1442
Richard Smith8654ae52018-10-10 23:13:35 +00001443 Conf.ProfileRemapping = std::move(ProfileRemapping);
Tim Shen50fedec2017-06-01 23:27:51 +00001444 Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
Teresa Johnson4cd016ab2017-11-13 15:38:33 +00001445 Conf.DebugPassManager = CGOpts.DebugPassManager;
Teresa Johnson66744f82018-05-05 14:37:29 +00001446 Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1447 Conf.RemarksFilename = CGOpts.OptRecordFile;
Francis Visoiu Mistrihdd422362019-03-12 21:22:27 +00001448 Conf.RemarksPasses = CGOpts.OptRecordPasses;
Francis Visoiu Mistrih34667512019-06-17 16:06:00 +00001449 Conf.RemarksFormat = CGOpts.OptRecordFormat;
Aaron Pucherte1dc4952019-06-15 15:38:51 +00001450 Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1451 Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001452 switch (Action) {
1453 case Backend_EmitNothing:
1454 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1455 return false;
1456 };
1457 break;
1458 case Backend_EmitLL:
1459 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1460 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1461 return false;
1462 };
1463 break;
1464 case Backend_EmitBC:
1465 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
Rafael Espindola76c8f822018-02-14 19:11:37 +00001466 WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001467 return false;
1468 };
1469 break;
1470 default:
1471 Conf.CGFileType = getCodeGenFileType(Action);
1472 break;
1473 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001474 if (Error E = thinBackend(
Teresa Johnson66744f82018-05-05 14:37:29 +00001475 Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001476 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1477 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1478 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1479 });
1480 }
1481}
1482
David Blaikie9c902b52011-09-25 23:23:43 +00001483void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001484 const HeaderSearchOptions &HeaderOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00001485 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +00001486 const clang::TargetOptions &TOpts,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001487 const LangOptions &LOpts,
1488 const llvm::DataLayout &TDesc, Module *M,
1489 BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +00001490 std::unique_ptr<raw_pwrite_stream> OS) {
Anton Afanasyevd880de22019-03-30 08:42:48 +00001491
1492 llvm::TimeTraceScope TimeScope("Backend", StringRef(""));
1493
Vitaly Buka769134d2018-02-16 23:38:22 +00001494 std::unique_ptr<llvm::Module> EmptyModule;
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001495 if (!CGOpts.ThinLTOIndexFile.empty()) {
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001496 // If we are performing a ThinLTO importing compile, load the function index
1497 // into memory and pass it into runThinLTOBackend, which will run the
1498 // function importer and invoke LTO passes.
1499 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
Teresa Johnson517729f2017-05-12 19:32:17 +00001500 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1501 /*IgnoreEmptyThinLTOIndexFile*/true);
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001502 if (!IndexOrErr) {
1503 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1504 "Error loading index file '" +
1505 CGOpts.ThinLTOIndexFile + "': ");
1506 return;
1507 }
1508 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1509 // A null CombinedIndex means we should skip ThinLTO compilation
1510 // (LLVM will optionally ignore empty index files, returning null instead
1511 // of an error).
Vitaly Buka769134d2018-02-16 23:38:22 +00001512 if (CombinedIndex) {
1513 if (!CombinedIndex->skipModuleByDistributedBackend()) {
1514 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1515 LOpts, std::move(OS), CGOpts.SampleProfileFile,
Richard Smith8654ae52018-10-10 23:13:35 +00001516 CGOpts.ProfileRemappingFile, Action);
Vitaly Buka769134d2018-02-16 23:38:22 +00001517 return;
1518 }
1519 // Distributed indexing detected that nothing from the module is needed
1520 // for the final linking. So we can skip the compilation. We sill need to
1521 // output an empty object file to make sure that a linker does not fail
1522 // trying to read it. Also for some features, like CFI, we must skip
1523 // the compilation as CombinedIndex does not contain all required
1524 // information.
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00001525 EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
Vitaly Buka769134d2018-02-16 23:38:22 +00001526 EmptyModule->setTargetTriple(M->getTargetTriple());
1527 M = EmptyModule.get();
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001528 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001529 }
1530
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001531 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001532
Chandler Carruth50f9e892016-12-23 20:44:01 +00001533 if (CGOpts.ExperimentalNewPassManager)
1534 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1535 else
1536 AsmHelper.EmitAssembly(Action, std::move(OS));
Alp Tokere83b9062014-01-02 15:08:04 +00001537
James Y Knightb214cbc2016-03-04 19:00:41 +00001538 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1539 // DataLayout.
1540 if (AsmHelper.TM) {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00001541 std::string DLDesc = M->getDataLayout().getStringRepresentation();
James Y Knightb214cbc2016-03-04 19:00:41 +00001542 if (DLDesc != TDesc.getStringRepresentation()) {
Alp Tokere83b9062014-01-02 15:08:04 +00001543 unsigned DiagID = Diags.getCustomDiagID(
1544 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1545 "expected target description '%1'");
James Y Knightb214cbc2016-03-04 19:00:41 +00001546 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
Alp Tokere83b9062014-01-02 15:08:04 +00001547 }
1548 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001549}
Steven Wu27fb5222016-05-11 16:26:03 +00001550
1551static const char* getSectionNameForBitcode(const Triple &T) {
1552 switch (T.getObjectFormat()) {
1553 case Triple::MachO:
1554 return "__LLVM,__bitcode";
1555 case Triple::COFF:
1556 case Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00001557 case Triple::Wasm:
Steven Wu27fb5222016-05-11 16:26:03 +00001558 case Triple::UnknownObjectFormat:
1559 return ".llvmbc";
Jason Liua03ae732019-03-12 22:01:10 +00001560 case Triple::XCOFF:
1561 llvm_unreachable("XCOFF is not yet implemented");
1562 break;
Steven Wu27fb5222016-05-11 16:26:03 +00001563 }
Simon Pilgrimbff9dae2016-05-11 21:55:37 +00001564 llvm_unreachable("Unimplemented ObjectFormatType");
Steven Wu27fb5222016-05-11 16:26:03 +00001565}
1566
1567static const char* getSectionNameForCommandline(const Triple &T) {
1568 switch (T.getObjectFormat()) {
1569 case Triple::MachO:
1570 return "__LLVM,__cmdline";
1571 case Triple::COFF:
1572 case Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00001573 case Triple::Wasm:
Steven Wu27fb5222016-05-11 16:26:03 +00001574 case Triple::UnknownObjectFormat:
1575 return ".llvmcmd";
Jason Liua03ae732019-03-12 22:01:10 +00001576 case Triple::XCOFF:
1577 llvm_unreachable("XCOFF is not yet implemented");
1578 break;
Steven Wu27fb5222016-05-11 16:26:03 +00001579 }
Simon Pilgrimbff9dae2016-05-11 21:55:37 +00001580 llvm_unreachable("Unimplemented ObjectFormatType");
Steven Wu27fb5222016-05-11 16:26:03 +00001581}
1582
1583// With -fembed-bitcode, save a copy of the llvm IR as data in the
1584// __LLVM,__bitcode section.
1585void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1586 llvm::MemoryBufferRef Buf) {
1587 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1588 return;
1589
Steven Wu2c059a52016-05-16 18:54:58 +00001590 // Save llvm.compiler.used and remote it.
1591 SmallVector<Constant*, 2> UsedArray;
Craig Topper7c89d042018-06-09 00:30:45 +00001592 SmallPtrSet<GlobalValue*, 4> UsedGlobals;
Steven Wu2c059a52016-05-16 18:54:58 +00001593 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1594 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1595 for (auto *GV : UsedGlobals) {
1596 if (GV->getName() != "llvm.embedded.module" &&
1597 GV->getName() != "llvm.cmdline")
1598 UsedArray.push_back(
1599 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1600 }
1601 if (Used)
1602 Used->eraseFromParent();
1603
Steven Wu27fb5222016-05-11 16:26:03 +00001604 // Embed the bitcode for the llvm module.
1605 std::string Data;
1606 ArrayRef<uint8_t> ModuleData;
1607 Triple T(M->getTargetTriple());
1608 // Create a constant that contains the bitcode.
1609 // In case of embedding a marker, ignore the input Buf and use the empty
1610 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1611 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1612 if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1613 (const unsigned char *)Buf.getBufferEnd())) {
1614 // If the input is LLVM Assembly, bitcode is produced by serializing
1615 // the module. Use-lists order need to be perserved in this case.
1616 llvm::raw_string_ostream OS(Data);
Rafael Espindola76c8f822018-02-14 19:11:37 +00001617 llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
Steven Wu27fb5222016-05-11 16:26:03 +00001618 ModuleData =
1619 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1620 } else
1621 // If the input is LLVM bitcode, write the input byte stream directly.
1622 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1623 Buf.getBufferSize());
1624 }
1625 llvm::Constant *ModuleConstant =
1626 llvm::ConstantDataArray::get(M->getContext(), ModuleData);
Steven Wu27fb5222016-05-11 16:26:03 +00001627 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
Steven Wu2c059a52016-05-16 18:54:58 +00001628 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
Steven Wu27fb5222016-05-11 16:26:03 +00001629 ModuleConstant);
1630 GV->setSection(getSectionNameForBitcode(T));
Steven Wu2c059a52016-05-16 18:54:58 +00001631 UsedArray.push_back(
1632 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
Steven Wu27fb5222016-05-11 16:26:03 +00001633 if (llvm::GlobalVariable *Old =
Steven Wu2c059a52016-05-16 18:54:58 +00001634 M->getGlobalVariable("llvm.embedded.module", true)) {
1635 assert(Old->hasOneUse() &&
1636 "llvm.embedded.module can only be used once in llvm.compiler.used");
Steven Wu27fb5222016-05-11 16:26:03 +00001637 GV->takeName(Old);
1638 Old->eraseFromParent();
1639 } else {
1640 GV->setName("llvm.embedded.module");
1641 }
1642
Steven Wu2c059a52016-05-16 18:54:58 +00001643 // Skip if only bitcode needs to be embedded.
1644 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1645 // Embed command-line options.
Saleem Abdulrasoolb1d50c12016-05-20 03:58:12 +00001646 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
Steven Wu2c059a52016-05-16 18:54:58 +00001647 CGOpts.CmdArgs.size());
1648 llvm::Constant *CmdConstant =
1649 llvm::ConstantDataArray::get(M->getContext(), CmdData);
1650 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1651 llvm::GlobalValue::PrivateLinkage,
1652 CmdConstant);
1653 GV->setSection(getSectionNameForCommandline(T));
1654 UsedArray.push_back(
1655 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1656 if (llvm::GlobalVariable *Old =
1657 M->getGlobalVariable("llvm.cmdline", true)) {
1658 assert(Old->hasOneUse() &&
1659 "llvm.cmdline can only be used once in llvm.compiler.used");
1660 GV->takeName(Old);
1661 Old->eraseFromParent();
1662 } else {
1663 GV->setName("llvm.cmdline");
1664 }
1665 }
1666
1667 if (UsedArray.empty())
Steven Wu27fb5222016-05-11 16:26:03 +00001668 return;
1669
Steven Wu2c059a52016-05-16 18:54:58 +00001670 // Recreate llvm.compiler.used.
1671 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1672 auto *NewUsed = new GlobalVariable(
1673 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1674 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1675 NewUsed->setSection("llvm.metadata");
Steven Wu27fb5222016-05-11 16:26:03 +00001676}