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