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