1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/CodeGen/BackendUtil.h"
11 #include "clang/Basic/CodeGenOptions.h"
12 #include "clang/Basic/Diagnostic.h"
13 #include "clang/Basic/LangOptions.h"
14 #include "clang/Basic/TargetOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/Utils.h"
17 #include "clang/Lex/HeaderSearchOptions.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/Bitcode/BitcodeWriter.h"
26 #include "llvm/Bitcode/BitcodeWriterPass.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSummaryIndex.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/LTO/LTOBackend.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Passes/PassBuilder.h"
40 #include "llvm/Support/BuryPointer.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/PrettyStackTrace.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Transforms/Coroutines.h"
50 #include "llvm/Transforms/IPO.h"
51 #include "llvm/Transforms/IPO/AlwaysInliner.h"
52 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
54 #include "llvm/Transforms/InstCombine/InstCombine.h"
55 #include "llvm/Transforms/Instrumentation.h"
56 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
57 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
58 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
59 #include "llvm/Transforms/ObjCARC.h"
60 #include "llvm/Transforms/Scalar.h"
61 #include "llvm/Transforms/Scalar/GVN.h"
62 #include "llvm/Transforms/Utils.h"
63 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
64 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
65 #include "llvm/Transforms/Utils/SymbolRewriter.h"
66 #include <memory>
67 using namespace clang;
68 using namespace llvm;
69 
70 namespace {
71 
72 // Default filename used for profile generation.
73 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
74 
75 class EmitAssemblyHelper {
76   DiagnosticsEngine &Diags;
77   const HeaderSearchOptions &HSOpts;
78   const CodeGenOptions &CodeGenOpts;
79   const clang::TargetOptions &TargetOpts;
80   const LangOptions &LangOpts;
81   Module *TheModule;
82 
83   Timer CodeGenerationTime;
84 
85   std::unique_ptr<raw_pwrite_stream> OS;
86 
87   TargetIRAnalysis getTargetIRAnalysis() const {
88     if (TM)
89       return TM->getTargetIRAnalysis();
90 
91     return TargetIRAnalysis();
92   }
93 
94   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
95 
96   /// Generates the TargetMachine.
97   /// Leaves TM unchanged if it is unable to create the target machine.
98   /// Some of our clang tests specify triples which are not built
99   /// into clang. This is okay because these tests check the generated
100   /// IR, and they require DataLayout which depends on the triple.
101   /// In this case, we allow this method to fail and not report an error.
102   /// When MustCreateTM is used, we print an error if we are unable to load
103   /// the requested target.
104   void CreateTargetMachine(bool MustCreateTM);
105 
106   /// Add passes necessary to emit assembly or LLVM IR.
107   ///
108   /// \return True on success.
109   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
110                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
111 
112   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
113     std::error_code EC;
114     auto F = llvm::make_unique<llvm::ToolOutputFile>(Path, EC,
115                                                      llvm::sys::fs::F_None);
116     if (EC) {
117       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
118       F.reset();
119     }
120     return F;
121   }
122 
123 public:
124   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
125                      const HeaderSearchOptions &HeaderSearchOpts,
126                      const CodeGenOptions &CGOpts,
127                      const clang::TargetOptions &TOpts,
128                      const LangOptions &LOpts, Module *M)
129       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
130         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
131         CodeGenerationTime("codegen", "Code Generation Time") {}
132 
133   ~EmitAssemblyHelper() {
134     if (CodeGenOpts.DisableFree)
135       BuryPointer(std::move(TM));
136   }
137 
138   std::unique_ptr<TargetMachine> TM;
139 
140   void EmitAssembly(BackendAction Action,
141                     std::unique_ptr<raw_pwrite_stream> OS);
142 
143   void EmitAssemblyWithNewPassManager(BackendAction Action,
144                                       std::unique_ptr<raw_pwrite_stream> OS);
145 };
146 
147 // We need this wrapper to access LangOpts and CGOpts from extension functions
148 // that we add to the PassManagerBuilder.
149 class PassManagerBuilderWrapper : public PassManagerBuilder {
150 public:
151   PassManagerBuilderWrapper(const Triple &TargetTriple,
152                             const CodeGenOptions &CGOpts,
153                             const LangOptions &LangOpts)
154       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
155         LangOpts(LangOpts) {}
156   const Triple &getTargetTriple() const { return TargetTriple; }
157   const CodeGenOptions &getCGOpts() const { return CGOpts; }
158   const LangOptions &getLangOpts() const { return LangOpts; }
159 
160 private:
161   const Triple &TargetTriple;
162   const CodeGenOptions &CGOpts;
163   const LangOptions &LangOpts;
164 };
165 }
166 
167 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
168   if (Builder.OptLevel > 0)
169     PM.add(createObjCARCAPElimPass());
170 }
171 
172 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
173   if (Builder.OptLevel > 0)
174     PM.add(createObjCARCExpandPass());
175 }
176 
177 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
178   if (Builder.OptLevel > 0)
179     PM.add(createObjCARCOptPass());
180 }
181 
182 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
183                                      legacy::PassManagerBase &PM) {
184   PM.add(createAddDiscriminatorsPass());
185 }
186 
187 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
188                                   legacy::PassManagerBase &PM) {
189   PM.add(createBoundsCheckingLegacyPass());
190 }
191 
192 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
193                                      legacy::PassManagerBase &PM) {
194   const PassManagerBuilderWrapper &BuilderWrapper =
195       static_cast<const PassManagerBuilderWrapper&>(Builder);
196   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
197   SanitizerCoverageOptions Opts;
198   Opts.CoverageType =
199       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
200   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
201   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
202   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
203   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
204   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
205   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
206   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
207   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
208   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
209   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
210   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
211   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
212   PM.add(createSanitizerCoverageModulePass(Opts));
213 }
214 
215 // Check if ASan should use GC-friendly instrumentation for globals.
216 // First of all, there is no point if -fdata-sections is off (expect for MachO,
217 // where this is not a factor). Also, on ELF this feature requires an assembler
218 // extension that only works with -integrated-as at the moment.
219 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
220   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
221     return false;
222   switch (T.getObjectFormat()) {
223   case Triple::MachO:
224   case Triple::COFF:
225     return true;
226   case Triple::ELF:
227     return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
228   default:
229     return false;
230   }
231 }
232 
233 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
234                                       legacy::PassManagerBase &PM) {
235   const PassManagerBuilderWrapper &BuilderWrapper =
236       static_cast<const PassManagerBuilderWrapper&>(Builder);
237   const Triple &T = BuilderWrapper.getTargetTriple();
238   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
239   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
240   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
241   bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
242   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
243   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
244                                             UseAfterScope));
245   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
246                                           UseGlobalsGC, UseOdrIndicator));
247 }
248 
249 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
250                                             legacy::PassManagerBase &PM) {
251   PM.add(createAddressSanitizerFunctionPass(
252       /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
253   PM.add(createAddressSanitizerModulePass(
254       /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
255       /*UseOdrIndicator*/ false));
256 }
257 
258 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
259                                             legacy::PassManagerBase &PM) {
260   const PassManagerBuilderWrapper &BuilderWrapper =
261       static_cast<const PassManagerBuilderWrapper &>(Builder);
262   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
263   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
264   PM.add(createHWAddressSanitizerPass(/*CompileKernel*/ false, Recover));
265 }
266 
267 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
268                                             legacy::PassManagerBase &PM) {
269   PM.add(createHWAddressSanitizerPass(
270       /*CompileKernel*/ true, /*Recover*/ true));
271 }
272 
273 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
274                                              legacy::PassManagerBase &PM,
275                                              bool CompileKernel) {
276   const PassManagerBuilderWrapper &BuilderWrapper =
277       static_cast<const PassManagerBuilderWrapper&>(Builder);
278   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
279   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
280   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
281   PM.add(createMemorySanitizerLegacyPassPass(TrackOrigins, Recover, CompileKernel));
282 
283   // MemorySanitizer inserts complex instrumentation that mostly follows
284   // the logic of the original code, but operates on "shadow" values.
285   // It can benefit from re-running some general purpose optimization passes.
286   if (Builder.OptLevel > 0) {
287     PM.add(createEarlyCSEPass());
288     PM.add(createReassociatePass());
289     PM.add(createLICMPass());
290     PM.add(createGVNPass());
291     PM.add(createInstructionCombiningPass());
292     PM.add(createDeadStoreEliminationPass());
293   }
294 }
295 
296 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
297                                    legacy::PassManagerBase &PM) {
298   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
299 }
300 
301 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
302                                          legacy::PassManagerBase &PM) {
303   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
304 }
305 
306 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
307                                    legacy::PassManagerBase &PM) {
308   PM.add(createThreadSanitizerPass());
309 }
310 
311 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
312                                      legacy::PassManagerBase &PM) {
313   const PassManagerBuilderWrapper &BuilderWrapper =
314       static_cast<const PassManagerBuilderWrapper&>(Builder);
315   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
316   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
317 }
318 
319 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
320                                        legacy::PassManagerBase &PM) {
321   const PassManagerBuilderWrapper &BuilderWrapper =
322       static_cast<const PassManagerBuilderWrapper&>(Builder);
323   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
324   EfficiencySanitizerOptions Opts;
325   if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
326     Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
327   else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
328     Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
329   PM.add(createEfficiencySanitizerPass(Opts));
330 }
331 
332 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
333                                          const CodeGenOptions &CodeGenOpts) {
334   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
335   if (!CodeGenOpts.SimplifyLibCalls)
336     TLII->disableAllFunctions();
337   else {
338     // Disable individual libc/libm calls in TargetLibraryInfo.
339     LibFunc F;
340     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
341       if (TLII->getLibFunc(FuncName, F))
342         TLII->setUnavailable(F);
343   }
344 
345   switch (CodeGenOpts.getVecLib()) {
346   case CodeGenOptions::Accelerate:
347     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
348     break;
349   case CodeGenOptions::SVML:
350     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
351     break;
352   default:
353     break;
354   }
355   return TLII;
356 }
357 
358 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
359                                   legacy::PassManager *MPM) {
360   llvm::SymbolRewriter::RewriteDescriptorList DL;
361 
362   llvm::SymbolRewriter::RewriteMapParser MapParser;
363   for (const auto &MapFile : Opts.RewriteMapFiles)
364     MapParser.parse(MapFile, &DL);
365 
366   MPM->add(createRewriteSymbolsPass(DL));
367 }
368 
369 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
370   switch (CodeGenOpts.OptimizationLevel) {
371   default:
372     llvm_unreachable("Invalid optimization level!");
373   case 0:
374     return CodeGenOpt::None;
375   case 1:
376     return CodeGenOpt::Less;
377   case 2:
378     return CodeGenOpt::Default; // O2/Os/Oz
379   case 3:
380     return CodeGenOpt::Aggressive;
381   }
382 }
383 
384 static Optional<llvm::CodeModel::Model>
385 getCodeModel(const CodeGenOptions &CodeGenOpts) {
386   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
387                            .Case("tiny", llvm::CodeModel::Tiny)
388                            .Case("small", llvm::CodeModel::Small)
389                            .Case("kernel", llvm::CodeModel::Kernel)
390                            .Case("medium", llvm::CodeModel::Medium)
391                            .Case("large", llvm::CodeModel::Large)
392                            .Case("default", ~1u)
393                            .Default(~0u);
394   assert(CodeModel != ~0u && "invalid code model!");
395   if (CodeModel == ~1u)
396     return None;
397   return static_cast<llvm::CodeModel::Model>(CodeModel);
398 }
399 
400 static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
401   if (Action == Backend_EmitObj)
402     return TargetMachine::CGFT_ObjectFile;
403   else if (Action == Backend_EmitMCNull)
404     return TargetMachine::CGFT_Null;
405   else {
406     assert(Action == Backend_EmitAssembly && "Invalid action!");
407     return TargetMachine::CGFT_AssemblyFile;
408   }
409 }
410 
411 static void initTargetOptions(llvm::TargetOptions &Options,
412                               const CodeGenOptions &CodeGenOpts,
413                               const clang::TargetOptions &TargetOpts,
414                               const LangOptions &LangOpts,
415                               const HeaderSearchOptions &HSOpts) {
416   Options.ThreadModel =
417       llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
418           .Case("posix", llvm::ThreadModel::POSIX)
419           .Case("single", llvm::ThreadModel::Single);
420 
421   // Set float ABI type.
422   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
423           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
424          "Invalid Floating Point ABI!");
425   Options.FloatABIType =
426       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
427           .Case("soft", llvm::FloatABI::Soft)
428           .Case("softfp", llvm::FloatABI::Soft)
429           .Case("hard", llvm::FloatABI::Hard)
430           .Default(llvm::FloatABI::Default);
431 
432   // Set FP fusion mode.
433   switch (LangOpts.getDefaultFPContractMode()) {
434   case LangOptions::FPC_Off:
435     // Preserve any contraction performed by the front-end.  (Strict performs
436     // splitting of the muladd intrinsic in the backend.)
437     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
438     break;
439   case LangOptions::FPC_On:
440     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
441     break;
442   case LangOptions::FPC_Fast:
443     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
444     break;
445   }
446 
447   Options.UseInitArray = CodeGenOpts.UseInitArray;
448   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
449   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
450   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
451 
452   // Set EABI version.
453   Options.EABIVersion = TargetOpts.EABIVersion;
454 
455   if (LangOpts.SjLjExceptions)
456     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
457   if (LangOpts.SEHExceptions)
458     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
459   if (LangOpts.DWARFExceptions)
460     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
461 
462   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
463   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
464   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
465   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
466   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
467   Options.FunctionSections = CodeGenOpts.FunctionSections;
468   Options.DataSections = CodeGenOpts.DataSections;
469   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
470   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
471   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
472   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
473   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
474   Options.EmitAddrsig = CodeGenOpts.Addrsig;
475 
476   if (CodeGenOpts.getSplitDwarfMode() != CodeGenOptions::NoFission)
477     Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
478   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
479   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
480   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
481   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
482   Options.MCOptions.MCIncrementalLinkerCompatible =
483       CodeGenOpts.IncrementalLinkerCompatible;
484   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
485   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
486   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
487   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
488   Options.MCOptions.ABIName = TargetOpts.ABI;
489   for (const auto &Entry : HSOpts.UserEntries)
490     if (!Entry.IsFramework &&
491         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
492          Entry.Group == frontend::IncludeDirGroup::Angled ||
493          Entry.Group == frontend::IncludeDirGroup::System))
494       Options.MCOptions.IASSearchPaths.push_back(
495           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
496 }
497 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
498   if (CodeGenOpts.DisableGCov)
499     return None;
500   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
501     return None;
502   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
503   // LLVM's -default-gcov-version flag is set to something invalid.
504   GCOVOptions Options;
505   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
506   Options.EmitData = CodeGenOpts.EmitGcovArcs;
507   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
508   Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
509   Options.NoRedZone = CodeGenOpts.DisableRedZone;
510   Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
511   Options.Filter = CodeGenOpts.ProfileFilterFiles;
512   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
513   Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
514   return Options;
515 }
516 
517 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
518                                       legacy::FunctionPassManager &FPM) {
519   // Handle disabling of all LLVM passes, where we want to preserve the
520   // internal module before any optimization.
521   if (CodeGenOpts.DisableLLVMPasses)
522     return;
523 
524   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
525   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
526   // are inserted before PMBuilder ones - they'd get the default-constructed
527   // TLI with an unknown target otherwise.
528   Triple TargetTriple(TheModule->getTargetTriple());
529   std::unique_ptr<TargetLibraryInfoImpl> TLII(
530       createTLII(TargetTriple, CodeGenOpts));
531 
532   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
533 
534   // At O0 and O1 we only run the always inliner which is more efficient. At
535   // higher optimization levels we run the normal inliner.
536   if (CodeGenOpts.OptimizationLevel <= 1) {
537     bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
538                                      !CodeGenOpts.DisableLifetimeMarkers);
539     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
540   } else {
541     // We do not want to inline hot callsites for SamplePGO module-summary build
542     // because profile annotation will happen again in ThinLTO backend, and we
543     // want the IR of the hot path to match the profile.
544     PMBuilder.Inliner = createFunctionInliningPass(
545         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
546         (!CodeGenOpts.SampleProfileFile.empty() &&
547          CodeGenOpts.PrepareForThinLTO));
548   }
549 
550   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
551   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
552   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
553   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
554 
555   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
556   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
557   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
558   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
559   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
560 
561   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
562 
563   if (TM)
564     TM->adjustPassManager(PMBuilder);
565 
566   if (CodeGenOpts.DebugInfoForProfiling ||
567       !CodeGenOpts.SampleProfileFile.empty())
568     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
569                            addAddDiscriminatorsPass);
570 
571   // In ObjC ARC mode, add the main ARC optimization passes.
572   if (LangOpts.ObjCAutoRefCount) {
573     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
574                            addObjCARCExpandPass);
575     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
576                            addObjCARCAPElimPass);
577     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
578                            addObjCARCOptPass);
579   }
580 
581   if (LangOpts.CoroutinesTS)
582     addCoroutinePassesToExtensionPoints(PMBuilder);
583 
584   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
585     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
586                            addBoundsCheckingPass);
587     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
588                            addBoundsCheckingPass);
589   }
590 
591   if (CodeGenOpts.SanitizeCoverageType ||
592       CodeGenOpts.SanitizeCoverageIndirectCalls ||
593       CodeGenOpts.SanitizeCoverageTraceCmp) {
594     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
595                            addSanitizerCoveragePass);
596     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
597                            addSanitizerCoveragePass);
598   }
599 
600   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
601     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
602                            addAddressSanitizerPasses);
603     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
604                            addAddressSanitizerPasses);
605   }
606 
607   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
608     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
609                            addKernelAddressSanitizerPasses);
610     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
611                            addKernelAddressSanitizerPasses);
612   }
613 
614   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
615     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
616                            addHWAddressSanitizerPasses);
617     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
618                            addHWAddressSanitizerPasses);
619   }
620 
621   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
622     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
623                            addKernelHWAddressSanitizerPasses);
624     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
625                            addKernelHWAddressSanitizerPasses);
626   }
627 
628   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
629     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
630                            addMemorySanitizerPass);
631     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
632                            addMemorySanitizerPass);
633   }
634 
635   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
636     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
637                            addKernelMemorySanitizerPass);
638     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
639                            addKernelMemorySanitizerPass);
640   }
641 
642   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
643     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
644                            addThreadSanitizerPass);
645     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
646                            addThreadSanitizerPass);
647   }
648 
649   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
650     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
651                            addDataFlowSanitizerPass);
652     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
653                            addDataFlowSanitizerPass);
654   }
655 
656   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
657     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
658                            addEfficiencySanitizerPass);
659     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
660                            addEfficiencySanitizerPass);
661   }
662 
663   // Set up the per-function pass manager.
664   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
665   if (CodeGenOpts.VerifyModule)
666     FPM.add(createVerifierPass());
667 
668   // Set up the per-module pass manager.
669   if (!CodeGenOpts.RewriteMapFiles.empty())
670     addSymbolRewriterPass(CodeGenOpts, &MPM);
671 
672   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
673     MPM.add(createGCOVProfilerPass(*Options));
674     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
675       MPM.add(createStripSymbolsPass(true));
676   }
677 
678   if (CodeGenOpts.hasProfileClangInstr()) {
679     InstrProfOptions Options;
680     Options.NoRedZone = CodeGenOpts.DisableRedZone;
681     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
682 
683     // TODO: Surface the option to emit atomic profile counter increments at
684     // the driver level.
685     Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
686 
687     MPM.add(createInstrProfilingLegacyPass(Options));
688   }
689   if (CodeGenOpts.hasProfileIRInstr()) {
690     PMBuilder.EnablePGOInstrGen = true;
691     if (!CodeGenOpts.InstrProfileOutput.empty())
692       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
693     else
694       PMBuilder.PGOInstrGen = DefaultProfileGenName;
695   }
696   if (CodeGenOpts.hasProfileIRUse())
697     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
698 
699   if (!CodeGenOpts.SampleProfileFile.empty())
700     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
701 
702   PMBuilder.populateFunctionPassManager(FPM);
703   PMBuilder.populateModulePassManager(MPM);
704 }
705 
706 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
707   SmallVector<const char *, 16> BackendArgs;
708   BackendArgs.push_back("clang"); // Fake program name.
709   if (!CodeGenOpts.DebugPass.empty()) {
710     BackendArgs.push_back("-debug-pass");
711     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
712   }
713   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
714     BackendArgs.push_back("-limit-float-precision");
715     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
716   }
717   BackendArgs.push_back(nullptr);
718   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
719                                     BackendArgs.data());
720 }
721 
722 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
723   // Create the TargetMachine for generating code.
724   std::string Error;
725   std::string Triple = TheModule->getTargetTriple();
726   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
727   if (!TheTarget) {
728     if (MustCreateTM)
729       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
730     return;
731   }
732 
733   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
734   std::string FeaturesStr =
735       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
736   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
737   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
738 
739   llvm::TargetOptions Options;
740   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
741   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
742                                           Options, RM, CM, OptLevel));
743 }
744 
745 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
746                                        BackendAction Action,
747                                        raw_pwrite_stream &OS,
748                                        raw_pwrite_stream *DwoOS) {
749   // Add LibraryInfo.
750   llvm::Triple TargetTriple(TheModule->getTargetTriple());
751   std::unique_ptr<TargetLibraryInfoImpl> TLII(
752       createTLII(TargetTriple, CodeGenOpts));
753   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
754 
755   // Normal mode, emit a .s or .o file by running the code generator. Note,
756   // this also adds codegenerator level optimization passes.
757   TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
758 
759   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
760   // "codegen" passes so that it isn't run multiple times when there is
761   // inlining happening.
762   if (CodeGenOpts.OptimizationLevel > 0)
763     CodeGenPasses.add(createObjCARCContractPass());
764 
765   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
766                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
767     Diags.Report(diag::err_fe_unable_to_interface_with_target);
768     return false;
769   }
770 
771   return true;
772 }
773 
774 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
775                                       std::unique_ptr<raw_pwrite_stream> OS) {
776   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
777 
778   setCommandLineOpts(CodeGenOpts);
779 
780   bool UsesCodeGen = (Action != Backend_EmitNothing &&
781                       Action != Backend_EmitBC &&
782                       Action != Backend_EmitLL);
783   CreateTargetMachine(UsesCodeGen);
784 
785   if (UsesCodeGen && !TM)
786     return;
787   if (TM)
788     TheModule->setDataLayout(TM->createDataLayout());
789 
790   legacy::PassManager PerModulePasses;
791   PerModulePasses.add(
792       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
793 
794   legacy::FunctionPassManager PerFunctionPasses(TheModule);
795   PerFunctionPasses.add(
796       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
797 
798   CreatePasses(PerModulePasses, PerFunctionPasses);
799 
800   legacy::PassManager CodeGenPasses;
801   CodeGenPasses.add(
802       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
803 
804   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
805 
806   switch (Action) {
807   case Backend_EmitNothing:
808     break;
809 
810   case Backend_EmitBC:
811     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
812       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
813         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
814         if (!ThinLinkOS)
815           return;
816       }
817       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
818                                CodeGenOpts.EnableSplitLTOUnit);
819       PerModulePasses.add(createWriteThinLTOBitcodePass(
820           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
821     } else {
822       // Emit a module summary by default for Regular LTO except for ld64
823       // targets
824       bool EmitLTOSummary =
825           (CodeGenOpts.PrepareForLTO &&
826            !CodeGenOpts.DisableLLVMPasses &&
827            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
828                llvm::Triple::Apple);
829       if (EmitLTOSummary) {
830         if (!TheModule->getModuleFlag("ThinLTO"))
831           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
832         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
833                                  CodeGenOpts.EnableSplitLTOUnit);
834       }
835 
836       PerModulePasses.add(createBitcodeWriterPass(
837           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
838     }
839     break;
840 
841   case Backend_EmitLL:
842     PerModulePasses.add(
843         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
844     break;
845 
846   default:
847     if (!CodeGenOpts.SplitDwarfFile.empty() &&
848         (CodeGenOpts.getSplitDwarfMode() == CodeGenOptions::SplitFileFission)) {
849       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
850       if (!DwoOS)
851         return;
852     }
853     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
854                        DwoOS ? &DwoOS->os() : nullptr))
855       return;
856   }
857 
858   // Before executing passes, print the final values of the LLVM options.
859   cl::PrintOptionValues();
860 
861   // Run passes. For now we do all passes at once, but eventually we
862   // would like to have the option of streaming code generation.
863 
864   {
865     PrettyStackTraceString CrashInfo("Per-function optimization");
866 
867     PerFunctionPasses.doInitialization();
868     for (Function &F : *TheModule)
869       if (!F.isDeclaration())
870         PerFunctionPasses.run(F);
871     PerFunctionPasses.doFinalization();
872   }
873 
874   {
875     PrettyStackTraceString CrashInfo("Per-module optimization passes");
876     PerModulePasses.run(*TheModule);
877   }
878 
879   {
880     PrettyStackTraceString CrashInfo("Code generation");
881     CodeGenPasses.run(*TheModule);
882   }
883 
884   if (ThinLinkOS)
885     ThinLinkOS->keep();
886   if (DwoOS)
887     DwoOS->keep();
888 }
889 
890 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
891   switch (Opts.OptimizationLevel) {
892   default:
893     llvm_unreachable("Invalid optimization level!");
894 
895   case 1:
896     return PassBuilder::O1;
897 
898   case 2:
899     switch (Opts.OptimizeSize) {
900     default:
901       llvm_unreachable("Invalid optimization level for size!");
902 
903     case 0:
904       return PassBuilder::O2;
905 
906     case 1:
907       return PassBuilder::Os;
908 
909     case 2:
910       return PassBuilder::Oz;
911     }
912 
913   case 3:
914     return PassBuilder::O3;
915   }
916 }
917 
918 /// A clean version of `EmitAssembly` that uses the new pass manager.
919 ///
920 /// Not all features are currently supported in this system, but where
921 /// necessary it falls back to the legacy pass manager to at least provide
922 /// basic functionality.
923 ///
924 /// This API is planned to have its functionality finished and then to replace
925 /// `EmitAssembly` at some point in the future when the default switches.
926 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
927     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
928   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
929   setCommandLineOpts(CodeGenOpts);
930 
931   // The new pass manager always makes a target machine available to passes
932   // during construction.
933   CreateTargetMachine(/*MustCreateTM*/ true);
934   if (!TM)
935     // This will already be diagnosed, just bail.
936     return;
937   TheModule->setDataLayout(TM->createDataLayout());
938 
939   Optional<PGOOptions> PGOOpt;
940 
941   if (CodeGenOpts.hasProfileIRInstr())
942     // -fprofile-generate.
943     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
944                             ? DefaultProfileGenName
945                             : CodeGenOpts.InstrProfileOutput,
946                         "", "", "", true,
947                         CodeGenOpts.DebugInfoForProfiling);
948   else if (CodeGenOpts.hasProfileIRUse())
949     // -fprofile-use.
950     PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "",
951                         CodeGenOpts.ProfileRemappingFile, false,
952                         CodeGenOpts.DebugInfoForProfiling);
953   else if (!CodeGenOpts.SampleProfileFile.empty())
954     // -fprofile-sample-use
955     PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile,
956                         CodeGenOpts.ProfileRemappingFile, false,
957                         CodeGenOpts.DebugInfoForProfiling);
958   else if (CodeGenOpts.DebugInfoForProfiling)
959     // -fdebug-info-for-profiling
960     PGOOpt = PGOOptions("", "", "", "", false, true);
961 
962   PassBuilder PB(TM.get(), PGOOpt);
963 
964   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
965   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
966   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
967   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
968 
969   // Register the AA manager first so that our version is the one used.
970   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
971 
972   // Register the target library analysis directly and give it a customized
973   // preset TLI.
974   Triple TargetTriple(TheModule->getTargetTriple());
975   std::unique_ptr<TargetLibraryInfoImpl> TLII(
976       createTLII(TargetTriple, CodeGenOpts));
977   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
978   MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
979 
980   // Register all the basic analyses with the managers.
981   PB.registerModuleAnalyses(MAM);
982   PB.registerCGSCCAnalyses(CGAM);
983   PB.registerFunctionAnalyses(FAM);
984   PB.registerLoopAnalyses(LAM);
985   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
986 
987   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
988 
989   if (!CodeGenOpts.DisableLLVMPasses) {
990     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
991     bool IsLTO = CodeGenOpts.PrepareForLTO;
992 
993     if (CodeGenOpts.OptimizationLevel == 0) {
994       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
995         MPM.addPass(GCOVProfilerPass(*Options));
996 
997       // Build a minimal pipeline based on the semantics required by Clang,
998       // which is just that always inlining occurs.
999       MPM.addPass(AlwaysInlinerPass());
1000 
1001       // At -O0 we directly run necessary sanitizer passes.
1002       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1003         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1004 
1005       // Lastly, add semantically necessary passes for LTO.
1006       if (IsLTO || IsThinLTO) {
1007         MPM.addPass(CanonicalizeAliasesPass());
1008         MPM.addPass(NameAnonGlobalPass());
1009       }
1010     } else {
1011       // Map our optimization levels into one of the distinct levels used to
1012       // configure the pipeline.
1013       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1014 
1015       // Register callbacks to schedule sanitizer passes at the appropriate part of
1016       // the pipeline.
1017       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1018         PB.registerScalarOptimizerLateEPCallback(
1019             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1020               FPM.addPass(BoundsCheckingPass());
1021             });
1022       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1023         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1024           MPM.addPass(GCOVProfilerPass(*Options));
1025         });
1026 
1027       if (IsThinLTO) {
1028         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1029             Level, CodeGenOpts.DebugPassManager);
1030         MPM.addPass(CanonicalizeAliasesPass());
1031         MPM.addPass(NameAnonGlobalPass());
1032       } else if (IsLTO) {
1033         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1034                                                 CodeGenOpts.DebugPassManager);
1035         MPM.addPass(CanonicalizeAliasesPass());
1036         MPM.addPass(NameAnonGlobalPass());
1037       } else {
1038         MPM = PB.buildPerModuleDefaultPipeline(Level,
1039                                                CodeGenOpts.DebugPassManager);
1040       }
1041     }
1042   }
1043 
1044   // FIXME: We still use the legacy pass manager to do code generation. We
1045   // create that pass manager here and use it as needed below.
1046   legacy::PassManager CodeGenPasses;
1047   bool NeedCodeGen = false;
1048   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1049 
1050   // Append any output we need to the pass manager.
1051   switch (Action) {
1052   case Backend_EmitNothing:
1053     break;
1054 
1055   case Backend_EmitBC:
1056     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1057       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1058         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1059         if (!ThinLinkOS)
1060           return;
1061       }
1062       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1063                                CodeGenOpts.EnableSplitLTOUnit);
1064       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1065                                                            : nullptr));
1066     } else {
1067       // Emit a module summary by default for Regular LTO except for ld64
1068       // targets
1069       bool EmitLTOSummary =
1070           (CodeGenOpts.PrepareForLTO &&
1071            !CodeGenOpts.DisableLLVMPasses &&
1072            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1073                llvm::Triple::Apple);
1074       if (EmitLTOSummary) {
1075         if (!TheModule->getModuleFlag("ThinLTO"))
1076           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1077         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1078                                  CodeGenOpts.EnableSplitLTOUnit);
1079       }
1080       MPM.addPass(
1081           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1082     }
1083     break;
1084 
1085   case Backend_EmitLL:
1086     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1087     break;
1088 
1089   case Backend_EmitAssembly:
1090   case Backend_EmitMCNull:
1091   case Backend_EmitObj:
1092     NeedCodeGen = true;
1093     CodeGenPasses.add(
1094         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1095     if (!CodeGenOpts.SplitDwarfFile.empty()) {
1096       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
1097       if (!DwoOS)
1098         return;
1099     }
1100     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1101                        DwoOS ? &DwoOS->os() : nullptr))
1102       // FIXME: Should we handle this error differently?
1103       return;
1104     break;
1105   }
1106 
1107   // Before executing passes, print the final values of the LLVM options.
1108   cl::PrintOptionValues();
1109 
1110   // Now that we have all of the passes ready, run them.
1111   {
1112     PrettyStackTraceString CrashInfo("Optimizer");
1113     MPM.run(*TheModule, MAM);
1114   }
1115 
1116   // Now if needed, run the legacy PM for codegen.
1117   if (NeedCodeGen) {
1118     PrettyStackTraceString CrashInfo("Code generation");
1119     CodeGenPasses.run(*TheModule);
1120   }
1121 
1122   if (ThinLinkOS)
1123     ThinLinkOS->keep();
1124   if (DwoOS)
1125     DwoOS->keep();
1126 }
1127 
1128 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1129   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1130   if (!BMsOrErr)
1131     return BMsOrErr.takeError();
1132 
1133   // The bitcode file may contain multiple modules, we want the one that is
1134   // marked as being the ThinLTO module.
1135   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1136     return *Bm;
1137 
1138   return make_error<StringError>("Could not find module summary",
1139                                  inconvertibleErrorCode());
1140 }
1141 
1142 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1143   for (BitcodeModule &BM : BMs) {
1144     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1145     if (LTOInfo && LTOInfo->IsThinLTO)
1146       return &BM;
1147   }
1148   return nullptr;
1149 }
1150 
1151 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1152                               const HeaderSearchOptions &HeaderOpts,
1153                               const CodeGenOptions &CGOpts,
1154                               const clang::TargetOptions &TOpts,
1155                               const LangOptions &LOpts,
1156                               std::unique_ptr<raw_pwrite_stream> OS,
1157                               std::string SampleProfile,
1158                               std::string ProfileRemapping,
1159                               BackendAction Action) {
1160   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1161       ModuleToDefinedGVSummaries;
1162   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1163 
1164   setCommandLineOpts(CGOpts);
1165 
1166   // We can simply import the values mentioned in the combined index, since
1167   // we should only invoke this using the individual indexes written out
1168   // via a WriteIndexesThinBackend.
1169   FunctionImporter::ImportMapTy ImportList;
1170   for (auto &GlobalList : *CombinedIndex) {
1171     // Ignore entries for undefined references.
1172     if (GlobalList.second.SummaryList.empty())
1173       continue;
1174 
1175     auto GUID = GlobalList.first;
1176     for (auto &Summary : GlobalList.second.SummaryList) {
1177       // Skip the summaries for the importing module. These are included to
1178       // e.g. record required linkage changes.
1179       if (Summary->modulePath() == M->getModuleIdentifier())
1180         continue;
1181       // Add an entry to provoke importing by thinBackend.
1182       ImportList[Summary->modulePath()].insert(GUID);
1183     }
1184   }
1185 
1186   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1187   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1188 
1189   for (auto &I : ImportList) {
1190     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1191         llvm::MemoryBuffer::getFile(I.first());
1192     if (!MBOrErr) {
1193       errs() << "Error loading imported file '" << I.first()
1194              << "': " << MBOrErr.getError().message() << "\n";
1195       return;
1196     }
1197 
1198     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1199     if (!BMOrErr) {
1200       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1201         errs() << "Error loading imported file '" << I.first()
1202                << "': " << EIB.message() << '\n';
1203       });
1204       return;
1205     }
1206     ModuleMap.insert({I.first(), *BMOrErr});
1207 
1208     OwnedImports.push_back(std::move(*MBOrErr));
1209   }
1210   auto AddStream = [&](size_t Task) {
1211     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1212   };
1213   lto::Config Conf;
1214   if (CGOpts.SaveTempsFilePrefix != "") {
1215     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1216                                     /* UseInputModulePath */ false)) {
1217       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1218         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1219                << '\n';
1220       });
1221     }
1222   }
1223   Conf.CPU = TOpts.CPU;
1224   Conf.CodeModel = getCodeModel(CGOpts);
1225   Conf.MAttrs = TOpts.Features;
1226   Conf.RelocModel = CGOpts.RelocationModel;
1227   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1228   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1229   Conf.SampleProfile = std::move(SampleProfile);
1230   Conf.ProfileRemapping = std::move(ProfileRemapping);
1231   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1232   Conf.DebugPassManager = CGOpts.DebugPassManager;
1233   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1234   Conf.RemarksFilename = CGOpts.OptRecordFile;
1235   Conf.DwoPath = CGOpts.SplitDwarfFile;
1236   switch (Action) {
1237   case Backend_EmitNothing:
1238     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1239       return false;
1240     };
1241     break;
1242   case Backend_EmitLL:
1243     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1244       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1245       return false;
1246     };
1247     break;
1248   case Backend_EmitBC:
1249     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1250       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1251       return false;
1252     };
1253     break;
1254   default:
1255     Conf.CGFileType = getCodeGenFileType(Action);
1256     break;
1257   }
1258   if (Error E = thinBackend(
1259           Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1260           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1261     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1262       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1263     });
1264   }
1265 }
1266 
1267 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1268                               const HeaderSearchOptions &HeaderOpts,
1269                               const CodeGenOptions &CGOpts,
1270                               const clang::TargetOptions &TOpts,
1271                               const LangOptions &LOpts,
1272                               const llvm::DataLayout &TDesc, Module *M,
1273                               BackendAction Action,
1274                               std::unique_ptr<raw_pwrite_stream> OS) {
1275   std::unique_ptr<llvm::Module> EmptyModule;
1276   if (!CGOpts.ThinLTOIndexFile.empty()) {
1277     // If we are performing a ThinLTO importing compile, load the function index
1278     // into memory and pass it into runThinLTOBackend, which will run the
1279     // function importer and invoke LTO passes.
1280     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1281         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1282                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1283     if (!IndexOrErr) {
1284       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1285                             "Error loading index file '" +
1286                             CGOpts.ThinLTOIndexFile + "': ");
1287       return;
1288     }
1289     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1290     // A null CombinedIndex means we should skip ThinLTO compilation
1291     // (LLVM will optionally ignore empty index files, returning null instead
1292     // of an error).
1293     if (CombinedIndex) {
1294       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1295         runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1296                           LOpts, std::move(OS), CGOpts.SampleProfileFile,
1297                           CGOpts.ProfileRemappingFile, Action);
1298         return;
1299       }
1300       // Distributed indexing detected that nothing from the module is needed
1301       // for the final linking. So we can skip the compilation. We sill need to
1302       // output an empty object file to make sure that a linker does not fail
1303       // trying to read it. Also for some features, like CFI, we must skip
1304       // the compilation as CombinedIndex does not contain all required
1305       // information.
1306       EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
1307       EmptyModule->setTargetTriple(M->getTargetTriple());
1308       M = EmptyModule.get();
1309     }
1310   }
1311 
1312   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1313 
1314   if (CGOpts.ExperimentalNewPassManager)
1315     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1316   else
1317     AsmHelper.EmitAssembly(Action, std::move(OS));
1318 
1319   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1320   // DataLayout.
1321   if (AsmHelper.TM) {
1322     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1323     if (DLDesc != TDesc.getStringRepresentation()) {
1324       unsigned DiagID = Diags.getCustomDiagID(
1325           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1326                                     "expected target description '%1'");
1327       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1328     }
1329   }
1330 }
1331 
1332 static const char* getSectionNameForBitcode(const Triple &T) {
1333   switch (T.getObjectFormat()) {
1334   case Triple::MachO:
1335     return "__LLVM,__bitcode";
1336   case Triple::COFF:
1337   case Triple::ELF:
1338   case Triple::Wasm:
1339   case Triple::UnknownObjectFormat:
1340     return ".llvmbc";
1341   }
1342   llvm_unreachable("Unimplemented ObjectFormatType");
1343 }
1344 
1345 static const char* getSectionNameForCommandline(const Triple &T) {
1346   switch (T.getObjectFormat()) {
1347   case Triple::MachO:
1348     return "__LLVM,__cmdline";
1349   case Triple::COFF:
1350   case Triple::ELF:
1351   case Triple::Wasm:
1352   case Triple::UnknownObjectFormat:
1353     return ".llvmcmd";
1354   }
1355   llvm_unreachable("Unimplemented ObjectFormatType");
1356 }
1357 
1358 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1359 // __LLVM,__bitcode section.
1360 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1361                          llvm::MemoryBufferRef Buf) {
1362   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1363     return;
1364 
1365   // Save llvm.compiler.used and remote it.
1366   SmallVector<Constant*, 2> UsedArray;
1367   SmallPtrSet<GlobalValue*, 4> UsedGlobals;
1368   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1369   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1370   for (auto *GV : UsedGlobals) {
1371     if (GV->getName() != "llvm.embedded.module" &&
1372         GV->getName() != "llvm.cmdline")
1373       UsedArray.push_back(
1374           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1375   }
1376   if (Used)
1377     Used->eraseFromParent();
1378 
1379   // Embed the bitcode for the llvm module.
1380   std::string Data;
1381   ArrayRef<uint8_t> ModuleData;
1382   Triple T(M->getTargetTriple());
1383   // Create a constant that contains the bitcode.
1384   // In case of embedding a marker, ignore the input Buf and use the empty
1385   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1386   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1387     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1388                    (const unsigned char *)Buf.getBufferEnd())) {
1389       // If the input is LLVM Assembly, bitcode is produced by serializing
1390       // the module. Use-lists order need to be perserved in this case.
1391       llvm::raw_string_ostream OS(Data);
1392       llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
1393       ModuleData =
1394           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1395     } else
1396       // If the input is LLVM bitcode, write the input byte stream directly.
1397       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1398                                      Buf.getBufferSize());
1399   }
1400   llvm::Constant *ModuleConstant =
1401       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1402   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1403       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1404       ModuleConstant);
1405   GV->setSection(getSectionNameForBitcode(T));
1406   UsedArray.push_back(
1407       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1408   if (llvm::GlobalVariable *Old =
1409           M->getGlobalVariable("llvm.embedded.module", true)) {
1410     assert(Old->hasOneUse() &&
1411            "llvm.embedded.module can only be used once in llvm.compiler.used");
1412     GV->takeName(Old);
1413     Old->eraseFromParent();
1414   } else {
1415     GV->setName("llvm.embedded.module");
1416   }
1417 
1418   // Skip if only bitcode needs to be embedded.
1419   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1420     // Embed command-line options.
1421     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1422                               CGOpts.CmdArgs.size());
1423     llvm::Constant *CmdConstant =
1424       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1425     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1426                                   llvm::GlobalValue::PrivateLinkage,
1427                                   CmdConstant);
1428     GV->setSection(getSectionNameForCommandline(T));
1429     UsedArray.push_back(
1430         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1431     if (llvm::GlobalVariable *Old =
1432             M->getGlobalVariable("llvm.cmdline", true)) {
1433       assert(Old->hasOneUse() &&
1434              "llvm.cmdline can only be used once in llvm.compiler.used");
1435       GV->takeName(Old);
1436       Old->eraseFromParent();
1437     } else {
1438       GV->setName("llvm.cmdline");
1439     }
1440   }
1441 
1442   if (UsedArray.empty())
1443     return;
1444 
1445   // Recreate llvm.compiler.used.
1446   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1447   auto *NewUsed = new GlobalVariable(
1448       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1449       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1450   NewUsed->setSection("llvm.metadata");
1451 }
1452