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