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/Debugify.h"
85 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
86 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
87 #include "llvm/Transforms/Utils/SymbolRewriter.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.SanitizeCoverageIgnorelistFiles));
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.getSanitizeAddressDtor();
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 void addEntryExitInstrumentationPass(const PassManagerBuilder &Builder,
371                                             legacy::PassManagerBase &PM) {
372   PM.add(createEntryExitInstrumenterPass());
373 }
374 
375 static void
376 addPostInlineEntryExitInstrumentationPass(const PassManagerBuilder &Builder,
377                                           legacy::PassManagerBase &PM) {
378   PM.add(createPostInlineEntryExitInstrumenterPass());
379 }
380 
381 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
382                                          const CodeGenOptions &CodeGenOpts) {
383   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
384 
385   switch (CodeGenOpts.getVecLib()) {
386   case CodeGenOptions::Accelerate:
387     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
388     break;
389   case CodeGenOptions::LIBMVEC:
390     switch(TargetTriple.getArch()) {
391       default:
392         break;
393       case llvm::Triple::x86_64:
394         TLII->addVectorizableFunctionsFromVecLib
395                 (TargetLibraryInfoImpl::LIBMVEC_X86);
396         break;
397     }
398     break;
399   case CodeGenOptions::MASSV:
400     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
401     break;
402   case CodeGenOptions::SVML:
403     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
404     break;
405   case CodeGenOptions::Darwin_libsystem_m:
406     TLII->addVectorizableFunctionsFromVecLib(
407         TargetLibraryInfoImpl::DarwinLibSystemM);
408     break;
409   default:
410     break;
411   }
412   return TLII;
413 }
414 
415 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
416                                   legacy::PassManager *MPM) {
417   llvm::SymbolRewriter::RewriteDescriptorList DL;
418 
419   llvm::SymbolRewriter::RewriteMapParser MapParser;
420   for (const auto &MapFile : Opts.RewriteMapFiles)
421     MapParser.parse(MapFile, &DL);
422 
423   MPM->add(createRewriteSymbolsPass(DL));
424 }
425 
426 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
427   switch (CodeGenOpts.OptimizationLevel) {
428   default:
429     llvm_unreachable("Invalid optimization level!");
430   case 0:
431     return CodeGenOpt::None;
432   case 1:
433     return CodeGenOpt::Less;
434   case 2:
435     return CodeGenOpt::Default; // O2/Os/Oz
436   case 3:
437     return CodeGenOpt::Aggressive;
438   }
439 }
440 
441 static Optional<llvm::CodeModel::Model>
442 getCodeModel(const CodeGenOptions &CodeGenOpts) {
443   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
444                            .Case("tiny", llvm::CodeModel::Tiny)
445                            .Case("small", llvm::CodeModel::Small)
446                            .Case("kernel", llvm::CodeModel::Kernel)
447                            .Case("medium", llvm::CodeModel::Medium)
448                            .Case("large", llvm::CodeModel::Large)
449                            .Case("default", ~1u)
450                            .Default(~0u);
451   assert(CodeModel != ~0u && "invalid code model!");
452   if (CodeModel == ~1u)
453     return None;
454   return static_cast<llvm::CodeModel::Model>(CodeModel);
455 }
456 
457 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
458   if (Action == Backend_EmitObj)
459     return CGFT_ObjectFile;
460   else if (Action == Backend_EmitMCNull)
461     return CGFT_Null;
462   else {
463     assert(Action == Backend_EmitAssembly && "Invalid action!");
464     return CGFT_AssemblyFile;
465   }
466 }
467 
468 static bool initTargetOptions(DiagnosticsEngine &Diags,
469                               llvm::TargetOptions &Options,
470                               const CodeGenOptions &CodeGenOpts,
471                               const clang::TargetOptions &TargetOpts,
472                               const LangOptions &LangOpts,
473                               const HeaderSearchOptions &HSOpts) {
474   switch (LangOpts.getThreadModel()) {
475   case LangOptions::ThreadModelKind::POSIX:
476     Options.ThreadModel = llvm::ThreadModel::POSIX;
477     break;
478   case LangOptions::ThreadModelKind::Single:
479     Options.ThreadModel = llvm::ThreadModel::Single;
480     break;
481   }
482 
483   // Set float ABI type.
484   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
485           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
486          "Invalid Floating Point ABI!");
487   Options.FloatABIType =
488       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
489           .Case("soft", llvm::FloatABI::Soft)
490           .Case("softfp", llvm::FloatABI::Soft)
491           .Case("hard", llvm::FloatABI::Hard)
492           .Default(llvm::FloatABI::Default);
493 
494   // Set FP fusion mode.
495   switch (LangOpts.getDefaultFPContractMode()) {
496   case LangOptions::FPM_Off:
497     // Preserve any contraction performed by the front-end.  (Strict performs
498     // splitting of the muladd intrinsic in the backend.)
499     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
500     break;
501   case LangOptions::FPM_On:
502   case LangOptions::FPM_FastHonorPragmas:
503     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
504     break;
505   case LangOptions::FPM_Fast:
506     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
507     break;
508   }
509 
510   Options.BinutilsVersion =
511       llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
512   Options.UseInitArray = CodeGenOpts.UseInitArray;
513   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
514   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
515   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
516 
517   // Set EABI version.
518   Options.EABIVersion = TargetOpts.EABIVersion;
519 
520   if (LangOpts.hasSjLjExceptions())
521     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
522   if (LangOpts.hasSEHExceptions())
523     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
524   if (LangOpts.hasDWARFExceptions())
525     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
526   if (LangOpts.hasWasmExceptions())
527     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
528 
529   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
530   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
531   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
532   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
533   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
534 
535   Options.BBSections =
536       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
537           .Case("all", llvm::BasicBlockSection::All)
538           .Case("labels", llvm::BasicBlockSection::Labels)
539           .StartsWith("list=", llvm::BasicBlockSection::List)
540           .Case("none", llvm::BasicBlockSection::None)
541           .Default(llvm::BasicBlockSection::None);
542 
543   if (Options.BBSections == llvm::BasicBlockSection::List) {
544     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
545         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
546     if (!MBOrErr) {
547       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
548           << MBOrErr.getError().message();
549       return false;
550     }
551     Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
552   }
553 
554   Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
555   Options.FunctionSections = CodeGenOpts.FunctionSections;
556   Options.DataSections = CodeGenOpts.DataSections;
557   Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
558   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
559   Options.UniqueBasicBlockSectionNames =
560       CodeGenOpts.UniqueBasicBlockSectionNames;
561   Options.StackProtectorGuard =
562       llvm::StringSwitch<llvm::StackProtectorGuards>(
563           CodeGenOpts.StackProtectorGuard)
564           .Case("tls", llvm::StackProtectorGuards::TLS)
565           .Case("global", llvm::StackProtectorGuards::Global)
566           .Case("sysreg", llvm::StackProtectorGuards::SysReg)
567           .Default(llvm::StackProtectorGuards::None);
568   Options.StackProtectorGuardOffset = CodeGenOpts.StackProtectorGuardOffset;
569   Options.StackProtectorGuardReg = CodeGenOpts.StackProtectorGuardReg;
570   Options.TLSSize = CodeGenOpts.TLSSize;
571   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
572   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
573   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
574   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
575   Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
576   Options.EmitAddrsig = CodeGenOpts.Addrsig;
577   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
578   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
579   Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI;
580   Options.PseudoProbeForProfiling = CodeGenOpts.PseudoProbeForProfiling;
581   Options.ValueTrackingVariableLocations =
582       CodeGenOpts.ValueTrackingVariableLocations;
583   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
584 
585   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
586   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
587   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
588   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
589   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
590   Options.MCOptions.MCIncrementalLinkerCompatible =
591       CodeGenOpts.IncrementalLinkerCompatible;
592   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
593   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
594   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
595   Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
596   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
597   Options.MCOptions.ABIName = TargetOpts.ABI;
598   for (const auto &Entry : HSOpts.UserEntries)
599     if (!Entry.IsFramework &&
600         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
601          Entry.Group == frontend::IncludeDirGroup::Angled ||
602          Entry.Group == frontend::IncludeDirGroup::System))
603       Options.MCOptions.IASSearchPaths.push_back(
604           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
605   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
606   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
607   Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
608 
609   return true;
610 }
611 
612 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
613                                             const LangOptions &LangOpts) {
614   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
615     return None;
616   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
617   // LLVM's -default-gcov-version flag is set to something invalid.
618   GCOVOptions Options;
619   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
620   Options.EmitData = CodeGenOpts.EmitGcovArcs;
621   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
622   Options.NoRedZone = CodeGenOpts.DisableRedZone;
623   Options.Filter = CodeGenOpts.ProfileFilterFiles;
624   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
625   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
626   return Options;
627 }
628 
629 static Optional<InstrProfOptions>
630 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
631                     const LangOptions &LangOpts) {
632   if (!CodeGenOpts.hasProfileClangInstr())
633     return None;
634   InstrProfOptions Options;
635   Options.NoRedZone = CodeGenOpts.DisableRedZone;
636   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
637   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
638   return Options;
639 }
640 
641 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
642                                       legacy::FunctionPassManager &FPM) {
643   // Handle disabling of all LLVM passes, where we want to preserve the
644   // internal module before any optimization.
645   if (CodeGenOpts.DisableLLVMPasses)
646     return;
647 
648   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
649   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
650   // are inserted before PMBuilder ones - they'd get the default-constructed
651   // TLI with an unknown target otherwise.
652   Triple TargetTriple(TheModule->getTargetTriple());
653   std::unique_ptr<TargetLibraryInfoImpl> TLII(
654       createTLII(TargetTriple, CodeGenOpts));
655 
656   // If we reached here with a non-empty index file name, then the index file
657   // was empty and we are not performing ThinLTO backend compilation (used in
658   // testing in a distributed build environment). Drop any the type test
659   // assume sequences inserted for whole program vtables so that codegen doesn't
660   // complain.
661   if (!CodeGenOpts.ThinLTOIndexFile.empty())
662     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
663                                      /*ImportSummary=*/nullptr,
664                                      /*DropTypeTests=*/true));
665 
666   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
667 
668   // At O0 and O1 we only run the always inliner which is more efficient. At
669   // higher optimization levels we run the normal inliner.
670   if (CodeGenOpts.OptimizationLevel <= 1) {
671     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
672                                       !CodeGenOpts.DisableLifetimeMarkers) ||
673                                      LangOpts.Coroutines);
674     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
675   } else {
676     // We do not want to inline hot callsites for SamplePGO module-summary build
677     // because profile annotation will happen again in ThinLTO backend, and we
678     // want the IR of the hot path to match the profile.
679     PMBuilder.Inliner = createFunctionInliningPass(
680         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
681         (!CodeGenOpts.SampleProfileFile.empty() &&
682          CodeGenOpts.PrepareForThinLTO));
683   }
684 
685   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
686   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
687   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
688   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
689   // Only enable CGProfilePass when using integrated assembler, since
690   // non-integrated assemblers don't recognize .cgprofile section.
691   PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
692 
693   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
694   // Loop interleaving in the loop vectorizer has historically been set to be
695   // enabled when loop unrolling is enabled.
696   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
697   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
698   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
699   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
700   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
701 
702   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
703 
704   if (TM)
705     TM->adjustPassManager(PMBuilder);
706 
707   if (CodeGenOpts.DebugInfoForProfiling ||
708       !CodeGenOpts.SampleProfileFile.empty())
709     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
710                            addAddDiscriminatorsPass);
711 
712   // In ObjC ARC mode, add the main ARC optimization passes.
713   if (LangOpts.ObjCAutoRefCount) {
714     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
715                            addObjCARCExpandPass);
716     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
717                            addObjCARCAPElimPass);
718     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
719                            addObjCARCOptPass);
720   }
721 
722   if (LangOpts.Coroutines)
723     addCoroutinePassesToExtensionPoints(PMBuilder);
724 
725   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
726     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
727                            addMemProfilerPasses);
728     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
729                            addMemProfilerPasses);
730   }
731 
732   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
733     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
734                            addBoundsCheckingPass);
735     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
736                            addBoundsCheckingPass);
737   }
738 
739   if (CodeGenOpts.SanitizeCoverageType ||
740       CodeGenOpts.SanitizeCoverageIndirectCalls ||
741       CodeGenOpts.SanitizeCoverageTraceCmp) {
742     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
743                            addSanitizerCoveragePass);
744     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
745                            addSanitizerCoveragePass);
746   }
747 
748   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
749     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
750                            addAddressSanitizerPasses);
751     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
752                            addAddressSanitizerPasses);
753   }
754 
755   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
756     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
757                            addKernelAddressSanitizerPasses);
758     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
759                            addKernelAddressSanitizerPasses);
760   }
761 
762   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
763     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
764                            addHWAddressSanitizerPasses);
765     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
766                            addHWAddressSanitizerPasses);
767   }
768 
769   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
770     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
771                            addKernelHWAddressSanitizerPasses);
772     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
773                            addKernelHWAddressSanitizerPasses);
774   }
775 
776   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
777     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
778                            addMemorySanitizerPass);
779     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
780                            addMemorySanitizerPass);
781   }
782 
783   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
784     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
785                            addKernelMemorySanitizerPass);
786     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
787                            addKernelMemorySanitizerPass);
788   }
789 
790   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
791     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
792                            addThreadSanitizerPass);
793     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
794                            addThreadSanitizerPass);
795   }
796 
797   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
798     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
799                            addDataFlowSanitizerPass);
800     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
801                            addDataFlowSanitizerPass);
802   }
803 
804   if (CodeGenOpts.InstrumentFunctions ||
805       CodeGenOpts.InstrumentFunctionEntryBare ||
806       CodeGenOpts.InstrumentFunctionsAfterInlining ||
807       CodeGenOpts.InstrumentForProfiling) {
808     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
809                            addEntryExitInstrumentationPass);
810     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
811                            addEntryExitInstrumentationPass);
812     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
813                            addPostInlineEntryExitInstrumentationPass);
814     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
815                            addPostInlineEntryExitInstrumentationPass);
816   }
817 
818   // Set up the per-function pass manager.
819   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
820   if (CodeGenOpts.VerifyModule)
821     FPM.add(createVerifierPass());
822 
823   // Set up the per-module pass manager.
824   if (!CodeGenOpts.RewriteMapFiles.empty())
825     addSymbolRewriterPass(CodeGenOpts, &MPM);
826 
827   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) {
828     MPM.add(createGCOVProfilerPass(*Options));
829     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
830       MPM.add(createStripSymbolsPass(true));
831   }
832 
833   if (Optional<InstrProfOptions> Options =
834           getInstrProfOptions(CodeGenOpts, LangOpts))
835     MPM.add(createInstrProfilingLegacyPass(*Options, false));
836 
837   bool hasIRInstr = false;
838   if (CodeGenOpts.hasProfileIRInstr()) {
839     PMBuilder.EnablePGOInstrGen = true;
840     hasIRInstr = true;
841   }
842   if (CodeGenOpts.hasProfileCSIRInstr()) {
843     assert(!CodeGenOpts.hasProfileCSIRUse() &&
844            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
845            "same time");
846     assert(!hasIRInstr &&
847            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
848            "same time");
849     PMBuilder.EnablePGOCSInstrGen = true;
850     hasIRInstr = true;
851   }
852   if (hasIRInstr) {
853     if (!CodeGenOpts.InstrProfileOutput.empty())
854       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
855     else
856       PMBuilder.PGOInstrGen = std::string(DefaultProfileGenName);
857   }
858   if (CodeGenOpts.hasProfileIRUse()) {
859     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
860     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
861   }
862 
863   if (!CodeGenOpts.SampleProfileFile.empty())
864     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
865 
866   PMBuilder.populateFunctionPassManager(FPM);
867   PMBuilder.populateModulePassManager(MPM);
868 }
869 
870 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
871   SmallVector<const char *, 16> BackendArgs;
872   BackendArgs.push_back("clang"); // Fake program name.
873   if (!CodeGenOpts.DebugPass.empty()) {
874     BackendArgs.push_back("-debug-pass");
875     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
876     // New PM supports structure dumping. Old PM is still used for codegen,
877     // so we need to pass both options.
878     if (!CodeGenOpts.LegacyPassManager && CodeGenOpts.DebugPass == "Structure")
879       BackendArgs.push_back("-debug-pass-structure");
880   }
881   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
882     BackendArgs.push_back("-limit-float-precision");
883     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
884   }
885   // Check for the default "clang" invocation that won't set any cl::opt values.
886   // Skip trying to parse the command line invocation to avoid the issues
887   // described below.
888   if (BackendArgs.size() == 1)
889     return;
890   BackendArgs.push_back(nullptr);
891   // FIXME: The command line parser below is not thread-safe and shares a global
892   // state, so this call might crash or overwrite the options of another Clang
893   // instance in the same process.
894   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
895                                     BackendArgs.data());
896 }
897 
898 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
899   // Create the TargetMachine for generating code.
900   std::string Error;
901   std::string Triple = TheModule->getTargetTriple();
902   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
903   if (!TheTarget) {
904     if (MustCreateTM)
905       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
906     return;
907   }
908 
909   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
910   std::string FeaturesStr =
911       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
912   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
913   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
914 
915   llvm::TargetOptions Options;
916   if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
917                          HSOpts))
918     return;
919   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
920                                           Options, RM, CM, OptLevel));
921 }
922 
923 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
924                                        BackendAction Action,
925                                        raw_pwrite_stream &OS,
926                                        raw_pwrite_stream *DwoOS) {
927   // Add LibraryInfo.
928   llvm::Triple TargetTriple(TheModule->getTargetTriple());
929   std::unique_ptr<TargetLibraryInfoImpl> TLII(
930       createTLII(TargetTriple, CodeGenOpts));
931   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
932 
933   // Normal mode, emit a .s or .o file by running the code generator. Note,
934   // this also adds codegenerator level optimization passes.
935   CodeGenFileType CGFT = getCodeGenFileType(Action);
936 
937   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
938   // "codegen" passes so that it isn't run multiple times when there is
939   // inlining happening.
940   if (CodeGenOpts.OptimizationLevel > 0)
941     CodeGenPasses.add(createObjCARCContractPass());
942 
943   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
944                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
945     Diags.Report(diag::err_fe_unable_to_interface_with_target);
946     return false;
947   }
948 
949   return true;
950 }
951 
952 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
953                                       std::unique_ptr<raw_pwrite_stream> OS) {
954   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
955 
956   setCommandLineOpts(CodeGenOpts);
957 
958   bool UsesCodeGen = (Action != Backend_EmitNothing &&
959                       Action != Backend_EmitBC &&
960                       Action != Backend_EmitLL);
961   CreateTargetMachine(UsesCodeGen);
962 
963   if (UsesCodeGen && !TM)
964     return;
965   if (TM)
966     TheModule->setDataLayout(TM->createDataLayout());
967 
968   DebugifyCustomPassManager PerModulePasses;
969   DebugInfoPerPassMap DIPreservationMap;
970   if (CodeGenOpts.EnableDIPreservationVerify) {
971     PerModulePasses.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
972     PerModulePasses.setDIPreservationMap(DIPreservationMap);
973 
974     if (!CodeGenOpts.DIBugsReportFilePath.empty())
975       PerModulePasses.setOrigDIVerifyBugsReportFilePath(
976           CodeGenOpts.DIBugsReportFilePath);
977   }
978   PerModulePasses.add(
979       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
980 
981   legacy::FunctionPassManager PerFunctionPasses(TheModule);
982   PerFunctionPasses.add(
983       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
984 
985   CreatePasses(PerModulePasses, PerFunctionPasses);
986 
987   legacy::PassManager CodeGenPasses;
988   CodeGenPasses.add(
989       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
990 
991   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
992 
993   switch (Action) {
994   case Backend_EmitNothing:
995     break;
996 
997   case Backend_EmitBC:
998     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
999       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1000         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1001         if (!ThinLinkOS)
1002           return;
1003       }
1004       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1005                                CodeGenOpts.EnableSplitLTOUnit);
1006       PerModulePasses.add(createWriteThinLTOBitcodePass(
1007           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1008     } else {
1009       // Emit a module summary by default for Regular LTO except for ld64
1010       // targets
1011       bool EmitLTOSummary =
1012           (CodeGenOpts.PrepareForLTO &&
1013            !CodeGenOpts.DisableLLVMPasses &&
1014            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1015                llvm::Triple::Apple);
1016       if (EmitLTOSummary) {
1017         if (!TheModule->getModuleFlag("ThinLTO"))
1018           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1019         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1020                                  uint32_t(1));
1021       }
1022 
1023       PerModulePasses.add(createBitcodeWriterPass(
1024           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1025     }
1026     break;
1027 
1028   case Backend_EmitLL:
1029     PerModulePasses.add(
1030         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1031     break;
1032 
1033   default:
1034     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1035       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1036       if (!DwoOS)
1037         return;
1038     }
1039     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1040                        DwoOS ? &DwoOS->os() : nullptr))
1041       return;
1042   }
1043 
1044   // Before executing passes, print the final values of the LLVM options.
1045   cl::PrintOptionValues();
1046 
1047   // Run passes. For now we do all passes at once, but eventually we
1048   // would like to have the option of streaming code generation.
1049 
1050   {
1051     PrettyStackTraceString CrashInfo("Per-function optimization");
1052     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
1053 
1054     PerFunctionPasses.doInitialization();
1055     for (Function &F : *TheModule)
1056       if (!F.isDeclaration())
1057         PerFunctionPasses.run(F);
1058     PerFunctionPasses.doFinalization();
1059   }
1060 
1061   {
1062     PrettyStackTraceString CrashInfo("Per-module optimization passes");
1063     llvm::TimeTraceScope TimeScope("PerModulePasses");
1064     PerModulePasses.run(*TheModule);
1065   }
1066 
1067   {
1068     PrettyStackTraceString CrashInfo("Code generation");
1069     llvm::TimeTraceScope TimeScope("CodeGenPasses");
1070     CodeGenPasses.run(*TheModule);
1071   }
1072 
1073   if (ThinLinkOS)
1074     ThinLinkOS->keep();
1075   if (DwoOS)
1076     DwoOS->keep();
1077 }
1078 
1079 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
1080   switch (Opts.OptimizationLevel) {
1081   default:
1082     llvm_unreachable("Invalid optimization level!");
1083 
1084   case 0:
1085     return PassBuilder::OptimizationLevel::O0;
1086 
1087   case 1:
1088     return PassBuilder::OptimizationLevel::O1;
1089 
1090   case 2:
1091     switch (Opts.OptimizeSize) {
1092     default:
1093       llvm_unreachable("Invalid optimization level for size!");
1094 
1095     case 0:
1096       return PassBuilder::OptimizationLevel::O2;
1097 
1098     case 1:
1099       return PassBuilder::OptimizationLevel::Os;
1100 
1101     case 2:
1102       return PassBuilder::OptimizationLevel::Oz;
1103     }
1104 
1105   case 3:
1106     return PassBuilder::OptimizationLevel::O3;
1107   }
1108 }
1109 
1110 static void addSanitizers(const Triple &TargetTriple,
1111                           const CodeGenOptions &CodeGenOpts,
1112                           const LangOptions &LangOpts, PassBuilder &PB) {
1113   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
1114                                          PassBuilder::OptimizationLevel Level) {
1115     if (CodeGenOpts.SanitizeCoverageType ||
1116         CodeGenOpts.SanitizeCoverageIndirectCalls ||
1117         CodeGenOpts.SanitizeCoverageTraceCmp) {
1118       auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1119       MPM.addPass(ModuleSanitizerCoveragePass(
1120           SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1121           CodeGenOpts.SanitizeCoverageIgnorelistFiles));
1122     }
1123 
1124     auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1125       if (LangOpts.Sanitize.has(Mask)) {
1126         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1127         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1128 
1129         MPM.addPass(
1130             MemorySanitizerPass({TrackOrigins, Recover, CompileKernel}));
1131         FunctionPassManager FPM;
1132         FPM.addPass(
1133             MemorySanitizerPass({TrackOrigins, Recover, CompileKernel}));
1134         if (Level != PassBuilder::OptimizationLevel::O0) {
1135           // MemorySanitizer inserts complex instrumentation that mostly
1136           // follows the logic of the original code, but operates on
1137           // "shadow" values. It can benefit from re-running some
1138           // general purpose optimization passes.
1139           FPM.addPass(EarlyCSEPass());
1140           // TODO: Consider add more passes like in
1141           // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
1142           // difference on size. It's not clear if the rest is still
1143           // usefull. InstCombinePass breakes
1144           // compiler-rt/test/msan/select_origin.cpp.
1145         }
1146         MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1147       }
1148     };
1149     MSanPass(SanitizerKind::Memory, false);
1150     MSanPass(SanitizerKind::KernelMemory, true);
1151 
1152     if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1153       MPM.addPass(ThreadSanitizerPass());
1154       MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1155     }
1156 
1157     auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1158       if (LangOpts.Sanitize.has(Mask)) {
1159         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1160         bool UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1161         bool ModuleUseAfterScope = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1162         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1163         llvm::AsanDtorKind DestructorKind =
1164             CodeGenOpts.getSanitizeAddressDtor();
1165         MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1166         MPM.addPass(ModuleAddressSanitizerPass(
1167             CompileKernel, Recover, ModuleUseAfterScope, UseOdrIndicator,
1168             DestructorKind));
1169         MPM.addPass(createModuleToFunctionPassAdaptor(
1170             AddressSanitizerPass(CompileKernel, Recover, UseAfterScope)));
1171       }
1172     };
1173     ASanPass(SanitizerKind::Address, false);
1174     ASanPass(SanitizerKind::KernelAddress, true);
1175 
1176     auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1177       if (LangOpts.Sanitize.has(Mask)) {
1178         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1179         MPM.addPass(HWAddressSanitizerPass(CompileKernel, Recover));
1180       }
1181     };
1182     HWASanPass(SanitizerKind::HWAddress, false);
1183     HWASanPass(SanitizerKind::KernelHWAddress, true);
1184 
1185     if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
1186       MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
1187     }
1188   });
1189 }
1190 
1191 /// A clean version of `EmitAssembly` that uses the new pass manager.
1192 ///
1193 /// Not all features are currently supported in this system, but where
1194 /// necessary it falls back to the legacy pass manager to at least provide
1195 /// basic functionality.
1196 ///
1197 /// This API is planned to have its functionality finished and then to replace
1198 /// `EmitAssembly` at some point in the future when the default switches.
1199 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
1200     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
1201   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1202   setCommandLineOpts(CodeGenOpts);
1203 
1204   bool RequiresCodeGen = (Action != Backend_EmitNothing &&
1205                           Action != Backend_EmitBC &&
1206                           Action != Backend_EmitLL);
1207   CreateTargetMachine(RequiresCodeGen);
1208 
1209   if (RequiresCodeGen && !TM)
1210     return;
1211   if (TM)
1212     TheModule->setDataLayout(TM->createDataLayout());
1213 
1214   Optional<PGOOptions> PGOOpt;
1215 
1216   if (CodeGenOpts.hasProfileIRInstr())
1217     // -fprofile-generate.
1218     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1219                             ? std::string(DefaultProfileGenName)
1220                             : CodeGenOpts.InstrProfileOutput,
1221                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1222                         CodeGenOpts.DebugInfoForProfiling);
1223   else if (CodeGenOpts.hasProfileIRUse()) {
1224     // -fprofile-use.
1225     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1226                                                     : PGOOptions::NoCSAction;
1227     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1228                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1229                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1230   } else if (!CodeGenOpts.SampleProfileFile.empty())
1231     // -fprofile-sample-use
1232     PGOOpt = PGOOptions(
1233         CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
1234         PGOOptions::SampleUse, PGOOptions::NoCSAction,
1235         CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
1236   else if (CodeGenOpts.PseudoProbeForProfiling)
1237     // -fpseudo-probe-for-profiling
1238     PGOOpt =
1239         PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
1240                    CodeGenOpts.DebugInfoForProfiling, true);
1241   else if (CodeGenOpts.DebugInfoForProfiling)
1242     // -fdebug-info-for-profiling
1243     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1244                         PGOOptions::NoCSAction, true);
1245 
1246   // Check to see if we want to generate a CS profile.
1247   if (CodeGenOpts.hasProfileCSIRInstr()) {
1248     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1249            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1250            "the same time");
1251     if (PGOOpt.hasValue()) {
1252       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1253              PGOOpt->Action != PGOOptions::SampleUse &&
1254              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1255              " pass");
1256       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1257                                      ? std::string(DefaultProfileGenName)
1258                                      : CodeGenOpts.InstrProfileOutput;
1259       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1260     } else
1261       PGOOpt = PGOOptions("",
1262                           CodeGenOpts.InstrProfileOutput.empty()
1263                               ? std::string(DefaultProfileGenName)
1264                               : CodeGenOpts.InstrProfileOutput,
1265                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1266                           CodeGenOpts.DebugInfoForProfiling);
1267   }
1268 
1269   PipelineTuningOptions PTO;
1270   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1271   // For historical reasons, loop interleaving is set to mirror setting for loop
1272   // unrolling.
1273   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1274   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1275   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1276   PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
1277   // Only enable CGProfilePass when using integrated assembler, since
1278   // non-integrated assemblers don't recognize .cgprofile section.
1279   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1280   PTO.Coroutines = LangOpts.Coroutines;
1281 
1282   LoopAnalysisManager LAM;
1283   FunctionAnalysisManager FAM;
1284   CGSCCAnalysisManager CGAM;
1285   ModuleAnalysisManager MAM;
1286 
1287   PassInstrumentationCallbacks PIC;
1288   StandardInstrumentations SI(CodeGenOpts.DebugPassManager);
1289   SI.registerCallbacks(PIC, &FAM);
1290   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1291 
1292   // Attempt to load pass plugins and register their callbacks with PB.
1293   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1294     auto PassPlugin = PassPlugin::Load(PluginFN);
1295     if (PassPlugin) {
1296       PassPlugin->registerPassBuilderCallbacks(PB);
1297     } else {
1298       Diags.Report(diag::err_fe_unable_to_load_plugin)
1299           << PluginFN << toString(PassPlugin.takeError());
1300     }
1301   }
1302 #define HANDLE_EXTENSION(Ext)                                                  \
1303   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1304 #include "llvm/Support/Extension.def"
1305 
1306   // Register the AA manager first so that our version is the one used.
1307   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
1308 
1309   // Register the target library analysis directly and give it a customized
1310   // preset TLI.
1311   Triple TargetTriple(TheModule->getTargetTriple());
1312   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1313       createTLII(TargetTriple, CodeGenOpts));
1314   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1315 
1316   // Register all the basic analyses with the managers.
1317   PB.registerModuleAnalyses(MAM);
1318   PB.registerCGSCCAnalyses(CGAM);
1319   PB.registerFunctionAnalyses(FAM);
1320   PB.registerLoopAnalyses(LAM);
1321   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1322 
1323   ModulePassManager MPM;
1324 
1325   if (!CodeGenOpts.DisableLLVMPasses) {
1326     // Map our optimization levels into one of the distinct levels used to
1327     // configure the pipeline.
1328     PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
1329 
1330     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1331     bool IsLTO = CodeGenOpts.PrepareForLTO;
1332 
1333     if (LangOpts.ObjCAutoRefCount) {
1334       PB.registerPipelineStartEPCallback(
1335           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1336             if (Level != PassBuilder::OptimizationLevel::O0)
1337               MPM.addPass(
1338                   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1339           });
1340       PB.registerPipelineEarlySimplificationEPCallback(
1341           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1342             if (Level != PassBuilder::OptimizationLevel::O0)
1343               MPM.addPass(ObjCARCAPElimPass());
1344           });
1345       PB.registerScalarOptimizerLateEPCallback(
1346           [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1347             if (Level != PassBuilder::OptimizationLevel::O0)
1348               FPM.addPass(ObjCARCOptPass());
1349           });
1350     }
1351 
1352     // If we reached here with a non-empty index file name, then the index
1353     // file was empty and we are not performing ThinLTO backend compilation
1354     // (used in testing in a distributed build environment).
1355     bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
1356     // If so drop any the type test assume sequences inserted for whole program
1357     // vtables so that codegen doesn't complain.
1358     if (IsThinLTOPostLink)
1359       PB.registerPipelineStartEPCallback(
1360           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1361             MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1362                                            /*ImportSummary=*/nullptr,
1363                                            /*DropTypeTests=*/true));
1364           });
1365 
1366     if (CodeGenOpts.InstrumentFunctions ||
1367         CodeGenOpts.InstrumentFunctionEntryBare ||
1368         CodeGenOpts.InstrumentFunctionsAfterInlining ||
1369         CodeGenOpts.InstrumentForProfiling) {
1370       PB.registerPipelineStartEPCallback(
1371           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1372             MPM.addPass(createModuleToFunctionPassAdaptor(
1373                 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1374           });
1375       PB.registerOptimizerLastEPCallback(
1376           [](ModulePassManager &MPM, PassBuilder::OptimizationLevel Level) {
1377             MPM.addPass(createModuleToFunctionPassAdaptor(
1378                 EntryExitInstrumenterPass(/*PostInlining=*/true)));
1379           });
1380     }
1381 
1382     // Register callbacks to schedule sanitizer passes at the appropriate part
1383     // of the pipeline.
1384     if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1385       PB.registerScalarOptimizerLateEPCallback(
1386           [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
1387             FPM.addPass(BoundsCheckingPass());
1388           });
1389 
1390     // Don't add sanitizers if we are here from ThinLTO PostLink. That already
1391     // done on PreLink stage.
1392     if (!IsThinLTOPostLink)
1393       addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1394 
1395     if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1396       PB.registerPipelineStartEPCallback(
1397           [Options](ModulePassManager &MPM,
1398                     PassBuilder::OptimizationLevel Level) {
1399             MPM.addPass(GCOVProfilerPass(*Options));
1400           });
1401     if (Optional<InstrProfOptions> Options =
1402             getInstrProfOptions(CodeGenOpts, LangOpts))
1403       PB.registerPipelineStartEPCallback(
1404           [Options](ModulePassManager &MPM,
1405                     PassBuilder::OptimizationLevel Level) {
1406             MPM.addPass(InstrProfiling(*Options, false));
1407           });
1408 
1409     if (CodeGenOpts.OptimizationLevel == 0) {
1410       MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
1411     } else if (IsThinLTO) {
1412       MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
1413     } else if (IsLTO) {
1414       MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
1415     } else {
1416       MPM = PB.buildPerModuleDefaultPipeline(Level);
1417     }
1418 
1419     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1420       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1421       MPM.addPass(ModuleMemProfilerPass());
1422     }
1423   }
1424 
1425   // FIXME: We still use the legacy pass manager to do code generation. We
1426   // create that pass manager here and use it as needed below.
1427   legacy::PassManager CodeGenPasses;
1428   bool NeedCodeGen = false;
1429   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1430 
1431   // Append any output we need to the pass manager.
1432   switch (Action) {
1433   case Backend_EmitNothing:
1434     break;
1435 
1436   case Backend_EmitBC:
1437     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1438       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1439         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1440         if (!ThinLinkOS)
1441           return;
1442       }
1443       TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1444                                CodeGenOpts.EnableSplitLTOUnit);
1445       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1446                                                            : nullptr));
1447     } else {
1448       // Emit a module summary by default for Regular LTO except for ld64
1449       // targets
1450       bool EmitLTOSummary =
1451           (CodeGenOpts.PrepareForLTO &&
1452            !CodeGenOpts.DisableLLVMPasses &&
1453            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1454                llvm::Triple::Apple);
1455       if (EmitLTOSummary) {
1456         if (!TheModule->getModuleFlag("ThinLTO"))
1457           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1458         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1459                                  uint32_t(1));
1460       }
1461       MPM.addPass(
1462           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1463     }
1464     break;
1465 
1466   case Backend_EmitLL:
1467     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1468     break;
1469 
1470   case Backend_EmitAssembly:
1471   case Backend_EmitMCNull:
1472   case Backend_EmitObj:
1473     NeedCodeGen = true;
1474     CodeGenPasses.add(
1475         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1476     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1477       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1478       if (!DwoOS)
1479         return;
1480     }
1481     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1482                        DwoOS ? &DwoOS->os() : nullptr))
1483       // FIXME: Should we handle this error differently?
1484       return;
1485     break;
1486   }
1487 
1488   // Before executing passes, print the final values of the LLVM options.
1489   cl::PrintOptionValues();
1490 
1491   // Now that we have all of the passes ready, run them.
1492   {
1493     PrettyStackTraceString CrashInfo("Optimizer");
1494     MPM.run(*TheModule, MAM);
1495   }
1496 
1497   // Now if needed, run the legacy PM for codegen.
1498   if (NeedCodeGen) {
1499     PrettyStackTraceString CrashInfo("Code generation");
1500     CodeGenPasses.run(*TheModule);
1501   }
1502 
1503   if (ThinLinkOS)
1504     ThinLinkOS->keep();
1505   if (DwoOS)
1506     DwoOS->keep();
1507 }
1508 
1509 static void runThinLTOBackend(
1510     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1511     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1512     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1513     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1514     std::string ProfileRemapping, BackendAction Action) {
1515   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1516       ModuleToDefinedGVSummaries;
1517   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1518 
1519   setCommandLineOpts(CGOpts);
1520 
1521   // We can simply import the values mentioned in the combined index, since
1522   // we should only invoke this using the individual indexes written out
1523   // via a WriteIndexesThinBackend.
1524   FunctionImporter::ImportMapTy ImportList;
1525   if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1526     return;
1527 
1528   auto AddStream = [&](size_t Task) {
1529     return std::make_unique<lto::NativeObjectStream>(std::move(OS));
1530   };
1531   lto::Config Conf;
1532   if (CGOpts.SaveTempsFilePrefix != "") {
1533     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1534                                     /* UseInputModulePath */ false)) {
1535       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1536         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1537                << '\n';
1538       });
1539     }
1540   }
1541   Conf.CPU = TOpts.CPU;
1542   Conf.CodeModel = getCodeModel(CGOpts);
1543   Conf.MAttrs = TOpts.Features;
1544   Conf.RelocModel = CGOpts.RelocationModel;
1545   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1546   Conf.OptLevel = CGOpts.OptimizationLevel;
1547   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1548   Conf.SampleProfile = std::move(SampleProfile);
1549   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1550   // For historical reasons, loop interleaving is set to mirror setting for loop
1551   // unrolling.
1552   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1553   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1554   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1555   // Only enable CGProfilePass when using integrated assembler, since
1556   // non-integrated assemblers don't recognize .cgprofile section.
1557   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1558 
1559   // Context sensitive profile.
1560   if (CGOpts.hasProfileCSIRInstr()) {
1561     Conf.RunCSIRInstr = true;
1562     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1563   } else if (CGOpts.hasProfileCSIRUse()) {
1564     Conf.RunCSIRInstr = false;
1565     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1566   }
1567 
1568   Conf.ProfileRemapping = std::move(ProfileRemapping);
1569   Conf.UseNewPM = !CGOpts.LegacyPassManager;
1570   Conf.DebugPassManager = CGOpts.DebugPassManager;
1571   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1572   Conf.RemarksFilename = CGOpts.OptRecordFile;
1573   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1574   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1575   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1576   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1577   switch (Action) {
1578   case Backend_EmitNothing:
1579     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1580       return false;
1581     };
1582     break;
1583   case Backend_EmitLL:
1584     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1585       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1586       return false;
1587     };
1588     break;
1589   case Backend_EmitBC:
1590     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1591       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1592       return false;
1593     };
1594     break;
1595   default:
1596     Conf.CGFileType = getCodeGenFileType(Action);
1597     break;
1598   }
1599   if (Error E =
1600           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1601                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1602                       /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1603     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1604       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1605     });
1606   }
1607 }
1608 
1609 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1610                               const HeaderSearchOptions &HeaderOpts,
1611                               const CodeGenOptions &CGOpts,
1612                               const clang::TargetOptions &TOpts,
1613                               const LangOptions &LOpts,
1614                               StringRef TDesc, Module *M,
1615                               BackendAction Action,
1616                               std::unique_ptr<raw_pwrite_stream> OS) {
1617 
1618   llvm::TimeTraceScope TimeScope("Backend");
1619 
1620   std::unique_ptr<llvm::Module> EmptyModule;
1621   if (!CGOpts.ThinLTOIndexFile.empty()) {
1622     // If we are performing a ThinLTO importing compile, load the function index
1623     // into memory and pass it into runThinLTOBackend, which will run the
1624     // function importer and invoke LTO passes.
1625     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1626         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1627                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1628     if (!IndexOrErr) {
1629       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1630                             "Error loading index file '" +
1631                             CGOpts.ThinLTOIndexFile + "': ");
1632       return;
1633     }
1634     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1635     // A null CombinedIndex means we should skip ThinLTO compilation
1636     // (LLVM will optionally ignore empty index files, returning null instead
1637     // of an error).
1638     if (CombinedIndex) {
1639       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1640         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1641                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1642                           CGOpts.ProfileRemappingFile, Action);
1643         return;
1644       }
1645       // Distributed indexing detected that nothing from the module is needed
1646       // for the final linking. So we can skip the compilation. We sill need to
1647       // output an empty object file to make sure that a linker does not fail
1648       // trying to read it. Also for some features, like CFI, we must skip
1649       // the compilation as CombinedIndex does not contain all required
1650       // information.
1651       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1652       EmptyModule->setTargetTriple(M->getTargetTriple());
1653       M = EmptyModule.get();
1654     }
1655   }
1656 
1657   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1658 
1659   if (!CGOpts.LegacyPassManager)
1660     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1661   else
1662     AsmHelper.EmitAssembly(Action, std::move(OS));
1663 
1664   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1665   // DataLayout.
1666   if (AsmHelper.TM) {
1667     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1668     if (DLDesc != TDesc) {
1669       unsigned DiagID = Diags.getCustomDiagID(
1670           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1671                                     "expected target description '%1'");
1672       Diags.Report(DiagID) << DLDesc << TDesc;
1673     }
1674   }
1675 }
1676 
1677 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1678 // __LLVM,__bitcode section.
1679 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1680                          llvm::MemoryBufferRef Buf) {
1681   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1682     return;
1683   llvm::EmbedBitcodeInModule(
1684       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1685       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1686       CGOpts.CmdArgs);
1687 }
1688