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