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/MC/TargetRegistry.h"
42 #include "llvm/Object/OffloadBinary.h"
43 #include "llvm/Passes/PassBuilder.h"
44 #include "llvm/Passes/PassPlugin.h"
45 #include "llvm/Passes/StandardInstrumentations.h"
46 #include "llvm/Support/BuryPointer.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/PrettyStackTrace.h"
50 #include "llvm/Support/TimeProfiler.h"
51 #include "llvm/Support/Timer.h"
52 #include "llvm/Support/ToolOutputFile.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Target/TargetOptions.h"
56 #include "llvm/Transforms/Coroutines.h"
57 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
58 #include "llvm/Transforms/Coroutines/CoroEarly.h"
59 #include "llvm/Transforms/Coroutines/CoroElide.h"
60 #include "llvm/Transforms/Coroutines/CoroSplit.h"
61 #include "llvm/Transforms/IPO.h"
62 #include "llvm/Transforms/IPO/AlwaysInliner.h"
63 #include "llvm/Transforms/IPO/LowerTypeTests.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/AddressSanitizerOptions.h"
69 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
70 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
71 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
72 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
73 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
74 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
75 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
76 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
77 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
78 #include "llvm/Transforms/ObjCARC.h"
79 #include "llvm/Transforms/Scalar.h"
80 #include "llvm/Transforms/Scalar/EarlyCSE.h"
81 #include "llvm/Transforms/Scalar/GVN.h"
82 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
83 #include "llvm/Transforms/Utils.h"
84 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
85 #include "llvm/Transforms/Utils/Debugify.h"
86 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
87 #include "llvm/Transforms/Utils/ModuleUtils.h"
88 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
89 #include "llvm/Transforms/Utils/SymbolRewriter.h"
90 #include <memory>
91 using namespace clang;
92 using namespace llvm;
93 
94 #define HANDLE_EXTENSION(Ext)                                                  \
95   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
96 #include "llvm/Support/Extension.def"
97 
98 namespace llvm {
99 extern cl::opt<bool> DebugInfoCorrelate;
100 }
101 
102 namespace {
103 
104 // Default filename used for profile generation.
105 std::string getDefaultProfileGenName() {
106   return DebugInfoCorrelate ? "default_%p.proflite" : "default_%m.profraw";
107 }
108 
109 class EmitAssemblyHelper {
110   DiagnosticsEngine &Diags;
111   const HeaderSearchOptions &HSOpts;
112   const CodeGenOptions &CodeGenOpts;
113   const clang::TargetOptions &TargetOpts;
114   const LangOptions &LangOpts;
115   Module *TheModule;
116 
117   Timer CodeGenerationTime;
118 
119   std::unique_ptr<raw_pwrite_stream> OS;
120 
121   Triple TargetTriple;
122 
123   TargetIRAnalysis getTargetIRAnalysis() const {
124     if (TM)
125       return TM->getTargetIRAnalysis();
126 
127     return TargetIRAnalysis();
128   }
129 
130   /// Generates the TargetMachine.
131   /// Leaves TM unchanged if it is unable to create the target machine.
132   /// Some of our clang tests specify triples which are not built
133   /// into clang. This is okay because these tests check the generated
134   /// IR, and they require DataLayout which depends on the triple.
135   /// In this case, we allow this method to fail and not report an error.
136   /// When MustCreateTM is used, we print an error if we are unable to load
137   /// the requested target.
138   void CreateTargetMachine(bool MustCreateTM);
139 
140   /// Add passes necessary to emit assembly or LLVM IR.
141   ///
142   /// \return True on success.
143   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
144                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
145 
146   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
147     std::error_code EC;
148     auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
149                                                      llvm::sys::fs::OF_None);
150     if (EC) {
151       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
152       F.reset();
153     }
154     return F;
155   }
156 
157   void
158   RunOptimizationPipeline(BackendAction Action,
159                           std::unique_ptr<raw_pwrite_stream> &OS,
160                           std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS);
161   void RunCodegenPipeline(BackendAction Action,
162                           std::unique_ptr<raw_pwrite_stream> &OS,
163                           std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
164 
165   /// Check whether we should emit a module summary for regular LTO.
166   /// The module summary should be emitted by default for regular LTO
167   /// except for ld64 targets.
168   ///
169   /// \return True if the module summary should be emitted.
170   bool shouldEmitRegularLTOSummary() const {
171     return CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
172            TargetTriple.getVendor() != llvm::Triple::Apple;
173   }
174 
175 public:
176   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
177                      const HeaderSearchOptions &HeaderSearchOpts,
178                      const CodeGenOptions &CGOpts,
179                      const clang::TargetOptions &TOpts,
180                      const LangOptions &LOpts, Module *M)
181       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
182         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
183         CodeGenerationTime("codegen", "Code Generation Time"),
184         TargetTriple(TheModule->getTargetTriple()) {}
185 
186   ~EmitAssemblyHelper() {
187     if (CodeGenOpts.DisableFree)
188       BuryPointer(std::move(TM));
189   }
190 
191   std::unique_ptr<TargetMachine> TM;
192 
193   // Emit output using the new pass manager for the optimization pipeline.
194   void EmitAssembly(BackendAction Action,
195                     std::unique_ptr<raw_pwrite_stream> OS);
196 };
197 }
198 
199 static SanitizerCoverageOptions
200 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
201   SanitizerCoverageOptions Opts;
202   Opts.CoverageType =
203       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
204   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
205   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
206   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
207   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
208   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
209   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
210   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
211   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
212   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
213   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
214   Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
215   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
216   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
217   Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
218   Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
219   return Opts;
220 }
221 
222 // Check if ASan should use GC-friendly instrumentation for globals.
223 // First of all, there is no point if -fdata-sections is off (expect for MachO,
224 // where this is not a factor). Also, on ELF this feature requires an assembler
225 // extension that only works with -integrated-as at the moment.
226 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
227   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
228     return false;
229   switch (T.getObjectFormat()) {
230   case Triple::MachO:
231   case Triple::COFF:
232     return true;
233   case Triple::ELF:
234     return !CGOpts.DisableIntegratedAS;
235   case Triple::GOFF:
236     llvm::report_fatal_error("ASan not implemented for GOFF");
237   case Triple::XCOFF:
238     llvm::report_fatal_error("ASan not implemented for XCOFF.");
239   case Triple::Wasm:
240   case Triple::DXContainer:
241   case Triple::SPIRV:
242   case Triple::UnknownObjectFormat:
243     break;
244   }
245   return false;
246 }
247 
248 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
249                                          const CodeGenOptions &CodeGenOpts) {
250   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
251 
252   switch (CodeGenOpts.getVecLib()) {
253   case CodeGenOptions::Accelerate:
254     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
255     break;
256   case CodeGenOptions::LIBMVEC:
257     switch(TargetTriple.getArch()) {
258       default:
259         break;
260       case llvm::Triple::x86_64:
261         TLII->addVectorizableFunctionsFromVecLib
262                 (TargetLibraryInfoImpl::LIBMVEC_X86);
263         break;
264     }
265     break;
266   case CodeGenOptions::MASSV:
267     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
268     break;
269   case CodeGenOptions::SVML:
270     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
271     break;
272   case CodeGenOptions::Darwin_libsystem_m:
273     TLII->addVectorizableFunctionsFromVecLib(
274         TargetLibraryInfoImpl::DarwinLibSystemM);
275     break;
276   default:
277     break;
278   }
279   return TLII;
280 }
281 
282 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
283   switch (CodeGenOpts.OptimizationLevel) {
284   default:
285     llvm_unreachable("Invalid optimization level!");
286   case 0:
287     return CodeGenOpt::None;
288   case 1:
289     return CodeGenOpt::Less;
290   case 2:
291     return CodeGenOpt::Default; // O2/Os/Oz
292   case 3:
293     return CodeGenOpt::Aggressive;
294   }
295 }
296 
297 static Optional<llvm::CodeModel::Model>
298 getCodeModel(const CodeGenOptions &CodeGenOpts) {
299   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
300                            .Case("tiny", llvm::CodeModel::Tiny)
301                            .Case("small", llvm::CodeModel::Small)
302                            .Case("kernel", llvm::CodeModel::Kernel)
303                            .Case("medium", llvm::CodeModel::Medium)
304                            .Case("large", llvm::CodeModel::Large)
305                            .Case("default", ~1u)
306                            .Default(~0u);
307   assert(CodeModel != ~0u && "invalid code model!");
308   if (CodeModel == ~1u)
309     return None;
310   return static_cast<llvm::CodeModel::Model>(CodeModel);
311 }
312 
313 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
314   if (Action == Backend_EmitObj)
315     return CGFT_ObjectFile;
316   else if (Action == Backend_EmitMCNull)
317     return CGFT_Null;
318   else {
319     assert(Action == Backend_EmitAssembly && "Invalid action!");
320     return CGFT_AssemblyFile;
321   }
322 }
323 
324 static bool actionRequiresCodeGen(BackendAction Action) {
325   return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
326          Action != Backend_EmitLL;
327 }
328 
329 static bool initTargetOptions(DiagnosticsEngine &Diags,
330                               llvm::TargetOptions &Options,
331                               const CodeGenOptions &CodeGenOpts,
332                               const clang::TargetOptions &TargetOpts,
333                               const LangOptions &LangOpts,
334                               const HeaderSearchOptions &HSOpts) {
335   switch (LangOpts.getThreadModel()) {
336   case LangOptions::ThreadModelKind::POSIX:
337     Options.ThreadModel = llvm::ThreadModel::POSIX;
338     break;
339   case LangOptions::ThreadModelKind::Single:
340     Options.ThreadModel = llvm::ThreadModel::Single;
341     break;
342   }
343 
344   // Set float ABI type.
345   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
346           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
347          "Invalid Floating Point ABI!");
348   Options.FloatABIType =
349       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
350           .Case("soft", llvm::FloatABI::Soft)
351           .Case("softfp", llvm::FloatABI::Soft)
352           .Case("hard", llvm::FloatABI::Hard)
353           .Default(llvm::FloatABI::Default);
354 
355   // Set FP fusion mode.
356   switch (LangOpts.getDefaultFPContractMode()) {
357   case LangOptions::FPM_Off:
358     // Preserve any contraction performed by the front-end.  (Strict performs
359     // splitting of the muladd intrinsic in the backend.)
360     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
361     break;
362   case LangOptions::FPM_On:
363   case LangOptions::FPM_FastHonorPragmas:
364     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
365     break;
366   case LangOptions::FPM_Fast:
367     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
368     break;
369   }
370 
371   Options.BinutilsVersion =
372       llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
373   Options.UseInitArray = CodeGenOpts.UseInitArray;
374   Options.LowerGlobalDtorsViaCxaAtExit =
375       CodeGenOpts.RegisterGlobalDtorsWithAtExit;
376   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
377   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
378   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
379 
380   // Set EABI version.
381   Options.EABIVersion = TargetOpts.EABIVersion;
382 
383   if (LangOpts.hasSjLjExceptions())
384     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
385   if (LangOpts.hasSEHExceptions())
386     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
387   if (LangOpts.hasDWARFExceptions())
388     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
389   if (LangOpts.hasWasmExceptions())
390     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
391 
392   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
393   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
394   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
395   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
396   Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
397 
398   Options.BBSections =
399       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
400           .Case("all", llvm::BasicBlockSection::All)
401           .Case("labels", llvm::BasicBlockSection::Labels)
402           .StartsWith("list=", llvm::BasicBlockSection::List)
403           .Case("none", llvm::BasicBlockSection::None)
404           .Default(llvm::BasicBlockSection::None);
405 
406   if (Options.BBSections == llvm::BasicBlockSection::List) {
407     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
408         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
409     if (!MBOrErr) {
410       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
411           << MBOrErr.getError().message();
412       return false;
413     }
414     Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
415   }
416 
417   Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
418   Options.FunctionSections = CodeGenOpts.FunctionSections;
419   Options.DataSections = CodeGenOpts.DataSections;
420   Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
421   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
422   Options.UniqueBasicBlockSectionNames =
423       CodeGenOpts.UniqueBasicBlockSectionNames;
424   Options.TLSSize = CodeGenOpts.TLSSize;
425   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
426   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
427   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
428   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
429   Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
430   Options.EmitAddrsig = CodeGenOpts.Addrsig;
431   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
432   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
433   Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI;
434   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
435   Options.LoopAlignment = CodeGenOpts.LoopAlignment;
436   Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
437   Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
438   Options.Hotpatch = CodeGenOpts.HotPatch;
439   Options.JMCInstrument = CodeGenOpts.JMCInstrument;
440 
441   switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
442   case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
443     Options.SwiftAsyncFramePointer =
444         SwiftAsyncFramePointerMode::DeploymentBased;
445     break;
446 
447   case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
448     Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
449     break;
450 
451   case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
452     Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
453     break;
454   }
455 
456   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
457   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
458   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
459   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
460   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
461   Options.MCOptions.MCIncrementalLinkerCompatible =
462       CodeGenOpts.IncrementalLinkerCompatible;
463   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
464   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
465   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
466   Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
467   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
468   Options.MCOptions.ABIName = TargetOpts.ABI;
469   for (const auto &Entry : HSOpts.UserEntries)
470     if (!Entry.IsFramework &&
471         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
472          Entry.Group == frontend::IncludeDirGroup::Angled ||
473          Entry.Group == frontend::IncludeDirGroup::System))
474       Options.MCOptions.IASSearchPaths.push_back(
475           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
476   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
477   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
478   Options.MisExpect = CodeGenOpts.MisExpect;
479 
480   return true;
481 }
482 
483 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
484                                             const LangOptions &LangOpts) {
485   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
486     return None;
487   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
488   // LLVM's -default-gcov-version flag is set to something invalid.
489   GCOVOptions Options;
490   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
491   Options.EmitData = CodeGenOpts.EmitGcovArcs;
492   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
493   Options.NoRedZone = CodeGenOpts.DisableRedZone;
494   Options.Filter = CodeGenOpts.ProfileFilterFiles;
495   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
496   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
497   return Options;
498 }
499 
500 static Optional<InstrProfOptions>
501 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
502                     const LangOptions &LangOpts) {
503   if (!CodeGenOpts.hasProfileClangInstr())
504     return None;
505   InstrProfOptions Options;
506   Options.NoRedZone = CodeGenOpts.DisableRedZone;
507   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
508   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
509   return Options;
510 }
511 
512 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
513   SmallVector<const char *, 16> BackendArgs;
514   BackendArgs.push_back("clang"); // Fake program name.
515   if (!CodeGenOpts.DebugPass.empty()) {
516     BackendArgs.push_back("-debug-pass");
517     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
518   }
519   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
520     BackendArgs.push_back("-limit-float-precision");
521     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
522   }
523   // Check for the default "clang" invocation that won't set any cl::opt values.
524   // Skip trying to parse the command line invocation to avoid the issues
525   // described below.
526   if (BackendArgs.size() == 1)
527     return;
528   BackendArgs.push_back(nullptr);
529   // FIXME: The command line parser below is not thread-safe and shares a global
530   // state, so this call might crash or overwrite the options of another Clang
531   // instance in the same process.
532   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
533                                     BackendArgs.data());
534 }
535 
536 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
537   // Create the TargetMachine for generating code.
538   std::string Error;
539   std::string Triple = TheModule->getTargetTriple();
540   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
541   if (!TheTarget) {
542     if (MustCreateTM)
543       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
544     return;
545   }
546 
547   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
548   std::string FeaturesStr =
549       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
550   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
551   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
552 
553   llvm::TargetOptions Options;
554   if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
555                          HSOpts))
556     return;
557   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
558                                           Options, RM, CM, OptLevel));
559 }
560 
561 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
562                                        BackendAction Action,
563                                        raw_pwrite_stream &OS,
564                                        raw_pwrite_stream *DwoOS) {
565   // Add LibraryInfo.
566   std::unique_ptr<TargetLibraryInfoImpl> TLII(
567       createTLII(TargetTriple, CodeGenOpts));
568   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
569 
570   // Normal mode, emit a .s or .o file by running the code generator. Note,
571   // this also adds codegenerator level optimization passes.
572   CodeGenFileType CGFT = getCodeGenFileType(Action);
573 
574   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
575   // "codegen" passes so that it isn't run multiple times when there is
576   // inlining happening.
577   if (CodeGenOpts.OptimizationLevel > 0)
578     CodeGenPasses.add(createObjCARCContractPass());
579 
580   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
581                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
582     Diags.Report(diag::err_fe_unable_to_interface_with_target);
583     return false;
584   }
585 
586   return true;
587 }
588 
589 static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
590   switch (Opts.OptimizationLevel) {
591   default:
592     llvm_unreachable("Invalid optimization level!");
593 
594   case 0:
595     return OptimizationLevel::O0;
596 
597   case 1:
598     return OptimizationLevel::O1;
599 
600   case 2:
601     switch (Opts.OptimizeSize) {
602     default:
603       llvm_unreachable("Invalid optimization level for size!");
604 
605     case 0:
606       return OptimizationLevel::O2;
607 
608     case 1:
609       return OptimizationLevel::Os;
610 
611     case 2:
612       return OptimizationLevel::Oz;
613     }
614 
615   case 3:
616     return OptimizationLevel::O3;
617   }
618 }
619 
620 static void addSanitizers(const Triple &TargetTriple,
621                           const CodeGenOptions &CodeGenOpts,
622                           const LangOptions &LangOpts, PassBuilder &PB) {
623   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
624                                          OptimizationLevel Level) {
625     if (CodeGenOpts.hasSanitizeCoverage()) {
626       auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
627       MPM.addPass(ModuleSanitizerCoveragePass(
628           SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
629           CodeGenOpts.SanitizeCoverageIgnorelistFiles));
630     }
631 
632     auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
633       if (LangOpts.Sanitize.has(Mask)) {
634         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
635         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
636 
637         MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
638                                        CodeGenOpts.SanitizeMemoryParamRetval);
639         MPM.addPass(ModuleMemorySanitizerPass(options));
640         FunctionPassManager FPM;
641         FPM.addPass(MemorySanitizerPass(options));
642         if (Level != OptimizationLevel::O0) {
643           // MemorySanitizer inserts complex instrumentation that mostly
644           // follows the logic of the original code, but operates on
645           // "shadow" values. It can benefit from re-running some
646           // general purpose optimization passes.
647           FPM.addPass(EarlyCSEPass());
648           // TODO: Consider add more passes like in
649           // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
650           // difference on size. It's not clear if the rest is still
651           // usefull. InstCombinePass breakes
652           // compiler-rt/test/msan/select_origin.cpp.
653         }
654         MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
655       }
656     };
657     MSanPass(SanitizerKind::Memory, false);
658     MSanPass(SanitizerKind::KernelMemory, true);
659 
660     if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
661       MPM.addPass(ModuleThreadSanitizerPass());
662       MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
663     }
664 
665     auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
666       if (LangOpts.Sanitize.has(Mask)) {
667         bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
668         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
669         llvm::AsanDtorKind DestructorKind =
670             CodeGenOpts.getSanitizeAddressDtor();
671         AddressSanitizerOptions Opts;
672         Opts.CompileKernel = CompileKernel;
673         Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
674         Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
675         Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
676         MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
677         MPM.addPass(ModuleAddressSanitizerPass(
678             Opts, UseGlobalGC, UseOdrIndicator, DestructorKind));
679       }
680     };
681     ASanPass(SanitizerKind::Address, false);
682     ASanPass(SanitizerKind::KernelAddress, true);
683 
684     auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
685       if (LangOpts.Sanitize.has(Mask)) {
686         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
687         MPM.addPass(HWAddressSanitizerPass(
688             {CompileKernel, Recover,
689              /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
690       }
691     };
692     HWASanPass(SanitizerKind::HWAddress, false);
693     HWASanPass(SanitizerKind::KernelHWAddress, true);
694 
695     if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
696       MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
697     }
698   });
699 }
700 
701 void EmitAssemblyHelper::RunOptimizationPipeline(
702     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
703     std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS) {
704   Optional<PGOOptions> PGOOpt;
705 
706   if (CodeGenOpts.hasProfileIRInstr())
707     // -fprofile-generate.
708     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
709                             ? getDefaultProfileGenName()
710                             : CodeGenOpts.InstrProfileOutput,
711                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
712                         CodeGenOpts.DebugInfoForProfiling);
713   else if (CodeGenOpts.hasProfileIRUse()) {
714     // -fprofile-use.
715     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
716                                                     : PGOOptions::NoCSAction;
717     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
718                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
719                         CSAction, CodeGenOpts.DebugInfoForProfiling);
720   } else if (!CodeGenOpts.SampleProfileFile.empty())
721     // -fprofile-sample-use
722     PGOOpt = PGOOptions(
723         CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
724         PGOOptions::SampleUse, PGOOptions::NoCSAction,
725         CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
726   else if (CodeGenOpts.PseudoProbeForProfiling)
727     // -fpseudo-probe-for-profiling
728     PGOOpt =
729         PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
730                    CodeGenOpts.DebugInfoForProfiling, true);
731   else if (CodeGenOpts.DebugInfoForProfiling)
732     // -fdebug-info-for-profiling
733     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
734                         PGOOptions::NoCSAction, true);
735 
736   // Check to see if we want to generate a CS profile.
737   if (CodeGenOpts.hasProfileCSIRInstr()) {
738     assert(!CodeGenOpts.hasProfileCSIRUse() &&
739            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
740            "the same time");
741     if (PGOOpt.hasValue()) {
742       assert(PGOOpt->Action != PGOOptions::IRInstr &&
743              PGOOpt->Action != PGOOptions::SampleUse &&
744              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
745              " pass");
746       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
747                                      ? getDefaultProfileGenName()
748                                      : CodeGenOpts.InstrProfileOutput;
749       PGOOpt->CSAction = PGOOptions::CSIRInstr;
750     } else
751       PGOOpt = PGOOptions("",
752                           CodeGenOpts.InstrProfileOutput.empty()
753                               ? getDefaultProfileGenName()
754                               : CodeGenOpts.InstrProfileOutput,
755                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
756                           CodeGenOpts.DebugInfoForProfiling);
757   }
758   if (TM)
759     TM->setPGOOption(PGOOpt);
760 
761   PipelineTuningOptions PTO;
762   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
763   // For historical reasons, loop interleaving is set to mirror setting for loop
764   // unrolling.
765   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
766   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
767   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
768   PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
769   // Only enable CGProfilePass when using integrated assembler, since
770   // non-integrated assemblers don't recognize .cgprofile section.
771   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
772 
773   LoopAnalysisManager LAM;
774   FunctionAnalysisManager FAM;
775   CGSCCAnalysisManager CGAM;
776   ModuleAnalysisManager MAM;
777 
778   bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
779   PassInstrumentationCallbacks PIC;
780   PrintPassOptions PrintPassOpts;
781   PrintPassOpts.Indent = DebugPassStructure;
782   PrintPassOpts.SkipAnalyses = DebugPassStructure;
783   StandardInstrumentations SI(CodeGenOpts.DebugPassManager ||
784                                   DebugPassStructure,
785                               /*VerifyEach*/ false, PrintPassOpts);
786   SI.registerCallbacks(PIC, &FAM);
787   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
788 
789   // Attempt to load pass plugins and register their callbacks with PB.
790   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
791     auto PassPlugin = PassPlugin::Load(PluginFN);
792     if (PassPlugin) {
793       PassPlugin->registerPassBuilderCallbacks(PB);
794     } else {
795       Diags.Report(diag::err_fe_unable_to_load_plugin)
796           << PluginFN << toString(PassPlugin.takeError());
797     }
798   }
799 #define HANDLE_EXTENSION(Ext)                                                  \
800   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
801 #include "llvm/Support/Extension.def"
802 
803   // Register the target library analysis directly and give it a customized
804   // preset TLI.
805   std::unique_ptr<TargetLibraryInfoImpl> TLII(
806       createTLII(TargetTriple, CodeGenOpts));
807   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
808 
809   // Register all the basic analyses with the managers.
810   PB.registerModuleAnalyses(MAM);
811   PB.registerCGSCCAnalyses(CGAM);
812   PB.registerFunctionAnalyses(FAM);
813   PB.registerLoopAnalyses(LAM);
814   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
815 
816   ModulePassManager MPM;
817 
818   if (!CodeGenOpts.DisableLLVMPasses) {
819     // Map our optimization levels into one of the distinct levels used to
820     // configure the pipeline.
821     OptimizationLevel Level = mapToLevel(CodeGenOpts);
822 
823     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
824     bool IsLTO = CodeGenOpts.PrepareForLTO;
825 
826     if (LangOpts.ObjCAutoRefCount) {
827       PB.registerPipelineStartEPCallback(
828           [](ModulePassManager &MPM, OptimizationLevel Level) {
829             if (Level != OptimizationLevel::O0)
830               MPM.addPass(
831                   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
832           });
833       PB.registerPipelineEarlySimplificationEPCallback(
834           [](ModulePassManager &MPM, OptimizationLevel Level) {
835             if (Level != OptimizationLevel::O0)
836               MPM.addPass(ObjCARCAPElimPass());
837           });
838       PB.registerScalarOptimizerLateEPCallback(
839           [](FunctionPassManager &FPM, OptimizationLevel Level) {
840             if (Level != OptimizationLevel::O0)
841               FPM.addPass(ObjCARCOptPass());
842           });
843     }
844 
845     // If we reached here with a non-empty index file name, then the index
846     // file was empty and we are not performing ThinLTO backend compilation
847     // (used in testing in a distributed build environment).
848     bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
849     // If so drop any the type test assume sequences inserted for whole program
850     // vtables so that codegen doesn't complain.
851     if (IsThinLTOPostLink)
852       PB.registerPipelineStartEPCallback(
853           [](ModulePassManager &MPM, OptimizationLevel Level) {
854             MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
855                                            /*ImportSummary=*/nullptr,
856                                            /*DropTypeTests=*/true));
857           });
858 
859     if (CodeGenOpts.InstrumentFunctions ||
860         CodeGenOpts.InstrumentFunctionEntryBare ||
861         CodeGenOpts.InstrumentFunctionsAfterInlining ||
862         CodeGenOpts.InstrumentForProfiling) {
863       PB.registerPipelineStartEPCallback(
864           [](ModulePassManager &MPM, OptimizationLevel Level) {
865             MPM.addPass(createModuleToFunctionPassAdaptor(
866                 EntryExitInstrumenterPass(/*PostInlining=*/false)));
867           });
868       PB.registerOptimizerLastEPCallback(
869           [](ModulePassManager &MPM, OptimizationLevel Level) {
870             MPM.addPass(createModuleToFunctionPassAdaptor(
871                 EntryExitInstrumenterPass(/*PostInlining=*/true)));
872           });
873     }
874 
875     // Register callbacks to schedule sanitizer passes at the appropriate part
876     // of the pipeline.
877     if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
878       PB.registerScalarOptimizerLateEPCallback(
879           [](FunctionPassManager &FPM, OptimizationLevel Level) {
880             FPM.addPass(BoundsCheckingPass());
881           });
882 
883     // Don't add sanitizers if we are here from ThinLTO PostLink. That already
884     // done on PreLink stage.
885     if (!IsThinLTOPostLink)
886       addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
887 
888     if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
889       PB.registerPipelineStartEPCallback(
890           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
891             MPM.addPass(GCOVProfilerPass(*Options));
892           });
893     if (Optional<InstrProfOptions> Options =
894             getInstrProfOptions(CodeGenOpts, LangOpts))
895       PB.registerPipelineStartEPCallback(
896           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
897             MPM.addPass(InstrProfiling(*Options, false));
898           });
899 
900     if (CodeGenOpts.OptimizationLevel == 0) {
901       MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
902     } else if (IsThinLTO) {
903       MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
904     } else if (IsLTO) {
905       MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
906     } else {
907       MPM = PB.buildPerModuleDefaultPipeline(Level);
908     }
909 
910     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
911       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
912       MPM.addPass(ModuleMemProfilerPass());
913     }
914   }
915 
916   // Add a verifier pass if requested. We don't have to do this if the action
917   // requires code generation because there will already be a verifier pass in
918   // the code-generation pipeline.
919   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
920     MPM.addPass(VerifierPass());
921 
922   switch (Action) {
923   case Backend_EmitBC:
924     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
925       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
926         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
927         if (!ThinLinkOS)
928           return;
929       }
930       if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
931         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
932                                  CodeGenOpts.EnableSplitLTOUnit);
933       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
934                                                            : nullptr));
935     } else {
936       // Emit a module summary by default for Regular LTO except for ld64
937       // targets
938       bool EmitLTOSummary = shouldEmitRegularLTOSummary();
939       if (EmitLTOSummary) {
940         if (!TheModule->getModuleFlag("ThinLTO"))
941           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
942         if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
943           TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
944                                    uint32_t(1));
945       }
946       MPM.addPass(
947           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
948     }
949     break;
950 
951   case Backend_EmitLL:
952     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
953     break;
954 
955   default:
956     break;
957   }
958 
959   // Now that we have all of the passes ready, run them.
960   {
961     PrettyStackTraceString CrashInfo("Optimizer");
962     llvm::TimeTraceScope TimeScope("Optimizer");
963     MPM.run(*TheModule, MAM);
964   }
965 }
966 
967 void EmitAssemblyHelper::RunCodegenPipeline(
968     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
969     std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
970   // We still use the legacy PM to run the codegen pipeline since the new PM
971   // does not work with the codegen pipeline.
972   // FIXME: make the new PM work with the codegen pipeline.
973   legacy::PassManager CodeGenPasses;
974 
975   // Append any output we need to the pass manager.
976   switch (Action) {
977   case Backend_EmitAssembly:
978   case Backend_EmitMCNull:
979   case Backend_EmitObj:
980     CodeGenPasses.add(
981         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
982     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
983       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
984       if (!DwoOS)
985         return;
986     }
987     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
988                        DwoOS ? &DwoOS->os() : nullptr))
989       // FIXME: Should we handle this error differently?
990       return;
991     break;
992   default:
993     return;
994   }
995 
996   {
997     PrettyStackTraceString CrashInfo("Code generation");
998     llvm::TimeTraceScope TimeScope("CodeGenPasses");
999     CodeGenPasses.run(*TheModule);
1000   }
1001 }
1002 
1003 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
1004                                       std::unique_ptr<raw_pwrite_stream> OS) {
1005   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1006   setCommandLineOpts(CodeGenOpts);
1007 
1008   bool RequiresCodeGen = actionRequiresCodeGen(Action);
1009   CreateTargetMachine(RequiresCodeGen);
1010 
1011   if (RequiresCodeGen && !TM)
1012     return;
1013   if (TM)
1014     TheModule->setDataLayout(TM->createDataLayout());
1015 
1016   // Before executing passes, print the final values of the LLVM options.
1017   cl::PrintOptionValues();
1018 
1019   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1020   RunOptimizationPipeline(Action, OS, ThinLinkOS);
1021   RunCodegenPipeline(Action, OS, DwoOS);
1022 
1023   if (ThinLinkOS)
1024     ThinLinkOS->keep();
1025   if (DwoOS)
1026     DwoOS->keep();
1027 }
1028 
1029 static void runThinLTOBackend(
1030     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1031     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1032     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1033     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1034     std::string ProfileRemapping, BackendAction Action) {
1035   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1036       ModuleToDefinedGVSummaries;
1037   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1038 
1039   setCommandLineOpts(CGOpts);
1040 
1041   // We can simply import the values mentioned in the combined index, since
1042   // we should only invoke this using the individual indexes written out
1043   // via a WriteIndexesThinBackend.
1044   FunctionImporter::ImportMapTy ImportList;
1045   if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1046     return;
1047 
1048   auto AddStream = [&](size_t Task) {
1049     return std::make_unique<CachedFileStream>(std::move(OS),
1050                                               CGOpts.ObjectFilenameForDebug);
1051   };
1052   lto::Config Conf;
1053   if (CGOpts.SaveTempsFilePrefix != "") {
1054     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1055                                     /* UseInputModulePath */ false)) {
1056       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1057         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1058                << '\n';
1059       });
1060     }
1061   }
1062   Conf.CPU = TOpts.CPU;
1063   Conf.CodeModel = getCodeModel(CGOpts);
1064   Conf.MAttrs = TOpts.Features;
1065   Conf.RelocModel = CGOpts.RelocationModel;
1066   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1067   Conf.OptLevel = CGOpts.OptimizationLevel;
1068   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1069   Conf.SampleProfile = std::move(SampleProfile);
1070   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1071   // For historical reasons, loop interleaving is set to mirror setting for loop
1072   // unrolling.
1073   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1074   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1075   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1076   // Only enable CGProfilePass when using integrated assembler, since
1077   // non-integrated assemblers don't recognize .cgprofile section.
1078   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1079 
1080   // Context sensitive profile.
1081   if (CGOpts.hasProfileCSIRInstr()) {
1082     Conf.RunCSIRInstr = true;
1083     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1084   } else if (CGOpts.hasProfileCSIRUse()) {
1085     Conf.RunCSIRInstr = false;
1086     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1087   }
1088 
1089   Conf.ProfileRemapping = std::move(ProfileRemapping);
1090   Conf.DebugPassManager = CGOpts.DebugPassManager;
1091   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1092   Conf.RemarksFilename = CGOpts.OptRecordFile;
1093   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1094   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1095   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1096   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1097   switch (Action) {
1098   case Backend_EmitNothing:
1099     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1100       return false;
1101     };
1102     break;
1103   case Backend_EmitLL:
1104     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1105       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1106       return false;
1107     };
1108     break;
1109   case Backend_EmitBC:
1110     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1111       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1112       return false;
1113     };
1114     break;
1115   default:
1116     Conf.CGFileType = getCodeGenFileType(Action);
1117     break;
1118   }
1119   if (Error E =
1120           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1121                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1122                       /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1123     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1124       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1125     });
1126   }
1127 }
1128 
1129 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1130                               const HeaderSearchOptions &HeaderOpts,
1131                               const CodeGenOptions &CGOpts,
1132                               const clang::TargetOptions &TOpts,
1133                               const LangOptions &LOpts,
1134                               StringRef TDesc, Module *M,
1135                               BackendAction Action,
1136                               std::unique_ptr<raw_pwrite_stream> OS) {
1137 
1138   llvm::TimeTraceScope TimeScope("Backend");
1139 
1140   std::unique_ptr<llvm::Module> EmptyModule;
1141   if (!CGOpts.ThinLTOIndexFile.empty()) {
1142     // If we are performing a ThinLTO importing compile, load the function index
1143     // into memory and pass it into runThinLTOBackend, which will run the
1144     // function importer and invoke LTO passes.
1145     std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1146     if (Error E = llvm::getModuleSummaryIndexForFile(
1147                       CGOpts.ThinLTOIndexFile,
1148                       /*IgnoreEmptyThinLTOIndexFile*/ true)
1149                       .moveInto(CombinedIndex)) {
1150       logAllUnhandledErrors(std::move(E), errs(),
1151                             "Error loading index file '" +
1152                             CGOpts.ThinLTOIndexFile + "': ");
1153       return;
1154     }
1155 
1156     // A null CombinedIndex means we should skip ThinLTO compilation
1157     // (LLVM will optionally ignore empty index files, returning null instead
1158     // of an error).
1159     if (CombinedIndex) {
1160       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1161         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1162                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1163                           CGOpts.ProfileRemappingFile, Action);
1164         return;
1165       }
1166       // Distributed indexing detected that nothing from the module is needed
1167       // for the final linking. So we can skip the compilation. We sill need to
1168       // output an empty object file to make sure that a linker does not fail
1169       // trying to read it. Also for some features, like CFI, we must skip
1170       // the compilation as CombinedIndex does not contain all required
1171       // information.
1172       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1173       EmptyModule->setTargetTriple(M->getTargetTriple());
1174       M = EmptyModule.get();
1175     }
1176   }
1177 
1178   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1179   AsmHelper.EmitAssembly(Action, std::move(OS));
1180 
1181   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1182   // DataLayout.
1183   if (AsmHelper.TM) {
1184     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1185     if (DLDesc != TDesc) {
1186       unsigned DiagID = Diags.getCustomDiagID(
1187           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1188                                     "expected target description '%1'");
1189       Diags.Report(DiagID) << DLDesc << TDesc;
1190     }
1191   }
1192 }
1193 
1194 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1195 // __LLVM,__bitcode section.
1196 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1197                          llvm::MemoryBufferRef Buf) {
1198   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1199     return;
1200   llvm::embedBitcodeInModule(
1201       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1202       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1203       CGOpts.CmdArgs);
1204 }
1205 
1206 void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1207                         DiagnosticsEngine &Diags) {
1208   if (CGOpts.OffloadObjects.empty())
1209     return;
1210 
1211   for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1212     SmallVector<StringRef, 4> ObjectFields;
1213     OffloadObject.split(ObjectFields, ',');
1214 
1215     if (ObjectFields.size() != 4) {
1216       auto DiagID = Diags.getCustomDiagID(
1217           DiagnosticsEngine::Error, "Expected at least four arguments '%0'");
1218       Diags.Report(DiagID) << OffloadObject;
1219       return;
1220     }
1221 
1222     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1223         llvm::MemoryBuffer::getFileOrSTDIN(ObjectFields[0]);
1224     if (std::error_code EC = ObjectOrErr.getError()) {
1225       auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1226                                           "could not open '%0' for embedding");
1227       Diags.Report(DiagID) << ObjectFields[0];
1228       return;
1229     }
1230 
1231     OffloadBinary::OffloadingImage Image{};
1232     Image.TheImageKind = getImageKind(ObjectFields[0].rsplit(".").second);
1233     Image.TheOffloadKind = getOffloadKind(ObjectFields[1]);
1234     Image.StringData = {{"triple", ObjectFields[2]}, {"arch", ObjectFields[3]}};
1235     Image.Image = **ObjectOrErr;
1236 
1237     std::unique_ptr<MemoryBuffer> OffloadBuffer = OffloadBinary::write(Image);
1238     llvm::embedBufferInModule(*M, *OffloadBuffer, ".llvm.offloading",
1239                               Align(OffloadBinary::getAlignment()));
1240   }
1241 }
1242