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/StackSafetyAnalysis.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/PassManager.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/LTO/LTOBackend.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Passes/PassBuilder.h"
41 #include "llvm/Passes/PassPlugin.h"
42 #include "llvm/Passes/StandardInstrumentations.h"
43 #include "llvm/Support/BuryPointer.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/PrettyStackTrace.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TimeProfiler.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Transforms/Coroutines.h"
55 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
56 #include "llvm/Transforms/Coroutines/CoroEarly.h"
57 #include "llvm/Transforms/Coroutines/CoroElide.h"
58 #include "llvm/Transforms/Coroutines/CoroSplit.h"
59 #include "llvm/Transforms/IPO.h"
60 #include "llvm/Transforms/IPO/AlwaysInliner.h"
61 #include "llvm/Transforms/IPO/LowerTypeTests.h"
62 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
63 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
64 #include "llvm/Transforms/InstCombine/InstCombine.h"
65 #include "llvm/Transforms/Instrumentation.h"
66 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
67 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
68 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
69 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
70 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
71 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
72 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
73 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
74 #include "llvm/Transforms/ObjCARC.h"
75 #include "llvm/Transforms/Scalar.h"
76 #include "llvm/Transforms/Scalar/GVN.h"
77 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
78 #include "llvm/Transforms/Utils.h"
79 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
80 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
81 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
82 #include "llvm/Transforms/Utils/SymbolRewriter.h"
83 #include "llvm/Transforms/Utils/UniqueInternalLinkageNames.h"
84 #include <memory>
85 using namespace clang;
86 using namespace llvm;
87 
88 #define HANDLE_EXTENSION(Ext)                                                  \
89   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
90 #include "llvm/Support/Extension.def"
91 
92 namespace {
93 
94 // Default filename used for profile generation.
95 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
96 
97 class EmitAssemblyHelper {
98   DiagnosticsEngine &Diags;
99   const HeaderSearchOptions &HSOpts;
100   const CodeGenOptions &CodeGenOpts;
101   const clang::TargetOptions &TargetOpts;
102   const LangOptions &LangOpts;
103   Module *TheModule;
104 
105   Timer CodeGenerationTime;
106 
107   std::unique_ptr<raw_pwrite_stream> OS;
108 
109   TargetIRAnalysis getTargetIRAnalysis() const {
110     if (TM)
111       return TM->getTargetIRAnalysis();
112 
113     return TargetIRAnalysis();
114   }
115 
116   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
117 
118   /// Generates the TargetMachine.
119   /// Leaves TM unchanged if it is unable to create the target machine.
120   /// Some of our clang tests specify triples which are not built
121   /// into clang. This is okay because these tests check the generated
122   /// IR, and they require DataLayout which depends on the triple.
123   /// In this case, we allow this method to fail and not report an error.
124   /// When MustCreateTM is used, we print an error if we are unable to load
125   /// the requested target.
126   void CreateTargetMachine(bool MustCreateTM);
127 
128   /// Add passes necessary to emit assembly or LLVM IR.
129   ///
130   /// \return True on success.
131   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
132                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
133 
134   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
135     std::error_code EC;
136     auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
137                                                      llvm::sys::fs::OF_None);
138     if (EC) {
139       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
140       F.reset();
141     }
142     return F;
143   }
144 
145 public:
146   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
147                      const HeaderSearchOptions &HeaderSearchOpts,
148                      const CodeGenOptions &CGOpts,
149                      const clang::TargetOptions &TOpts,
150                      const LangOptions &LOpts, Module *M)
151       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
152         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
153         CodeGenerationTime("codegen", "Code Generation Time") {}
154 
155   ~EmitAssemblyHelper() {
156     if (CodeGenOpts.DisableFree)
157       BuryPointer(std::move(TM));
158   }
159 
160   std::unique_ptr<TargetMachine> TM;
161 
162   void EmitAssembly(BackendAction Action,
163                     std::unique_ptr<raw_pwrite_stream> OS);
164 
165   void EmitAssemblyWithNewPassManager(BackendAction Action,
166                                       std::unique_ptr<raw_pwrite_stream> OS);
167 };
168 
169 // We need this wrapper to access LangOpts and CGOpts from extension functions
170 // that we add to the PassManagerBuilder.
171 class PassManagerBuilderWrapper : public PassManagerBuilder {
172 public:
173   PassManagerBuilderWrapper(const Triple &TargetTriple,
174                             const CodeGenOptions &CGOpts,
175                             const LangOptions &LangOpts)
176       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
177         LangOpts(LangOpts) {}
178   const Triple &getTargetTriple() const { return TargetTriple; }
179   const CodeGenOptions &getCGOpts() const { return CGOpts; }
180   const LangOptions &getLangOpts() const { return LangOpts; }
181 
182 private:
183   const Triple &TargetTriple;
184   const CodeGenOptions &CGOpts;
185   const LangOptions &LangOpts;
186 };
187 }
188 
189 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
190   if (Builder.OptLevel > 0)
191     PM.add(createObjCARCAPElimPass());
192 }
193 
194 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
195   if (Builder.OptLevel > 0)
196     PM.add(createObjCARCExpandPass());
197 }
198 
199 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
200   if (Builder.OptLevel > 0)
201     PM.add(createObjCARCOptPass());
202 }
203 
204 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
205                                      legacy::PassManagerBase &PM) {
206   PM.add(createAddDiscriminatorsPass());
207 }
208 
209 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
210                                   legacy::PassManagerBase &PM) {
211   PM.add(createBoundsCheckingLegacyPass());
212 }
213 
214 static SanitizerCoverageOptions
215 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
216   SanitizerCoverageOptions Opts;
217   Opts.CoverageType =
218       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
219   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
220   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
221   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
222   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
223   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
224   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
225   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
226   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
227   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
228   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
229   Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
230   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
231   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
232   return Opts;
233 }
234 
235 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
236                                      legacy::PassManagerBase &PM) {
237   const PassManagerBuilderWrapper &BuilderWrapper =
238       static_cast<const PassManagerBuilderWrapper &>(Builder);
239   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
240   auto Opts = getSancovOptsFromCGOpts(CGOpts);
241   PM.add(createModuleSanitizerCoverageLegacyPassPass(
242       Opts, CGOpts.SanitizeCoverageAllowlistFiles,
243       CGOpts.SanitizeCoverageBlocklistFiles));
244 }
245 
246 // Check if ASan should use GC-friendly instrumentation for globals.
247 // First of all, there is no point if -fdata-sections is off (expect for MachO,
248 // where this is not a factor). Also, on ELF this feature requires an assembler
249 // extension that only works with -integrated-as at the moment.
250 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
251   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
252     return false;
253   switch (T.getObjectFormat()) {
254   case Triple::MachO:
255   case Triple::COFF:
256     return true;
257   case Triple::ELF:
258     return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
259   case Triple::GOFF:
260     llvm::report_fatal_error("ASan not implemented for GOFF");
261   case Triple::XCOFF:
262     llvm::report_fatal_error("ASan not implemented for XCOFF.");
263   case Triple::Wasm:
264   case Triple::UnknownObjectFormat:
265     break;
266   }
267   return false;
268 }
269 
270 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
271                                       legacy::PassManagerBase &PM) {
272   const PassManagerBuilderWrapper &BuilderWrapper =
273       static_cast<const PassManagerBuilderWrapper&>(Builder);
274   const Triple &T = BuilderWrapper.getTargetTriple();
275   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
276   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
277   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
278   bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
279   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
280   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
281                                             UseAfterScope));
282   PM.add(createModuleAddressSanitizerLegacyPassPass(
283       /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator));
284 }
285 
286 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
287                                             legacy::PassManagerBase &PM) {
288   PM.add(createAddressSanitizerFunctionPass(
289       /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false));
290   PM.add(createModuleAddressSanitizerLegacyPassPass(
291       /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
292       /*UseOdrIndicator*/ false));
293 }
294 
295 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
296                                             legacy::PassManagerBase &PM) {
297   const PassManagerBuilderWrapper &BuilderWrapper =
298       static_cast<const PassManagerBuilderWrapper &>(Builder);
299   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
300   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
301   PM.add(
302       createHWAddressSanitizerLegacyPassPass(/*CompileKernel*/ false, Recover));
303 }
304 
305 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
306                                             legacy::PassManagerBase &PM) {
307   PM.add(createHWAddressSanitizerLegacyPassPass(
308       /*CompileKernel*/ true, /*Recover*/ true));
309 }
310 
311 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
312                                              legacy::PassManagerBase &PM,
313                                              bool CompileKernel) {
314   const PassManagerBuilderWrapper &BuilderWrapper =
315       static_cast<const PassManagerBuilderWrapper&>(Builder);
316   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
317   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
318   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
319   PM.add(createMemorySanitizerLegacyPassPass(
320       MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel}));
321 
322   // MemorySanitizer inserts complex instrumentation that mostly follows
323   // the logic of the original code, but operates on "shadow" values.
324   // It can benefit from re-running some general purpose optimization passes.
325   if (Builder.OptLevel > 0) {
326     PM.add(createEarlyCSEPass());
327     PM.add(createReassociatePass());
328     PM.add(createLICMPass());
329     PM.add(createGVNPass());
330     PM.add(createInstructionCombiningPass());
331     PM.add(createDeadStoreEliminationPass());
332   }
333 }
334 
335 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
336                                    legacy::PassManagerBase &PM) {
337   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
338 }
339 
340 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
341                                          legacy::PassManagerBase &PM) {
342   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
343 }
344 
345 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
346                                    legacy::PassManagerBase &PM) {
347   PM.add(createThreadSanitizerLegacyPassPass());
348 }
349 
350 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
351                                      legacy::PassManagerBase &PM) {
352   const PassManagerBuilderWrapper &BuilderWrapper =
353       static_cast<const PassManagerBuilderWrapper&>(Builder);
354   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
355   PM.add(
356       createDataFlowSanitizerLegacyPassPass(LangOpts.SanitizerBlacklistFiles));
357 }
358 
359 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
360                                          const CodeGenOptions &CodeGenOpts) {
361   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
362 
363   switch (CodeGenOpts.getVecLib()) {
364   case CodeGenOptions::Accelerate:
365     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
366     break;
367   case CodeGenOptions::MASSV:
368     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
369     break;
370   case CodeGenOptions::SVML:
371     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
372     break;
373   default:
374     break;
375   }
376   return TLII;
377 }
378 
379 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
380                                   legacy::PassManager *MPM) {
381   llvm::SymbolRewriter::RewriteDescriptorList DL;
382 
383   llvm::SymbolRewriter::RewriteMapParser MapParser;
384   for (const auto &MapFile : Opts.RewriteMapFiles)
385     MapParser.parse(MapFile, &DL);
386 
387   MPM->add(createRewriteSymbolsPass(DL));
388 }
389 
390 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
391   switch (CodeGenOpts.OptimizationLevel) {
392   default:
393     llvm_unreachable("Invalid optimization level!");
394   case 0:
395     return CodeGenOpt::None;
396   case 1:
397     return CodeGenOpt::Less;
398   case 2:
399     return CodeGenOpt::Default; // O2/Os/Oz
400   case 3:
401     return CodeGenOpt::Aggressive;
402   }
403 }
404 
405 static Optional<llvm::CodeModel::Model>
406 getCodeModel(const CodeGenOptions &CodeGenOpts) {
407   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
408                            .Case("tiny", llvm::CodeModel::Tiny)
409                            .Case("small", llvm::CodeModel::Small)
410                            .Case("kernel", llvm::CodeModel::Kernel)
411                            .Case("medium", llvm::CodeModel::Medium)
412                            .Case("large", llvm::CodeModel::Large)
413                            .Case("default", ~1u)
414                            .Default(~0u);
415   assert(CodeModel != ~0u && "invalid code model!");
416   if (CodeModel == ~1u)
417     return None;
418   return static_cast<llvm::CodeModel::Model>(CodeModel);
419 }
420 
421 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
422   if (Action == Backend_EmitObj)
423     return CGFT_ObjectFile;
424   else if (Action == Backend_EmitMCNull)
425     return CGFT_Null;
426   else {
427     assert(Action == Backend_EmitAssembly && "Invalid action!");
428     return CGFT_AssemblyFile;
429   }
430 }
431 
432 static void initTargetOptions(DiagnosticsEngine &Diags,
433                               llvm::TargetOptions &Options,
434                               const CodeGenOptions &CodeGenOpts,
435                               const clang::TargetOptions &TargetOpts,
436                               const LangOptions &LangOpts,
437                               const HeaderSearchOptions &HSOpts) {
438   Options.ThreadModel =
439       llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
440           .Case("posix", llvm::ThreadModel::POSIX)
441           .Case("single", llvm::ThreadModel::Single);
442 
443   // Set float ABI type.
444   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
445           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
446          "Invalid Floating Point ABI!");
447   Options.FloatABIType =
448       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
449           .Case("soft", llvm::FloatABI::Soft)
450           .Case("softfp", llvm::FloatABI::Soft)
451           .Case("hard", llvm::FloatABI::Hard)
452           .Default(llvm::FloatABI::Default);
453 
454   // Set FP fusion mode.
455   switch (LangOpts.getDefaultFPContractMode()) {
456   case LangOptions::FPM_Off:
457     // Preserve any contraction performed by the front-end.  (Strict performs
458     // splitting of the muladd intrinsic in the backend.)
459     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
460     break;
461   case LangOptions::FPM_On:
462     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
463     break;
464   case LangOptions::FPM_Fast:
465     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
466     break;
467   }
468 
469   Options.UseInitArray = CodeGenOpts.UseInitArray;
470   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
471   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
472   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
473 
474   // Set EABI version.
475   Options.EABIVersion = TargetOpts.EABIVersion;
476 
477   if (LangOpts.SjLjExceptions)
478     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
479   if (LangOpts.SEHExceptions)
480     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
481   if (LangOpts.DWARFExceptions)
482     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
483   if (LangOpts.WasmExceptions)
484     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
485 
486   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
487   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
488   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
489   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
490   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
491 
492   Options.BBSections =
493       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
494           .Case("all", llvm::BasicBlockSection::All)
495           .Case("labels", llvm::BasicBlockSection::Labels)
496           .StartsWith("list=", llvm::BasicBlockSection::List)
497           .Case("none", llvm::BasicBlockSection::None)
498           .Default(llvm::BasicBlockSection::None);
499 
500   if (Options.BBSections == llvm::BasicBlockSection::List) {
501     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
502         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
503     if (!MBOrErr)
504       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
505           << MBOrErr.getError().message();
506     else
507       Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
508   }
509 
510   Options.FunctionSections = CodeGenOpts.FunctionSections;
511   Options.DataSections = CodeGenOpts.DataSections;
512   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
513   Options.UniqueBasicBlockSectionNames =
514       CodeGenOpts.UniqueBasicBlockSectionNames;
515   Options.TLSSize = CodeGenOpts.TLSSize;
516   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
517   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
518   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
519   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
520   Options.EmitAddrsig = CodeGenOpts.Addrsig;
521   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
522   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
523   Options.ValueTrackingVariableLocations =
524       CodeGenOpts.ValueTrackingVariableLocations;
525   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
526 
527   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
528   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
529   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
530   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
531   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
532   Options.MCOptions.MCIncrementalLinkerCompatible =
533       CodeGenOpts.IncrementalLinkerCompatible;
534   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
535   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
536   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
537   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
538   Options.MCOptions.ABIName = TargetOpts.ABI;
539   for (const auto &Entry : HSOpts.UserEntries)
540     if (!Entry.IsFramework &&
541         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
542          Entry.Group == frontend::IncludeDirGroup::Angled ||
543          Entry.Group == frontend::IncludeDirGroup::System))
544       Options.MCOptions.IASSearchPaths.push_back(
545           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
546   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
547   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
548 }
549 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
550   if (CodeGenOpts.DisableGCov)
551     return None;
552   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
553     return None;
554   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
555   // LLVM's -default-gcov-version flag is set to something invalid.
556   GCOVOptions Options;
557   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
558   Options.EmitData = CodeGenOpts.EmitGcovArcs;
559   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
560   Options.NoRedZone = CodeGenOpts.DisableRedZone;
561   Options.Filter = CodeGenOpts.ProfileFilterFiles;
562   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
563   return Options;
564 }
565 
566 static Optional<InstrProfOptions>
567 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
568                     const LangOptions &LangOpts) {
569   if (!CodeGenOpts.hasProfileClangInstr())
570     return None;
571   InstrProfOptions Options;
572   Options.NoRedZone = CodeGenOpts.DisableRedZone;
573   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
574 
575   // TODO: Surface the option to emit atomic profile counter increments at
576   // the driver level.
577   Options.Atomic = LangOpts.Sanitize.has(SanitizerKind::Thread);
578   return Options;
579 }
580 
581 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
582                                       legacy::FunctionPassManager &FPM) {
583   // Handle disabling of all LLVM passes, where we want to preserve the
584   // internal module before any optimization.
585   if (CodeGenOpts.DisableLLVMPasses)
586     return;
587 
588   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
589   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
590   // are inserted before PMBuilder ones - they'd get the default-constructed
591   // TLI with an unknown target otherwise.
592   Triple TargetTriple(TheModule->getTargetTriple());
593   std::unique_ptr<TargetLibraryInfoImpl> TLII(
594       createTLII(TargetTriple, CodeGenOpts));
595 
596   // If we reached here with a non-empty index file name, then the index file
597   // was empty and we are not performing ThinLTO backend compilation (used in
598   // testing in a distributed build environment). Drop any the type test
599   // assume sequences inserted for whole program vtables so that codegen doesn't
600   // complain.
601   if (!CodeGenOpts.ThinLTOIndexFile.empty())
602     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
603                                      /*ImportSummary=*/nullptr,
604                                      /*DropTypeTests=*/true));
605 
606   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
607 
608   // At O0 and O1 we only run the always inliner which is more efficient. At
609   // higher optimization levels we run the normal inliner.
610   if (CodeGenOpts.OptimizationLevel <= 1) {
611     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
612                                       !CodeGenOpts.DisableLifetimeMarkers) ||
613                                      LangOpts.Coroutines);
614     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
615   } else {
616     // We do not want to inline hot callsites for SamplePGO module-summary build
617     // because profile annotation will happen again in ThinLTO backend, and we
618     // want the IR of the hot path to match the profile.
619     PMBuilder.Inliner = createFunctionInliningPass(
620         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
621         (!CodeGenOpts.SampleProfileFile.empty() &&
622          CodeGenOpts.PrepareForThinLTO));
623   }
624 
625   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
626   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
627   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
628   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
629   // Only enable CGProfilePass when using integrated assembler, since
630   // non-integrated assemblers don't recognize .cgprofile section.
631   PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
632 
633   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
634   // Loop interleaving in the loop vectorizer has historically been set to be
635   // enabled when loop unrolling is enabled.
636   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
637   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
638   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
639   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
640   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
641 
642   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
643 
644   if (TM)
645     TM->adjustPassManager(PMBuilder);
646 
647   if (CodeGenOpts.DebugInfoForProfiling ||
648       !CodeGenOpts.SampleProfileFile.empty())
649     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
650                            addAddDiscriminatorsPass);
651 
652   // In ObjC ARC mode, add the main ARC optimization passes.
653   if (LangOpts.ObjCAutoRefCount) {
654     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
655                            addObjCARCExpandPass);
656     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
657                            addObjCARCAPElimPass);
658     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
659                            addObjCARCOptPass);
660   }
661 
662   if (LangOpts.Coroutines)
663     addCoroutinePassesToExtensionPoints(PMBuilder);
664 
665   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
666     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
667                            addBoundsCheckingPass);
668     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
669                            addBoundsCheckingPass);
670   }
671 
672   if (CodeGenOpts.SanitizeCoverageType ||
673       CodeGenOpts.SanitizeCoverageIndirectCalls ||
674       CodeGenOpts.SanitizeCoverageTraceCmp) {
675     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
676                            addSanitizerCoveragePass);
677     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
678                            addSanitizerCoveragePass);
679   }
680 
681   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
682     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
683                            addAddressSanitizerPasses);
684     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
685                            addAddressSanitizerPasses);
686   }
687 
688   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
689     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
690                            addKernelAddressSanitizerPasses);
691     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
692                            addKernelAddressSanitizerPasses);
693   }
694 
695   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
696     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
697                            addHWAddressSanitizerPasses);
698     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
699                            addHWAddressSanitizerPasses);
700   }
701 
702   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
703     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
704                            addKernelHWAddressSanitizerPasses);
705     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
706                            addKernelHWAddressSanitizerPasses);
707   }
708 
709   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
710     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
711                            addMemorySanitizerPass);
712     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
713                            addMemorySanitizerPass);
714   }
715 
716   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
717     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
718                            addKernelMemorySanitizerPass);
719     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
720                            addKernelMemorySanitizerPass);
721   }
722 
723   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
724     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
725                            addThreadSanitizerPass);
726     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
727                            addThreadSanitizerPass);
728   }
729 
730   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
731     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
732                            addDataFlowSanitizerPass);
733     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
734                            addDataFlowSanitizerPass);
735   }
736 
737   // Set up the per-function pass manager.
738   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
739   if (CodeGenOpts.VerifyModule)
740     FPM.add(createVerifierPass());
741 
742   // Set up the per-module pass manager.
743   if (!CodeGenOpts.RewriteMapFiles.empty())
744     addSymbolRewriterPass(CodeGenOpts, &MPM);
745 
746   // Add UniqueInternalLinkageNames Pass which renames internal linkage symbols
747   // with unique names.
748   if (CodeGenOpts.UniqueInternalLinkageNames) {
749     MPM.add(createUniqueInternalLinkageNamesPass());
750   }
751 
752   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
753     MPM.add(createGCOVProfilerPass(*Options));
754     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
755       MPM.add(createStripSymbolsPass(true));
756   }
757 
758   if (Optional<InstrProfOptions> Options =
759           getInstrProfOptions(CodeGenOpts, LangOpts))
760     MPM.add(createInstrProfilingLegacyPass(*Options, false));
761 
762   bool hasIRInstr = false;
763   if (CodeGenOpts.hasProfileIRInstr()) {
764     PMBuilder.EnablePGOInstrGen = true;
765     hasIRInstr = true;
766   }
767   if (CodeGenOpts.hasProfileCSIRInstr()) {
768     assert(!CodeGenOpts.hasProfileCSIRUse() &&
769            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
770            "same time");
771     assert(!hasIRInstr &&
772            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
773            "same time");
774     PMBuilder.EnablePGOCSInstrGen = true;
775     hasIRInstr = true;
776   }
777   if (hasIRInstr) {
778     if (!CodeGenOpts.InstrProfileOutput.empty())
779       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
780     else
781       PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
782   }
783   if (CodeGenOpts.hasProfileIRUse()) {
784     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
785     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
786   }
787 
788   if (!CodeGenOpts.SampleProfileFile.empty())
789     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
790 
791   PMBuilder.populateFunctionPassManager(FPM);
792   PMBuilder.populateModulePassManager(MPM);
793 }
794 
795 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
796   SmallVector<const char *, 16> BackendArgs;
797   BackendArgs.push_back("clang"); // Fake program name.
798   if (!CodeGenOpts.DebugPass.empty()) {
799     BackendArgs.push_back("-debug-pass");
800     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
801   }
802   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
803     BackendArgs.push_back("-limit-float-precision");
804     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
805   }
806   BackendArgs.push_back(nullptr);
807   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
808                                     BackendArgs.data());
809 }
810 
811 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
812   // Create the TargetMachine for generating code.
813   std::string Error;
814   std::string Triple = TheModule->getTargetTriple();
815   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
816   if (!TheTarget) {
817     if (MustCreateTM)
818       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
819     return;
820   }
821 
822   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
823   std::string FeaturesStr =
824       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
825   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
826   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
827 
828   llvm::TargetOptions Options;
829   initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
830   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
831                                           Options, RM, CM, OptLevel));
832 }
833 
834 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
835                                        BackendAction Action,
836                                        raw_pwrite_stream &OS,
837                                        raw_pwrite_stream *DwoOS) {
838   // Add LibraryInfo.
839   llvm::Triple TargetTriple(TheModule->getTargetTriple());
840   std::unique_ptr<TargetLibraryInfoImpl> TLII(
841       createTLII(TargetTriple, CodeGenOpts));
842   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
843 
844   // Normal mode, emit a .s or .o file by running the code generator. Note,
845   // this also adds codegenerator level optimization passes.
846   CodeGenFileType CGFT = getCodeGenFileType(Action);
847 
848   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
849   // "codegen" passes so that it isn't run multiple times when there is
850   // inlining happening.
851   if (CodeGenOpts.OptimizationLevel > 0)
852     CodeGenPasses.add(createObjCARCContractPass());
853 
854   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
855                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
856     Diags.Report(diag::err_fe_unable_to_interface_with_target);
857     return false;
858   }
859 
860   return true;
861 }
862 
863 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
864                                       std::unique_ptr<raw_pwrite_stream> OS) {
865   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
866 
867   setCommandLineOpts(CodeGenOpts);
868 
869   bool UsesCodeGen = (Action != Backend_EmitNothing &&
870                       Action != Backend_EmitBC &&
871                       Action != Backend_EmitLL);
872   CreateTargetMachine(UsesCodeGen);
873 
874   if (UsesCodeGen && !TM)
875     return;
876   if (TM)
877     TheModule->setDataLayout(TM->createDataLayout());
878 
879   legacy::PassManager PerModulePasses;
880   PerModulePasses.add(
881       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
882 
883   legacy::FunctionPassManager PerFunctionPasses(TheModule);
884   PerFunctionPasses.add(
885       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
886 
887   CreatePasses(PerModulePasses, PerFunctionPasses);
888 
889   legacy::PassManager CodeGenPasses;
890   CodeGenPasses.add(
891       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
892 
893   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
894 
895   switch (Action) {
896   case Backend_EmitNothing:
897     break;
898 
899   case Backend_EmitBC:
900     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
901       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
902         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
903         if (!ThinLinkOS)
904           return;
905       }
906       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
907                                CodeGenOpts.EnableSplitLTOUnit);
908       PerModulePasses.add(createWriteThinLTOBitcodePass(
909           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
910     } else {
911       // Emit a module summary by default for Regular LTO except for ld64
912       // targets
913       bool EmitLTOSummary =
914           (CodeGenOpts.PrepareForLTO &&
915            !CodeGenOpts.DisableLLVMPasses &&
916            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
917                llvm::Triple::Apple);
918       if (EmitLTOSummary) {
919         if (!TheModule->getModuleFlag("ThinLTO"))
920           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
921         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
922                                  uint32_t(1));
923       }
924 
925       PerModulePasses.add(createBitcodeWriterPass(
926           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
927     }
928     break;
929 
930   case Backend_EmitLL:
931     PerModulePasses.add(
932         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
933     break;
934 
935   default:
936     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
937       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
938       if (!DwoOS)
939         return;
940     }
941     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
942                        DwoOS ? &DwoOS->os() : nullptr))
943       return;
944   }
945 
946   // Before executing passes, print the final values of the LLVM options.
947   cl::PrintOptionValues();
948 
949   // Run passes. For now we do all passes at once, but eventually we
950   // would like to have the option of streaming code generation.
951 
952   {
953     PrettyStackTraceString CrashInfo("Per-function optimization");
954     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
955 
956     PerFunctionPasses.doInitialization();
957     for (Function &F : *TheModule)
958       if (!F.isDeclaration())
959         PerFunctionPasses.run(F);
960     PerFunctionPasses.doFinalization();
961   }
962 
963   {
964     PrettyStackTraceString CrashInfo("Per-module optimization passes");
965     llvm::TimeTraceScope TimeScope("PerModulePasses");
966     PerModulePasses.run(*TheModule);
967   }
968 
969   {
970     PrettyStackTraceString CrashInfo("Code generation");
971     llvm::TimeTraceScope TimeScope("CodeGenPasses");
972     CodeGenPasses.run(*TheModule);
973   }
974 
975   if (ThinLinkOS)
976     ThinLinkOS->keep();
977   if (DwoOS)
978     DwoOS->keep();
979 }
980 
981 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
982   switch (Opts.OptimizationLevel) {
983   default:
984     llvm_unreachable("Invalid optimization level!");
985 
986   case 1:
987     return PassBuilder::OptimizationLevel::O1;
988 
989   case 2:
990     switch (Opts.OptimizeSize) {
991     default:
992       llvm_unreachable("Invalid optimization level for size!");
993 
994     case 0:
995       return PassBuilder::OptimizationLevel::O2;
996 
997     case 1:
998       return PassBuilder::OptimizationLevel::Os;
999 
1000     case 2:
1001       return PassBuilder::OptimizationLevel::Oz;
1002     }
1003 
1004   case 3:
1005     return PassBuilder::OptimizationLevel::O3;
1006   }
1007 }
1008 
1009 static void addCoroutinePassesAtO0(ModulePassManager &MPM,
1010                                    const LangOptions &LangOpts,
1011                                    const CodeGenOptions &CodeGenOpts) {
1012   if (!LangOpts.Coroutines)
1013     return;
1014 
1015   MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass()));
1016 
1017   CGSCCPassManager CGPM(CodeGenOpts.DebugPassManager);
1018   CGPM.addPass(CoroSplitPass());
1019   CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass()));
1020   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1021 
1022   MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass()));
1023 }
1024 
1025 static void addSanitizersAtO0(ModulePassManager &MPM,
1026                               const Triple &TargetTriple,
1027                               const LangOptions &LangOpts,
1028                               const CodeGenOptions &CodeGenOpts) {
1029   if (CodeGenOpts.SanitizeCoverageType ||
1030       CodeGenOpts.SanitizeCoverageIndirectCalls ||
1031       CodeGenOpts.SanitizeCoverageTraceCmp) {
1032     auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1033     MPM.addPass(ModuleSanitizerCoveragePass(
1034         SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1035         CodeGenOpts.SanitizeCoverageBlocklistFiles));
1036   }
1037 
1038   auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1039     MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1040     bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1041     MPM.addPass(createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1042         CompileKernel, Recover, CodeGenOpts.SanitizeAddressUseAfterScope)));
1043     bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1044     MPM.addPass(
1045         ModuleAddressSanitizerPass(CompileKernel, Recover, ModuleUseAfterScope,
1046                                    CodeGenOpts.SanitizeAddressUseOdrIndicator));
1047   };
1048 
1049   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1050     ASanPass(SanitizerKind::Address, /*CompileKernel=*/false);
1051   }
1052 
1053   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
1054     ASanPass(SanitizerKind::KernelAddress, /*CompileKernel=*/true);
1055   }
1056 
1057   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1058     bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1059     int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1060     MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1061     MPM.addPass(createModuleToFunctionPassAdaptor(
1062         MemorySanitizerPass({TrackOrigins, Recover, false})));
1063   }
1064 
1065   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
1066     MPM.addPass(createModuleToFunctionPassAdaptor(
1067         MemorySanitizerPass({0, false, /*Kernel=*/true})));
1068   }
1069 
1070   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1071     MPM.addPass(ThreadSanitizerPass());
1072     MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1073   }
1074 }
1075 
1076 /// A clean version of `EmitAssembly` that uses the new pass manager.
1077 ///
1078 /// Not all features are currently supported in this system, but where
1079 /// necessary it falls back to the legacy pass manager to at least provide
1080 /// basic functionality.
1081 ///
1082 /// This API is planned to have its functionality finished and then to replace
1083 /// `EmitAssembly` at some point in the future when the default switches.
1084 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1085     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1086   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
1087   setCommandLineOpts(CodeGenOpts);
1088 
1089   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1090                           Action != Backend_EmitBC &&
1091                           Action != Backend_EmitLL);
1092   CreateTargetMachine(RequiresCodeGen);
1093 
1094   if (RequiresCodeGen && !TM)
1095     return;
1096   if (TM)
1097     TheModule->setDataLayout(TM->createDataLayout());
1098 
1099   Optional<PGOOptions> PGOOpt;
1100 
1101   if (CodeGenOpts.hasProfileIRInstr())
1102     // -fprofile-generate.
1103     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1104                             ? std::string(DefaultProfileGenName)
1105                             : CodeGenOpts.InstrProfileOutput,
1106                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1107                         CodeGenOpts.DebugInfoForProfiling);
1108   else if (CodeGenOpts.hasProfileIRUse()) {
1109     // -fprofile-use.
1110     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1111                                                     : PGOOptions::NoCSAction;
1112     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1113                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1114                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1115   } else if (!CodeGenOpts.SampleProfileFile.empty())
1116     // -fprofile-sample-use
1117     PGOOpt =
1118         PGOOptions(CodeGenOpts.SampleProfileFile, "",
1119                    CodeGenOpts.ProfileRemappingFile, PGOOptions::SampleUse,
1120                    PGOOptions::NoCSAction, CodeGenOpts.DebugInfoForProfiling);
1121   else if (CodeGenOpts.DebugInfoForProfiling)
1122     // -fdebug-info-for-profiling
1123     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1124                         PGOOptions::NoCSAction, true);
1125 
1126   // Check to see if we want to generate a CS profile.
1127   if (CodeGenOpts.hasProfileCSIRInstr()) {
1128     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1129            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1130            "the same time");
1131     if (PGOOpt.hasValue()) {
1132       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1133              PGOOpt->Action != PGOOptions::SampleUse &&
1134              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1135              " pass");
1136       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1137                                      ? std::string(DefaultProfileGenName)
1138                                      : CodeGenOpts.InstrProfileOutput;
1139       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1140     } else
1141       PGOOpt = PGOOptions("",
1142                           CodeGenOpts.InstrProfileOutput.empty()
1143                               ? std::string(DefaultProfileGenName)
1144                               : CodeGenOpts.InstrProfileOutput,
1145                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1146                           CodeGenOpts.DebugInfoForProfiling);
1147   }
1148 
1149   PipelineTuningOptions PTO;
1150   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1151   // For historical reasons, loop interleaving is set to mirror setting for loop
1152   // unrolling.
1153   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1154   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1155   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1156   // Only enable CGProfilePass when using integrated assembler, since
1157   // non-integrated assemblers don't recognize .cgprofile section.
1158   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1159   PTO.Coroutines = LangOpts.Coroutines;
1160 
1161   PassInstrumentationCallbacks PIC;
1162   StandardInstrumentations SI(CodeGenOpts.DebugPassManager);
1163   SI.registerCallbacks(PIC);
1164   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1165 
1166   // Attempt to load pass plugins and register their callbacks with PB.
1167   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1168     auto PassPlugin = PassPlugin::Load(PluginFN);
1169     if (PassPlugin) {
1170       PassPlugin->registerPassBuilderCallbacks(PB);
1171     } else {
1172       Diags.Report(diag::err_fe_unable_to_load_plugin)
1173           << PluginFN << toString(PassPlugin.takeError());
1174     }
1175   }
1176 #define HANDLE_EXTENSION(Ext)                                                  \
1177   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1178 #include "llvm/Support/Extension.def"
1179 
1180   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
1181   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
1182   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
1183   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
1184 
1185   // Register the AA manager first so that our version is the one used.
1186   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1187 
1188   // Register the target library analysis directly and give it a customized
1189   // preset TLI.
1190   Triple TargetTriple(TheModule->getTargetTriple());
1191   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1192       createTLII(TargetTriple, CodeGenOpts));
1193   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1194 
1195   // Register all the basic analyses with the managers.
1196   PB.registerModuleAnalyses(MAM);
1197   PB.registerCGSCCAnalyses(CGAM);
1198   PB.registerFunctionAnalyses(FAM);
1199   PB.registerLoopAnalyses(LAM);
1200   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1201 
1202   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
1203 
1204   if (!CodeGenOpts.DisableLLVMPasses) {
1205     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1206     bool IsLTO = CodeGenOpts.PrepareForLTO;
1207 
1208     if (CodeGenOpts.OptimizationLevel == 0) {
1209       // If we reached here with a non-empty index file name, then the index
1210       // file was empty and we are not performing ThinLTO backend compilation
1211       // (used in testing in a distributed build environment). Drop any the type
1212       // test assume sequences inserted for whole program vtables so that
1213       // codegen doesn't complain.
1214       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1215         MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1216                                        /*ImportSummary=*/nullptr,
1217                                        /*DropTypeTests=*/true));
1218       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1219         MPM.addPass(GCOVProfilerPass(*Options));
1220       if (Optional<InstrProfOptions> Options =
1221               getInstrProfOptions(CodeGenOpts, LangOpts))
1222         MPM.addPass(InstrProfiling(*Options, false));
1223 
1224       // Build a minimal pipeline based on the semantics required by Clang,
1225       // which is just that always inlining occurs. Further, disable generating
1226       // lifetime intrinsics to avoid enabling further optimizations during
1227       // code generation.
1228       // However, we need to insert lifetime intrinsics to avoid invalid access
1229       // caused by multithreaded coroutines.
1230       MPM.addPass(
1231           AlwaysInlinerPass(/*InsertLifetimeIntrinsics=*/LangOpts.Coroutines));
1232 
1233       // At -O0, we can still do PGO. Add all the requested passes for
1234       // instrumentation PGO, if requested.
1235       if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr ||
1236                      PGOOpt->Action == PGOOptions::IRUse))
1237         PB.addPGOInstrPassesForO0(
1238             MPM, CodeGenOpts.DebugPassManager,
1239             /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr),
1240             /* IsCS */ false, PGOOpt->ProfileFile,
1241             PGOOpt->ProfileRemappingFile);
1242 
1243       // At -O0 we directly run necessary sanitizer passes.
1244       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1245         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
1246 
1247       // Add UniqueInternalLinkageNames Pass which renames internal linkage
1248       // symbols with unique names.
1249       if (CodeGenOpts.UniqueInternalLinkageNames) {
1250         MPM.addPass(UniqueInternalLinkageNamesPass());
1251       }
1252 
1253       // Lastly, add semantically necessary passes for LTO.
1254       if (IsLTO || IsThinLTO) {
1255         MPM.addPass(CanonicalizeAliasesPass());
1256         MPM.addPass(NameAnonGlobalPass());
1257       }
1258     } else {
1259       // Map our optimization levels into one of the distinct levels used to
1260       // configure the pipeline.
1261       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1262 
1263       // If we reached here with a non-empty index file name, then the index
1264       // file was empty and we are not performing ThinLTO backend compilation
1265       // (used in testing in a distributed build environment). Drop any the type
1266       // test assume sequences inserted for whole program vtables so that
1267       // codegen doesn't complain.
1268       if (!CodeGenOpts.ThinLTOIndexFile.empty())
1269         PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1270           MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1271                                          /*ImportSummary=*/nullptr,
1272                                          /*DropTypeTests=*/true));
1273         });
1274 
1275       PB.registerPipelineStartEPCallback([](ModulePassManager &MPM) {
1276         MPM.addPass(createModuleToFunctionPassAdaptor(
1277             EntryExitInstrumenterPass(/*PostInlining=*/false)));
1278       });
1279 
1280       // Register callbacks to schedule sanitizer passes at the appropriate part of
1281       // the pipeline.
1282       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1283         PB.registerScalarOptimizerLateEPCallback(
1284             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1285               FPM.addPass(BoundsCheckingPass());
1286             });
1287 
1288       if (CodeGenOpts.SanitizeCoverageType ||
1289           CodeGenOpts.SanitizeCoverageIndirectCalls ||
1290           CodeGenOpts.SanitizeCoverageTraceCmp) {
1291         PB.registerOptimizerLastEPCallback(
1292             [this](ModulePassManager &MPM,
1293                    PassBuilder::OptimizationLevel Level) {
1294               auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1295               MPM.addPass(ModuleSanitizerCoveragePass(
1296                   SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1297                   CodeGenOpts.SanitizeCoverageBlocklistFiles));
1298             });
1299       }
1300 
1301       if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
1302         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1303         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Memory);
1304         PB.registerOptimizerLastEPCallback(
1305             [TrackOrigins, Recover](ModulePassManager &MPM,
1306                                     PassBuilder::OptimizationLevel Level) {
1307               MPM.addPass(MemorySanitizerPass({TrackOrigins, Recover, false}));
1308               MPM.addPass(createModuleToFunctionPassAdaptor(
1309                   MemorySanitizerPass({TrackOrigins, Recover, false})));
1310             });
1311       }
1312       if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1313         PB.registerOptimizerLastEPCallback(
1314             [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1315               MPM.addPass(ThreadSanitizerPass());
1316               MPM.addPass(
1317                   createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1318             });
1319       }
1320       if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
1321         bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::Address);
1322         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1323         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1324         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1325         PB.registerOptimizerLastEPCallback(
1326             [Recover, UseAfterScope, ModuleUseAfterScope, UseOdrIndicator](
1327                 ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1328               MPM.addPass(
1329                   RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1330               MPM.addPass(ModuleAddressSanitizerPass(
1331                   /*CompileKernel=*/false, Recover, ModuleUseAfterScope,
1332                   UseOdrIndicator));
1333               MPM.addPass(
1334                   createModuleToFunctionPassAdaptor(AddressSanitizerPass(
1335                       /*CompileKernel=*/false, Recover, UseAfterScope)));
1336             });
1337       }
1338       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
1339         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1340           MPM.addPass(GCOVProfilerPass(*Options));
1341         });
1342       if (Optional<InstrProfOptions> Options =
1343               getInstrProfOptions(CodeGenOpts, LangOpts))
1344         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
1345           MPM.addPass(InstrProfiling(*Options, false));
1346         });
1347 
1348       // Add UniqueInternalLinkageNames Pass which renames internal linkage
1349       // symbols with unique names.
1350       if (CodeGenOpts.UniqueInternalLinkageNames) {
1351         MPM.addPass(UniqueInternalLinkageNamesPass());
1352       }
1353 
1354       if (IsThinLTO) {
1355         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
1356             Level, CodeGenOpts.DebugPassManager);
1357         MPM.addPass(CanonicalizeAliasesPass());
1358         MPM.addPass(NameAnonGlobalPass());
1359       } else if (IsLTO) {
1360         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
1361                                                 CodeGenOpts.DebugPassManager);
1362         MPM.addPass(CanonicalizeAliasesPass());
1363         MPM.addPass(NameAnonGlobalPass());
1364       } else {
1365         MPM = PB.buildPerModuleDefaultPipeline(Level,
1366                                                CodeGenOpts.DebugPassManager);
1367       }
1368     }
1369 
1370     if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
1371       bool Recover = CodeGenOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
1372       MPM.addPass(HWAddressSanitizerPass(
1373           /*CompileKernel=*/false, Recover));
1374     }
1375     if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
1376       MPM.addPass(HWAddressSanitizerPass(
1377           /*CompileKernel=*/true, /*Recover=*/true));
1378     }
1379 
1380     if (CodeGenOpts.OptimizationLevel == 0) {
1381       // FIXME: the backends do not handle matrix intrinsics currently. Make
1382       // sure they are also lowered in O0. A lightweight version of the pass
1383       // should run in the backend pipeline on demand.
1384       if (LangOpts.MatrixTypes)
1385         MPM.addPass(
1386             createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass()));
1387 
1388       addCoroutinePassesAtO0(MPM, LangOpts, CodeGenOpts);
1389       addSanitizersAtO0(MPM, TargetTriple, LangOpts, CodeGenOpts);
1390     }
1391   }
1392 
1393   // FIXME: We still use the legacy pass manager to do code generation. We
1394   // create that pass manager here and use it as needed below.
1395   legacy::PassManager CodeGenPasses;
1396   bool NeedCodeGen = false;
1397   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1398 
1399   // Append any output we need to the pass manager.
1400   switch (Action) {
1401   case Backend_EmitNothing:
1402     break;
1403 
1404   case Backend_EmitBC:
1405     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1406       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1407         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1408         if (!ThinLinkOS)
1409           return;
1410       }
1411       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1412                                CodeGenOpts.EnableSplitLTOUnit);
1413       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1414                                                            : nullptr));
1415     } else {
1416       // Emit a module summary by default for Regular LTO except for ld64
1417       // targets
1418       bool EmitLTOSummary =
1419           (CodeGenOpts.PrepareForLTO &&
1420            !CodeGenOpts.DisableLLVMPasses &&
1421            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1422                llvm::Triple::Apple);
1423       if (EmitLTOSummary) {
1424         if (!TheModule->getModuleFlag("ThinLTO"))
1425           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1426         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1427                                  uint32_t(1));
1428       }
1429       MPM.addPass(
1430           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1431     }
1432     break;
1433 
1434   case Backend_EmitLL:
1435     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1436     break;
1437 
1438   case Backend_EmitAssembly:
1439   case Backend_EmitMCNull:
1440   case Backend_EmitObj:
1441     NeedCodeGen = true;
1442     CodeGenPasses.add(
1443         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1444     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1445       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1446       if (!DwoOS)
1447         return;
1448     }
1449     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1450                        DwoOS ? &DwoOS->os() : nullptr))
1451       // FIXME: Should we handle this error differently?
1452       return;
1453     break;
1454   }
1455 
1456   // Before executing passes, print the final values of the LLVM options.
1457   cl::PrintOptionValues();
1458 
1459   // Now that we have all of the passes ready, run them.
1460   {
1461     PrettyStackTraceString CrashInfo("Optimizer");
1462     MPM.run(*TheModule, MAM);
1463   }
1464 
1465   // Now if needed, run the legacy PM for codegen.
1466   if (NeedCodeGen) {
1467     PrettyStackTraceString CrashInfo("Code generation");
1468     CodeGenPasses.run(*TheModule);
1469   }
1470 
1471   if (ThinLinkOS)
1472     ThinLinkOS->keep();
1473   if (DwoOS)
1474     DwoOS->keep();
1475 }
1476 
1477 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1478   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1479   if (!BMsOrErr)
1480     return BMsOrErr.takeError();
1481 
1482   // The bitcode file may contain multiple modules, we want the one that is
1483   // marked as being the ThinLTO module.
1484   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1485     return *Bm;
1486 
1487   return make_error<StringError>("Could not find module summary",
1488                                  inconvertibleErrorCode());
1489 }
1490 
1491 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1492   for (BitcodeModule &BM : BMs) {
1493     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1494     if (LTOInfo && LTOInfo->IsThinLTO)
1495       return &BM;
1496   }
1497   return nullptr;
1498 }
1499 
1500 static void runThinLTOBackend(
1501     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1502     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1503     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1504     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1505     std::string ProfileRemapping, BackendAction Action) {
1506   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1507       ModuleToDefinedGVSummaries;
1508   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1509 
1510   setCommandLineOpts(CGOpts);
1511 
1512   // We can simply import the values mentioned in the combined index, since
1513   // we should only invoke this using the individual indexes written out
1514   // via a WriteIndexesThinBackend.
1515   FunctionImporter::ImportMapTy ImportList;
1516   for (auto &GlobalList : *CombinedIndex) {
1517     // Ignore entries for undefined references.
1518     if (GlobalList.second.SummaryList.empty())
1519       continue;
1520 
1521     auto GUID = GlobalList.first;
1522     for (auto &Summary : GlobalList.second.SummaryList) {
1523       // Skip the summaries for the importing module. These are included to
1524       // e.g. record required linkage changes.
1525       if (Summary->modulePath() == M->getModuleIdentifier())
1526         continue;
1527       // Add an entry to provoke importing by thinBackend.
1528       ImportList[Summary->modulePath()].insert(GUID);
1529     }
1530   }
1531 
1532   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1533   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1534 
1535   for (auto &I : ImportList) {
1536     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1537         llvm::MemoryBuffer::getFile(I.first());
1538     if (!MBOrErr) {
1539       errs() << "Error loading imported file '" << I.first()
1540              << "': " << MBOrErr.getError().message() << "\n";
1541       return;
1542     }
1543 
1544     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1545     if (!BMOrErr) {
1546       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1547         errs() << "Error loading imported file '" << I.first()
1548                << "': " << EIB.message() << '\n';
1549       });
1550       return;
1551     }
1552     ModuleMap.insert({I.first(), *BMOrErr});
1553 
1554     OwnedImports.push_back(std::move(*MBOrErr));
1555   }
1556   auto AddStream = [&](size_t Task) {
1557     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1558   };
1559   lto::Config Conf;
1560   if (CGOpts.SaveTempsFilePrefix != "") {
1561     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1562                                     /* UseInputModulePath */ false)) {
1563       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1564         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1565                << '\n';
1566       });
1567     }
1568   }
1569   Conf.CPU = TOpts.CPU;
1570   Conf.CodeModel = getCodeModel(CGOpts);
1571   Conf.MAttrs = TOpts.Features;
1572   Conf.RelocModel = CGOpts.RelocationModel;
1573   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1574   Conf.OptLevel = CGOpts.OptimizationLevel;
1575   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1576   Conf.SampleProfile = std::move(SampleProfile);
1577   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1578   // For historical reasons, loop interleaving is set to mirror setting for loop
1579   // unrolling.
1580   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1581   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1582   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1583   // Only enable CGProfilePass when using integrated assembler, since
1584   // non-integrated assemblers don't recognize .cgprofile section.
1585   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1586 
1587   // Context sensitive profile.
1588   if (CGOpts.hasProfileCSIRInstr()) {
1589     Conf.RunCSIRInstr = true;
1590     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1591   } else if (CGOpts.hasProfileCSIRUse()) {
1592     Conf.RunCSIRInstr = false;
1593     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1594   }
1595 
1596   Conf.ProfileRemapping = std::move(ProfileRemapping);
1597   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1598   Conf.DebugPassManager = CGOpts.DebugPassManager;
1599   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1600   Conf.RemarksFilename = CGOpts.OptRecordFile;
1601   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1602   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1603   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1604   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1605   switch (Action) {
1606   case Backend_EmitNothing:
1607     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1608       return false;
1609     };
1610     break;
1611   case Backend_EmitLL:
1612     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1613       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1614       return false;
1615     };
1616     break;
1617   case Backend_EmitBC:
1618     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1619       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1620       return false;
1621     };
1622     break;
1623   default:
1624     Conf.CGFileType = getCodeGenFileType(Action);
1625     break;
1626   }
1627   if (Error E = thinBackend(
1628           Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1629           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1630     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1631       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1632     });
1633   }
1634 }
1635 
1636 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1637                               const HeaderSearchOptions &HeaderOpts,
1638                               const CodeGenOptions &CGOpts,
1639                               const clang::TargetOptions &TOpts,
1640                               const LangOptions &LOpts,
1641                               const llvm::DataLayout &TDesc, Module *M,
1642                               BackendAction Action,
1643                               std::unique_ptr<raw_pwrite_stream> OS) {
1644 
1645   llvm::TimeTraceScope TimeScope("Backend");
1646 
1647   std::unique_ptr<llvm::Module> EmptyModule;
1648   if (!CGOpts.ThinLTOIndexFile.empty()) {
1649     // If we are performing a ThinLTO importing compile, load the function index
1650     // into memory and pass it into runThinLTOBackend, which will run the
1651     // function importer and invoke LTO passes.
1652     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1653         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1654                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1655     if (!IndexOrErr) {
1656       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1657                             "Error loading index file '" +
1658                             CGOpts.ThinLTOIndexFile + "': ");
1659       return;
1660     }
1661     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1662     // A null CombinedIndex means we should skip ThinLTO compilation
1663     // (LLVM will optionally ignore empty index files, returning null instead
1664     // of an error).
1665     if (CombinedIndex) {
1666       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1667         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1668                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1669                           CGOpts.ProfileRemappingFile, Action);
1670         return;
1671       }
1672       // Distributed indexing detected that nothing from the module is needed
1673       // for the final linking. So we can skip the compilation. We sill need to
1674       // output an empty object file to make sure that a linker does not fail
1675       // trying to read it. Also for some features, like CFI, we must skip
1676       // the compilation as CombinedIndex does not contain all required
1677       // information.
1678       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1679       EmptyModule->setTargetTriple(M->getTargetTriple());
1680       M = EmptyModule.get();
1681     }
1682   }
1683 
1684   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1685 
1686   if (CGOpts.ExperimentalNewPassManager)
1687     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1688   else
1689     AsmHelper.EmitAssembly(Action, std::move(OS));
1690 
1691   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1692   // DataLayout.
1693   if (AsmHelper.TM) {
1694     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1695     if (DLDesc != TDesc.getStringRepresentation()) {
1696       unsigned DiagID = Diags.getCustomDiagID(
1697           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1698                                     "expected target description '%1'");
1699       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1700     }
1701   }
1702 }
1703 
1704 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1705 // __LLVM,__bitcode section.
1706 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1707                          llvm::MemoryBufferRef Buf) {
1708   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1709     return;
1710   llvm::EmbedBitcodeInModule(
1711       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1712       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1713       &CGOpts.CmdArgs);
1714 }
1715