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