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 =
459       CodeGenOpts.NoDwarfDirectoryAsm
460           ? llvm::MCTargetOptions::DisableDwarfDirectory
461           : llvm::MCTargetOptions::EnableDwarfDirectory;
462   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
463   Options.MCOptions.MCIncrementalLinkerCompatible =
464       CodeGenOpts.IncrementalLinkerCompatible;
465   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
466   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
467   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
468   Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
469   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
470   Options.MCOptions.ABIName = TargetOpts.ABI;
471   for (const auto &Entry : HSOpts.UserEntries)
472     if (!Entry.IsFramework &&
473         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
474          Entry.Group == frontend::IncludeDirGroup::Angled ||
475          Entry.Group == frontend::IncludeDirGroup::System))
476       Options.MCOptions.IASSearchPaths.push_back(
477           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
478   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
479   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
480   Options.MisExpect = CodeGenOpts.MisExpect;
481 
482   return true;
483 }
484 
485 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
486                                             const LangOptions &LangOpts) {
487   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
488     return None;
489   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
490   // LLVM's -default-gcov-version flag is set to something invalid.
491   GCOVOptions Options;
492   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
493   Options.EmitData = CodeGenOpts.EmitGcovArcs;
494   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
495   Options.NoRedZone = CodeGenOpts.DisableRedZone;
496   Options.Filter = CodeGenOpts.ProfileFilterFiles;
497   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
498   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
499   return Options;
500 }
501 
502 static Optional<InstrProfOptions>
503 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
504                     const LangOptions &LangOpts) {
505   if (!CodeGenOpts.hasProfileClangInstr())
506     return None;
507   InstrProfOptions Options;
508   Options.NoRedZone = CodeGenOpts.DisableRedZone;
509   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
510   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
511   return Options;
512 }
513 
514 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
515   SmallVector<const char *, 16> BackendArgs;
516   BackendArgs.push_back("clang"); // Fake program name.
517   if (!CodeGenOpts.DebugPass.empty()) {
518     BackendArgs.push_back("-debug-pass");
519     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
520   }
521   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
522     BackendArgs.push_back("-limit-float-precision");
523     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
524   }
525   // Check for the default "clang" invocation that won't set any cl::opt values.
526   // Skip trying to parse the command line invocation to avoid the issues
527   // described below.
528   if (BackendArgs.size() == 1)
529     return;
530   BackendArgs.push_back(nullptr);
531   // FIXME: The command line parser below is not thread-safe and shares a global
532   // state, so this call might crash or overwrite the options of another Clang
533   // instance in the same process.
534   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
535                                     BackendArgs.data());
536 }
537 
538 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
539   // Create the TargetMachine for generating code.
540   std::string Error;
541   std::string Triple = TheModule->getTargetTriple();
542   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
543   if (!TheTarget) {
544     if (MustCreateTM)
545       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
546     return;
547   }
548 
549   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
550   std::string FeaturesStr =
551       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
552   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
553   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
554 
555   llvm::TargetOptions Options;
556   if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
557                          HSOpts))
558     return;
559   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
560                                           Options, RM, CM, OptLevel));
561 }
562 
563 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
564                                        BackendAction Action,
565                                        raw_pwrite_stream &OS,
566                                        raw_pwrite_stream *DwoOS) {
567   // Add LibraryInfo.
568   std::unique_ptr<TargetLibraryInfoImpl> TLII(
569       createTLII(TargetTriple, CodeGenOpts));
570   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
571 
572   // Normal mode, emit a .s or .o file by running the code generator. Note,
573   // this also adds codegenerator level optimization passes.
574   CodeGenFileType CGFT = getCodeGenFileType(Action);
575 
576   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
577   // "codegen" passes so that it isn't run multiple times when there is
578   // inlining happening.
579   if (CodeGenOpts.OptimizationLevel > 0)
580     CodeGenPasses.add(createObjCARCContractPass());
581 
582   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
583                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
584     Diags.Report(diag::err_fe_unable_to_interface_with_target);
585     return false;
586   }
587 
588   return true;
589 }
590 
591 static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
592   switch (Opts.OptimizationLevel) {
593   default:
594     llvm_unreachable("Invalid optimization level!");
595 
596   case 0:
597     return OptimizationLevel::O0;
598 
599   case 1:
600     return OptimizationLevel::O1;
601 
602   case 2:
603     switch (Opts.OptimizeSize) {
604     default:
605       llvm_unreachable("Invalid optimization level for size!");
606 
607     case 0:
608       return OptimizationLevel::O2;
609 
610     case 1:
611       return OptimizationLevel::Os;
612 
613     case 2:
614       return OptimizationLevel::Oz;
615     }
616 
617   case 3:
618     return OptimizationLevel::O3;
619   }
620 }
621 
622 static void addSanitizers(const Triple &TargetTriple,
623                           const CodeGenOptions &CodeGenOpts,
624                           const LangOptions &LangOpts, PassBuilder &PB) {
625   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
626                                          OptimizationLevel Level) {
627     if (CodeGenOpts.hasSanitizeCoverage()) {
628       auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
629       MPM.addPass(ModuleSanitizerCoveragePass(
630           SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
631           CodeGenOpts.SanitizeCoverageIgnorelistFiles));
632     }
633 
634     auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
635       if (LangOpts.Sanitize.has(Mask)) {
636         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
637         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
638 
639         MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
640                                        CodeGenOpts.SanitizeMemoryParamRetval);
641         MPM.addPass(ModuleMemorySanitizerPass(options));
642         FunctionPassManager FPM;
643         FPM.addPass(MemorySanitizerPass(options));
644         if (Level != OptimizationLevel::O0) {
645           // MemorySanitizer inserts complex instrumentation that mostly
646           // follows the logic of the original code, but operates on
647           // "shadow" values. It can benefit from re-running some
648           // general purpose optimization passes.
649           FPM.addPass(EarlyCSEPass());
650           // TODO: Consider add more passes like in
651           // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
652           // difference on size. It's not clear if the rest is still
653           // usefull. InstCombinePass breakes
654           // compiler-rt/test/msan/select_origin.cpp.
655         }
656         MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
657       }
658     };
659     MSanPass(SanitizerKind::Memory, false);
660     MSanPass(SanitizerKind::KernelMemory, true);
661 
662     if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
663       MPM.addPass(ModuleThreadSanitizerPass());
664       MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
665     }
666 
667     auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
668       if (LangOpts.Sanitize.has(Mask)) {
669         bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
670         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
671         llvm::AsanDtorKind DestructorKind =
672             CodeGenOpts.getSanitizeAddressDtor();
673         AddressSanitizerOptions Opts;
674         Opts.CompileKernel = CompileKernel;
675         Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
676         Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
677         Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
678         MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
679         MPM.addPass(ModuleAddressSanitizerPass(
680             Opts, UseGlobalGC, UseOdrIndicator, DestructorKind));
681       }
682     };
683     ASanPass(SanitizerKind::Address, false);
684     ASanPass(SanitizerKind::KernelAddress, true);
685 
686     auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
687       if (LangOpts.Sanitize.has(Mask)) {
688         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
689         MPM.addPass(HWAddressSanitizerPass(
690             {CompileKernel, Recover,
691              /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
692       }
693     };
694     HWASanPass(SanitizerKind::HWAddress, false);
695     HWASanPass(SanitizerKind::KernelHWAddress, true);
696 
697     if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
698       MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
699     }
700   });
701 }
702 
703 void EmitAssemblyHelper::RunOptimizationPipeline(
704     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
705     std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS) {
706   Optional<PGOOptions> PGOOpt;
707 
708   if (CodeGenOpts.hasProfileIRInstr())
709     // -fprofile-generate.
710     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
711                             ? getDefaultProfileGenName()
712                             : CodeGenOpts.InstrProfileOutput,
713                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
714                         CodeGenOpts.DebugInfoForProfiling);
715   else if (CodeGenOpts.hasProfileIRUse()) {
716     // -fprofile-use.
717     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
718                                                     : PGOOptions::NoCSAction;
719     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
720                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
721                         CSAction, CodeGenOpts.DebugInfoForProfiling);
722   } else if (!CodeGenOpts.SampleProfileFile.empty())
723     // -fprofile-sample-use
724     PGOOpt = PGOOptions(
725         CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
726         PGOOptions::SampleUse, PGOOptions::NoCSAction,
727         CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
728   else if (CodeGenOpts.PseudoProbeForProfiling)
729     // -fpseudo-probe-for-profiling
730     PGOOpt =
731         PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
732                    CodeGenOpts.DebugInfoForProfiling, true);
733   else if (CodeGenOpts.DebugInfoForProfiling)
734     // -fdebug-info-for-profiling
735     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
736                         PGOOptions::NoCSAction, true);
737 
738   // Check to see if we want to generate a CS profile.
739   if (CodeGenOpts.hasProfileCSIRInstr()) {
740     assert(!CodeGenOpts.hasProfileCSIRUse() &&
741            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
742            "the same time");
743     if (PGOOpt.hasValue()) {
744       assert(PGOOpt->Action != PGOOptions::IRInstr &&
745              PGOOpt->Action != PGOOptions::SampleUse &&
746              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
747              " pass");
748       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
749                                      ? getDefaultProfileGenName()
750                                      : CodeGenOpts.InstrProfileOutput;
751       PGOOpt->CSAction = PGOOptions::CSIRInstr;
752     } else
753       PGOOpt = PGOOptions("",
754                           CodeGenOpts.InstrProfileOutput.empty()
755                               ? getDefaultProfileGenName()
756                               : CodeGenOpts.InstrProfileOutput,
757                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
758                           CodeGenOpts.DebugInfoForProfiling);
759   }
760   if (TM)
761     TM->setPGOOption(PGOOpt);
762 
763   PipelineTuningOptions PTO;
764   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
765   // For historical reasons, loop interleaving is set to mirror setting for loop
766   // unrolling.
767   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
768   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
769   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
770   PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
771   // Only enable CGProfilePass when using integrated assembler, since
772   // non-integrated assemblers don't recognize .cgprofile section.
773   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
774 
775   LoopAnalysisManager LAM;
776   FunctionAnalysisManager FAM;
777   CGSCCAnalysisManager CGAM;
778   ModuleAnalysisManager MAM;
779 
780   bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
781   PassInstrumentationCallbacks PIC;
782   PrintPassOptions PrintPassOpts;
783   PrintPassOpts.Indent = DebugPassStructure;
784   PrintPassOpts.SkipAnalyses = DebugPassStructure;
785   StandardInstrumentations SI(CodeGenOpts.DebugPassManager ||
786                                   DebugPassStructure,
787                               /*VerifyEach*/ false, PrintPassOpts);
788   SI.registerCallbacks(PIC, &FAM);
789   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
790 
791   // Attempt to load pass plugins and register their callbacks with PB.
792   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
793     auto PassPlugin = PassPlugin::Load(PluginFN);
794     if (PassPlugin) {
795       PassPlugin->registerPassBuilderCallbacks(PB);
796     } else {
797       Diags.Report(diag::err_fe_unable_to_load_plugin)
798           << PluginFN << toString(PassPlugin.takeError());
799     }
800   }
801 #define HANDLE_EXTENSION(Ext)                                                  \
802   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
803 #include "llvm/Support/Extension.def"
804 
805   // Register the target library analysis directly and give it a customized
806   // preset TLI.
807   std::unique_ptr<TargetLibraryInfoImpl> TLII(
808       createTLII(TargetTriple, CodeGenOpts));
809   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
810 
811   // Register all the basic analyses with the managers.
812   PB.registerModuleAnalyses(MAM);
813   PB.registerCGSCCAnalyses(CGAM);
814   PB.registerFunctionAnalyses(FAM);
815   PB.registerLoopAnalyses(LAM);
816   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
817 
818   ModulePassManager MPM;
819 
820   if (!CodeGenOpts.DisableLLVMPasses) {
821     // Map our optimization levels into one of the distinct levels used to
822     // configure the pipeline.
823     OptimizationLevel Level = mapToLevel(CodeGenOpts);
824 
825     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
826     bool IsLTO = CodeGenOpts.PrepareForLTO;
827 
828     if (LangOpts.ObjCAutoRefCount) {
829       PB.registerPipelineStartEPCallback(
830           [](ModulePassManager &MPM, OptimizationLevel Level) {
831             if (Level != OptimizationLevel::O0)
832               MPM.addPass(
833                   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
834           });
835       PB.registerPipelineEarlySimplificationEPCallback(
836           [](ModulePassManager &MPM, OptimizationLevel Level) {
837             if (Level != OptimizationLevel::O0)
838               MPM.addPass(ObjCARCAPElimPass());
839           });
840       PB.registerScalarOptimizerLateEPCallback(
841           [](FunctionPassManager &FPM, OptimizationLevel Level) {
842             if (Level != OptimizationLevel::O0)
843               FPM.addPass(ObjCARCOptPass());
844           });
845     }
846 
847     // If we reached here with a non-empty index file name, then the index
848     // file was empty and we are not performing ThinLTO backend compilation
849     // (used in testing in a distributed build environment).
850     bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
851     // If so drop any the type test assume sequences inserted for whole program
852     // vtables so that codegen doesn't complain.
853     if (IsThinLTOPostLink)
854       PB.registerPipelineStartEPCallback(
855           [](ModulePassManager &MPM, OptimizationLevel Level) {
856             MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
857                                            /*ImportSummary=*/nullptr,
858                                            /*DropTypeTests=*/true));
859           });
860 
861     if (CodeGenOpts.InstrumentFunctions ||
862         CodeGenOpts.InstrumentFunctionEntryBare ||
863         CodeGenOpts.InstrumentFunctionsAfterInlining ||
864         CodeGenOpts.InstrumentForProfiling) {
865       PB.registerPipelineStartEPCallback(
866           [](ModulePassManager &MPM, OptimizationLevel Level) {
867             MPM.addPass(createModuleToFunctionPassAdaptor(
868                 EntryExitInstrumenterPass(/*PostInlining=*/false)));
869           });
870       PB.registerOptimizerLastEPCallback(
871           [](ModulePassManager &MPM, OptimizationLevel Level) {
872             MPM.addPass(createModuleToFunctionPassAdaptor(
873                 EntryExitInstrumenterPass(/*PostInlining=*/true)));
874           });
875     }
876 
877     // Register callbacks to schedule sanitizer passes at the appropriate part
878     // of the pipeline.
879     if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
880       PB.registerScalarOptimizerLateEPCallback(
881           [](FunctionPassManager &FPM, OptimizationLevel Level) {
882             FPM.addPass(BoundsCheckingPass());
883           });
884 
885     // Don't add sanitizers if we are here from ThinLTO PostLink. That already
886     // done on PreLink stage.
887     if (!IsThinLTOPostLink)
888       addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
889 
890     if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
891       PB.registerPipelineStartEPCallback(
892           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
893             MPM.addPass(GCOVProfilerPass(*Options));
894           });
895     if (Optional<InstrProfOptions> Options =
896             getInstrProfOptions(CodeGenOpts, LangOpts))
897       PB.registerPipelineStartEPCallback(
898           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
899             MPM.addPass(InstrProfiling(*Options, false));
900           });
901 
902     if (CodeGenOpts.OptimizationLevel == 0) {
903       MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
904     } else if (IsThinLTO) {
905       MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
906     } else if (IsLTO) {
907       MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
908     } else {
909       MPM = PB.buildPerModuleDefaultPipeline(Level);
910     }
911 
912     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
913       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
914       MPM.addPass(ModuleMemProfilerPass());
915     }
916   }
917 
918   // Add a verifier pass if requested. We don't have to do this if the action
919   // requires code generation because there will already be a verifier pass in
920   // the code-generation pipeline.
921   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
922     MPM.addPass(VerifierPass());
923 
924   switch (Action) {
925   case Backend_EmitBC:
926     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
927       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
928         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
929         if (!ThinLinkOS)
930           return;
931       }
932       if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
933         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
934                                  CodeGenOpts.EnableSplitLTOUnit);
935       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
936                                                            : nullptr));
937     } else {
938       // Emit a module summary by default for Regular LTO except for ld64
939       // targets
940       bool EmitLTOSummary = shouldEmitRegularLTOSummary();
941       if (EmitLTOSummary) {
942         if (!TheModule->getModuleFlag("ThinLTO"))
943           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
944         if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
945           TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
946                                    uint32_t(1));
947       }
948       MPM.addPass(
949           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
950     }
951     break;
952 
953   case Backend_EmitLL:
954     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
955     break;
956 
957   default:
958     break;
959   }
960 
961   // Now that we have all of the passes ready, run them.
962   {
963     PrettyStackTraceString CrashInfo("Optimizer");
964     llvm::TimeTraceScope TimeScope("Optimizer");
965     MPM.run(*TheModule, MAM);
966   }
967 }
968 
969 void EmitAssemblyHelper::RunCodegenPipeline(
970     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
971     std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
972   // We still use the legacy PM to run the codegen pipeline since the new PM
973   // does not work with the codegen pipeline.
974   // FIXME: make the new PM work with the codegen pipeline.
975   legacy::PassManager CodeGenPasses;
976 
977   // Append any output we need to the pass manager.
978   switch (Action) {
979   case Backend_EmitAssembly:
980   case Backend_EmitMCNull:
981   case Backend_EmitObj:
982     CodeGenPasses.add(
983         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
984     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
985       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
986       if (!DwoOS)
987         return;
988     }
989     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
990                        DwoOS ? &DwoOS->os() : nullptr))
991       // FIXME: Should we handle this error differently?
992       return;
993     break;
994   default:
995     return;
996   }
997 
998   {
999     PrettyStackTraceString CrashInfo("Code generation");
1000     llvm::TimeTraceScope TimeScope("CodeGenPasses");
1001     CodeGenPasses.run(*TheModule);
1002   }
1003 }
1004 
1005 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
1006                                       std::unique_ptr<raw_pwrite_stream> OS) {
1007   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1008   setCommandLineOpts(CodeGenOpts);
1009 
1010   bool RequiresCodeGen = actionRequiresCodeGen(Action);
1011   CreateTargetMachine(RequiresCodeGen);
1012 
1013   if (RequiresCodeGen && !TM)
1014     return;
1015   if (TM)
1016     TheModule->setDataLayout(TM->createDataLayout());
1017 
1018   // Before executing passes, print the final values of the LLVM options.
1019   cl::PrintOptionValues();
1020 
1021   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1022   RunOptimizationPipeline(Action, OS, ThinLinkOS);
1023   RunCodegenPipeline(Action, OS, DwoOS);
1024 
1025   if (ThinLinkOS)
1026     ThinLinkOS->keep();
1027   if (DwoOS)
1028     DwoOS->keep();
1029 }
1030 
1031 static void runThinLTOBackend(
1032     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1033     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1034     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1035     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1036     std::string ProfileRemapping, BackendAction Action) {
1037   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1038       ModuleToDefinedGVSummaries;
1039   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1040 
1041   setCommandLineOpts(CGOpts);
1042 
1043   // We can simply import the values mentioned in the combined index, since
1044   // we should only invoke this using the individual indexes written out
1045   // via a WriteIndexesThinBackend.
1046   FunctionImporter::ImportMapTy ImportList;
1047   if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1048     return;
1049 
1050   auto AddStream = [&](size_t Task) {
1051     return std::make_unique<CachedFileStream>(std::move(OS),
1052                                               CGOpts.ObjectFilenameForDebug);
1053   };
1054   lto::Config Conf;
1055   if (CGOpts.SaveTempsFilePrefix != "") {
1056     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1057                                     /* UseInputModulePath */ false)) {
1058       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1059         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1060                << '\n';
1061       });
1062     }
1063   }
1064   Conf.CPU = TOpts.CPU;
1065   Conf.CodeModel = getCodeModel(CGOpts);
1066   Conf.MAttrs = TOpts.Features;
1067   Conf.RelocModel = CGOpts.RelocationModel;
1068   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1069   Conf.OptLevel = CGOpts.OptimizationLevel;
1070   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1071   Conf.SampleProfile = std::move(SampleProfile);
1072   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1073   // For historical reasons, loop interleaving is set to mirror setting for loop
1074   // unrolling.
1075   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1076   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1077   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1078   // Only enable CGProfilePass when using integrated assembler, since
1079   // non-integrated assemblers don't recognize .cgprofile section.
1080   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1081 
1082   // Context sensitive profile.
1083   if (CGOpts.hasProfileCSIRInstr()) {
1084     Conf.RunCSIRInstr = true;
1085     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1086   } else if (CGOpts.hasProfileCSIRUse()) {
1087     Conf.RunCSIRInstr = false;
1088     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1089   }
1090 
1091   Conf.ProfileRemapping = std::move(ProfileRemapping);
1092   Conf.DebugPassManager = CGOpts.DebugPassManager;
1093   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1094   Conf.RemarksFilename = CGOpts.OptRecordFile;
1095   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1096   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1097   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1098   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1099   switch (Action) {
1100   case Backend_EmitNothing:
1101     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1102       return false;
1103     };
1104     break;
1105   case Backend_EmitLL:
1106     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1107       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1108       return false;
1109     };
1110     break;
1111   case Backend_EmitBC:
1112     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1113       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1114       return false;
1115     };
1116     break;
1117   default:
1118     Conf.CGFileType = getCodeGenFileType(Action);
1119     break;
1120   }
1121   if (Error E =
1122           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1123                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1124                       /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1125     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1126       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1127     });
1128   }
1129 }
1130 
1131 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1132                               const HeaderSearchOptions &HeaderOpts,
1133                               const CodeGenOptions &CGOpts,
1134                               const clang::TargetOptions &TOpts,
1135                               const LangOptions &LOpts,
1136                               StringRef TDesc, Module *M,
1137                               BackendAction Action,
1138                               std::unique_ptr<raw_pwrite_stream> OS) {
1139 
1140   llvm::TimeTraceScope TimeScope("Backend");
1141 
1142   std::unique_ptr<llvm::Module> EmptyModule;
1143   if (!CGOpts.ThinLTOIndexFile.empty()) {
1144     // If we are performing a ThinLTO importing compile, load the function index
1145     // into memory and pass it into runThinLTOBackend, which will run the
1146     // function importer and invoke LTO passes.
1147     std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1148     if (Error E = llvm::getModuleSummaryIndexForFile(
1149                       CGOpts.ThinLTOIndexFile,
1150                       /*IgnoreEmptyThinLTOIndexFile*/ true)
1151                       .moveInto(CombinedIndex)) {
1152       logAllUnhandledErrors(std::move(E), errs(),
1153                             "Error loading index file '" +
1154                             CGOpts.ThinLTOIndexFile + "': ");
1155       return;
1156     }
1157 
1158     // A null CombinedIndex means we should skip ThinLTO compilation
1159     // (LLVM will optionally ignore empty index files, returning null instead
1160     // of an error).
1161     if (CombinedIndex) {
1162       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1163         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1164                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1165                           CGOpts.ProfileRemappingFile, Action);
1166         return;
1167       }
1168       // Distributed indexing detected that nothing from the module is needed
1169       // for the final linking. So we can skip the compilation. We sill need to
1170       // output an empty object file to make sure that a linker does not fail
1171       // trying to read it. Also for some features, like CFI, we must skip
1172       // the compilation as CombinedIndex does not contain all required
1173       // information.
1174       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1175       EmptyModule->setTargetTriple(M->getTargetTriple());
1176       M = EmptyModule.get();
1177     }
1178   }
1179 
1180   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1181   AsmHelper.EmitAssembly(Action, std::move(OS));
1182 
1183   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1184   // DataLayout.
1185   if (AsmHelper.TM) {
1186     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1187     if (DLDesc != TDesc) {
1188       unsigned DiagID = Diags.getCustomDiagID(
1189           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1190                                     "expected target description '%1'");
1191       Diags.Report(DiagID) << DLDesc << TDesc;
1192     }
1193   }
1194 }
1195 
1196 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1197 // __LLVM,__bitcode section.
1198 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1199                          llvm::MemoryBufferRef Buf) {
1200   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1201     return;
1202   llvm::embedBitcodeInModule(
1203       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1204       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1205       CGOpts.CmdArgs);
1206 }
1207 
1208 void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1209                         DiagnosticsEngine &Diags) {
1210   if (CGOpts.OffloadObjects.empty())
1211     return;
1212 
1213   for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1214     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1215         llvm::MemoryBuffer::getFileOrSTDIN(OffloadObject);
1216     if (std::error_code EC = ObjectOrErr.getError()) {
1217       auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1218                                           "could not open '%0' for embedding");
1219       Diags.Report(DiagID) << OffloadObject;
1220       return;
1221     }
1222 
1223     llvm::embedBufferInModule(*M, **ObjectOrErr, ".llvm.offloading",
1224                               Align(OffloadBinary::getAlignment()));
1225   }
1226 }
1227