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 
458   if (CodeGenOpts.EnableSplitDwarf)
459     Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
460   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
461   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
462   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
463   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
464   Options.MCOptions.MCIncrementalLinkerCompatible =
465       CodeGenOpts.IncrementalLinkerCompatible;
466   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
467   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
468   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
469   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
470   Options.MCOptions.ABIName = TargetOpts.ABI;
471   for (const auto &Entry : HSOpts.UserEntries)
472     if (!Entry.IsFramework &&
473         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
474          Entry.Group == frontend::IncludeDirGroup::Angled ||
475          Entry.Group == frontend::IncludeDirGroup::System))
476       Options.MCOptions.IASSearchPaths.push_back(
477           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
478 }
479 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts) {
480   if (CodeGenOpts.DisableGCov)
481     return None;
482   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
483     return None;
484   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
485   // LLVM's -default-gcov-version flag is set to something invalid.
486   GCOVOptions Options;
487   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
488   Options.EmitData = CodeGenOpts.EmitGcovArcs;
489   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
490   Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
491   Options.NoRedZone = CodeGenOpts.DisableRedZone;
492   Options.FunctionNamesInData = !CodeGenOpts.CoverageNoFunctionNamesInData;
493   Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
494   return Options;
495 }
496 
497 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
498                                       legacy::FunctionPassManager &FPM) {
499   // Handle disabling of all LLVM passes, where we want to preserve the
500   // internal module before any optimization.
501   if (CodeGenOpts.DisableLLVMPasses)
502     return;
503 
504   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
505   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
506   // are inserted before PMBuilder ones - they'd get the default-constructed
507   // TLI with an unknown target otherwise.
508   Triple TargetTriple(TheModule->getTargetTriple());
509   std::unique_ptr<TargetLibraryInfoImpl> TLII(
510       createTLII(TargetTriple, CodeGenOpts));
511 
512   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
513 
514   // At O0 and O1 we only run the always inliner which is more efficient. At
515   // higher optimization levels we run the normal inliner.
516   if (CodeGenOpts.OptimizationLevel <= 1) {
517     bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
518                                      !CodeGenOpts.DisableLifetimeMarkers);
519     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
520   } else {
521     // We do not want to inline hot callsites for SamplePGO module-summary build
522     // because profile annotation will happen again in ThinLTO backend, and we
523     // want the IR of the hot path to match the profile.
524     PMBuilder.Inliner = createFunctionInliningPass(
525         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
526         (!CodeGenOpts.SampleProfileFile.empty() &&
527          CodeGenOpts.PrepareForThinLTO));
528   }
529 
530   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
531   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
532   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
533   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
534 
535   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
536   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
537   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
538   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
539   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
540 
541   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
542 
543   if (TM)
544     TM->adjustPassManager(PMBuilder);
545 
546   if (CodeGenOpts.DebugInfoForProfiling ||
547       !CodeGenOpts.SampleProfileFile.empty())
548     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
549                            addAddDiscriminatorsPass);
550 
551   // In ObjC ARC mode, add the main ARC optimization passes.
552   if (LangOpts.ObjCAutoRefCount) {
553     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
554                            addObjCARCExpandPass);
555     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
556                            addObjCARCAPElimPass);
557     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
558                            addObjCARCOptPass);
559   }
560 
561   if (LangOpts.CoroutinesTS)
562     addCoroutinePassesToExtensionPoints(PMBuilder);
563 
564   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
565     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
566                            addBoundsCheckingPass);
567     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
568                            addBoundsCheckingPass);
569   }
570 
571   if (CodeGenOpts.SanitizeCoverageType ||
572       CodeGenOpts.SanitizeCoverageIndirectCalls ||
573       CodeGenOpts.SanitizeCoverageTraceCmp) {
574     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
575                            addSanitizerCoveragePass);
576     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
577                            addSanitizerCoveragePass);
578   }
579 
580   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
581     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
582                            addAddressSanitizerPasses);
583     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
584                            addAddressSanitizerPasses);
585   }
586 
587   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
588     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
589                            addKernelAddressSanitizerPasses);
590     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
591                            addKernelAddressSanitizerPasses);
592   }
593 
594   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
595     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
596                            addHWAddressSanitizerPasses);
597     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
598                            addHWAddressSanitizerPasses);
599   }
600 
601   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
602     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
603                            addKernelHWAddressSanitizerPasses);
604     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
605                            addKernelHWAddressSanitizerPasses);
606   }
607 
608   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
609     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
610                            addMemorySanitizerPass);
611     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
612                            addMemorySanitizerPass);
613   }
614 
615   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
616     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
617                            addThreadSanitizerPass);
618     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
619                            addThreadSanitizerPass);
620   }
621 
622   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
623     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
624                            addDataFlowSanitizerPass);
625     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
626                            addDataFlowSanitizerPass);
627   }
628 
629   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
630     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
631                            addEfficiencySanitizerPass);
632     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
633                            addEfficiencySanitizerPass);
634   }
635 
636   // Set up the per-function pass manager.
637   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
638   if (CodeGenOpts.VerifyModule)
639     FPM.add(createVerifierPass());
640 
641   // Set up the per-module pass manager.
642   if (!CodeGenOpts.RewriteMapFiles.empty())
643     addSymbolRewriterPass(CodeGenOpts, &MPM);
644 
645   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts)) {
646     MPM.add(createGCOVProfilerPass(*Options));
647     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
648       MPM.add(createStripSymbolsPass(true));
649   }
650 
651   if (CodeGenOpts.hasProfileClangInstr()) {
652     InstrProfOptions Options;
653     Options.NoRedZone = CodeGenOpts.DisableRedZone;
654     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
655     MPM.add(createInstrProfilingLegacyPass(Options));
656   }
657   if (CodeGenOpts.hasProfileIRInstr()) {
658     PMBuilder.EnablePGOInstrGen = true;
659     if (!CodeGenOpts.InstrProfileOutput.empty())
660       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
661     else
662       PMBuilder.PGOInstrGen = DefaultProfileGenName;
663   }
664   if (CodeGenOpts.hasProfileIRUse())
665     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
666 
667   if (!CodeGenOpts.SampleProfileFile.empty())
668     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
669 
670   PMBuilder.populateFunctionPassManager(FPM);
671   PMBuilder.populateModulePassManager(MPM);
672 }
673 
674 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
675   SmallVector<const char *, 16> BackendArgs;
676   BackendArgs.push_back("clang"); // Fake program name.
677   if (!CodeGenOpts.DebugPass.empty()) {
678     BackendArgs.push_back("-debug-pass");
679     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
680   }
681   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
682     BackendArgs.push_back("-limit-float-precision");
683     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
684   }
685   BackendArgs.push_back(nullptr);
686   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
687                                     BackendArgs.data());
688 }
689 
690 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
691   // Create the TargetMachine for generating code.
692   std::string Error;
693   std::string Triple = TheModule->getTargetTriple();
694   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
695   if (!TheTarget) {
696     if (MustCreateTM)
697       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
698     return;
699   }
700 
701   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
702   std::string FeaturesStr =
703       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
704   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
705   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
706 
707   llvm::TargetOptions Options;
708   initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
709   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
710                                           Options, RM, CM, OptLevel));
711 }
712 
713 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
714                                        BackendAction Action,
715                                        raw_pwrite_stream &OS,
716                                        raw_pwrite_stream *DwoOS) {
717   // Add LibraryInfo.
718   llvm::Triple TargetTriple(TheModule->getTargetTriple());
719   std::unique_ptr<TargetLibraryInfoImpl> TLII(
720       createTLII(TargetTriple, CodeGenOpts));
721   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
722 
723   // Normal mode, emit a .s or .o file by running the code generator. Note,
724   // this also adds codegenerator level optimization passes.
725   TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
726 
727   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
728   // "codegen" passes so that it isn't run multiple times when there is
729   // inlining happening.
730   if (CodeGenOpts.OptimizationLevel > 0)
731     CodeGenPasses.add(createObjCARCContractPass());
732 
733   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
734                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
735     Diags.Report(diag::err_fe_unable_to_interface_with_target);
736     return false;
737   }
738 
739   return true;
740 }
741 
742 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
743                                       std::unique_ptr<raw_pwrite_stream> OS) {
744   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
745 
746   setCommandLineOpts(CodeGenOpts);
747 
748   bool UsesCodeGen = (Action != Backend_EmitNothing &&
749                       Action != Backend_EmitBC &&
750                       Action != Backend_EmitLL);
751   CreateTargetMachine(UsesCodeGen);
752 
753   if (UsesCodeGen && !TM)
754     return;
755   if (TM)
756     TheModule->setDataLayout(TM->createDataLayout());
757 
758   legacy::PassManager PerModulePasses;
759   PerModulePasses.add(
760       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
761 
762   legacy::FunctionPassManager PerFunctionPasses(TheModule);
763   PerFunctionPasses.add(
764       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
765 
766   CreatePasses(PerModulePasses, PerFunctionPasses);
767 
768   legacy::PassManager CodeGenPasses;
769   CodeGenPasses.add(
770       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
771 
772   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
773 
774   switch (Action) {
775   case Backend_EmitNothing:
776     break;
777 
778   case Backend_EmitBC:
779     if (CodeGenOpts.PrepareForThinLTO) {
780       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
781         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
782         if (!ThinLinkOS)
783           return;
784       }
785       PerModulePasses.add(createWriteThinLTOBitcodePass(
786           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
787     } else {
788       // Emit a module summary by default for Regular LTO except for ld64
789       // targets
790       bool EmitLTOSummary =
791           (CodeGenOpts.PrepareForLTO &&
792            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
793                llvm::Triple::Apple);
794       if (EmitLTOSummary && !TheModule->getModuleFlag("ThinLTO"))
795         TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
796 
797       PerModulePasses.add(
798           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
799                                   EmitLTOSummary));
800     }
801     break;
802 
803   case Backend_EmitLL:
804     PerModulePasses.add(
805         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
806     break;
807 
808   default:
809     if (!CodeGenOpts.SplitDwarfFile.empty()) {
810       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
811       if (!DwoOS)
812         return;
813     }
814     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
815                        DwoOS ? &DwoOS->os() : nullptr))
816       return;
817   }
818 
819   // Before executing passes, print the final values of the LLVM options.
820   cl::PrintOptionValues();
821 
822   // Run passes. For now we do all passes at once, but eventually we
823   // would like to have the option of streaming code generation.
824 
825   {
826     PrettyStackTraceString CrashInfo("Per-function optimization");
827 
828     PerFunctionPasses.doInitialization();
829     for (Function &F : *TheModule)
830       if (!F.isDeclaration())
831         PerFunctionPasses.run(F);
832     PerFunctionPasses.doFinalization();
833   }
834 
835   {
836     PrettyStackTraceString CrashInfo("Per-module optimization passes");
837     PerModulePasses.run(*TheModule);
838   }
839 
840   {
841     PrettyStackTraceString CrashInfo("Code generation");
842     CodeGenPasses.run(*TheModule);
843   }
844 
845   if (ThinLinkOS)
846     ThinLinkOS->keep();
847   if (DwoOS)
848     DwoOS->keep();
849 }
850 
851 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
852   switch (Opts.OptimizationLevel) {
853   default:
854     llvm_unreachable("Invalid optimization level!");
855 
856   case 1:
857     return PassBuilder::O1;
858 
859   case 2:
860     switch (Opts.OptimizeSize) {
861     default:
862       llvm_unreachable("Invalid optimization level for size!");
863 
864     case 0:
865       return PassBuilder::O2;
866 
867     case 1:
868       return PassBuilder::Os;
869 
870     case 2:
871       return PassBuilder::Oz;
872     }
873 
874   case 3:
875     return PassBuilder::O3;
876   }
877 }
878 
879 /// A clean version of `EmitAssembly` that uses the new pass manager.
880 ///
881 /// Not all features are currently supported in this system, but where
882 /// necessary it falls back to the legacy pass manager to at least provide
883 /// basic functionality.
884 ///
885 /// This API is planned to have its functionality finished and then to replace
886 /// `EmitAssembly` at some point in the future when the default switches.
887 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
888     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
889   TimeRegion Region(FrontendTimesIsEnabled ? &CodeGenerationTime : nullptr);
890   setCommandLineOpts(CodeGenOpts);
891 
892   // The new pass manager always makes a target machine available to passes
893   // during construction.
894   CreateTargetMachine(/*MustCreateTM*/ true);
895   if (!TM)
896     // This will already be diagnosed, just bail.
897     return;
898   TheModule->setDataLayout(TM->createDataLayout());
899 
900   Optional<PGOOptions> PGOOpt;
901 
902   if (CodeGenOpts.hasProfileIRInstr())
903     // -fprofile-generate.
904     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
905                             ? DefaultProfileGenName
906                             : CodeGenOpts.InstrProfileOutput,
907                         "", "", true, CodeGenOpts.DebugInfoForProfiling);
908   else if (CodeGenOpts.hasProfileIRUse())
909     // -fprofile-use.
910     PGOOpt = PGOOptions("", CodeGenOpts.ProfileInstrumentUsePath, "", false,
911                         CodeGenOpts.DebugInfoForProfiling);
912   else if (!CodeGenOpts.SampleProfileFile.empty())
913     // -fprofile-sample-use
914     PGOOpt = PGOOptions("", "", CodeGenOpts.SampleProfileFile, false,
915                         CodeGenOpts.DebugInfoForProfiling);
916   else if (CodeGenOpts.DebugInfoForProfiling)
917     // -fdebug-info-for-profiling
918     PGOOpt = PGOOptions("", "", "", false, true);
919 
920   PassBuilder PB(TM.get(), PGOOpt);
921 
922   LoopAnalysisManager LAM(CodeGenOpts.DebugPassManager);
923   FunctionAnalysisManager FAM(CodeGenOpts.DebugPassManager);
924   CGSCCAnalysisManager CGAM(CodeGenOpts.DebugPassManager);
925   ModuleAnalysisManager MAM(CodeGenOpts.DebugPassManager);
926 
927   // Register the AA manager first so that our version is the one used.
928   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
929 
930   // Register the target library analysis directly and give it a customized
931   // preset TLI.
932   Triple TargetTriple(TheModule->getTargetTriple());
933   std::unique_ptr<TargetLibraryInfoImpl> TLII(
934       createTLII(TargetTriple, CodeGenOpts));
935   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
936   MAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
937 
938   // Register all the basic analyses with the managers.
939   PB.registerModuleAnalyses(MAM);
940   PB.registerCGSCCAnalyses(CGAM);
941   PB.registerFunctionAnalyses(FAM);
942   PB.registerLoopAnalyses(LAM);
943   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
944 
945   ModulePassManager MPM(CodeGenOpts.DebugPassManager);
946 
947   if (!CodeGenOpts.DisableLLVMPasses) {
948     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
949     bool IsLTO = CodeGenOpts.PrepareForLTO;
950 
951     if (CodeGenOpts.OptimizationLevel == 0) {
952       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
953         MPM.addPass(GCOVProfilerPass(*Options));
954 
955       // Build a minimal pipeline based on the semantics required by Clang,
956       // which is just that always inlining occurs.
957       MPM.addPass(AlwaysInlinerPass());
958 
959       // At -O0 we directly run necessary sanitizer passes.
960       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
961         MPM.addPass(createModuleToFunctionPassAdaptor(BoundsCheckingPass()));
962 
963       // Lastly, add a semantically necessary pass for LTO.
964       if (IsLTO || IsThinLTO)
965         MPM.addPass(NameAnonGlobalPass());
966     } else {
967       // Map our optimization levels into one of the distinct levels used to
968       // configure the pipeline.
969       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
970 
971       // Register callbacks to schedule sanitizer passes at the appropriate part of
972       // the pipeline.
973       if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
974         PB.registerScalarOptimizerLateEPCallback(
975             [](FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) {
976               FPM.addPass(BoundsCheckingPass());
977             });
978       if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts))
979         PB.registerPipelineStartEPCallback([Options](ModulePassManager &MPM) {
980           MPM.addPass(GCOVProfilerPass(*Options));
981         });
982 
983       if (IsThinLTO) {
984         MPM = PB.buildThinLTOPreLinkDefaultPipeline(
985             Level, CodeGenOpts.DebugPassManager);
986         MPM.addPass(NameAnonGlobalPass());
987       } else if (IsLTO) {
988         MPM = PB.buildLTOPreLinkDefaultPipeline(Level,
989                                                 CodeGenOpts.DebugPassManager);
990         MPM.addPass(NameAnonGlobalPass());
991       } else {
992         MPM = PB.buildPerModuleDefaultPipeline(Level,
993                                                CodeGenOpts.DebugPassManager);
994       }
995     }
996   }
997 
998   // FIXME: We still use the legacy pass manager to do code generation. We
999   // create that pass manager here and use it as needed below.
1000   legacy::PassManager CodeGenPasses;
1001   bool NeedCodeGen = false;
1002   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1003 
1004   // Append any output we need to the pass manager.
1005   switch (Action) {
1006   case Backend_EmitNothing:
1007     break;
1008 
1009   case Backend_EmitBC:
1010     if (CodeGenOpts.PrepareForThinLTO) {
1011       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1012         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1013         if (!ThinLinkOS)
1014           return;
1015       }
1016       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1017                                                            : nullptr));
1018     } else {
1019       // Emit a module summary by default for Regular LTO except for ld64
1020       // targets
1021       bool EmitLTOSummary =
1022           (CodeGenOpts.PrepareForLTO &&
1023            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1024                llvm::Triple::Apple);
1025       if (EmitLTOSummary && !TheModule->getModuleFlag("ThinLTO"))
1026         TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1027 
1028       MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
1029                                     EmitLTOSummary));
1030     }
1031     break;
1032 
1033   case Backend_EmitLL:
1034     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1035     break;
1036 
1037   case Backend_EmitAssembly:
1038   case Backend_EmitMCNull:
1039   case Backend_EmitObj:
1040     NeedCodeGen = true;
1041     CodeGenPasses.add(
1042         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1043     if (!CodeGenOpts.SplitDwarfFile.empty()) {
1044       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfFile);
1045       if (!DwoOS)
1046         return;
1047     }
1048     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1049                        DwoOS ? &DwoOS->os() : nullptr))
1050       // FIXME: Should we handle this error differently?
1051       return;
1052     break;
1053   }
1054 
1055   // Before executing passes, print the final values of the LLVM options.
1056   cl::PrintOptionValues();
1057 
1058   // Now that we have all of the passes ready, run them.
1059   {
1060     PrettyStackTraceString CrashInfo("Optimizer");
1061     MPM.run(*TheModule, MAM);
1062   }
1063 
1064   // Now if needed, run the legacy PM for codegen.
1065   if (NeedCodeGen) {
1066     PrettyStackTraceString CrashInfo("Code generation");
1067     CodeGenPasses.run(*TheModule);
1068   }
1069 
1070   if (ThinLinkOS)
1071     ThinLinkOS->keep();
1072   if (DwoOS)
1073     DwoOS->keep();
1074 }
1075 
1076 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
1077   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1078   if (!BMsOrErr)
1079     return BMsOrErr.takeError();
1080 
1081   // The bitcode file may contain multiple modules, we want the one that is
1082   // marked as being the ThinLTO module.
1083   if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr))
1084     return *Bm;
1085 
1086   return make_error<StringError>("Could not find module summary",
1087                                  inconvertibleErrorCode());
1088 }
1089 
1090 BitcodeModule *clang::FindThinLTOModule(MutableArrayRef<BitcodeModule> BMs) {
1091   for (BitcodeModule &BM : BMs) {
1092     Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
1093     if (LTOInfo && LTOInfo->IsThinLTO)
1094       return &BM;
1095   }
1096   return nullptr;
1097 }
1098 
1099 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
1100                               const HeaderSearchOptions &HeaderOpts,
1101                               const CodeGenOptions &CGOpts,
1102                               const clang::TargetOptions &TOpts,
1103                               const LangOptions &LOpts,
1104                               std::unique_ptr<raw_pwrite_stream> OS,
1105                               std::string SampleProfile,
1106                               BackendAction Action) {
1107   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1108       ModuleToDefinedGVSummaries;
1109   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1110 
1111   setCommandLineOpts(CGOpts);
1112 
1113   // We can simply import the values mentioned in the combined index, since
1114   // we should only invoke this using the individual indexes written out
1115   // via a WriteIndexesThinBackend.
1116   FunctionImporter::ImportMapTy ImportList;
1117   for (auto &GlobalList : *CombinedIndex) {
1118     // Ignore entries for undefined references.
1119     if (GlobalList.second.SummaryList.empty())
1120       continue;
1121 
1122     auto GUID = GlobalList.first;
1123     assert(GlobalList.second.SummaryList.size() == 1 &&
1124            "Expected individual combined index to have one summary per GUID");
1125     auto &Summary = GlobalList.second.SummaryList[0];
1126     // Skip the summaries for the importing module. These are included to
1127     // e.g. record required linkage changes.
1128     if (Summary->modulePath() == M->getModuleIdentifier())
1129       continue;
1130     // Doesn't matter what value we plug in to the map, just needs an entry
1131     // to provoke importing by thinBackend.
1132     ImportList[Summary->modulePath()][GUID] = 1;
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