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.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
437   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
438   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
439 
440   if (CodeGenOpts.EnableSplitDwarf)
441     Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
442   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
443   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
444   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
445   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
446   Options.MCOptions.MCIncrementalLinkerCompatible =
447       CodeGenOpts.IncrementalLinkerCompatible;
448   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
449   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
450   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
451   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
452   Options.MCOptions.ABIName = TargetOpts.ABI;
453   for (const auto &Entry : HSOpts.UserEntries)
454     if (!Entry.IsFramework &&
455         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
456          Entry.Group == frontend::IncludeDirGroup::Angled ||
457          Entry.Group == frontend::IncludeDirGroup::System))
458       Options.MCOptions.IASSearchPaths.push_back(
459           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
460 }
461 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
462   if (CodeGenOpts.DisableGCov)
463     return None;
464   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
465     return None;
466   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
467   // LLVM's -default-gcov-version flag is set to something invalid.
468   GCOVOptions Options;
469   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
470   Options.EmitData = CodeGenOpts.EmitGcovArcs;
471   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
472   Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
473   Options.NoRedZone = CodeGenOpts.DisableRedZone;
474   Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
475   Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
476   return Options;
477 }
478 
479 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
480                                       legacy::FunctionPassManager &FPM) {
481   // Handle disabling of all LLVM passes, where we want to preserve the
482   // internal module before any optimization.
483   if (CodeGenOpts.DisableLLVMPasses)
484     return;
485 
486   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
487   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
488   // are inserted before PMBuilder ones - they'd get the default-constructed
489   // TLI with an unknown target otherwise.
490   Triple TargetTriple(TheModule->getTargetTriple());
491   std::unique_ptr<TargetLibraryInfoImpl> TLII(
492       createTLII(TargetTriple, CodeGenOpts));
493 
494   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
495 
496   // At O0 and O1 we only run the always inliner which is more efficient. At
497   // higher optimization levels we run the normal inliner.
498   if (CodeGenOpts.OptimizationLevel <= 1) {
499     bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
500                                      !CodeGenOpts.DisableLifetimeMarkers);
501     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
502   } else {
503     // We do not want to inline hot callsites for SamplePGO module-summary build
504     // because profile annotation will happen again in ThinLTO backend, and we
505     // want the IR of the hot path to match the profile.
506     PMBuilder.Inliner = createFunctionInliningPass(
507         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
508         (!CodeGenOpts.SampleProfileFile.empty() &&
509          CodeGenOpts.EmitSummaryIndex));
510   }
511 
512   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
513   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
514   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
515   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
516 
517   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
518   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
519   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
520   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
521   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
522 
523   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
524 
525   if (TM)
526     TM->adjustPassManager(PMBuilder);
527 
528   if (CodeGenOpts.DebugInfoForProfiling ||
529       !CodeGenOpts.SampleProfileFile.empty())
530     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
531                            addAddDiscriminatorsPass);
532 
533   // In ObjC ARC mode, add the main ARC optimization passes.
534   if (LangOpts.ObjCAutoRefCount) {
535     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
536                            addObjCARCExpandPass);
537     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
538                            addObjCARCAPElimPass);
539     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
540                            addObjCARCOptPass);
541   }
542 
543   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
544     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
545                            addBoundsCheckingPass);
546     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
547                            addBoundsCheckingPass);
548   }
549 
550   if (CodeGenOpts.SanitizeCoverageType ||
551       CodeGenOpts.SanitizeCoverageIndirectCalls ||
552       CodeGenOpts.SanitizeCoverageTraceCmp) {
553     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
554                            addSanitizerCoveragePass);
555     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
556                            addSanitizerCoveragePass);
557   }
558 
559   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
560     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
561                            addAddressSanitizerPasses);
562     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
563                            addAddressSanitizerPasses);
564   }
565 
566   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
567     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
568                            addKernelAddressSanitizerPasses);
569     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
570                            addKernelAddressSanitizerPasses);
571   }
572 
573   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
574     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
575                            addHWAddressSanitizerPasses);
576     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
577                            addHWAddressSanitizerPasses);
578   }
579 
580   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
581     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
582                            addMemorySanitizerPass);
583     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
584                            addMemorySanitizerPass);
585   }
586 
587   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
588     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
589                            addThreadSanitizerPass);
590     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
591                            addThreadSanitizerPass);
592   }
593 
594   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
595     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
596                            addDataFlowSanitizerPass);
597     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
598                            addDataFlowSanitizerPass);
599   }
600 
601   if (LangOpts.CoroutinesTS)
602     addCoroutinePassesToExtensionPoints(PMBuilder);
603 
604   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
605     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
606                            addEfficiencySanitizerPass);
607     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
608                            addEfficiencySanitizerPass);
609   }
610 
611   // Set up the per-function pass manager.
612   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
613   if (CodeGenOpts.VerifyModule)
614     FPM.add(createVerifierPass());
615 
616   // Set up the per-module pass manager.
617   if (!CodeGenOpts.RewriteMapFiles.empty())
618     addSymbolRewriterPass(CodeGenOpts, &MPM);
619 
620   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
621     MPM.add(createGCOVProfilerPass(*Options));
622     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
623       MPM.add(createStripSymbolsPass(true));
624   }
625 
626   if (CodeGenOpts.hasProfileClangInstr()) {
627     InstrProfOptions Options;
628     Options.NoRedZone = CodeGenOpts.DisableRedZone;
629     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
630     MPM.add(createInstrProfilingLegacyPass(Options));
631   }
632   if (CodeGenOpts.hasProfileIRInstr()) {
633     PMBuilder.EnablePGOInstrGen = true;
634     if (!CodeGenOpts.InstrProfileOutput.empty())
635       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
636     else
637       PMBuilder.PGOInstrGen = DefaultProfileGenName;
638   }
639   if (CodeGenOpts.hasProfileIRUse())
640     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
641 
642   if (!CodeGenOpts.SampleProfileFile.empty())
643     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
644 
645   PMBuilder.populateFunctionPassManager(FPM);
646   PMBuilder.populateModulePassManager(MPM);
647 }
648 
649 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
650   SmallVector<const char *, 16> BackendArgs;
651   BackendArgs.push_back("clang"); // Fake program name.
652   if (!CodeGenOpts.DebugPass.empty()) {
653     BackendArgs.push_back("-debug-pass");
654     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
655   }
656   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
657     BackendArgs.push_back("-limit-float-precision");
658     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
659   }
660   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
661     BackendArgs.push_back(BackendOption.c_str());
662   BackendArgs.push_back(nullptr);
663   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
664                                     BackendArgs.data());
665 }
666 
667 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
668   // Create the TargetMachine for generating code.
669   std::string Error;
670   std::string Triple = TheModule->getTargetTriple();
671   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
672   if (!TheTarget) {
673     if (MustCreateTM)
674       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
675     return;
676   }
677 
678   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
679   std::string FeaturesStr =
680       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
681   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
682   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
683 
684   llvm::TargetOptions Options;
685   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
686   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
687                                           Options, RM, CM, OptLevel));
688 }
689 
690 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
691                                        BackendAction Action,
692                                        raw_pwrite_stream &OS) {
693   // Add LibraryInfo.
694   llvm::Triple TargetTriple(TheModule->getTargetTriple());
695   std::unique_ptr<TargetLibraryInfoImpl> TLII(
696       createTLII(TargetTriple, CodeGenOpts));
697   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
698 
699   // Normal mode, emit a .s or .o file by running the code generator. Note,
700   // this also adds codegenerator level optimization passes.
701   TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
702 
703   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
704   // "codegen" passes so that it isn't run multiple times when there is
705   // inlining happening.
706   if (CodeGenOpts.OptimizationLevel > 0)
707     CodeGenPasses.add(createObjCARCContractPass());
708 
709   if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
710                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
711     Diags.Report(diag::err_fe_unable_to_interface_with_target);
712     return false;
713   }
714 
715   return true;
716 }
717 
718 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
719                                       std::unique_ptr<raw_pwrite_stream> OS) {
720   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
721 
722   setCommandLineOpts(CodeGenOpts);
723 
724   bool UsesCodeGen = (Action != Backend_EmitNothing &&
725                       Action != Backend_EmitBC &&
726                       Action != Backend_EmitLL);
727   CreateTargetMachine(UsesCodeGen);
728 
729   if (UsesCodeGen && !TM)
730     return;
731   if (TM)
732     TheModule->setDataLayout(TM->createDataLayout());
733 
734   legacy::PassManager PerModulePasses;
735   PerModulePasses.add(
736       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
737 
738   legacy::FunctionPassManager PerFunctionPasses(TheModule);
739   PerFunctionPasses.add(
740       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
741 
742   CreatePasses(PerModulePasses, PerFunctionPasses);
743 
744   legacy::PassManager CodeGenPasses;
745   CodeGenPasses.add(
746       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
747 
748   std::unique_ptr<raw_fd_ostream> ThinLinkOS;
749 
750   switch (Action) {
751   case Backend_EmitNothing:
752     break;
753 
754   case Backend_EmitBC:
755     if (CodeGenOpts.EmitSummaryIndex) {
756       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
757         std::error_code EC;
758         ThinLinkOS.reset(new llvm::raw_fd_ostream(
759             CodeGenOpts.ThinLinkBitcodeFile, EC,
760             llvm::sys::fs::F_None));
761         if (EC) {
762           Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
763                                                            << EC.message();
764           return;
765         }
766       }
767       PerModulePasses.add(
768           createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
769     }
770     else
771       PerModulePasses.add(
772           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
773     break;
774 
775   case Backend_EmitLL:
776     PerModulePasses.add(
777         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
778     break;
779 
780   default:
781     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
782       return;
783   }
784 
785   // Before executing passes, print the final values of the LLVM options.
786   cl::PrintOptionValues();
787 
788   // Run passes. For now we do all passes at once, but eventually we
789   // would like to have the option of streaming code generation.
790 
791   {
792     PrettyStackTraceString CrashInfo("Per-function optimization");
793 
794     PerFunctionPasses.doInitialization();
795     for (Function &F : *TheModule)
796       if (!F.isDeclaration())
797         PerFunctionPasses.run(F);
798     PerFunctionPasses.doFinalization();
799   }
800 
801   {
802     PrettyStackTraceString CrashInfo("Per-module optimization passes");
803     PerModulePasses.run(*TheModule);
804   }
805 
806   {
807     PrettyStackTraceString CrashInfo("Code generation");
808     CodeGenPasses.run(*TheModule);
809   }
810 }
811 
812 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
813   switch (Opts.OptimizationLevel) {
814   default:
815     llvm_unreachable("Invalid optimization level!");
816 
817   case 1:
818     return PassBuilder::O1;
819 
820   case 2:
821     switch (Opts.OptimizeSize) {
822     default:
823       llvm_unreachable("Invalide optimization level for size!");
824 
825     case 0:
826       return PassBuilder::O2;
827 
828     case 1:
829       return PassBuilder::Os;
830 
831     case 2:
832       return PassBuilder::Oz;
833     }
834 
835   case 3:
836     return PassBuilder::O3;
837   }
838 }
839 
840 /// A clean version of `EmitAssembly` that uses the new pass manager.
841 ///
842 /// Not all features are currently supported in this system, but where
843 /// necessary it falls back to the legacy pass manager to at least provide
844 /// basic functionality.
845 ///
846 /// This API is planned to have its functionality finished and then to replace
847 /// `EmitAssembly` at some point in the future when the default switches.
848 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
849     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
850   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
851   setCommandLineOpts(CodeGenOpts);
852 
853   // The new pass manager always makes a target machine available to passes
854   // during construction.
855   CreateTargetMachine(/*MustCreateTM*/ true);
856   if (!TM)
857     // This will already be diagnosed, just bail.
858     return;
859   TheModule->setDataLayout(TM->createDataLayout());
860 
861   Optional<PGOOptions> PGOOpt;
862 
863   if (CodeGenOpts.hasProfileIRInstr())
864     // -fprofile-generate.
865     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
866                             ? DefaultProfileGenName
867                             : CodeGenOpts.InstrProfileOutput,
868                         "", "", true, CodeGenOpts.DebugInfoForProfiling);
869   else if (CodeGenOpts.hasProfileIRUse())
870     // -fprofile-use.
871     PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "", false,
872                         CodeGenOpts.DebugInfoForProfiling);
873   else if (!CodeGenOpts.SampleProfileFile.empty())
874     // -fprofile-sample-use
875     PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile, false,
876                         CodeGenOpts.DebugInfoForProfiling);
877   else if (CodeGenOpts.DebugInfoForProfiling)
878     // -fdebug-info-for-profiling
879     PGOOpt = PGOOptions("", "", "", false, true);
880 
881   PassBuilder PB(TM.get(), PGOOpt);
882 
883   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
884   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
885   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
886   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
887 
888   // Register the AA manager first so that our version is the one used.
889   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
890 
891   // Register the target library analysis directly and give it a customized
892   // preset TLI.
893   Triple TargetTriple(TheModule->getTargetTriple());
894   std::unique_ptr<TargetLibraryInfoImpl> TLII(
895       createTLII(TargetTriple, CodeGenOpts));
896   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
897   MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
898 
899   // Register all the basic analyses with the managers.
900   PB.registerModuleAnalyses(MAM);
901   PB.registerCGSCCAnalyses(CGAM);
902   PB.registerFunctionAnalyses(FAM);
903   PB.registerLoopAnalyses(LAM);
904   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
905 
906   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
907 
908   if (!CodeGenOpts.DisableLLVMPasses) {
909     bool IsThinLTO = CodeGenOpts.EmitSummaryIndex;
910     bool IsLTO = CodeGenOpts.PrepareForLTO;
911 
912     if (CodeGenOpts.OptimizationLevel == 0) {
913       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
914         MPM.addPass(GCOVProfilerPass(*Options));
915 
916       // Build a minimal pipeline based on the semantics required by Clang,
917       // which is just that always inlining occurs.
918       MPM.addPass(AlwaysInlinerPass());
919 
920       // At -O0 we directly run necessary sanitizer passes.
921       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
922         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
923 
924       // Lastly, add a semantically necessary pass for ThinLTO.
925       if (IsThinLTO)
926         MPM.addPass(NameAnonGlobalPass());
927     } else {
928       // Map our optimization levels into one of the distinct levels used to
929       // configure the pipeline.
930       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
931 
932       // Register callbacks to schedule sanitizer passes at the appropriate part of
933       // the pipeline.
934       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
935         PB.registerScalarOptimizerLateEPCallback(
936             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
937               FPM.addPass(BoundsCheckingPass());
938             });
939       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
940         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
941           MPM.addPass(GCOVProfilerPass(*Options));
942         });
943 
944       if (IsThinLTO) {
945         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
946             Level, CodeGenOpts.DebugPassManager);
947         MPM.addPass(NameAnonGlobalPass());
948       } else if (IsLTO) {
949         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
950                                                 CodeGenOpts.DebugPassManager);
951       } else {
952         MPM = PB.buildPerModuleDefaultPipeline(Level,
953                                                CodeGenOpts.DebugPassManager);
954       }
955     }
956   }
957 
958   // FIXME: We still use the legacy pass manager to do code generation. We
959   // create that pass manager here and use it as needed below.
960   legacy::PassManager CodeGenPasses;
961   bool NeedCodeGen = false;
962   Optional<raw_fd_ostream> ThinLinkOS;
963 
964   // Append any output we need to the pass manager.
965   switch (Action) {
966   case Backend_EmitNothing:
967     break;
968 
969   case Backend_EmitBC:
970     if (CodeGenOpts.EmitSummaryIndex) {
971       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
972         std::error_code EC;
973         ThinLinkOS.emplace(CodeGenOpts.ThinLinkBitcodeFile, EC,
974                            llvm::sys::fs::F_None);
975         if (EC) {
976           Diags.Report(diag::err_fe_unable_to_open_output)
977               << CodeGenOpts.ThinLinkBitcodeFile << EC.message();
978           return;
979         }
980       }
981       MPM.addPass(
982           ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &*ThinLinkOS : nullptr));
983     } else {
984       MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
985                                     CodeGenOpts.EmitSummaryIndex,
986                                     CodeGenOpts.EmitSummaryIndex));
987     }
988     break;
989 
990   case Backend_EmitLL:
991     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
992     break;
993 
994   case Backend_EmitAssembly:
995   case Backend_EmitMCNull:
996   case Backend_EmitObj:
997     NeedCodeGen = true;
998     CodeGenPasses.add(
999         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1000     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
1001       // FIXME: Should we handle this error differently?
1002       return;
1003     break;
1004   }
1005 
1006   // Before executing passes, print the final values of the LLVM options.
1007   cl::PrintOptionValues();
1008 
1009   // Now that we have all of the passes ready, run them.
1010   {
1011     PrettyStackTraceString CrashInfo("Optimizer");
1012     MPM.run(*TheModule, MAM);
1013   }
1014 
1015   // Now if needed, run the legacy PM for codegen.
1016   if (NeedCodeGen) {
1017     PrettyStackTraceString CrashInfo("Code generation");
1018     CodeGenPasses.run(*TheModule);
1019   }
1020 }
1021 
1022 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1023   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1024   if (!BMsOrErr)
1025     return BMsOrErr.takeError();
1026 
1027   // The bitcode file may contain multiple modules, we want the one that is
1028   // marked as being the ThinLTO module.
1029   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1030     return *Bm;
1031 
1032   return make_error<StringError>("Could not find module summary",
1033                                  inconvertibleErrorCode());
1034 }
1035 
1036 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1037   for (BitcodeModule &BM : BMs) {
1038     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1039     if (LTOInfo && LTOInfo->IsThinLTO)
1040       return &BM;
1041   }
1042   return nullptr;
1043 }
1044 
1045 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1046                               const HeaderSearchOptions &HeaderOpts,
1047                               const CodeGenOptions &CGOpts,
1048                               const clang::TargetOptions &TOpts,
1049                               const LangOptions &LOpts,
1050                               std::unique_ptr<raw_pwrite_stream> OS,
1051                               std::string SampleProfile,
1052                               BackendAction Action) {
1053   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1054       ModuleToDefinedGVSummaries;
1055   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1056 
1057   setCommandLineOpts(CGOpts);
1058 
1059   // We can simply import the values mentioned in the combined index, since
1060   // we should only invoke this using the individual indexes written out
1061   // via a WriteIndexesThinBackend.
1062   FunctionImporter::ImportMapTy ImportList;
1063   for (auto &GlobalList : *CombinedIndex) {
1064     // Ignore entries for undefined references.
1065     if (GlobalList.second.SummaryList.empty())
1066       continue;
1067 
1068     auto GUID = GlobalList.first;
1069     assert(GlobalList.second.SummaryList.size() == 1 &&
1070            "Expected individual combined index to have one summary per GUID");
1071     auto &Summary = GlobalList.second.SummaryList[0];
1072     // Skip the summaries for the importing module. These are included to
1073     // e.g. record required linkage changes.
1074     if (Summary->modulePath() == M->getModuleIdentifier())
1075       continue;
1076     // Doesn't matter what value we plug in to the map, just needs an entry
1077     // to provoke importing by thinBackend.
1078     ImportList[Summary->modulePath()][GUID] = 1;
1079   }
1080 
1081   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1082   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1083 
1084   for (auto &I : ImportList) {
1085     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1086         llvm::MemoryBuffer::getFile(I.first());
1087     if (!MBOrErr) {
1088       errs() << "Error loading imported file '" << I.first()
1089              << "': " << MBOrErr.getError().message() << "\n";
1090       return;
1091     }
1092 
1093     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1094     if (!BMOrErr) {
1095       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1096         errs() << "Error loading imported file '" << I.first()
1097                << "': " << EIB.message() << '\n';
1098       });
1099       return;
1100     }
1101     ModuleMap.insert({I.first(), *BMOrErr});
1102 
1103     OwnedImports.push_back(std::move(*MBOrErr));
1104   }
1105   auto AddStream = [&](size_t Task) {
1106     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1107   };
1108   lto::Config Conf;
1109   Conf.CPU = TOpts.CPU;
1110   Conf.CodeModel = getCodeModel(CGOpts);
1111   Conf.MAttrs = TOpts.Features;
1112   Conf.RelocModel = CGOpts.RelocationModel;
1113   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1114   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1115   Conf.SampleProfile = std::move(SampleProfile);
1116   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1117   Conf.DebugPassManager = CGOpts.DebugPassManager;
1118   switch (Action) {
1119   case Backend_EmitNothing:
1120     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1121       return false;
1122     };
1123     break;
1124   case Backend_EmitLL:
1125     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1126       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1127       return false;
1128     };
1129     break;
1130   case Backend_EmitBC:
1131     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1132       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1133       return false;
1134     };
1135     break;
1136   default:
1137     Conf.CGFileType = getCodeGenFileType(Action);
1138     break;
1139   }
1140   if (Error E = thinBackend(
1141           Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
1142           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1143     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1144       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1145     });
1146   }
1147 }
1148 
1149 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1150                               const HeaderSearchOptions &HeaderOpts,
1151                               const CodeGenOptions &CGOpts,
1152                               const clang::TargetOptions &TOpts,
1153                               const LangOptions &LOpts,
1154                               const llvm::DataLayout &TDesc, Module *M,
1155                               BackendAction Action,
1156                               std::unique_ptr<raw_pwrite_stream> OS) {
1157   std::unique_ptr<llvm::Module> EmptyModule;
1158   if (!CGOpts.ThinLTOIndexFile.empty()) {
1159     // If we are performing a ThinLTO importing compile, load the function index
1160     // into memory and pass it into runThinLTOBackend, which will run the
1161     // function importer and invoke LTO passes.
1162     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1163         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1164                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1165     if (!IndexOrErr) {
1166       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1167                             "Error loading index file '" +
1168                             CGOpts.ThinLTOIndexFile + "': ");
1169       return;
1170     }
1171     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1172     // A null CombinedIndex means we should skip ThinLTO compilation
1173     // (LLVM will optionally ignore empty index files, returning null instead
1174     // of an error).
1175     if (CombinedIndex) {
1176       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1177         runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1178                           LOpts, std::move(OS), CGOpts.SampleProfileFile,
1179                           Action);
1180         return;
1181       }
1182       // Distributed indexing detected that nothing from the module is needed
1183       // for the final linking. So we can skip the compilation. We sill need to
1184       // output an empty object file to make sure that a linker does not fail
1185       // trying to read it. Also for some features, like CFI, we must skip
1186       // the compilation as CombinedIndex does not contain all required
1187       // information.
1188       EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
1189       EmptyModule->setTargetTriple(M->getTargetTriple());
1190       M = EmptyModule.get();
1191     }
1192   }
1193 
1194   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1195 
1196   if (CGOpts.ExperimentalNewPassManager)
1197     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1198   else
1199     AsmHelper.EmitAssembly(Action, std::move(OS));
1200 
1201   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1202   // DataLayout.
1203   if (AsmHelper.TM) {
1204     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1205     if (DLDesc != TDesc.getStringRepresentation()) {
1206       unsigned DiagID = Diags.getCustomDiagID(
1207           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1208                                     "expected target description '%1'");
1209       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1210     }
1211   }
1212 }
1213 
1214 static const char* getSectionNameForBitcode(const Triple &T) {
1215   switch (T.getObjectFormat()) {
1216   case Triple::MachO:
1217     return "__LLVM,__bitcode";
1218   case Triple::COFF:
1219   case Triple::ELF:
1220   case Triple::Wasm:
1221   case Triple::UnknownObjectFormat:
1222     return ".llvmbc";
1223   }
1224   llvm_unreachable("Unimplemented ObjectFormatType");
1225 }
1226 
1227 static const char* getSectionNameForCommandline(const Triple &T) {
1228   switch (T.getObjectFormat()) {
1229   case Triple::MachO:
1230     return "__LLVM,__cmdline";
1231   case Triple::COFF:
1232   case Triple::ELF:
1233   case Triple::Wasm:
1234   case Triple::UnknownObjectFormat:
1235     return ".llvmcmd";
1236   }
1237   llvm_unreachable("Unimplemented ObjectFormatType");
1238 }
1239 
1240 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1241 // __LLVM,__bitcode section.
1242 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1243                          llvm::MemoryBufferRef Buf) {
1244   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1245     return;
1246 
1247   // Save llvm.compiler.used and remote it.
1248   SmallVector<Constant*, 2> UsedArray;
1249   SmallSet<GlobalValue*, 4> UsedGlobals;
1250   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1251   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1252   for (auto *GV : UsedGlobals) {
1253     if (GV->getName() != "llvm.embedded.module" &&
1254         GV->getName() != "llvm.cmdline")
1255       UsedArray.push_back(
1256           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1257   }
1258   if (Used)
1259     Used->eraseFromParent();
1260 
1261   // Embed the bitcode for the llvm module.
1262   std::string Data;
1263   ArrayRef<uint8_t> ModuleData;
1264   Triple T(M->getTargetTriple());
1265   // Create a constant that contains the bitcode.
1266   // In case of embedding a marker, ignore the input Buf and use the empty
1267   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1268   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1269     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1270                    (const unsigned char *)Buf.getBufferEnd())) {
1271       // If the input is LLVM Assembly, bitcode is produced by serializing
1272       // the module. Use-lists order need to be perserved in this case.
1273       llvm::raw_string_ostream OS(Data);
1274       llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
1275       ModuleData =
1276           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1277     } else
1278       // If the input is LLVM bitcode, write the input byte stream directly.
1279       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1280                                      Buf.getBufferSize());
1281   }
1282   llvm::Constant *ModuleConstant =
1283       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1284   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1285       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1286       ModuleConstant);
1287   GV->setSection(getSectionNameForBitcode(T));
1288   UsedArray.push_back(
1289       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1290   if (llvm::GlobalVariable *Old =
1291           M->getGlobalVariable("llvm.embedded.module", true)) {
1292     assert(Old->hasOneUse() &&
1293            "llvm.embedded.module can only be used once in llvm.compiler.used");
1294     GV->takeName(Old);
1295     Old->eraseFromParent();
1296   } else {
1297     GV->setName("llvm.embedded.module");
1298   }
1299 
1300   // Skip if only bitcode needs to be embedded.
1301   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1302     // Embed command-line options.
1303     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1304                               CGOpts.CmdArgs.size());
1305     llvm::Constant *CmdConstant =
1306       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1307     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1308                                   llvm::GlobalValue::PrivateLinkage,
1309                                   CmdConstant);
1310     GV->setSection(getSectionNameForCommandline(T));
1311     UsedArray.push_back(
1312         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1313     if (llvm::GlobalVariable *Old =
1314             M->getGlobalVariable("llvm.cmdline", true)) {
1315       assert(Old->hasOneUse() &&
1316              "llvm.cmdline can only be used once in llvm.compiler.used");
1317       GV->takeName(Old);
1318       Old->eraseFromParent();
1319     } else {
1320       GV->setName("llvm.cmdline");
1321     }
1322   }
1323 
1324   if (UsedArray.empty())
1325     return;
1326 
1327   // Recreate llvm.compiler.used.
1328   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1329   auto *NewUsed = new GlobalVariable(
1330       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1331       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1332   NewUsed->setSection("llvm.metadata");
1333 }
1334