1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/CodeGen/BackendUtil.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/Utils.h"
17 #include "clang/Lex/HeaderSearchOptions.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/Bitcode/BitcodeWriter.h"
26 #include "llvm/Bitcode/BitcodeWriterPass.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSummaryIndex.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/LTO/LTOBackend.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Passes/PassBuilder.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/PrettyStackTrace.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Transforms/Coroutines.h"
49 #include "llvm/Transforms/GCOVProfiler.h"
50 #include "llvm/Transforms/IPO.h"
51 #include "llvm/Transforms/IPO/AlwaysInliner.h"
52 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
54 #include "llvm/Transforms/Instrumentation.h"
55 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
56 #include "llvm/Transforms/ObjCARC.h"
57 #include "llvm/Transforms/Scalar.h"
58 #include "llvm/Transforms/Scalar/GVN.h"
59 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
60 #include "llvm/Transforms/Utils/SymbolRewriter.h"
61 #include <memory>
62 using namespace clang;
63 using namespace llvm;
64 
65 namespace {
66 
67 // Default filename used for profile generation.
68 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
69 
70 class EmitAssemblyHelper {
71   DiagnosticsEngine &Diags;
72   const HeaderSearchOptions &HSOpts;
73   const CodeGenOptions &CodeGenOpts;
74   const clang::TargetOptions &TargetOpts;
75   const LangOptions &LangOpts;
76   Module *TheModule;
77 
78   Timer CodeGenerationTime;
79 
80   std::unique_ptr<raw_pwrite_stream> OS;
81 
82   TargetIRAnalysis getTargetIRAnalysis() const {
83     if (TM)
84       return TM->getTargetIRAnalysis();
85 
86     return TargetIRAnalysis();
87   }
88 
89   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
90 
91   /// Generates the TargetMachine.
92   /// Leaves TM unchanged if it is unable to create the target machine.
93   /// Some of our clang tests specify triples which are not built
94   /// into clang. This is okay because these tests check the generated
95   /// IR, and they require DataLayout which depends on the triple.
96   /// In this case, we allow this method to fail and not report an error.
97   /// When MustCreateTM is used, we print an error if we are unable to load
98   /// the requested target.
99   void CreateTargetMachine(bool MustCreateTM);
100 
101   /// Add passes necessary to emit assembly or LLVM IR.
102   ///
103   /// \return True on success.
104   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
105                      raw_pwrite_stream &OS);
106 
107 public:
108   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
109                      const HeaderSearchOptions &HeaderSearchOpts,
110                      const CodeGenOptions &CGOpts,
111                      const clang::TargetOptions &TOpts,
112                      const LangOptions &LOpts, Module *M)
113       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
114         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
115         CodeGenerationTime("codegen", "Code Generation Time") {}
116 
117   ~EmitAssemblyHelper() {
118     if (CodeGenOpts.DisableFree)
119       BuryPointer(std::move(TM));
120   }
121 
122   std::unique_ptr<TargetMachine> TM;
123 
124   void EmitAssembly(BackendAction Action,
125                     std::unique_ptr<raw_pwrite_stream> OS);
126 
127   void EmitAssemblyWithNewPassManager(BackendAction Action,
128                                       std::unique_ptr<raw_pwrite_stream> OS);
129 };
130 
131 // We need this wrapper to access LangOpts and CGOpts from extension functions
132 // that we add to the PassManagerBuilder.
133 class PassManagerBuilderWrapper : public PassManagerBuilder {
134 public:
135   PassManagerBuilderWrapper(const Triple &TargetTriple,
136                             const CodeGenOptions &CGOpts,
137                             const LangOptions &LangOpts)
138       : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
139         LangOpts(LangOpts) {}
140   const Triple &getTargetTriple() const { return TargetTriple; }
141   const CodeGenOptions &getCGOpts() const { return CGOpts; }
142   const LangOptions &getLangOpts() const { return LangOpts; }
143 
144 private:
145   const Triple &TargetTriple;
146   const CodeGenOptions &CGOpts;
147   const LangOptions &LangOpts;
148 };
149 }
150 
151 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
152   if (Builder.OptLevel > 0)
153     PM.add(createObjCARCAPElimPass());
154 }
155 
156 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
157   if (Builder.OptLevel > 0)
158     PM.add(createObjCARCExpandPass());
159 }
160 
161 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
162   if (Builder.OptLevel > 0)
163     PM.add(createObjCARCOptPass());
164 }
165 
166 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
167                                      legacy::PassManagerBase &PM) {
168   PM.add(createAddDiscriminatorsPass());
169 }
170 
171 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
172                                   legacy::PassManagerBase &PM) {
173   PM.add(createBoundsCheckingLegacyPass());
174 }
175 
176 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
177                                      legacy::PassManagerBase &PM) {
178   const PassManagerBuilderWrapper &BuilderWrapper =
179       static_cast<const PassManagerBuilderWrapper&>(Builder);
180   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
181   SanitizerCoverageOptions Opts;
182   Opts.CoverageType =
183       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
184   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
185   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
186   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
187   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
188   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
189   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
190   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
191   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
192   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
193   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
194   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
195   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
196   PM.add(createSanitizerCoverageModulePass(Opts));
197 }
198 
199 // Check if ASan should use GC-friendly instrumentation for globals.
200 // First of all, there is no point if -fdata-sections is off (expect for MachO,
201 // where this is not a factor). Also, on ELF this feature requires an assembler
202 // extension that only works with -integrated-as at the moment.
203 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
204   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
205     return false;
206   switch (T.getObjectFormat()) {
207   case Triple::MachO:
208   case Triple::COFF:
209     return true;
210   case Triple::ELF:
211     return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
212   default:
213     return false;
214   }
215 }
216 
217 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
218                                       legacy::PassManagerBase &PM) {
219   const PassManagerBuilderWrapper &BuilderWrapper =
220       static_cast<const PassManagerBuilderWrapper&>(Builder);
221   const Triple &T = BuilderWrapper.getTargetTriple();
222   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
223   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
224   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
225   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
226   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
227                                             UseAfterScope));
228   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
229                                           UseGlobalsGC));
230 }
231 
232 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
233                                             legacy::PassManagerBase &PM) {
234   PM.add(createAddressSanitizerFunctionPass(
235       /*CompileKernel*/ true,
236       /*Recover*/ true, /*UseAfterScope*/ false));
237   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
238                                           /*Recover*/true));
239 }
240 
241 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
242                                             legacy::PassManagerBase &PM) {
243   const PassManagerBuilderWrapper &BuilderWrapper =
244       static_cast<const PassManagerBuilderWrapper &>(Builder);
245   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
246   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
247   PM.add(createHWAddressSanitizerPass(Recover));
248 }
249 
250 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
251                                    legacy::PassManagerBase &PM) {
252   const PassManagerBuilderWrapper &BuilderWrapper =
253       static_cast<const PassManagerBuilderWrapper&>(Builder);
254   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
255   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
256   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
257   PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
258 
259   // MemorySanitizer inserts complex instrumentation that mostly follows
260   // the logic of the original code, but operates on "shadow" values.
261   // It can benefit from re-running some general purpose optimization passes.
262   if (Builder.OptLevel > 0) {
263     PM.add(createEarlyCSEPass());
264     PM.add(createReassociatePass());
265     PM.add(createLICMPass());
266     PM.add(createGVNPass());
267     PM.add(createInstructionCombiningPass());
268     PM.add(createDeadStoreEliminationPass());
269   }
270 }
271 
272 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
273                                    legacy::PassManagerBase &PM) {
274   PM.add(createThreadSanitizerPass());
275 }
276 
277 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
278                                      legacy::PassManagerBase &PM) {
279   const PassManagerBuilderWrapper &BuilderWrapper =
280       static_cast<const PassManagerBuilderWrapper&>(Builder);
281   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
282   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
283 }
284 
285 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
286                                        legacy::PassManagerBase &PM) {
287   const PassManagerBuilderWrapper &BuilderWrapper =
288       static_cast<const PassManagerBuilderWrapper&>(Builder);
289   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
290   EfficiencySanitizerOptions Opts;
291   if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
292     Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
293   else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
294     Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
295   PM.add(createEfficiencySanitizerPass(Opts));
296 }
297 
298 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
299                                          const CodeGenOptions &CodeGenOpts) {
300   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
301   if (!CodeGenOpts.SimplifyLibCalls)
302     TLII->disableAllFunctions();
303   else {
304     // Disable individual libc/libm calls in TargetLibraryInfo.
305     LibFunc F;
306     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
307       if (TLII->getLibFunc(FuncName, F))
308         TLII->setUnavailable(F);
309   }
310 
311   switch (CodeGenOpts.getVecLib()) {
312   case CodeGenOptions::Accelerate:
313     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
314     break;
315   case CodeGenOptions::SVML:
316     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
317     break;
318   default:
319     break;
320   }
321   return TLII;
322 }
323 
324 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
325                                   legacy::PassManager *MPM) {
326   llvm::SymbolRewriter::RewriteDescriptorList DL;
327 
328   llvm::SymbolRewriter::RewriteMapParser MapParser;
329   for (const auto &MapFile : Opts.RewriteMapFiles)
330     MapParser.parse(MapFile, &DL);
331 
332   MPM->add(createRewriteSymbolsPass(DL));
333 }
334 
335 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
336   switch (CodeGenOpts.OptimizationLevel) {
337   default:
338     llvm_unreachable("Invalid optimization level!");
339   case 0:
340     return CodeGenOpt::None;
341   case 1:
342     return CodeGenOpt::Less;
343   case 2:
344     return CodeGenOpt::Default; // O2/Os/Oz
345   case 3:
346     return CodeGenOpt::Aggressive;
347   }
348 }
349 
350 static Optional<llvm::CodeModel::Model>
351 getCodeModel(const CodeGenOptions &CodeGenOpts) {
352   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
353                            .Case("small", llvm::CodeModel::Small)
354                            .Case("kernel", llvm::CodeModel::Kernel)
355                            .Case("medium", llvm::CodeModel::Medium)
356                            .Case("large", llvm::CodeModel::Large)
357                            .Case("default", ~1u)
358                            .Default(~0u);
359   assert(CodeModel != ~0u && "invalid code model!");
360   if (CodeModel == ~1u)
361     return None;
362   return static_cast<llvm::CodeModel::Model>(CodeModel);
363 }
364 
365 static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
366   if (Action == Backend_EmitObj)
367     return TargetMachine::CGFT_ObjectFile;
368   else if (Action == Backend_EmitMCNull)
369     return TargetMachine::CGFT_Null;
370   else {
371     assert(Action == Backend_EmitAssembly && "Invalid action!");
372     return TargetMachine::CGFT_AssemblyFile;
373   }
374 }
375 
376 static void initTargetOptions(llvm::TargetOptions &Options,
377                               const CodeGenOptions &CodeGenOpts,
378                               const clang::TargetOptions &TargetOpts,
379                               const LangOptions &LangOpts,
380                               const HeaderSearchOptions &HSOpts) {
381   Options.ThreadModel =
382       llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
383           .Case("posix", llvm::ThreadModel::POSIX)
384           .Case("single", llvm::ThreadModel::Single);
385 
386   // Set float ABI type.
387   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
388           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
389          "Invalid Floating Point ABI!");
390   Options.FloatABIType =
391       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
392           .Case("soft", llvm::FloatABI::Soft)
393           .Case("softfp", llvm::FloatABI::Soft)
394           .Case("hard", llvm::FloatABI::Hard)
395           .Default(llvm::FloatABI::Default);
396 
397   // Set FP fusion mode.
398   switch (LangOpts.getDefaultFPContractMode()) {
399   case LangOptions::FPC_Off:
400     // Preserve any contraction performed by the front-end.  (Strict performs
401     // splitting of the muladd instrinsic in the backend.)
402     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
403     break;
404   case LangOptions::FPC_On:
405     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
406     break;
407   case LangOptions::FPC_Fast:
408     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
409     break;
410   }
411 
412   Options.UseInitArray = CodeGenOpts.UseInitArray;
413   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
414   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
415   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
416 
417   // Set EABI version.
418   Options.EABIVersion = TargetOpts.EABIVersion;
419 
420   if (LangOpts.SjLjExceptions)
421     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
422   if (LangOpts.SEHExceptions)
423     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
424   if (LangOpts.DWARFExceptions)
425     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
426 
427   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
428   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
429   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
430   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
431   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
432   Options.FunctionSections = CodeGenOpts.FunctionSections;
433   Options.DataSections = CodeGenOpts.DataSections;
434   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
435   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
436   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
437   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
438 
439   if (CodeGenOpts.EnableSplitDwarf)
440     Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
441   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
442   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
443   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
444   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
445   Options.MCOptions.MCIncrementalLinkerCompatible =
446       CodeGenOpts.IncrementalLinkerCompatible;
447   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
448   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
449   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
450   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
451   Options.MCOptions.ABIName = TargetOpts.ABI;
452   for (const auto &Entry : HSOpts.UserEntries)
453     if (!Entry.IsFramework &&
454         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
455          Entry.Group == frontend::IncludeDirGroup::Angled ||
456          Entry.Group == frontend::IncludeDirGroup::System))
457       Options.MCOptions.IASSearchPaths.push_back(
458           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
459 }
460 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
461   if (CodeGenOpts.DisableGCov)
462     return None;
463   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
464     return None;
465   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
466   // LLVM's -default-gcov-version flag is set to something invalid.
467   GCOVOptions Options;
468   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
469   Options.EmitData = CodeGenOpts.EmitGcovArcs;
470   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
471   Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
472   Options.NoRedZone = CodeGenOpts.DisableRedZone;
473   Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
474   Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
475   return Options;
476 }
477 
478 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
479                                       legacy::FunctionPassManager &FPM) {
480   // Handle disabling of all LLVM passes, where we want to preserve the
481   // internal module before any optimization.
482   if (CodeGenOpts.DisableLLVMPasses)
483     return;
484 
485   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
486   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
487   // are inserted before PMBuilder ones - they'd get the default-constructed
488   // TLI with an unknown target otherwise.
489   Triple TargetTriple(TheModule->getTargetTriple());
490   std::unique_ptr<TargetLibraryInfoImpl> TLII(
491       createTLII(TargetTriple, CodeGenOpts));
492 
493   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
494 
495   // At O0 and O1 we only run the always inliner which is more efficient. At
496   // higher optimization levels we run the normal inliner.
497   if (CodeGenOpts.OptimizationLevel <= 1) {
498     bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
499                                      !CodeGenOpts.DisableLifetimeMarkers);
500     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
501   } else {
502     // We do not want to inline hot callsites for SamplePGO module-summary build
503     // because profile annotation will happen again in ThinLTO backend, and we
504     // want the IR of the hot path to match the profile.
505     PMBuilder.Inliner = createFunctionInliningPass(
506         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
507         (!CodeGenOpts.SampleProfileFile.empty() &&
508          CodeGenOpts.EmitSummaryIndex));
509   }
510 
511   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
512   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
513   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
514   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
515 
516   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
517   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
518   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
519   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
520   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
521 
522   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
523 
524   if (TM)
525     TM->adjustPassManager(PMBuilder);
526 
527   if (CodeGenOpts.DebugInfoForProfiling ||
528       !CodeGenOpts.SampleProfileFile.empty())
529     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
530                            addAddDiscriminatorsPass);
531 
532   // In ObjC ARC mode, add the main ARC optimization passes.
533   if (LangOpts.ObjCAutoRefCount) {
534     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
535                            addObjCARCExpandPass);
536     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
537                            addObjCARCAPElimPass);
538     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
539                            addObjCARCOptPass);
540   }
541 
542   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
543     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
544                            addBoundsCheckingPass);
545     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
546                            addBoundsCheckingPass);
547   }
548 
549   if (CodeGenOpts.SanitizeCoverageType ||
550       CodeGenOpts.SanitizeCoverageIndirectCalls ||
551       CodeGenOpts.SanitizeCoverageTraceCmp) {
552     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
553                            addSanitizerCoveragePass);
554     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
555                            addSanitizerCoveragePass);
556   }
557 
558   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
559     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
560                            addAddressSanitizerPasses);
561     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
562                            addAddressSanitizerPasses);
563   }
564 
565   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
566     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
567                            addKernelAddressSanitizerPasses);
568     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
569                            addKernelAddressSanitizerPasses);
570   }
571 
572   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
573     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
574                            addHWAddressSanitizerPasses);
575     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
576                            addHWAddressSanitizerPasses);
577   }
578 
579   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
580     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
581                            addMemorySanitizerPass);
582     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
583                            addMemorySanitizerPass);
584   }
585 
586   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
587     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
588                            addThreadSanitizerPass);
589     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
590                            addThreadSanitizerPass);
591   }
592 
593   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
594     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
595                            addDataFlowSanitizerPass);
596     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
597                            addDataFlowSanitizerPass);
598   }
599 
600   if (LangOpts.CoroutinesTS)
601     addCoroutinePassesToExtensionPoints(PMBuilder);
602 
603   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
604     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
605                            addEfficiencySanitizerPass);
606     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
607                            addEfficiencySanitizerPass);
608   }
609 
610   // Set up the per-function pass manager.
611   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
612   if (CodeGenOpts.VerifyModule)
613     FPM.add(createVerifierPass());
614 
615   // Set up the per-module pass manager.
616   if (!CodeGenOpts.RewriteMapFiles.empty())
617     addSymbolRewriterPass(CodeGenOpts, &MPM);
618 
619   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
620     MPM.add(createGCOVProfilerPass(*Options));
621     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
622       MPM.add(createStripSymbolsPass(true));
623   }
624 
625   if (CodeGenOpts.hasProfileClangInstr()) {
626     InstrProfOptions Options;
627     Options.NoRedZone = CodeGenOpts.DisableRedZone;
628     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
629     MPM.add(createInstrProfilingLegacyPass(Options));
630   }
631   if (CodeGenOpts.hasProfileIRInstr()) {
632     PMBuilder.EnablePGOInstrGen = true;
633     if (!CodeGenOpts.InstrProfileOutput.empty())
634       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
635     else
636       PMBuilder.PGOInstrGen = DefaultProfileGenName;
637   }
638   if (CodeGenOpts.hasProfileIRUse())
639     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
640 
641   if (!CodeGenOpts.SampleProfileFile.empty())
642     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
643 
644   PMBuilder.populateFunctionPassManager(FPM);
645   PMBuilder.populateModulePassManager(MPM);
646 }
647 
648 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
649   SmallVector<const char *, 16> BackendArgs;
650   BackendArgs.push_back("clang"); // Fake program name.
651   if (!CodeGenOpts.DebugPass.empty()) {
652     BackendArgs.push_back("-debug-pass");
653     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
654   }
655   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
656     BackendArgs.push_back("-limit-float-precision");
657     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
658   }
659   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
660     BackendArgs.push_back(BackendOption.c_str());
661   BackendArgs.push_back(nullptr);
662   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
663                                     BackendArgs.data());
664 }
665 
666 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
667   // Create the TargetMachine for generating code.
668   std::string Error;
669   std::string Triple = TheModule->getTargetTriple();
670   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
671   if (!TheTarget) {
672     if (MustCreateTM)
673       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
674     return;
675   }
676 
677   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
678   std::string FeaturesStr =
679       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
680   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
681   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
682 
683   llvm::TargetOptions Options;
684   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
685   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
686                                           Options, RM, CM, OptLevel));
687 }
688 
689 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
690                                        BackendAction Action,
691                                        raw_pwrite_stream &OS) {
692   // Add LibraryInfo.
693   llvm::Triple TargetTriple(TheModule->getTargetTriple());
694   std::unique_ptr<TargetLibraryInfoImpl> TLII(
695       createTLII(TargetTriple, CodeGenOpts));
696   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
697 
698   // Normal mode, emit a .s or .o file by running the code generator. Note,
699   // this also adds codegenerator level optimization passes.
700   TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
701 
702   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
703   // "codegen" passes so that it isn't run multiple times when there is
704   // inlining happening.
705   if (CodeGenOpts.OptimizationLevel > 0)
706     CodeGenPasses.add(createObjCARCContractPass());
707 
708   if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
709                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
710     Diags.Report(diag::err_fe_unable_to_interface_with_target);
711     return false;
712   }
713 
714   return true;
715 }
716 
717 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
718                                       std::unique_ptr<raw_pwrite_stream> OS) {
719   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
720 
721   setCommandLineOpts(CodeGenOpts);
722 
723   bool UsesCodeGen = (Action != Backend_EmitNothing &&
724                       Action != Backend_EmitBC &&
725                       Action != Backend_EmitLL);
726   CreateTargetMachine(UsesCodeGen);
727 
728   if (UsesCodeGen && !TM)
729     return;
730   if (TM)
731     TheModule->setDataLayout(TM->createDataLayout());
732 
733   legacy::PassManager PerModulePasses;
734   PerModulePasses.add(
735       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
736 
737   legacy::FunctionPassManager PerFunctionPasses(TheModule);
738   PerFunctionPasses.add(
739       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
740 
741   CreatePasses(PerModulePasses, PerFunctionPasses);
742 
743   legacy::PassManager CodeGenPasses;
744   CodeGenPasses.add(
745       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
746 
747   std::unique_ptr<raw_fd_ostream> ThinLinkOS;
748 
749   switch (Action) {
750   case Backend_EmitNothing:
751     break;
752 
753   case Backend_EmitBC:
754     if (CodeGenOpts.EmitSummaryIndex) {
755       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
756         std::error_code EC;
757         ThinLinkOS.reset(new llvm::raw_fd_ostream(
758             CodeGenOpts.ThinLinkBitcodeFile, EC,
759             llvm::sys::fs::F_None));
760         if (EC) {
761           Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
762                                                            << EC.message();
763           return;
764         }
765       }
766       PerModulePasses.add(
767           createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
768     }
769     else
770       PerModulePasses.add(
771           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
772     break;
773 
774   case Backend_EmitLL:
775     PerModulePasses.add(
776         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
777     break;
778 
779   default:
780     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
781       return;
782   }
783 
784   // Before executing passes, print the final values of the LLVM options.
785   cl::PrintOptionValues();
786 
787   // Run passes. For now we do all passes at once, but eventually we
788   // would like to have the option of streaming code generation.
789 
790   {
791     PrettyStackTraceString CrashInfo("Per-function optimization");
792 
793     PerFunctionPasses.doInitialization();
794     for (Function &F : *TheModule)
795       if (!F.isDeclaration())
796         PerFunctionPasses.run(F);
797     PerFunctionPasses.doFinalization();
798   }
799 
800   {
801     PrettyStackTraceString CrashInfo("Per-module optimization passes");
802     PerModulePasses.run(*TheModule);
803   }
804 
805   {
806     PrettyStackTraceString CrashInfo("Code generation");
807     CodeGenPasses.run(*TheModule);
808   }
809 }
810 
811 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
812   switch (Opts.OptimizationLevel) {
813   default:
814     llvm_unreachable("Invalid optimization level!");
815 
816   case 1:
817     return PassBuilder::O1;
818 
819   case 2:
820     switch (Opts.OptimizeSize) {
821     default:
822       llvm_unreachable("Invalide optimization level for size!");
823 
824     case 0:
825       return PassBuilder::O2;
826 
827     case 1:
828       return PassBuilder::Os;
829 
830     case 2:
831       return PassBuilder::Oz;
832     }
833 
834   case 3:
835     return PassBuilder::O3;
836   }
837 }
838 
839 /// A clean version of `EmitAssembly` that uses the new pass manager.
840 ///
841 /// Not all features are currently supported in this system, but where
842 /// necessary it falls back to the legacy pass manager to at least provide
843 /// basic functionality.
844 ///
845 /// This API is planned to have its functionality finished and then to replace
846 /// `EmitAssembly` at some point in the future when the default switches.
847 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
848     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
849   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
850   setCommandLineOpts(CodeGenOpts);
851 
852   // The new pass manager always makes a target machine available to passes
853   // during construction.
854   CreateTargetMachine(/*MustCreateTM*/ true);
855   if (!TM)
856     // This will already be diagnosed, just bail.
857     return;
858   TheModule->setDataLayout(TM->createDataLayout());
859 
860   Optional<PGOOptions> PGOOpt;
861 
862   if (CodeGenOpts.hasProfileIRInstr())
863     // -fprofile-generate.
864     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
865                             ? DefaultProfileGenName
866                             : CodeGenOpts.InstrProfileOutput,
867                         "", "", true, CodeGenOpts.DebugInfoForProfiling);
868   else if (CodeGenOpts.hasProfileIRUse())
869     // -fprofile-use.
870     PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "", false,
871                         CodeGenOpts.DebugInfoForProfiling);
872   else if (!CodeGenOpts.SampleProfileFile.empty())
873     // -fprofile-sample-use
874     PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile, false,
875                         CodeGenOpts.DebugInfoForProfiling);
876   else if (CodeGenOpts.DebugInfoForProfiling)
877     // -fdebug-info-for-profiling
878     PGOOpt = PGOOptions("", "", "", false, true);
879 
880   PassBuilder PB(TM.get(), PGOOpt);
881 
882   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
883   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
884   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
885   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
886 
887   // Register the AA manager first so that our version is the one used.
888   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
889 
890   // Register the target library analysis directly and give it a customized
891   // preset TLI.
892   Triple TargetTriple(TheModule->getTargetTriple());
893   std::unique_ptr<TargetLibraryInfoImpl> TLII(
894       createTLII(TargetTriple, CodeGenOpts));
895   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
896   MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
897 
898   // Register all the basic analyses with the managers.
899   PB.registerModuleAnalyses(MAM);
900   PB.registerCGSCCAnalyses(CGAM);
901   PB.registerFunctionAnalyses(FAM);
902   PB.registerLoopAnalyses(LAM);
903   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
904 
905   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
906 
907   if (!CodeGenOpts.DisableLLVMPasses) {
908     bool IsThinLTO = CodeGenOpts.EmitSummaryIndex;
909     bool IsLTO = CodeGenOpts.PrepareForLTO;
910 
911     if (CodeGenOpts.OptimizationLevel == 0) {
912       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
913         MPM.addPass(GCOVProfilerPass(*Options));
914 
915       // Build a minimal pipeline based on the semantics required by Clang,
916       // which is just that always inlining occurs.
917       MPM.addPass(AlwaysInlinerPass());
918 
919       // At -O0 we directly run necessary sanitizer passes.
920       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
921         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
922 
923       // Lastly, add a semantically necessary pass for ThinLTO.
924       if (IsThinLTO)
925         MPM.addPass(NameAnonGlobalPass());
926     } else {
927       // Map our optimization levels into one of the distinct levels used to
928       // configure the pipeline.
929       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
930 
931       // Register callbacks to schedule sanitizer passes at the appropriate part of
932       // the pipeline.
933       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
934         PB.registerScalarOptimizerLateEPCallback(
935             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
936               FPM.addPass(BoundsCheckingPass());
937             });
938       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
939         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
940           MPM.addPass(GCOVProfilerPass(*Options));
941         });
942 
943       if (IsThinLTO) {
944         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
945             Level, CodeGenOpts.DebugPassManager);
946         MPM.addPass(NameAnonGlobalPass());
947       } else if (IsLTO) {
948         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
949                                                 CodeGenOpts.DebugPassManager);
950       } else {
951         MPM = PB.buildPerModuleDefaultPipeline(Level,
952                                                CodeGenOpts.DebugPassManager);
953       }
954     }
955   }
956 
957   // FIXME: We still use the legacy pass manager to do code generation. We
958   // create that pass manager here and use it as needed below.
959   legacy::PassManager CodeGenPasses;
960   bool NeedCodeGen = false;
961   Optional<raw_fd_ostream> ThinLinkOS;
962 
963   // Append any output we need to the pass manager.
964   switch (Action) {
965   case Backend_EmitNothing:
966     break;
967 
968   case Backend_EmitBC:
969     if (CodeGenOpts.EmitSummaryIndex) {
970       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
971         std::error_code EC;
972         ThinLinkOS.emplace(CodeGenOpts.ThinLinkBitcodeFile, EC,
973                            llvm::sys::fs::F_None);
974         if (EC) {
975           Diags.Report(diag::err_fe_unable_to_open_output)
976               << CodeGenOpts.ThinLinkBitcodeFile << EC.message();
977           return;
978         }
979       }
980       MPM.addPass(
981           ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &*ThinLinkOS : nullptr));
982     } else {
983       MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
984                                     CodeGenOpts.EmitSummaryIndex,
985                                     CodeGenOpts.EmitSummaryIndex));
986     }
987     break;
988 
989   case Backend_EmitLL:
990     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
991     break;
992 
993   case Backend_EmitAssembly:
994   case Backend_EmitMCNull:
995   case Backend_EmitObj:
996     NeedCodeGen = true;
997     CodeGenPasses.add(
998         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
999     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
1000       // FIXME: Should we handle this error differently?
1001       return;
1002     break;
1003   }
1004 
1005   // Before executing passes, print the final values of the LLVM options.
1006   cl::PrintOptionValues();
1007 
1008   // Now that we have all of the passes ready, run them.
1009   {
1010     PrettyStackTraceString CrashInfo("Optimizer");
1011     MPM.run(*TheModule, MAM);
1012   }
1013 
1014   // Now if needed, run the legacy PM for codegen.
1015   if (NeedCodeGen) {
1016     PrettyStackTraceString CrashInfo("Code generation");
1017     CodeGenPasses.run(*TheModule);
1018   }
1019 }
1020 
1021 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1022   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1023   if (!BMsOrErr)
1024     return BMsOrErr.takeError();
1025 
1026   // The bitcode file may contain multiple modules, we want the one that is
1027   // marked as being the ThinLTO module.
1028   for (BitcodeModule &BM : *BMsOrErr) {
1029     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1030     if (LTOInfo && LTOInfo->IsThinLTO)
1031       return BM;
1032   }
1033 
1034   return make_error<StringError>("Could not find module summary",
1035                                  inconvertibleErrorCode());
1036 }
1037 
1038 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1039                               const HeaderSearchOptions &HeaderOpts,
1040                               const CodeGenOptions &CGOpts,
1041                               const clang::TargetOptions &TOpts,
1042                               const LangOptions &LOpts,
1043                               std::unique_ptr<raw_pwrite_stream> OS,
1044                               std::string SampleProfile,
1045                               BackendAction Action) {
1046   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1047       ModuleToDefinedGVSummaries;
1048   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1049 
1050   setCommandLineOpts(CGOpts);
1051 
1052   // We can simply import the values mentioned in the combined index, since
1053   // we should only invoke this using the individual indexes written out
1054   // via a WriteIndexesThinBackend.
1055   FunctionImporter::ImportMapTy ImportList;
1056   for (auto &GlobalList : *CombinedIndex) {
1057     // Ignore entries for undefined references.
1058     if (GlobalList.second.SummaryList.empty())
1059       continue;
1060 
1061     auto GUID = GlobalList.first;
1062     assert(GlobalList.second.SummaryList.size() == 1 &&
1063            "Expected individual combined index to have one summary per GUID");
1064     auto &Summary = GlobalList.second.SummaryList[0];
1065     // Skip the summaries for the importing module. These are included to
1066     // e.g. record required linkage changes.
1067     if (Summary->modulePath() == M->getModuleIdentifier())
1068       continue;
1069     // Doesn't matter what value we plug in to the map, just needs an entry
1070     // to provoke importing by thinBackend.
1071     ImportList[Summary->modulePath()][GUID] = 1;
1072   }
1073 
1074   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1075   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1076 
1077   for (auto &I : ImportList) {
1078     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1079         llvm::MemoryBuffer::getFile(I.first());
1080     if (!MBOrErr) {
1081       errs() << "Error loading imported file '" << I.first()
1082              << "': " << MBOrErr.getError().message() << "\n";
1083       return;
1084     }
1085 
1086     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1087     if (!BMOrErr) {
1088       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1089         errs() << "Error loading imported file '" << I.first()
1090                << "': " << EIB.message() << '\n';
1091       });
1092       return;
1093     }
1094     ModuleMap.insert({I.first(), *BMOrErr});
1095 
1096     OwnedImports.push_back(std::move(*MBOrErr));
1097   }
1098   auto AddStream = [&](size_t Task) {
1099     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1100   };
1101   lto::Config Conf;
1102   Conf.CPU = TOpts.CPU;
1103   Conf.CodeModel = getCodeModel(CGOpts);
1104   Conf.MAttrs = TOpts.Features;
1105   Conf.RelocModel = CGOpts.RelocationModel;
1106   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1107   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1108   Conf.SampleProfile = std::move(SampleProfile);
1109   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1110   Conf.DebugPassManager = CGOpts.DebugPassManager;
1111   switch (Action) {
1112   case Backend_EmitNothing:
1113     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1114       return false;
1115     };
1116     break;
1117   case Backend_EmitLL:
1118     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1119       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1120       return false;
1121     };
1122     break;
1123   case Backend_EmitBC:
1124     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1125       WriteBitcodeToFile(M, *OS, CGOpts.EmitLLVMUseLists);
1126       return false;
1127     };
1128     break;
1129   default:
1130     Conf.CGFileType = getCodeGenFileType(Action);
1131     break;
1132   }
1133   if (Error E = thinBackend(
1134           Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
1135           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1136     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1137       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1138     });
1139   }
1140 }
1141 
1142 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1143                               const HeaderSearchOptions &HeaderOpts,
1144                               const CodeGenOptions &CGOpts,
1145                               const clang::TargetOptions &TOpts,
1146                               const LangOptions &LOpts,
1147                               const llvm::DataLayout &TDesc, Module *M,
1148                               BackendAction Action,
1149                               std::unique_ptr<raw_pwrite_stream> OS) {
1150   if (!CGOpts.ThinLTOIndexFile.empty()) {
1151     // If we are performing a ThinLTO importing compile, load the function index
1152     // into memory and pass it into runThinLTOBackend, which will run the
1153     // function importer and invoke LTO passes.
1154     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1155         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1156                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1157     if (!IndexOrErr) {
1158       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1159                             "Error loading index file '" +
1160                             CGOpts.ThinLTOIndexFile + "': ");
1161       return;
1162     }
1163     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1164     // A null CombinedIndex means we should skip ThinLTO compilation
1165     // (LLVM will optionally ignore empty index files, returning null instead
1166     // of an error).
1167     bool DoThinLTOBackend = CombinedIndex != nullptr;
1168     if (DoThinLTOBackend) {
1169       runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1170                         LOpts, std::move(OS), CGOpts.SampleProfileFile, Action);
1171       return;
1172     }
1173   }
1174 
1175   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1176 
1177   if (CGOpts.ExperimentalNewPassManager)
1178     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1179   else
1180     AsmHelper.EmitAssembly(Action, std::move(OS));
1181 
1182   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1183   // DataLayout.
1184   if (AsmHelper.TM) {
1185     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1186     if (DLDesc != TDesc.getStringRepresentation()) {
1187       unsigned DiagID = Diags.getCustomDiagID(
1188           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1189                                     "expected target description '%1'");
1190       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1191     }
1192   }
1193 }
1194 
1195 static const char* getSectionNameForBitcode(const Triple &T) {
1196   switch (T.getObjectFormat()) {
1197   case Triple::MachO:
1198     return "__LLVM,__bitcode";
1199   case Triple::COFF:
1200   case Triple::ELF:
1201   case Triple::Wasm:
1202   case Triple::UnknownObjectFormat:
1203     return ".llvmbc";
1204   }
1205   llvm_unreachable("Unimplemented ObjectFormatType");
1206 }
1207 
1208 static const char* getSectionNameForCommandline(const Triple &T) {
1209   switch (T.getObjectFormat()) {
1210   case Triple::MachO:
1211     return "__LLVM,__cmdline";
1212   case Triple::COFF:
1213   case Triple::ELF:
1214   case Triple::Wasm:
1215   case Triple::UnknownObjectFormat:
1216     return ".llvmcmd";
1217   }
1218   llvm_unreachable("Unimplemented ObjectFormatType");
1219 }
1220 
1221 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1222 // __LLVM,__bitcode section.
1223 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1224                          llvm::MemoryBufferRef Buf) {
1225   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1226     return;
1227 
1228   // Save llvm.compiler.used and remote it.
1229   SmallVector<Constant*, 2> UsedArray;
1230   SmallSet<GlobalValue*, 4> UsedGlobals;
1231   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1232   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1233   for (auto *GV : UsedGlobals) {
1234     if (GV->getName() != "llvm.embedded.module" &&
1235         GV->getName() != "llvm.cmdline")
1236       UsedArray.push_back(
1237           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1238   }
1239   if (Used)
1240     Used->eraseFromParent();
1241 
1242   // Embed the bitcode for the llvm module.
1243   std::string Data;
1244   ArrayRef<uint8_t> ModuleData;
1245   Triple T(M->getTargetTriple());
1246   // Create a constant that contains the bitcode.
1247   // In case of embedding a marker, ignore the input Buf and use the empty
1248   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1249   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1250     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1251                    (const unsigned char *)Buf.getBufferEnd())) {
1252       // If the input is LLVM Assembly, bitcode is produced by serializing
1253       // the module. Use-lists order need to be perserved in this case.
1254       llvm::raw_string_ostream OS(Data);
1255       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1256       ModuleData =
1257           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1258     } else
1259       // If the input is LLVM bitcode, write the input byte stream directly.
1260       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1261                                      Buf.getBufferSize());
1262   }
1263   llvm::Constant *ModuleConstant =
1264       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1265   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1266       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1267       ModuleConstant);
1268   GV->setSection(getSectionNameForBitcode(T));
1269   UsedArray.push_back(
1270       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1271   if (llvm::GlobalVariable *Old =
1272           M->getGlobalVariable("llvm.embedded.module", true)) {
1273     assert(Old->hasOneUse() &&
1274            "llvm.embedded.module can only be used once in llvm.compiler.used");
1275     GV->takeName(Old);
1276     Old->eraseFromParent();
1277   } else {
1278     GV->setName("llvm.embedded.module");
1279   }
1280 
1281   // Skip if only bitcode needs to be embedded.
1282   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1283     // Embed command-line options.
1284     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1285                               CGOpts.CmdArgs.size());
1286     llvm::Constant *CmdConstant =
1287       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1288     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1289                                   llvm::GlobalValue::PrivateLinkage,
1290                                   CmdConstant);
1291     GV->setSection(getSectionNameForCommandline(T));
1292     UsedArray.push_back(
1293         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1294     if (llvm::GlobalVariable *Old =
1295             M->getGlobalVariable("llvm.cmdline", true)) {
1296       assert(Old->hasOneUse() &&
1297              "llvm.cmdline can only be used once in llvm.compiler.used");
1298       GV->takeName(Old);
1299       Old->eraseFromParent();
1300     } else {
1301       GV->setName("llvm.cmdline");
1302     }
1303   }
1304 
1305   if (UsedArray.empty())
1306     return;
1307 
1308   // Recreate llvm.compiler.used.
1309   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1310   auto *NewUsed = new GlobalVariable(
1311       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1312       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1313   NewUsed->setSection("llvm.metadata");
1314 }
1315