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     MPM.add(createInstrProfilingLegacyPass(Options));
657   }
658   if (CodeGenOpts.hasProfileIRInstr()) {
659     PMBuilder.EnablePGOInstrGen = true;
660     if (!CodeGenOpts.InstrProfileOutput.empty())
661       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
662     else
663       PMBuilder.PGOInstrGen = DefaultProfileGenName;
664   }
665   if (CodeGenOpts.hasProfileIRUse())
666     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
667 
668   if (!CodeGenOpts.SampleProfileFile.empty())
669     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
670 
671   PMBuilder.populateFunctionPassManager(FPM);
672   PMBuilder.populateModulePassManager(MPM);
673 }
674 
675 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
676   SmallVector<const char *, 16> BackendArgs;
677   BackendArgs.push_back("clang"); // Fake program name.
678   if (!CodeGenOpts.DebugPass.empty()) {
679     BackendArgs.push_back("-debug-pass");
680     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
681   }
682   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
683     BackendArgs.push_back("-limit-float-precision");
684     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
685   }
686   BackendArgs.push_back(nullptr);
687   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
688                                     BackendArgs.data());
689 }
690 
691 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
692   // Create the TargetMachine for generating code.
693   std::string Error;
694   std::string Triple = TheModule->getTargetTriple();
695   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
696   if (!TheTarget) {
697     if (MustCreateTM)
698       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
699     return;
700   }
701 
702   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
703   std::string FeaturesStr =
704       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
705   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
706   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
707 
708   llvm::TargetOptions Options;
709   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
710   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
711                                           Options, RM, CM, OptLevel));
712 }
713 
714 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
715                                        BackendAction Action,
716                                        raw_pwrite_stream &OS,
717                                        raw_pwrite_stream *DwoOS) {
718   // Add LibraryInfo.
719   llvm::Triple TargetTriple(TheModule->getTargetTriple());
720   std::unique_ptr<TargetLibraryInfoImpl> TLII(
721       createTLII(TargetTriple, CodeGenOpts));
722   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
723 
724   // Normal mode, emit a .s or .o file by running the code generator. Note,
725   // this also adds codegenerator level optimization passes.
726   TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
727 
728   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
729   // "codegen" passes so that it isn't run multiple times when there is
730   // inlining happening.
731   if (CodeGenOpts.OptimizationLevel > 0)
732     CodeGenPasses.add(createObjCARCContractPass());
733 
734   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
735                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
736     Diags.Report(diag::err_fe_unable_to_interface_with_target);
737     return false;
738   }
739 
740   return true;
741 }
742 
743 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
744                                       std::unique_ptr<raw_pwrite_stream> OS) {
745   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
746 
747   setCommandLineOpts(CodeGenOpts);
748 
749   bool UsesCodeGen = (Action != Backend_EmitNothing &&
750                       Action != Backend_EmitBC &&
751                       Action != Backend_EmitLL);
752   CreateTargetMachine(UsesCodeGen);
753 
754   if (UsesCodeGen && !TM)
755     return;
756   if (TM)
757     TheModule->setDataLayout(TM->createDataLayout());
758 
759   legacy::PassManager PerModulePasses;
760   PerModulePasses.add(
761       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
762 
763   legacy::FunctionPassManager PerFunctionPasses(TheModule);
764   PerFunctionPasses.add(
765       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
766 
767   CreatePasses(PerModulePasses, PerFunctionPasses);
768 
769   legacy::PassManager CodeGenPasses;
770   CodeGenPasses.add(
771       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
772 
773   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
774 
775   switch (Action) {
776   case Backend_EmitNothing:
777     break;
778 
779   case Backend_EmitBC:
780     if (CodeGenOpts.PrepareForThinLTO) {
781       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
782         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
783         if (!ThinLinkOS)
784           return;
785       }
786       PerModulePasses.add(createWriteThinLTOBitcodePass(
787           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
788     } else {
789       // Emit a module summary by default for Regular LTO except for ld64
790       // targets
791       bool EmitLTOSummary =
792           (CodeGenOpts.PrepareForLTO &&
793            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
794                llvm::Triple::Apple);
795       if (EmitLTOSummary && !TheModule->getModuleFlag("ThinLTO"))
796         TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
797 
798       PerModulePasses.add(
799           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
800                                   EmitLTOSummary));
801     }
802     break;
803 
804   case Backend_EmitLL:
805     PerModulePasses.add(
806         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
807     break;
808 
809   default:
810     if (!CodeGenOpts.SplitDwarfFile.empty()) {
811       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
812       if (!DwoOS)
813         return;
814     }
815     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
816                        DwoOS ? &DwoOS->os() : nullptr))
817       return;
818   }
819 
820   // Before executing passes, print the final values of the LLVM options.
821   cl::PrintOptionValues();
822 
823   // Run passes. For now we do all passes at once, but eventually we
824   // would like to have the option of streaming code generation.
825 
826   {
827     PrettyStackTraceString CrashInfo("Per-function optimization");
828 
829     PerFunctionPasses.doInitialization();
830     for (Function &F : *TheModule)
831       if (!F.isDeclaration())
832         PerFunctionPasses.run(F);
833     PerFunctionPasses.doFinalization();
834   }
835 
836   {
837     PrettyStackTraceString CrashInfo("Per-module optimization passes");
838     PerModulePasses.run(*TheModule);
839   }
840 
841   {
842     PrettyStackTraceString CrashInfo("Code generation");
843     CodeGenPasses.run(*TheModule);
844   }
845 
846   if (ThinLinkOS)
847     ThinLinkOS->keep();
848   if (DwoOS)
849     DwoOS->keep();
850 }
851 
852 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
853   switch (Opts.OptimizationLevel) {
854   default:
855     llvm_unreachable("Invalid optimization level!");
856 
857   case 1:
858     return PassBuilder::O1;
859 
860   case 2:
861     switch (Opts.OptimizeSize) {
862     default:
863       llvm_unreachable("Invalid optimization level for size!");
864 
865     case 0:
866       return PassBuilder::O2;
867 
868     case 1:
869       return PassBuilder::Os;
870 
871     case 2:
872       return PassBuilder::Oz;
873     }
874 
875   case 3:
876     return PassBuilder::O3;
877   }
878 }
879 
880 /// A clean version of `EmitAssembly` that uses the new pass manager.
881 ///
882 /// Not all features are currently supported in this system, but where
883 /// necessary it falls back to the legacy pass manager to at least provide
884 /// basic functionality.
885 ///
886 /// This API is planned to have its functionality finished and then to replace
887 /// `EmitAssembly` at some point in the future when the default switches.
888 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
889     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
890   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
891   setCommandLineOpts(CodeGenOpts);
892 
893   // The new pass manager always makes a target machine available to passes
894   // during construction.
895   CreateTargetMachine(/*MustCreateTM*/ true);
896   if (!TM)
897     // This will already be diagnosed, just bail.
898     return;
899   TheModule->setDataLayout(TM->createDataLayout());
900 
901   Optional<PGOOptions> PGOOpt;
902 
903   if (CodeGenOpts.hasProfileIRInstr())
904     // -fprofile-generate.
905     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
906                             ? DefaultProfileGenName
907                             : CodeGenOpts.InstrProfileOutput,
908                         "", "", true, CodeGenOpts.DebugInfoForProfiling);
909   else if (CodeGenOpts.hasProfileIRUse())
910     // -fprofile-use.
911     PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "", false,
912                         CodeGenOpts.DebugInfoForProfiling);
913   else if (!CodeGenOpts.SampleProfileFile.empty())
914     // -fprofile-sample-use
915     PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile, false,
916                         CodeGenOpts.DebugInfoForProfiling);
917   else if (CodeGenOpts.DebugInfoForProfiling)
918     // -fdebug-info-for-profiling
919     PGOOpt = PGOOptions("", "", "", false, true);
920 
921   PassBuilder PB(TM.get(), PGOOpt);
922 
923   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
924   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
925   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
926   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
927 
928   // Register the AA manager first so that our version is the one used.
929   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
930 
931   // Register the target library analysis directly and give it a customized
932   // preset TLI.
933   Triple TargetTriple(TheModule->getTargetTriple());
934   std::unique_ptr<TargetLibraryInfoImpl> TLII(
935       createTLII(TargetTriple, CodeGenOpts));
936   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
937   MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
938 
939   // Register all the basic analyses with the managers.
940   PB.registerModuleAnalyses(MAM);
941   PB.registerCGSCCAnalyses(CGAM);
942   PB.registerFunctionAnalyses(FAM);
943   PB.registerLoopAnalyses(LAM);
944   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
945 
946   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
947 
948   if (!CodeGenOpts.DisableLLVMPasses) {
949     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
950     bool IsLTO = CodeGenOpts.PrepareForLTO;
951 
952     if (CodeGenOpts.OptimizationLevel == 0) {
953       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
954         MPM.addPass(GCOVProfilerPass(*Options));
955 
956       // Build a minimal pipeline based on the semantics required by Clang,
957       // which is just that always inlining occurs.
958       MPM.addPass(AlwaysInlinerPass());
959 
960       // At -O0 we directly run necessary sanitizer passes.
961       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
962         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
963 
964       // Lastly, add a semantically necessary pass for LTO.
965       if (IsLTO || IsThinLTO)
966         MPM.addPass(NameAnonGlobalPass());
967     } else {
968       // Map our optimization levels into one of the distinct levels used to
969       // configure the pipeline.
970       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
971 
972       // Register callbacks to schedule sanitizer passes at the appropriate part of
973       // the pipeline.
974       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
975         PB.registerScalarOptimizerLateEPCallback(
976             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
977               FPM.addPass(BoundsCheckingPass());
978             });
979       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
980         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
981           MPM.addPass(GCOVProfilerPass(*Options));
982         });
983 
984       if (IsThinLTO) {
985         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
986             Level, CodeGenOpts.DebugPassManager);
987         MPM.addPass(NameAnonGlobalPass());
988       } else if (IsLTO) {
989         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
990                                                 CodeGenOpts.DebugPassManager);
991         MPM.addPass(NameAnonGlobalPass());
992       } else {
993         MPM = PB.buildPerModuleDefaultPipeline(Level,
994                                                CodeGenOpts.DebugPassManager);
995       }
996     }
997   }
998 
999   // FIXME: We still use the legacy pass manager to do code generation. We
1000   // create that pass manager here and use it as needed below.
1001   legacy::PassManager CodeGenPasses;
1002   bool NeedCodeGen = false;
1003   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1004 
1005   // Append any output we need to the pass manager.
1006   switch (Action) {
1007   case Backend_EmitNothing:
1008     break;
1009 
1010   case Backend_EmitBC:
1011     if (CodeGenOpts.PrepareForThinLTO) {
1012       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1013         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1014         if (!ThinLinkOS)
1015           return;
1016       }
1017       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1018                                                            : nullptr));
1019     } else {
1020       // Emit a module summary by default for Regular LTO except for ld64
1021       // targets
1022       bool EmitLTOSummary =
1023           (CodeGenOpts.PrepareForLTO &&
1024            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1025                llvm::Triple::Apple);
1026       if (EmitLTOSummary && !TheModule->getModuleFlag("ThinLTO"))
1027         TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1028 
1029       MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1030                                     EmitLTOSummary));
1031     }
1032     break;
1033 
1034   case Backend_EmitLL:
1035     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1036     break;
1037 
1038   case Backend_EmitAssembly:
1039   case Backend_EmitMCNull:
1040   case Backend_EmitObj:
1041     NeedCodeGen = true;
1042     CodeGenPasses.add(
1043         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1044     if (!CodeGenOpts.SplitDwarfFile.empty()) {
1045       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
1046       if (!DwoOS)
1047         return;
1048     }
1049     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1050                        DwoOS ? &DwoOS->os() : nullptr))
1051       // FIXME: Should we handle this error differently?
1052       return;
1053     break;
1054   }
1055 
1056   // Before executing passes, print the final values of the LLVM options.
1057   cl::PrintOptionValues();
1058 
1059   // Now that we have all of the passes ready, run them.
1060   {
1061     PrettyStackTraceString CrashInfo("Optimizer");
1062     MPM.run(*TheModule, MAM);
1063   }
1064 
1065   // Now if needed, run the legacy PM for codegen.
1066   if (NeedCodeGen) {
1067     PrettyStackTraceString CrashInfo("Code generation");
1068     CodeGenPasses.run(*TheModule);
1069   }
1070 
1071   if (ThinLinkOS)
1072     ThinLinkOS->keep();
1073   if (DwoOS)
1074     DwoOS->keep();
1075 }
1076 
1077 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1078   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1079   if (!BMsOrErr)
1080     return BMsOrErr.takeError();
1081 
1082   // The bitcode file may contain multiple modules, we want the one that is
1083   // marked as being the ThinLTO module.
1084   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1085     return *Bm;
1086 
1087   return make_error<StringError>("Could not find module summary",
1088                                  inconvertibleErrorCode());
1089 }
1090 
1091 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1092   for (BitcodeModule &BM : BMs) {
1093     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1094     if (LTOInfo && LTOInfo->IsThinLTO)
1095       return &BM;
1096   }
1097   return nullptr;
1098 }
1099 
1100 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1101                               const HeaderSearchOptions &HeaderOpts,
1102                               const CodeGenOptions &CGOpts,
1103                               const clang::TargetOptions &TOpts,
1104                               const LangOptions &LOpts,
1105                               std::unique_ptr<raw_pwrite_stream> OS,
1106                               std::string SampleProfile,
1107                               BackendAction Action) {
1108   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1109       ModuleToDefinedGVSummaries;
1110   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1111 
1112   setCommandLineOpts(CGOpts);
1113 
1114   // We can simply import the values mentioned in the combined index, since
1115   // we should only invoke this using the individual indexes written out
1116   // via a WriteIndexesThinBackend.
1117   FunctionImporter::ImportMapTy ImportList;
1118   for (auto &GlobalList : *CombinedIndex) {
1119     // Ignore entries for undefined references.
1120     if (GlobalList.second.SummaryList.empty())
1121       continue;
1122 
1123     auto GUID = GlobalList.first;
1124     assert(GlobalList.second.SummaryList.size() == 1 &&
1125            "Expected individual combined index to have one summary per GUID");
1126     auto &Summary = GlobalList.second.SummaryList[0];
1127     // Skip the summaries for the importing module. These are included to
1128     // e.g. record required linkage changes.
1129     if (Summary->modulePath() == M->getModuleIdentifier())
1130       continue;
1131     // Add an entry to provoke importing by thinBackend.
1132     ImportList[Summary->modulePath()].insert(GUID);
1133   }
1134 
1135   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
1136   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
1137 
1138   for (auto &I : ImportList) {
1139     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
1140         llvm::MemoryBuffer::getFile(I.first());
1141     if (!MBOrErr) {
1142       errs() << "Error loading imported file '" << I.first()
1143              << "': " << MBOrErr.getError().message() << "\n";
1144       return;
1145     }
1146 
1147     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1148     if (!BMOrErr) {
1149       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1150         errs() << "Error loading imported file '" << I.first()
1151                << "': " << EIB.message() << '\n';
1152       });
1153       return;
1154     }
1155     ModuleMap.insert({I.first(), *BMOrErr});
1156 
1157     OwnedImports.push_back(std::move(*MBOrErr));
1158   }
1159   auto AddStream = [&](size_t Task) {
1160     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
1161   };
1162   lto::Config Conf;
1163   if (CGOpts.SaveTempsFilePrefix != "") {
1164     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1165                                     /* UseInputModulePath */ false)) {
1166       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1167         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1168                << '\n';
1169       });
1170     }
1171   }
1172   Conf.CPU = TOpts.CPU;
1173   Conf.CodeModel = getCodeModel(CGOpts);
1174   Conf.MAttrs = TOpts.Features;
1175   Conf.RelocModel = CGOpts.RelocationModel;
1176   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1177   initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1178   Conf.SampleProfile = std::move(SampleProfile);
1179   Conf.UseNewPM = CGOpts.ExperimentalNewPassManager;
1180   Conf.DebugPassManager = CGOpts.DebugPassManager;
1181   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1182   Conf.RemarksFilename = CGOpts.OptRecordFile;
1183   Conf.DwoPath = CGOpts.SplitDwarfFile;
1184   switch (Action) {
1185   case Backend_EmitNothing:
1186     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1187       return false;
1188     };
1189     break;
1190   case Backend_EmitLL:
1191     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1192       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1193       return false;
1194     };
1195     break;
1196   case Backend_EmitBC:
1197     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1198       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1199       return false;
1200     };
1201     break;
1202   default:
1203     Conf.CGFileType = getCodeGenFileType(Action);
1204     break;
1205   }
1206   if (Error E = thinBackend(
1207           Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1208           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1209     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1210       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1211     });
1212   }
1213 }
1214 
1215 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1216                               const HeaderSearchOptions &HeaderOpts,
1217                               const CodeGenOptions &CGOpts,
1218                               const clang::TargetOptions &TOpts,
1219                               const LangOptions &LOpts,
1220                               const llvm::DataLayout &TDesc, Module *M,
1221                               BackendAction Action,
1222                               std::unique_ptr<raw_pwrite_stream> OS) {
1223   std::unique_ptr<llvm::Module> EmptyModule;
1224   if (!CGOpts.ThinLTOIndexFile.empty()) {
1225     // If we are performing a ThinLTO importing compile, load the function index
1226     // into memory and pass it into runThinLTOBackend, which will run the
1227     // function importer and invoke LTO passes.
1228     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1229         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile,
1230                                            /*IgnoreEmptyThinLTOIndexFile*/true);
1231     if (!IndexOrErr) {
1232       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1233                             "Error loading index file '" +
1234                             CGOpts.ThinLTOIndexFile + "': ");
1235       return;
1236     }
1237     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1238     // A null CombinedIndex means we should skip ThinLTO compilation
1239     // (LLVM will optionally ignore empty index files, returning null instead
1240     // of an error).
1241     if (CombinedIndex) {
1242       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1243         runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1244                           LOpts, std::move(OS), CGOpts.SampleProfileFile,
1245                           Action);
1246         return;
1247       }
1248       // Distributed indexing detected that nothing from the module is needed
1249       // for the final linking. So we can skip the compilation. We sill need to
1250       // output an empty object file to make sure that a linker does not fail
1251       // trying to read it. Also for some features, like CFI, we must skip
1252       // the compilation as CombinedIndex does not contain all required
1253       // information.
1254       EmptyModule = llvm::make_unique<llvm::Module>("empty", M->getContext());
1255       EmptyModule->setTargetTriple(M->getTargetTriple());
1256       M = EmptyModule.get();
1257     }
1258   }
1259 
1260   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1261 
1262   if (CGOpts.ExperimentalNewPassManager)
1263     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1264   else
1265     AsmHelper.EmitAssembly(Action, std::move(OS));
1266 
1267   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1268   // DataLayout.
1269   if (AsmHelper.TM) {
1270     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1271     if (DLDesc != TDesc.getStringRepresentation()) {
1272       unsigned DiagID = Diags.getCustomDiagID(
1273           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1274                                     "expected target description '%1'");
1275       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1276     }
1277   }
1278 }
1279 
1280 static const char* getSectionNameForBitcode(const Triple &T) {
1281   switch (T.getObjectFormat()) {
1282   case Triple::MachO:
1283     return "__LLVM,__bitcode";
1284   case Triple::COFF:
1285   case Triple::ELF:
1286   case Triple::Wasm:
1287   case Triple::UnknownObjectFormat:
1288     return ".llvmbc";
1289   }
1290   llvm_unreachable("Unimplemented ObjectFormatType");
1291 }
1292 
1293 static const char* getSectionNameForCommandline(const Triple &T) {
1294   switch (T.getObjectFormat()) {
1295   case Triple::MachO:
1296     return "__LLVM,__cmdline";
1297   case Triple::COFF:
1298   case Triple::ELF:
1299   case Triple::Wasm:
1300   case Triple::UnknownObjectFormat:
1301     return ".llvmcmd";
1302   }
1303   llvm_unreachable("Unimplemented ObjectFormatType");
1304 }
1305 
1306 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1307 // __LLVM,__bitcode section.
1308 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1309                          llvm::MemoryBufferRef Buf) {
1310   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1311     return;
1312 
1313   // Save llvm.compiler.used and remote it.
1314   SmallVector<Constant*, 2> UsedArray;
1315   SmallPtrSet<GlobalValue*, 4> UsedGlobals;
1316   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1317   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1318   for (auto *GV : UsedGlobals) {
1319     if (GV->getName() != "llvm.embedded.module" &&
1320         GV->getName() != "llvm.cmdline")
1321       UsedArray.push_back(
1322           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1323   }
1324   if (Used)
1325     Used->eraseFromParent();
1326 
1327   // Embed the bitcode for the llvm module.
1328   std::string Data;
1329   ArrayRef<uint8_t> ModuleData;
1330   Triple T(M->getTargetTriple());
1331   // Create a constant that contains the bitcode.
1332   // In case of embedding a marker, ignore the input Buf and use the empty
1333   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1334   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1335     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1336                    (const unsigned char *)Buf.getBufferEnd())) {
1337       // If the input is LLVM Assembly, bitcode is produced by serializing
1338       // the module. Use-lists order need to be perserved in this case.
1339       llvm::raw_string_ostream OS(Data);
1340       llvm::WriteBitcodeToFile(*M, OS, /* ShouldPreserveUseListOrder */ true);
1341       ModuleData =
1342           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1343     } else
1344       // If the input is LLVM bitcode, write the input byte stream directly.
1345       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1346                                      Buf.getBufferSize());
1347   }
1348   llvm::Constant *ModuleConstant =
1349       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1350   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1351       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1352       ModuleConstant);
1353   GV->setSection(getSectionNameForBitcode(T));
1354   UsedArray.push_back(
1355       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1356   if (llvm::GlobalVariable *Old =
1357           M->getGlobalVariable("llvm.embedded.module", true)) {
1358     assert(Old->hasOneUse() &&
1359            "llvm.embedded.module can only be used once in llvm.compiler.used");
1360     GV->takeName(Old);
1361     Old->eraseFromParent();
1362   } else {
1363     GV->setName("llvm.embedded.module");
1364   }
1365 
1366   // Skip if only bitcode needs to be embedded.
1367   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1368     // Embed command-line options.
1369     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1370                               CGOpts.CmdArgs.size());
1371     llvm::Constant *CmdConstant =
1372       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1373     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1374                                   llvm::GlobalValue::PrivateLinkage,
1375                                   CmdConstant);
1376     GV->setSection(getSectionNameForCommandline(T));
1377     UsedArray.push_back(
1378         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1379     if (llvm::GlobalVariable *Old =
1380             M->getGlobalVariable("llvm.cmdline", true)) {
1381       assert(Old->hasOneUse() &&
1382              "llvm.cmdline can only be used once in llvm.compiler.used");
1383       GV->takeName(Old);
1384       Old->eraseFromParent();
1385     } else {
1386       GV->setName("llvm.cmdline");
1387     }
1388   }
1389 
1390   if (UsedArray.empty())
1391     return;
1392 
1393   // Recreate llvm.compiler.used.
1394   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1395   auto *NewUsed = new GlobalVariable(
1396       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1397       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1398   NewUsed->setSection("llvm.metadata");
1399 }
1400