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