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