1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/CodeGen/BackendUtil.h"
10 #include "clang/Basic/CodeGenOptions.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/FrontendDiagnostic.h"
15 #include "clang/Frontend/Utils.h"
16 #include "clang/Lex/HeaderSearchOptions.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/StackSafetyAnalysis.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeReader.h"
26 #include "llvm/Bitcode/BitcodeWriter.h"
27 #include "llvm/Bitcode/BitcodeWriterPass.h"
28 #include "llvm/CodeGen/RegAllocRegistry.h"
29 #include "llvm/CodeGen/SchedulerRegistry.h"
30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/IRPrintingPasses.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/ModuleSummaryIndex.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/IR/Verifier.h"
38 #include "llvm/LTO/LTOBackend.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/SubtargetFeature.h"
41 #include "llvm/MC/TargetRegistry.h"
42 #include "llvm/Passes/PassBuilder.h"
43 #include "llvm/Passes/PassPlugin.h"
44 #include "llvm/Passes/StandardInstrumentations.h"
45 #include "llvm/Support/BuryPointer.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/PrettyStackTrace.h"
49 #include "llvm/Support/TimeProfiler.h"
50 #include "llvm/Support/Timer.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "llvm/Transforms/Coroutines.h"
56 #include "llvm/Transforms/Coroutines/CoroCleanup.h"
57 #include "llvm/Transforms/Coroutines/CoroEarly.h"
58 #include "llvm/Transforms/Coroutines/CoroElide.h"
59 #include "llvm/Transforms/Coroutines/CoroSplit.h"
60 #include "llvm/Transforms/IPO.h"
61 #include "llvm/Transforms/IPO/AlwaysInliner.h"
62 #include "llvm/Transforms/IPO/LowerTypeTests.h"
63 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
64 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
65 #include "llvm/Transforms/InstCombine/InstCombine.h"
66 #include "llvm/Transforms/Instrumentation.h"
67 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
68 #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
69 #include "llvm/Transforms/Instrumentation/BoundsChecking.h"
70 #include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
71 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
72 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
73 #include "llvm/Transforms/Instrumentation/InstrProfiling.h"
74 #include "llvm/Transforms/Instrumentation/MemProfiler.h"
75 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
76 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
77 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
78 #include "llvm/Transforms/ObjCARC.h"
79 #include "llvm/Transforms/Scalar.h"
80 #include "llvm/Transforms/Scalar/EarlyCSE.h"
81 #include "llvm/Transforms/Scalar/GVN.h"
82 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
83 #include "llvm/Transforms/Utils.h"
84 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
85 #include "llvm/Transforms/Utils/Debugify.h"
86 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
87 #include "llvm/Transforms/Utils/ModuleUtils.h"
88 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
89 #include "llvm/Transforms/Utils/SymbolRewriter.h"
90 #include <memory>
91 using namespace clang;
92 using namespace llvm;
93 
94 #define HANDLE_EXTENSION(Ext)                                                  \
95   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
96 #include "llvm/Support/Extension.def"
97 
98 namespace llvm {
99 extern cl::opt<bool> DebugInfoCorrelate;
100 }
101 
102 namespace {
103 
104 // Default filename used for profile generation.
105 std::string getDefaultProfileGenName() {
106   return DebugInfoCorrelate ? "default_%p.proflite" : "default_%m.profraw";
107 }
108 
109 class EmitAssemblyHelper {
110   DiagnosticsEngine &Diags;
111   const HeaderSearchOptions &HSOpts;
112   const CodeGenOptions &CodeGenOpts;
113   const clang::TargetOptions &TargetOpts;
114   const LangOptions &LangOpts;
115   Module *TheModule;
116 
117   Timer CodeGenerationTime;
118 
119   std::unique_ptr<raw_pwrite_stream> OS;
120 
121   TargetIRAnalysis getTargetIRAnalysis() const {
122     if (TM)
123       return TM->getTargetIRAnalysis();
124 
125     return TargetIRAnalysis();
126   }
127 
128   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
129 
130   /// Generates the TargetMachine.
131   /// Leaves TM unchanged if it is unable to create the target machine.
132   /// Some of our clang tests specify triples which are not built
133   /// into clang. This is okay because these tests check the generated
134   /// IR, and they require DataLayout which depends on the triple.
135   /// In this case, we allow this method to fail and not report an error.
136   /// When MustCreateTM is used, we print an error if we are unable to load
137   /// the requested target.
138   void CreateTargetMachine(bool MustCreateTM);
139 
140   /// Add passes necessary to emit assembly or LLVM IR.
141   ///
142   /// \return True on success.
143   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
144                      raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS);
145 
146   std::unique_ptr<llvm::ToolOutputFile> openOutputFile(StringRef Path) {
147     std::error_code EC;
148     auto F = std::make_unique<llvm::ToolOutputFile>(Path, EC,
149                                                      llvm::sys::fs::OF_None);
150     if (EC) {
151       Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
152       F.reset();
153     }
154     return F;
155   }
156 
157   void
158   RunOptimizationPipeline(BackendAction Action,
159                           std::unique_ptr<raw_pwrite_stream> &OS,
160                           std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS);
161   void RunCodegenPipeline(BackendAction Action,
162                           std::unique_ptr<raw_pwrite_stream> &OS,
163                           std::unique_ptr<llvm::ToolOutputFile> &DwoOS);
164 
165 public:
166   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
167                      const HeaderSearchOptions &HeaderSearchOpts,
168                      const CodeGenOptions &CGOpts,
169                      const clang::TargetOptions &TOpts,
170                      const LangOptions &LOpts, Module *M)
171       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
172         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
173         CodeGenerationTime("codegen", "Code Generation Time") {}
174 
175   ~EmitAssemblyHelper() {
176     if (CodeGenOpts.DisableFree)
177       BuryPointer(std::move(TM));
178   }
179 
180   std::unique_ptr<TargetMachine> TM;
181 
182   // Emit output using the legacy pass manager for the optimization pipeline.
183   // This will be removed soon when using the legacy pass manager for the
184   // optimization pipeline is no longer supported.
185   void EmitAssemblyWithLegacyPassManager(BackendAction Action,
186                                          std::unique_ptr<raw_pwrite_stream> OS);
187 
188   // Emit output using the new pass manager for the optimization pipeline. This
189   // is the default.
190   void EmitAssembly(BackendAction Action,
191                     std::unique_ptr<raw_pwrite_stream> OS);
192 };
193 
194 // We need this wrapper to access LangOpts and CGOpts from extension functions
195 // that we add to the PassManagerBuilder.
196 class PassManagerBuilderWrapper : public PassManagerBuilder {
197 public:
198   PassManagerBuilderWrapper(const Triple &TargetTriple,
199                             const CodeGenOptions &CGOpts,
200                             const LangOptions &LangOpts)
201       : TargetTriple(TargetTriple), CGOpts(CGOpts), LangOpts(LangOpts) {}
202   const Triple &getTargetTriple() const { return TargetTriple; }
203   const CodeGenOptions &getCGOpts() const { return CGOpts; }
204   const LangOptions &getLangOpts() const { return LangOpts; }
205 
206 private:
207   const Triple &TargetTriple;
208   const CodeGenOptions &CGOpts;
209   const LangOptions &LangOpts;
210 };
211 }
212 
213 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
214   if (Builder.OptLevel > 0)
215     PM.add(createObjCARCAPElimPass());
216 }
217 
218 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
219   if (Builder.OptLevel > 0)
220     PM.add(createObjCARCExpandPass());
221 }
222 
223 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
224   if (Builder.OptLevel > 0)
225     PM.add(createObjCARCOptPass());
226 }
227 
228 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
229                                      legacy::PassManagerBase &PM) {
230   PM.add(createAddDiscriminatorsPass());
231 }
232 
233 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
234                                   legacy::PassManagerBase &PM) {
235   PM.add(createBoundsCheckingLegacyPass());
236 }
237 
238 static SanitizerCoverageOptions
239 getSancovOptsFromCGOpts(const CodeGenOptions &CGOpts) {
240   SanitizerCoverageOptions Opts;
241   Opts.CoverageType =
242       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
243   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
244   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
245   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
246   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
247   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
248   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
249   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
250   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
251   Opts.NoPrune = CGOpts.SanitizeCoverageNoPrune;
252   Opts.Inline8bitCounters = CGOpts.SanitizeCoverageInline8bitCounters;
253   Opts.InlineBoolFlag = CGOpts.SanitizeCoverageInlineBoolFlag;
254   Opts.PCTable = CGOpts.SanitizeCoveragePCTable;
255   Opts.StackDepth = CGOpts.SanitizeCoverageStackDepth;
256   Opts.TraceLoads = CGOpts.SanitizeCoverageTraceLoads;
257   Opts.TraceStores = CGOpts.SanitizeCoverageTraceStores;
258   return Opts;
259 }
260 
261 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
262                                      legacy::PassManagerBase &PM) {
263   const PassManagerBuilderWrapper &BuilderWrapper =
264       static_cast<const PassManagerBuilderWrapper &>(Builder);
265   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
266   auto Opts = getSancovOptsFromCGOpts(CGOpts);
267   PM.add(createModuleSanitizerCoverageLegacyPassPass(
268       Opts, CGOpts.SanitizeCoverageAllowlistFiles,
269       CGOpts.SanitizeCoverageIgnorelistFiles));
270 }
271 
272 // Check if ASan should use GC-friendly instrumentation for globals.
273 // First of all, there is no point if -fdata-sections is off (expect for MachO,
274 // where this is not a factor). Also, on ELF this feature requires an assembler
275 // extension that only works with -integrated-as at the moment.
276 static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
277   if (!CGOpts.SanitizeAddressGlobalsDeadStripping)
278     return false;
279   switch (T.getObjectFormat()) {
280   case Triple::MachO:
281   case Triple::COFF:
282     return true;
283   case Triple::ELF:
284     return !CGOpts.DisableIntegratedAS;
285   case Triple::GOFF:
286     llvm::report_fatal_error("ASan not implemented for GOFF");
287   case Triple::XCOFF:
288     llvm::report_fatal_error("ASan not implemented for XCOFF.");
289   case Triple::Wasm:
290   case Triple::DXContainer:
291   case Triple::UnknownObjectFormat:
292     break;
293   }
294   return false;
295 }
296 
297 static void addMemProfilerPasses(const PassManagerBuilder &Builder,
298                                  legacy::PassManagerBase &PM) {
299   PM.add(createMemProfilerFunctionPass());
300   PM.add(createModuleMemProfilerLegacyPassPass());
301 }
302 
303 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
304                                       legacy::PassManagerBase &PM) {
305   const PassManagerBuilderWrapper &BuilderWrapper =
306       static_cast<const PassManagerBuilderWrapper&>(Builder);
307   const Triple &T = BuilderWrapper.getTargetTriple();
308   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
309   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
310   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
311   bool UseOdrIndicator = CGOpts.SanitizeAddressUseOdrIndicator;
312   bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
313   llvm::AsanDtorKind DestructorKind = CGOpts.getSanitizeAddressDtor();
314   llvm::AsanDetectStackUseAfterReturnMode UseAfterReturn =
315       CGOpts.getSanitizeAddressUseAfterReturn();
316   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
317                                             UseAfterScope, UseAfterReturn));
318   PM.add(createModuleAddressSanitizerLegacyPassPass(
319       /*CompileKernel*/ false, Recover, UseGlobalsGC, UseOdrIndicator,
320       DestructorKind));
321 }
322 
323 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
324                                             legacy::PassManagerBase &PM) {
325   PM.add(createAddressSanitizerFunctionPass(
326       /*CompileKernel*/ true, /*Recover*/ true, /*UseAfterScope*/ false,
327       /*UseAfterReturn*/ llvm::AsanDetectStackUseAfterReturnMode::Never));
328   PM.add(createModuleAddressSanitizerLegacyPassPass(
329       /*CompileKernel*/ true, /*Recover*/ true, /*UseGlobalsGC*/ true,
330       /*UseOdrIndicator*/ false));
331 }
332 
333 static void addHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
334                                             legacy::PassManagerBase &PM) {
335   const PassManagerBuilderWrapper &BuilderWrapper =
336       static_cast<const PassManagerBuilderWrapper &>(Builder);
337   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
338   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::HWAddress);
339   PM.add(createHWAddressSanitizerLegacyPassPass(
340       /*CompileKernel*/ false, Recover,
341       /*DisableOptimization*/ CGOpts.OptimizationLevel == 0));
342 }
343 
344 static void addKernelHWAddressSanitizerPasses(const PassManagerBuilder &Builder,
345                                               legacy::PassManagerBase &PM) {
346   const PassManagerBuilderWrapper &BuilderWrapper =
347       static_cast<const PassManagerBuilderWrapper &>(Builder);
348   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
349   PM.add(createHWAddressSanitizerLegacyPassPass(
350       /*CompileKernel*/ true, /*Recover*/ true,
351       /*DisableOptimization*/ CGOpts.OptimizationLevel == 0));
352 }
353 
354 static void addGeneralOptsForMemorySanitizer(const PassManagerBuilder &Builder,
355                                              legacy::PassManagerBase &PM,
356                                              bool CompileKernel) {
357   const PassManagerBuilderWrapper &BuilderWrapper =
358       static_cast<const PassManagerBuilderWrapper&>(Builder);
359   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
360   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
361   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
362   PM.add(createMemorySanitizerLegacyPassPass(
363       MemorySanitizerOptions{TrackOrigins, Recover, CompileKernel,
364                              CGOpts.SanitizeMemoryParamRetval != 0}));
365 
366   // MemorySanitizer inserts complex instrumentation that mostly follows
367   // the logic of the original code, but operates on "shadow" values.
368   // It can benefit from re-running some general purpose optimization passes.
369   if (Builder.OptLevel > 0) {
370     PM.add(createEarlyCSEPass());
371     PM.add(createReassociatePass());
372     PM.add(createLICMPass());
373     PM.add(createGVNPass());
374     PM.add(createInstructionCombiningPass());
375     PM.add(createDeadStoreEliminationPass());
376   }
377 }
378 
379 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
380                                    legacy::PassManagerBase &PM) {
381   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ false);
382 }
383 
384 static void addKernelMemorySanitizerPass(const PassManagerBuilder &Builder,
385                                          legacy::PassManagerBase &PM) {
386   addGeneralOptsForMemorySanitizer(Builder, PM, /*CompileKernel*/ true);
387 }
388 
389 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
390                                    legacy::PassManagerBase &PM) {
391   PM.add(createThreadSanitizerLegacyPassPass());
392 }
393 
394 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
395                                      legacy::PassManagerBase &PM) {
396   const PassManagerBuilderWrapper &BuilderWrapper =
397       static_cast<const PassManagerBuilderWrapper&>(Builder);
398   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
399   PM.add(createDataFlowSanitizerLegacyPassPass(LangOpts.NoSanitizeFiles));
400 }
401 
402 static void addEntryExitInstrumentationPass(const PassManagerBuilder &Builder,
403                                             legacy::PassManagerBase &PM) {
404   PM.add(createEntryExitInstrumenterPass());
405 }
406 
407 static void
408 addPostInlineEntryExitInstrumentationPass(const PassManagerBuilder &Builder,
409                                           legacy::PassManagerBase &PM) {
410   PM.add(createPostInlineEntryExitInstrumenterPass());
411 }
412 
413 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
414                                          const CodeGenOptions &CodeGenOpts) {
415   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
416 
417   switch (CodeGenOpts.getVecLib()) {
418   case CodeGenOptions::Accelerate:
419     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
420     break;
421   case CodeGenOptions::LIBMVEC:
422     switch(TargetTriple.getArch()) {
423       default:
424         break;
425       case llvm::Triple::x86_64:
426         TLII->addVectorizableFunctionsFromVecLib
427                 (TargetLibraryInfoImpl::LIBMVEC_X86);
428         break;
429     }
430     break;
431   case CodeGenOptions::MASSV:
432     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::MASSV);
433     break;
434   case CodeGenOptions::SVML:
435     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
436     break;
437   case CodeGenOptions::Darwin_libsystem_m:
438     TLII->addVectorizableFunctionsFromVecLib(
439         TargetLibraryInfoImpl::DarwinLibSystemM);
440     break;
441   default:
442     break;
443   }
444   return TLII;
445 }
446 
447 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
448                                   legacy::PassManager *MPM) {
449   llvm::SymbolRewriter::RewriteDescriptorList DL;
450 
451   llvm::SymbolRewriter::RewriteMapParser MapParser;
452   for (const auto &MapFile : Opts.RewriteMapFiles)
453     MapParser.parse(MapFile, &DL);
454 
455   MPM->add(createRewriteSymbolsPass(DL));
456 }
457 
458 static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
459   switch (CodeGenOpts.OptimizationLevel) {
460   default:
461     llvm_unreachable("Invalid optimization level!");
462   case 0:
463     return CodeGenOpt::None;
464   case 1:
465     return CodeGenOpt::Less;
466   case 2:
467     return CodeGenOpt::Default; // O2/Os/Oz
468   case 3:
469     return CodeGenOpt::Aggressive;
470   }
471 }
472 
473 static Optional<llvm::CodeModel::Model>
474 getCodeModel(const CodeGenOptions &CodeGenOpts) {
475   unsigned CodeModel = llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
476                            .Case("tiny", llvm::CodeModel::Tiny)
477                            .Case("small", llvm::CodeModel::Small)
478                            .Case("kernel", llvm::CodeModel::Kernel)
479                            .Case("medium", llvm::CodeModel::Medium)
480                            .Case("large", llvm::CodeModel::Large)
481                            .Case("default", ~1u)
482                            .Default(~0u);
483   assert(CodeModel != ~0u && "invalid code model!");
484   if (CodeModel == ~1u)
485     return None;
486   return static_cast<llvm::CodeModel::Model>(CodeModel);
487 }
488 
489 static CodeGenFileType getCodeGenFileType(BackendAction Action) {
490   if (Action == Backend_EmitObj)
491     return CGFT_ObjectFile;
492   else if (Action == Backend_EmitMCNull)
493     return CGFT_Null;
494   else {
495     assert(Action == Backend_EmitAssembly && "Invalid action!");
496     return CGFT_AssemblyFile;
497   }
498 }
499 
500 static bool actionRequiresCodeGen(BackendAction Action) {
501   return Action != Backend_EmitNothing && Action != Backend_EmitBC &&
502          Action != Backend_EmitLL;
503 }
504 
505 static bool initTargetOptions(DiagnosticsEngine &Diags,
506                               llvm::TargetOptions &Options,
507                               const CodeGenOptions &CodeGenOpts,
508                               const clang::TargetOptions &TargetOpts,
509                               const LangOptions &LangOpts,
510                               const HeaderSearchOptions &HSOpts) {
511   switch (LangOpts.getThreadModel()) {
512   case LangOptions::ThreadModelKind::POSIX:
513     Options.ThreadModel = llvm::ThreadModel::POSIX;
514     break;
515   case LangOptions::ThreadModelKind::Single:
516     Options.ThreadModel = llvm::ThreadModel::Single;
517     break;
518   }
519 
520   // Set float ABI type.
521   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
522           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
523          "Invalid Floating Point ABI!");
524   Options.FloatABIType =
525       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
526           .Case("soft", llvm::FloatABI::Soft)
527           .Case("softfp", llvm::FloatABI::Soft)
528           .Case("hard", llvm::FloatABI::Hard)
529           .Default(llvm::FloatABI::Default);
530 
531   // Set FP fusion mode.
532   switch (LangOpts.getDefaultFPContractMode()) {
533   case LangOptions::FPM_Off:
534     // Preserve any contraction performed by the front-end.  (Strict performs
535     // splitting of the muladd intrinsic in the backend.)
536     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
537     break;
538   case LangOptions::FPM_On:
539   case LangOptions::FPM_FastHonorPragmas:
540     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
541     break;
542   case LangOptions::FPM_Fast:
543     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
544     break;
545   }
546 
547   Options.BinutilsVersion =
548       llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion);
549   Options.UseInitArray = CodeGenOpts.UseInitArray;
550   Options.LowerGlobalDtorsViaCxaAtExit =
551       CodeGenOpts.RegisterGlobalDtorsWithAtExit;
552   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
553   Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections();
554   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
555 
556   // Set EABI version.
557   Options.EABIVersion = TargetOpts.EABIVersion;
558 
559   if (LangOpts.hasSjLjExceptions())
560     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
561   if (LangOpts.hasSEHExceptions())
562     Options.ExceptionModel = llvm::ExceptionHandling::WinEH;
563   if (LangOpts.hasDWARFExceptions())
564     Options.ExceptionModel = llvm::ExceptionHandling::DwarfCFI;
565   if (LangOpts.hasWasmExceptions())
566     Options.ExceptionModel = llvm::ExceptionHandling::Wasm;
567 
568   Options.NoInfsFPMath = LangOpts.NoHonorInfs;
569   Options.NoNaNsFPMath = LangOpts.NoHonorNaNs;
570   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
571   Options.UnsafeFPMath = LangOpts.UnsafeFPMath;
572   Options.ApproxFuncFPMath = LangOpts.ApproxFunc;
573 
574   Options.BBSections =
575       llvm::StringSwitch<llvm::BasicBlockSection>(CodeGenOpts.BBSections)
576           .Case("all", llvm::BasicBlockSection::All)
577           .Case("labels", llvm::BasicBlockSection::Labels)
578           .StartsWith("list=", llvm::BasicBlockSection::List)
579           .Case("none", llvm::BasicBlockSection::None)
580           .Default(llvm::BasicBlockSection::None);
581 
582   if (Options.BBSections == llvm::BasicBlockSection::List) {
583     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
584         MemoryBuffer::getFile(CodeGenOpts.BBSections.substr(5));
585     if (!MBOrErr) {
586       Diags.Report(diag::err_fe_unable_to_load_basic_block_sections_file)
587           << MBOrErr.getError().message();
588       return false;
589     }
590     Options.BBSectionsFuncListBuf = std::move(*MBOrErr);
591   }
592 
593   Options.EnableMachineFunctionSplitter = CodeGenOpts.SplitMachineFunctions;
594   Options.FunctionSections = CodeGenOpts.FunctionSections;
595   Options.DataSections = CodeGenOpts.DataSections;
596   Options.IgnoreXCOFFVisibility = LangOpts.IgnoreXCOFFVisibility;
597   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
598   Options.UniqueBasicBlockSectionNames =
599       CodeGenOpts.UniqueBasicBlockSectionNames;
600   Options.TLSSize = CodeGenOpts.TLSSize;
601   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
602   Options.ExplicitEmulatedTLS = CodeGenOpts.ExplicitEmulatedTLS;
603   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
604   Options.EmitStackSizeSection = CodeGenOpts.StackSizeSection;
605   Options.StackUsageOutput = CodeGenOpts.StackUsageOutput;
606   Options.EmitAddrsig = CodeGenOpts.Addrsig;
607   Options.ForceDwarfFrameSection = CodeGenOpts.ForceDwarfFrameSection;
608   Options.EmitCallSiteInfo = CodeGenOpts.EmitCallSiteInfo;
609   Options.EnableAIXExtendedAltivecABI = CodeGenOpts.EnableAIXExtendedAltivecABI;
610   Options.XRayOmitFunctionIndex = CodeGenOpts.XRayOmitFunctionIndex;
611   Options.LoopAlignment = CodeGenOpts.LoopAlignment;
612   Options.DebugStrictDwarf = CodeGenOpts.DebugStrictDwarf;
613   Options.ObjectFilenameForDebug = CodeGenOpts.ObjectFilenameForDebug;
614   Options.Hotpatch = CodeGenOpts.HotPatch;
615   Options.JMCInstrument = CodeGenOpts.JMCInstrument;
616 
617   switch (CodeGenOpts.getSwiftAsyncFramePointer()) {
618   case CodeGenOptions::SwiftAsyncFramePointerKind::Auto:
619     Options.SwiftAsyncFramePointer =
620         SwiftAsyncFramePointerMode::DeploymentBased;
621     break;
622 
623   case CodeGenOptions::SwiftAsyncFramePointerKind::Always:
624     Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Always;
625     break;
626 
627   case CodeGenOptions::SwiftAsyncFramePointerKind::Never:
628     Options.SwiftAsyncFramePointer = SwiftAsyncFramePointerMode::Never;
629     break;
630   }
631 
632   Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
633   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
634   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
635   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
636   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
637   Options.MCOptions.MCIncrementalLinkerCompatible =
638       CodeGenOpts.IncrementalLinkerCompatible;
639   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
640   Options.MCOptions.MCNoWarn = CodeGenOpts.NoWarn;
641   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
642   Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64;
643   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
644   Options.MCOptions.ABIName = TargetOpts.ABI;
645   for (const auto &Entry : HSOpts.UserEntries)
646     if (!Entry.IsFramework &&
647         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
648          Entry.Group == frontend::IncludeDirGroup::Angled ||
649          Entry.Group == frontend::IncludeDirGroup::System))
650       Options.MCOptions.IASSearchPaths.push_back(
651           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
652   Options.MCOptions.Argv0 = CodeGenOpts.Argv0;
653   Options.MCOptions.CommandLineArgs = CodeGenOpts.CommandLineArgs;
654   Options.MisExpect = CodeGenOpts.MisExpect;
655 
656   return true;
657 }
658 
659 static Optional<GCOVOptions> getGCOVOptions(const CodeGenOptions &CodeGenOpts,
660                                             const LangOptions &LangOpts) {
661   if (!CodeGenOpts.EmitGcovArcs && !CodeGenOpts.EmitGcovNotes)
662     return None;
663   // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
664   // LLVM's -default-gcov-version flag is set to something invalid.
665   GCOVOptions Options;
666   Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
667   Options.EmitData = CodeGenOpts.EmitGcovArcs;
668   llvm::copy(CodeGenOpts.CoverageVersion, std::begin(Options.Version));
669   Options.NoRedZone = CodeGenOpts.DisableRedZone;
670   Options.Filter = CodeGenOpts.ProfileFilterFiles;
671   Options.Exclude = CodeGenOpts.ProfileExcludeFiles;
672   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
673   return Options;
674 }
675 
676 static Optional<InstrProfOptions>
677 getInstrProfOptions(const CodeGenOptions &CodeGenOpts,
678                     const LangOptions &LangOpts) {
679   if (!CodeGenOpts.hasProfileClangInstr())
680     return None;
681   InstrProfOptions Options;
682   Options.NoRedZone = CodeGenOpts.DisableRedZone;
683   Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
684   Options.Atomic = CodeGenOpts.AtomicProfileUpdate;
685   return Options;
686 }
687 
688 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
689                                       legacy::FunctionPassManager &FPM) {
690   // Handle disabling of all LLVM passes, where we want to preserve the
691   // internal module before any optimization.
692   if (CodeGenOpts.DisableLLVMPasses)
693     return;
694 
695   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
696   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
697   // are inserted before PMBuilder ones - they'd get the default-constructed
698   // TLI with an unknown target otherwise.
699   Triple TargetTriple(TheModule->getTargetTriple());
700   std::unique_ptr<TargetLibraryInfoImpl> TLII(
701       createTLII(TargetTriple, CodeGenOpts));
702 
703   // If we reached here with a non-empty index file name, then the index file
704   // was empty and we are not performing ThinLTO backend compilation (used in
705   // testing in a distributed build environment). Drop any the type test
706   // assume sequences inserted for whole program vtables so that codegen doesn't
707   // complain.
708   if (!CodeGenOpts.ThinLTOIndexFile.empty())
709     MPM.add(createLowerTypeTestsPass(/*ExportSummary=*/nullptr,
710                                      /*ImportSummary=*/nullptr,
711                                      /*DropTypeTests=*/true));
712 
713   PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
714 
715   // At O0 and O1 we only run the always inliner which is more efficient. At
716   // higher optimization levels we run the normal inliner.
717   if (CodeGenOpts.OptimizationLevel <= 1) {
718     bool InsertLifetimeIntrinsics = ((CodeGenOpts.OptimizationLevel != 0 &&
719                                       !CodeGenOpts.DisableLifetimeMarkers) ||
720                                      LangOpts.Coroutines);
721     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
722   } else {
723     // We do not want to inline hot callsites for SamplePGO module-summary build
724     // because profile annotation will happen again in ThinLTO backend, and we
725     // want the IR of the hot path to match the profile.
726     PMBuilder.Inliner = createFunctionInliningPass(
727         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
728         (!CodeGenOpts.SampleProfileFile.empty() &&
729          CodeGenOpts.PrepareForThinLTO));
730   }
731 
732   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
733   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
734   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
735   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
736   // Only enable CGProfilePass when using integrated assembler, since
737   // non-integrated assemblers don't recognize .cgprofile section.
738   PMBuilder.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
739 
740   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
741   // Loop interleaving in the loop vectorizer has historically been set to be
742   // enabled when loop unrolling is enabled.
743   PMBuilder.LoopsInterleaved = CodeGenOpts.UnrollLoops;
744   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
745   PMBuilder.PrepareForThinLTO = CodeGenOpts.PrepareForThinLTO;
746   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
747   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
748 
749   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
750 
751   if (TM)
752     TM->adjustPassManager(PMBuilder);
753 
754   if (CodeGenOpts.DebugInfoForProfiling ||
755       !CodeGenOpts.SampleProfileFile.empty())
756     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
757                            addAddDiscriminatorsPass);
758 
759   // In ObjC ARC mode, add the main ARC optimization passes.
760   if (LangOpts.ObjCAutoRefCount) {
761     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
762                            addObjCARCExpandPass);
763     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
764                            addObjCARCAPElimPass);
765     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
766                            addObjCARCOptPass);
767   }
768 
769   if (LangOpts.Coroutines)
770     addCoroutinePassesToExtensionPoints(PMBuilder);
771 
772   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
773     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
774                            addMemProfilerPasses);
775     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
776                            addMemProfilerPasses);
777   }
778 
779   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
780     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
781                            addBoundsCheckingPass);
782     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
783                            addBoundsCheckingPass);
784   }
785 
786   if (CodeGenOpts.hasSanitizeCoverage()) {
787     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
788                            addSanitizerCoveragePass);
789     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
790                            addSanitizerCoveragePass);
791   }
792 
793   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
794     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
795                            addAddressSanitizerPasses);
796     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
797                            addAddressSanitizerPasses);
798   }
799 
800   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
801     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
802                            addKernelAddressSanitizerPasses);
803     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
804                            addKernelAddressSanitizerPasses);
805   }
806 
807   if (LangOpts.Sanitize.has(SanitizerKind::HWAddress)) {
808     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
809                            addHWAddressSanitizerPasses);
810     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
811                            addHWAddressSanitizerPasses);
812   }
813 
814   if (LangOpts.Sanitize.has(SanitizerKind::KernelHWAddress)) {
815     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
816                            addKernelHWAddressSanitizerPasses);
817     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
818                            addKernelHWAddressSanitizerPasses);
819   }
820 
821   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
822     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
823                            addMemorySanitizerPass);
824     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
825                            addMemorySanitizerPass);
826   }
827 
828   if (LangOpts.Sanitize.has(SanitizerKind::KernelMemory)) {
829     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
830                            addKernelMemorySanitizerPass);
831     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
832                            addKernelMemorySanitizerPass);
833   }
834 
835   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
836     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
837                            addThreadSanitizerPass);
838     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
839                            addThreadSanitizerPass);
840   }
841 
842   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
843     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
844                            addDataFlowSanitizerPass);
845     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
846                            addDataFlowSanitizerPass);
847   }
848 
849   if (CodeGenOpts.InstrumentFunctions ||
850       CodeGenOpts.InstrumentFunctionEntryBare ||
851       CodeGenOpts.InstrumentFunctionsAfterInlining ||
852       CodeGenOpts.InstrumentForProfiling) {
853     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
854                            addEntryExitInstrumentationPass);
855     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
856                            addEntryExitInstrumentationPass);
857     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
858                            addPostInlineEntryExitInstrumentationPass);
859     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
860                            addPostInlineEntryExitInstrumentationPass);
861   }
862 
863   // Set up the per-function pass manager.
864   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
865   if (CodeGenOpts.VerifyModule)
866     FPM.add(createVerifierPass());
867 
868   // Set up the per-module pass manager.
869   if (!CodeGenOpts.RewriteMapFiles.empty())
870     addSymbolRewriterPass(CodeGenOpts, &MPM);
871 
872   if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts)) {
873     MPM.add(createGCOVProfilerPass(*Options));
874     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
875       MPM.add(createStripSymbolsPass(true));
876   }
877 
878   if (Optional<InstrProfOptions> Options =
879           getInstrProfOptions(CodeGenOpts, LangOpts))
880     MPM.add(createInstrProfilingLegacyPass(*Options, false));
881 
882   bool hasIRInstr = false;
883   if (CodeGenOpts.hasProfileIRInstr()) {
884     PMBuilder.EnablePGOInstrGen = true;
885     hasIRInstr = true;
886   }
887   if (CodeGenOpts.hasProfileCSIRInstr()) {
888     assert(!CodeGenOpts.hasProfileCSIRUse() &&
889            "Cannot have both CSProfileUse pass and CSProfileGen pass at the "
890            "same time");
891     assert(!hasIRInstr &&
892            "Cannot have both ProfileGen pass and CSProfileGen pass at the "
893            "same time");
894     PMBuilder.EnablePGOCSInstrGen = true;
895     hasIRInstr = true;
896   }
897   if (hasIRInstr) {
898     if (!CodeGenOpts.InstrProfileOutput.empty())
899       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
900     else
901       PMBuilder.PGOInstrGen = getDefaultProfileGenName();
902   }
903   if (CodeGenOpts.hasProfileIRUse()) {
904     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
905     PMBuilder.EnablePGOCSInstrUse = CodeGenOpts.hasProfileCSIRUse();
906   }
907 
908   if (!CodeGenOpts.SampleProfileFile.empty())
909     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
910 
911   PMBuilder.populateFunctionPassManager(FPM);
912   PMBuilder.populateModulePassManager(MPM);
913 }
914 
915 static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
916   SmallVector<const char *, 16> BackendArgs;
917   BackendArgs.push_back("clang"); // Fake program name.
918   if (!CodeGenOpts.DebugPass.empty()) {
919     BackendArgs.push_back("-debug-pass");
920     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
921   }
922   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
923     BackendArgs.push_back("-limit-float-precision");
924     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
925   }
926   // Check for the default "clang" invocation that won't set any cl::opt values.
927   // Skip trying to parse the command line invocation to avoid the issues
928   // described below.
929   if (BackendArgs.size() == 1)
930     return;
931   BackendArgs.push_back(nullptr);
932   // FIXME: The command line parser below is not thread-safe and shares a global
933   // state, so this call might crash or overwrite the options of another Clang
934   // instance in the same process.
935   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
936                                     BackendArgs.data());
937 }
938 
939 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
940   // Create the TargetMachine for generating code.
941   std::string Error;
942   std::string Triple = TheModule->getTargetTriple();
943   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
944   if (!TheTarget) {
945     if (MustCreateTM)
946       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
947     return;
948   }
949 
950   Optional<llvm::CodeModel::Model> CM = getCodeModel(CodeGenOpts);
951   std::string FeaturesStr =
952       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
953   llvm::Reloc::Model RM = CodeGenOpts.RelocationModel;
954   CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
955 
956   llvm::TargetOptions Options;
957   if (!initTargetOptions(Diags, Options, CodeGenOpts, TargetOpts, LangOpts,
958                          HSOpts))
959     return;
960   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
961                                           Options, RM, CM, OptLevel));
962 }
963 
964 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
965                                        BackendAction Action,
966                                        raw_pwrite_stream &OS,
967                                        raw_pwrite_stream *DwoOS) {
968   // Add LibraryInfo.
969   llvm::Triple TargetTriple(TheModule->getTargetTriple());
970   std::unique_ptr<TargetLibraryInfoImpl> TLII(
971       createTLII(TargetTriple, CodeGenOpts));
972   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
973 
974   // Normal mode, emit a .s or .o file by running the code generator. Note,
975   // this also adds codegenerator level optimization passes.
976   CodeGenFileType CGFT = getCodeGenFileType(Action);
977 
978   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
979   // "codegen" passes so that it isn't run multiple times when there is
980   // inlining happening.
981   if (CodeGenOpts.OptimizationLevel > 0)
982     CodeGenPasses.add(createObjCARCContractPass());
983 
984   if (TM->addPassesToEmitFile(CodeGenPasses, OS, DwoOS, CGFT,
985                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
986     Diags.Report(diag::err_fe_unable_to_interface_with_target);
987     return false;
988   }
989 
990   return true;
991 }
992 
993 void EmitAssemblyHelper::EmitAssemblyWithLegacyPassManager(
994     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
995   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
996 
997   setCommandLineOpts(CodeGenOpts);
998 
999   bool UsesCodeGen = actionRequiresCodeGen(Action);
1000   CreateTargetMachine(UsesCodeGen);
1001 
1002   if (UsesCodeGen && !TM)
1003     return;
1004   if (TM)
1005     TheModule->setDataLayout(TM->createDataLayout());
1006 
1007   DebugifyCustomPassManager PerModulePasses;
1008   DebugInfoPerPass DebugInfoBeforePass;
1009   if (CodeGenOpts.EnableDIPreservationVerify) {
1010     PerModulePasses.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
1011     PerModulePasses.setDebugInfoBeforePass(DebugInfoBeforePass);
1012 
1013     if (!CodeGenOpts.DIBugsReportFilePath.empty())
1014       PerModulePasses.setOrigDIVerifyBugsReportFilePath(
1015           CodeGenOpts.DIBugsReportFilePath);
1016   }
1017   PerModulePasses.add(
1018       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1019 
1020   legacy::FunctionPassManager PerFunctionPasses(TheModule);
1021   PerFunctionPasses.add(
1022       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1023 
1024   CreatePasses(PerModulePasses, PerFunctionPasses);
1025 
1026   // Add a verifier pass if requested. We don't have to do this if the action
1027   // requires code generation because there will already be a verifier pass in
1028   // the code-generation pipeline.
1029   if (!UsesCodeGen && CodeGenOpts.VerifyModule)
1030     PerModulePasses.add(createVerifierPass());
1031 
1032   legacy::PassManager CodeGenPasses;
1033   CodeGenPasses.add(
1034       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1035 
1036   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1037 
1038   switch (Action) {
1039   case Backend_EmitNothing:
1040     break;
1041 
1042   case Backend_EmitBC:
1043     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1044       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1045         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1046         if (!ThinLinkOS)
1047           return;
1048       }
1049       if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1050         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1051                                  CodeGenOpts.EnableSplitLTOUnit);
1052       PerModulePasses.add(createWriteThinLTOBitcodePass(
1053           *OS, ThinLinkOS ? &ThinLinkOS->os() : nullptr));
1054     } else {
1055       // Emit a module summary by default for Regular LTO except for ld64
1056       // targets
1057       bool EmitLTOSummary =
1058           (CodeGenOpts.PrepareForLTO &&
1059            !CodeGenOpts.DisableLLVMPasses &&
1060            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1061                llvm::Triple::Apple);
1062       if (EmitLTOSummary) {
1063         if (!TheModule->getModuleFlag("ThinLTO"))
1064           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1065         if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1066           TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1067                                    uint32_t(1));
1068       }
1069 
1070       PerModulePasses.add(createBitcodeWriterPass(
1071           *OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1072     }
1073     break;
1074 
1075   case Backend_EmitLL:
1076     PerModulePasses.add(
1077         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1078     break;
1079 
1080   default:
1081     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1082       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1083       if (!DwoOS)
1084         return;
1085     }
1086     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1087                        DwoOS ? &DwoOS->os() : nullptr))
1088       return;
1089   }
1090 
1091   // Before executing passes, print the final values of the LLVM options.
1092   cl::PrintOptionValues();
1093 
1094   // Run passes. For now we do all passes at once, but eventually we
1095   // would like to have the option of streaming code generation.
1096 
1097   {
1098     PrettyStackTraceString CrashInfo("Per-function optimization");
1099     llvm::TimeTraceScope TimeScope("PerFunctionPasses");
1100 
1101     PerFunctionPasses.doInitialization();
1102     for (Function &F : *TheModule)
1103       if (!F.isDeclaration())
1104         PerFunctionPasses.run(F);
1105     PerFunctionPasses.doFinalization();
1106   }
1107 
1108   {
1109     PrettyStackTraceString CrashInfo("Per-module optimization passes");
1110     llvm::TimeTraceScope TimeScope("PerModulePasses");
1111     PerModulePasses.run(*TheModule);
1112   }
1113 
1114   {
1115     PrettyStackTraceString CrashInfo("Code generation");
1116     llvm::TimeTraceScope TimeScope("CodeGenPasses");
1117     CodeGenPasses.run(*TheModule);
1118   }
1119 
1120   if (ThinLinkOS)
1121     ThinLinkOS->keep();
1122   if (DwoOS)
1123     DwoOS->keep();
1124 }
1125 
1126 static OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
1127   switch (Opts.OptimizationLevel) {
1128   default:
1129     llvm_unreachable("Invalid optimization level!");
1130 
1131   case 0:
1132     return OptimizationLevel::O0;
1133 
1134   case 1:
1135     return OptimizationLevel::O1;
1136 
1137   case 2:
1138     switch (Opts.OptimizeSize) {
1139     default:
1140       llvm_unreachable("Invalid optimization level for size!");
1141 
1142     case 0:
1143       return OptimizationLevel::O2;
1144 
1145     case 1:
1146       return OptimizationLevel::Os;
1147 
1148     case 2:
1149       return OptimizationLevel::Oz;
1150     }
1151 
1152   case 3:
1153     return OptimizationLevel::O3;
1154   }
1155 }
1156 
1157 static void addSanitizers(const Triple &TargetTriple,
1158                           const CodeGenOptions &CodeGenOpts,
1159                           const LangOptions &LangOpts, PassBuilder &PB) {
1160   PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM,
1161                                          OptimizationLevel Level) {
1162     if (CodeGenOpts.hasSanitizeCoverage()) {
1163       auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
1164       MPM.addPass(ModuleSanitizerCoveragePass(
1165           SancovOpts, CodeGenOpts.SanitizeCoverageAllowlistFiles,
1166           CodeGenOpts.SanitizeCoverageIgnorelistFiles));
1167     }
1168 
1169     auto MSanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1170       if (LangOpts.Sanitize.has(Mask)) {
1171         int TrackOrigins = CodeGenOpts.SanitizeMemoryTrackOrigins;
1172         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1173 
1174         MemorySanitizerOptions options(TrackOrigins, Recover, CompileKernel,
1175                                        CodeGenOpts.SanitizeMemoryParamRetval);
1176         MPM.addPass(ModuleMemorySanitizerPass(options));
1177         FunctionPassManager FPM;
1178         FPM.addPass(MemorySanitizerPass(options));
1179         if (Level != OptimizationLevel::O0) {
1180           // MemorySanitizer inserts complex instrumentation that mostly
1181           // follows the logic of the original code, but operates on
1182           // "shadow" values. It can benefit from re-running some
1183           // general purpose optimization passes.
1184           FPM.addPass(EarlyCSEPass());
1185           // TODO: Consider add more passes like in
1186           // addGeneralOptsForMemorySanitizer. EarlyCSEPass makes visible
1187           // difference on size. It's not clear if the rest is still
1188           // usefull. InstCombinePass breakes
1189           // compiler-rt/test/msan/select_origin.cpp.
1190         }
1191         MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1192       }
1193     };
1194     MSanPass(SanitizerKind::Memory, false);
1195     MSanPass(SanitizerKind::KernelMemory, true);
1196 
1197     if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
1198       MPM.addPass(ModuleThreadSanitizerPass());
1199       MPM.addPass(createModuleToFunctionPassAdaptor(ThreadSanitizerPass()));
1200     }
1201 
1202     auto ASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1203       if (LangOpts.Sanitize.has(Mask)) {
1204         bool UseGlobalGC = asanUseGlobalsGC(TargetTriple, CodeGenOpts);
1205         bool UseOdrIndicator = CodeGenOpts.SanitizeAddressUseOdrIndicator;
1206         llvm::AsanDtorKind DestructorKind =
1207             CodeGenOpts.getSanitizeAddressDtor();
1208         AddressSanitizerOptions Opts;
1209         Opts.CompileKernel = CompileKernel;
1210         Opts.Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1211         Opts.UseAfterScope = CodeGenOpts.SanitizeAddressUseAfterScope;
1212         Opts.UseAfterReturn = CodeGenOpts.getSanitizeAddressUseAfterReturn();
1213         MPM.addPass(RequireAnalysisPass<ASanGlobalsMetadataAnalysis, Module>());
1214         MPM.addPass(ModuleAddressSanitizerPass(
1215             Opts, UseGlobalGC, UseOdrIndicator, DestructorKind));
1216       }
1217     };
1218     ASanPass(SanitizerKind::Address, false);
1219     ASanPass(SanitizerKind::KernelAddress, true);
1220 
1221     auto HWASanPass = [&](SanitizerMask Mask, bool CompileKernel) {
1222       if (LangOpts.Sanitize.has(Mask)) {
1223         bool Recover = CodeGenOpts.SanitizeRecover.has(Mask);
1224         MPM.addPass(HWAddressSanitizerPass(
1225             {CompileKernel, Recover,
1226              /*DisableOptimization=*/CodeGenOpts.OptimizationLevel == 0}));
1227       }
1228     };
1229     HWASanPass(SanitizerKind::HWAddress, false);
1230     HWASanPass(SanitizerKind::KernelHWAddress, true);
1231 
1232     if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
1233       MPM.addPass(DataFlowSanitizerPass(LangOpts.NoSanitizeFiles));
1234     }
1235   });
1236 }
1237 
1238 void EmitAssemblyHelper::RunOptimizationPipeline(
1239     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1240     std::unique_ptr<llvm::ToolOutputFile> &ThinLinkOS) {
1241   Optional<PGOOptions> PGOOpt;
1242 
1243   if (CodeGenOpts.hasProfileIRInstr())
1244     // -fprofile-generate.
1245     PGOOpt = PGOOptions(CodeGenOpts.InstrProfileOutput.empty()
1246                             ? getDefaultProfileGenName()
1247                             : CodeGenOpts.InstrProfileOutput,
1248                         "", "", PGOOptions::IRInstr, PGOOptions::NoCSAction,
1249                         CodeGenOpts.DebugInfoForProfiling);
1250   else if (CodeGenOpts.hasProfileIRUse()) {
1251     // -fprofile-use.
1252     auto CSAction = CodeGenOpts.hasProfileCSIRUse() ? PGOOptions::CSIRUse
1253                                                     : PGOOptions::NoCSAction;
1254     PGOOpt = PGOOptions(CodeGenOpts.ProfileInstrumentUsePath, "",
1255                         CodeGenOpts.ProfileRemappingFile, PGOOptions::IRUse,
1256                         CSAction, CodeGenOpts.DebugInfoForProfiling);
1257   } else if (!CodeGenOpts.SampleProfileFile.empty())
1258     // -fprofile-sample-use
1259     PGOOpt = PGOOptions(
1260         CodeGenOpts.SampleProfileFile, "", CodeGenOpts.ProfileRemappingFile,
1261         PGOOptions::SampleUse, PGOOptions::NoCSAction,
1262         CodeGenOpts.DebugInfoForProfiling, CodeGenOpts.PseudoProbeForProfiling);
1263   else if (CodeGenOpts.PseudoProbeForProfiling)
1264     // -fpseudo-probe-for-profiling
1265     PGOOpt =
1266         PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
1267                    CodeGenOpts.DebugInfoForProfiling, true);
1268   else if (CodeGenOpts.DebugInfoForProfiling)
1269     // -fdebug-info-for-profiling
1270     PGOOpt = PGOOptions("", "", "", PGOOptions::NoAction,
1271                         PGOOptions::NoCSAction, true);
1272 
1273   // Check to see if we want to generate a CS profile.
1274   if (CodeGenOpts.hasProfileCSIRInstr()) {
1275     assert(!CodeGenOpts.hasProfileCSIRUse() &&
1276            "Cannot have both CSProfileUse pass and CSProfileGen pass at "
1277            "the same time");
1278     if (PGOOpt.hasValue()) {
1279       assert(PGOOpt->Action != PGOOptions::IRInstr &&
1280              PGOOpt->Action != PGOOptions::SampleUse &&
1281              "Cannot run CSProfileGen pass with ProfileGen or SampleUse "
1282              " pass");
1283       PGOOpt->CSProfileGenFile = CodeGenOpts.InstrProfileOutput.empty()
1284                                      ? getDefaultProfileGenName()
1285                                      : CodeGenOpts.InstrProfileOutput;
1286       PGOOpt->CSAction = PGOOptions::CSIRInstr;
1287     } else
1288       PGOOpt = PGOOptions("",
1289                           CodeGenOpts.InstrProfileOutput.empty()
1290                               ? getDefaultProfileGenName()
1291                               : CodeGenOpts.InstrProfileOutput,
1292                           "", PGOOptions::NoAction, PGOOptions::CSIRInstr,
1293                           CodeGenOpts.DebugInfoForProfiling);
1294   }
1295   if (TM)
1296     TM->setPGOOption(PGOOpt);
1297 
1298   PipelineTuningOptions PTO;
1299   PTO.LoopUnrolling = CodeGenOpts.UnrollLoops;
1300   // For historical reasons, loop interleaving is set to mirror setting for loop
1301   // unrolling.
1302   PTO.LoopInterleaving = CodeGenOpts.UnrollLoops;
1303   PTO.LoopVectorization = CodeGenOpts.VectorizeLoop;
1304   PTO.SLPVectorization = CodeGenOpts.VectorizeSLP;
1305   PTO.MergeFunctions = CodeGenOpts.MergeFunctions;
1306   // Only enable CGProfilePass when using integrated assembler, since
1307   // non-integrated assemblers don't recognize .cgprofile section.
1308   PTO.CallGraphProfile = !CodeGenOpts.DisableIntegratedAS;
1309 
1310   LoopAnalysisManager LAM;
1311   FunctionAnalysisManager FAM;
1312   CGSCCAnalysisManager CGAM;
1313   ModuleAnalysisManager MAM;
1314 
1315   bool DebugPassStructure = CodeGenOpts.DebugPass == "Structure";
1316   PassInstrumentationCallbacks PIC;
1317   PrintPassOptions PrintPassOpts;
1318   PrintPassOpts.Indent = DebugPassStructure;
1319   PrintPassOpts.SkipAnalyses = DebugPassStructure;
1320   StandardInstrumentations SI(CodeGenOpts.DebugPassManager ||
1321                                   DebugPassStructure,
1322                               /*VerifyEach*/ false, PrintPassOpts);
1323   SI.registerCallbacks(PIC, &FAM);
1324   PassBuilder PB(TM.get(), PTO, PGOOpt, &PIC);
1325 
1326   // Attempt to load pass plugins and register their callbacks with PB.
1327   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
1328     auto PassPlugin = PassPlugin::Load(PluginFN);
1329     if (PassPlugin) {
1330       PassPlugin->registerPassBuilderCallbacks(PB);
1331     } else {
1332       Diags.Report(diag::err_fe_unable_to_load_plugin)
1333           << PluginFN << toString(PassPlugin.takeError());
1334     }
1335   }
1336 #define HANDLE_EXTENSION(Ext)                                                  \
1337   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
1338 #include "llvm/Support/Extension.def"
1339 
1340   // Register the target library analysis directly and give it a customized
1341   // preset TLI.
1342   Triple TargetTriple(TheModule->getTargetTriple());
1343   std::unique_ptr<TargetLibraryInfoImpl> TLII(
1344       createTLII(TargetTriple, CodeGenOpts));
1345   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
1346 
1347   // Register all the basic analyses with the managers.
1348   PB.registerModuleAnalyses(MAM);
1349   PB.registerCGSCCAnalyses(CGAM);
1350   PB.registerFunctionAnalyses(FAM);
1351   PB.registerLoopAnalyses(LAM);
1352   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
1353 
1354   ModulePassManager MPM;
1355 
1356   if (!CodeGenOpts.DisableLLVMPasses) {
1357     // Map our optimization levels into one of the distinct levels used to
1358     // configure the pipeline.
1359     OptimizationLevel Level = mapToLevel(CodeGenOpts);
1360 
1361     bool IsThinLTO = CodeGenOpts.PrepareForThinLTO;
1362     bool IsLTO = CodeGenOpts.PrepareForLTO;
1363 
1364     if (LangOpts.ObjCAutoRefCount) {
1365       PB.registerPipelineStartEPCallback(
1366           [](ModulePassManager &MPM, OptimizationLevel Level) {
1367             if (Level != OptimizationLevel::O0)
1368               MPM.addPass(
1369                   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
1370           });
1371       PB.registerPipelineEarlySimplificationEPCallback(
1372           [](ModulePassManager &MPM, OptimizationLevel Level) {
1373             if (Level != OptimizationLevel::O0)
1374               MPM.addPass(ObjCARCAPElimPass());
1375           });
1376       PB.registerScalarOptimizerLateEPCallback(
1377           [](FunctionPassManager &FPM, OptimizationLevel Level) {
1378             if (Level != OptimizationLevel::O0)
1379               FPM.addPass(ObjCARCOptPass());
1380           });
1381     }
1382 
1383     // If we reached here with a non-empty index file name, then the index
1384     // file was empty and we are not performing ThinLTO backend compilation
1385     // (used in testing in a distributed build environment).
1386     bool IsThinLTOPostLink = !CodeGenOpts.ThinLTOIndexFile.empty();
1387     // If so drop any the type test assume sequences inserted for whole program
1388     // vtables so that codegen doesn't complain.
1389     if (IsThinLTOPostLink)
1390       PB.registerPipelineStartEPCallback(
1391           [](ModulePassManager &MPM, OptimizationLevel Level) {
1392             MPM.addPass(LowerTypeTestsPass(/*ExportSummary=*/nullptr,
1393                                            /*ImportSummary=*/nullptr,
1394                                            /*DropTypeTests=*/true));
1395           });
1396 
1397     if (CodeGenOpts.InstrumentFunctions ||
1398         CodeGenOpts.InstrumentFunctionEntryBare ||
1399         CodeGenOpts.InstrumentFunctionsAfterInlining ||
1400         CodeGenOpts.InstrumentForProfiling) {
1401       PB.registerPipelineStartEPCallback(
1402           [](ModulePassManager &MPM, OptimizationLevel Level) {
1403             MPM.addPass(createModuleToFunctionPassAdaptor(
1404                 EntryExitInstrumenterPass(/*PostInlining=*/false)));
1405           });
1406       PB.registerOptimizerLastEPCallback(
1407           [](ModulePassManager &MPM, OptimizationLevel Level) {
1408             MPM.addPass(createModuleToFunctionPassAdaptor(
1409                 EntryExitInstrumenterPass(/*PostInlining=*/true)));
1410           });
1411     }
1412 
1413     // Register callbacks to schedule sanitizer passes at the appropriate part
1414     // of the pipeline.
1415     if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds))
1416       PB.registerScalarOptimizerLateEPCallback(
1417           [](FunctionPassManager &FPM, OptimizationLevel Level) {
1418             FPM.addPass(BoundsCheckingPass());
1419           });
1420 
1421     // Don't add sanitizers if we are here from ThinLTO PostLink. That already
1422     // done on PreLink stage.
1423     if (!IsThinLTOPostLink)
1424       addSanitizers(TargetTriple, CodeGenOpts, LangOpts, PB);
1425 
1426     if (Optional<GCOVOptions> Options = getGCOVOptions(CodeGenOpts, LangOpts))
1427       PB.registerPipelineStartEPCallback(
1428           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1429             MPM.addPass(GCOVProfilerPass(*Options));
1430           });
1431     if (Optional<InstrProfOptions> Options =
1432             getInstrProfOptions(CodeGenOpts, LangOpts))
1433       PB.registerPipelineStartEPCallback(
1434           [Options](ModulePassManager &MPM, OptimizationLevel Level) {
1435             MPM.addPass(InstrProfiling(*Options, false));
1436           });
1437 
1438     if (CodeGenOpts.OptimizationLevel == 0) {
1439       MPM = PB.buildO0DefaultPipeline(Level, IsLTO || IsThinLTO);
1440     } else if (IsThinLTO) {
1441       MPM = PB.buildThinLTOPreLinkDefaultPipeline(Level);
1442     } else if (IsLTO) {
1443       MPM = PB.buildLTOPreLinkDefaultPipeline(Level);
1444     } else {
1445       MPM = PB.buildPerModuleDefaultPipeline(Level);
1446     }
1447 
1448     if (!CodeGenOpts.MemoryProfileOutput.empty()) {
1449       MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
1450       MPM.addPass(ModuleMemProfilerPass());
1451     }
1452   }
1453 
1454   // Add a verifier pass if requested. We don't have to do this if the action
1455   // requires code generation because there will already be a verifier pass in
1456   // the code-generation pipeline.
1457   if (!actionRequiresCodeGen(Action) && CodeGenOpts.VerifyModule)
1458     MPM.addPass(VerifierPass());
1459 
1460   switch (Action) {
1461   case Backend_EmitBC:
1462     if (CodeGenOpts.PrepareForThinLTO && !CodeGenOpts.DisableLLVMPasses) {
1463       if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
1464         ThinLinkOS = openOutputFile(CodeGenOpts.ThinLinkBitcodeFile);
1465         if (!ThinLinkOS)
1466           return;
1467       }
1468       if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1469         TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1470                                  CodeGenOpts.EnableSplitLTOUnit);
1471       MPM.addPass(ThinLTOBitcodeWriterPass(*OS, ThinLinkOS ? &ThinLinkOS->os()
1472                                                            : nullptr));
1473     } else {
1474       // Emit a module summary by default for Regular LTO except for ld64
1475       // targets
1476       bool EmitLTOSummary =
1477           (CodeGenOpts.PrepareForLTO && !CodeGenOpts.DisableLLVMPasses &&
1478            llvm::Triple(TheModule->getTargetTriple()).getVendor() !=
1479                llvm::Triple::Apple);
1480       if (EmitLTOSummary) {
1481         if (!TheModule->getModuleFlag("ThinLTO"))
1482           TheModule->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
1483         if (!TheModule->getModuleFlag("EnableSplitLTOUnit"))
1484           TheModule->addModuleFlag(Module::Error, "EnableSplitLTOUnit",
1485                                    uint32_t(1));
1486       }
1487       MPM.addPass(
1488           BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists, EmitLTOSummary));
1489     }
1490     break;
1491 
1492   case Backend_EmitLL:
1493     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
1494     break;
1495 
1496   default:
1497     break;
1498   }
1499 
1500   // Now that we have all of the passes ready, run them.
1501   {
1502     PrettyStackTraceString CrashInfo("Optimizer");
1503     llvm::TimeTraceScope TimeScope("Optimizer");
1504     MPM.run(*TheModule, MAM);
1505   }
1506 }
1507 
1508 void EmitAssemblyHelper::RunCodegenPipeline(
1509     BackendAction Action, std::unique_ptr<raw_pwrite_stream> &OS,
1510     std::unique_ptr<llvm::ToolOutputFile> &DwoOS) {
1511   // We still use the legacy PM to run the codegen pipeline since the new PM
1512   // does not work with the codegen pipeline.
1513   // FIXME: make the new PM work with the codegen pipeline.
1514   legacy::PassManager CodeGenPasses;
1515 
1516   // Append any output we need to the pass manager.
1517   switch (Action) {
1518   case Backend_EmitAssembly:
1519   case Backend_EmitMCNull:
1520   case Backend_EmitObj:
1521     CodeGenPasses.add(
1522         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
1523     if (!CodeGenOpts.SplitDwarfOutput.empty()) {
1524       DwoOS = openOutputFile(CodeGenOpts.SplitDwarfOutput);
1525       if (!DwoOS)
1526         return;
1527     }
1528     if (!AddEmitPasses(CodeGenPasses, Action, *OS,
1529                        DwoOS ? &DwoOS->os() : nullptr))
1530       // FIXME: Should we handle this error differently?
1531       return;
1532     break;
1533   default:
1534     return;
1535   }
1536 
1537   {
1538     PrettyStackTraceString CrashInfo("Code generation");
1539     llvm::TimeTraceScope TimeScope("CodeGenPasses");
1540     CodeGenPasses.run(*TheModule);
1541   }
1542 }
1543 
1544 /// A clean version of `EmitAssembly` that uses the new pass manager.
1545 ///
1546 /// Not all features are currently supported in this system, but where
1547 /// necessary it falls back to the legacy pass manager to at least provide
1548 /// basic functionality.
1549 ///
1550 /// This API is planned to have its functionality finished and then to replace
1551 /// `EmitAssembly` at some point in the future when the default switches.
1552 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
1553                                       std::unique_ptr<raw_pwrite_stream> OS) {
1554   TimeRegion Region(CodeGenOpts.TimePasses ? &CodeGenerationTime : nullptr);
1555   setCommandLineOpts(CodeGenOpts);
1556 
1557   bool RequiresCodeGen = actionRequiresCodeGen(Action);
1558   CreateTargetMachine(RequiresCodeGen);
1559 
1560   if (RequiresCodeGen && !TM)
1561     return;
1562   if (TM)
1563     TheModule->setDataLayout(TM->createDataLayout());
1564 
1565   // Before executing passes, print the final values of the LLVM options.
1566   cl::PrintOptionValues();
1567 
1568   std::unique_ptr<llvm::ToolOutputFile> ThinLinkOS, DwoOS;
1569   RunOptimizationPipeline(Action, OS, ThinLinkOS);
1570   RunCodegenPipeline(Action, OS, DwoOS);
1571 
1572   if (ThinLinkOS)
1573     ThinLinkOS->keep();
1574   if (DwoOS)
1575     DwoOS->keep();
1576 }
1577 
1578 static void runThinLTOBackend(
1579     DiagnosticsEngine &Diags, ModuleSummaryIndex *CombinedIndex, Module *M,
1580     const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts,
1581     const clang::TargetOptions &TOpts, const LangOptions &LOpts,
1582     std::unique_ptr<raw_pwrite_stream> OS, std::string SampleProfile,
1583     std::string ProfileRemapping, BackendAction Action) {
1584   StringMap<DenseMap<GlobalValue::GUID, GlobalValueSummary *>>
1585       ModuleToDefinedGVSummaries;
1586   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1587 
1588   setCommandLineOpts(CGOpts);
1589 
1590   // We can simply import the values mentioned in the combined index, since
1591   // we should only invoke this using the individual indexes written out
1592   // via a WriteIndexesThinBackend.
1593   FunctionImporter::ImportMapTy ImportList;
1594   if (!lto::initImportList(*M, *CombinedIndex, ImportList))
1595     return;
1596 
1597   auto AddStream = [&](size_t Task) {
1598     return std::make_unique<CachedFileStream>(std::move(OS),
1599                                               CGOpts.ObjectFilenameForDebug);
1600   };
1601   lto::Config Conf;
1602   if (CGOpts.SaveTempsFilePrefix != "") {
1603     if (Error E = Conf.addSaveTemps(CGOpts.SaveTempsFilePrefix + ".",
1604                                     /* UseInputModulePath */ false)) {
1605       handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1606         errs() << "Error setting up ThinLTO save-temps: " << EIB.message()
1607                << '\n';
1608       });
1609     }
1610   }
1611   Conf.CPU = TOpts.CPU;
1612   Conf.CodeModel = getCodeModel(CGOpts);
1613   Conf.MAttrs = TOpts.Features;
1614   Conf.RelocModel = CGOpts.RelocationModel;
1615   Conf.CGOptLevel = getCGOptLevel(CGOpts);
1616   Conf.OptLevel = CGOpts.OptimizationLevel;
1617   initTargetOptions(Diags, Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
1618   Conf.SampleProfile = std::move(SampleProfile);
1619   Conf.PTO.LoopUnrolling = CGOpts.UnrollLoops;
1620   // For historical reasons, loop interleaving is set to mirror setting for loop
1621   // unrolling.
1622   Conf.PTO.LoopInterleaving = CGOpts.UnrollLoops;
1623   Conf.PTO.LoopVectorization = CGOpts.VectorizeLoop;
1624   Conf.PTO.SLPVectorization = CGOpts.VectorizeSLP;
1625   // Only enable CGProfilePass when using integrated assembler, since
1626   // non-integrated assemblers don't recognize .cgprofile section.
1627   Conf.PTO.CallGraphProfile = !CGOpts.DisableIntegratedAS;
1628 
1629   // Context sensitive profile.
1630   if (CGOpts.hasProfileCSIRInstr()) {
1631     Conf.RunCSIRInstr = true;
1632     Conf.CSIRProfile = std::move(CGOpts.InstrProfileOutput);
1633   } else if (CGOpts.hasProfileCSIRUse()) {
1634     Conf.RunCSIRInstr = false;
1635     Conf.CSIRProfile = std::move(CGOpts.ProfileInstrumentUsePath);
1636   }
1637 
1638   Conf.ProfileRemapping = std::move(ProfileRemapping);
1639   Conf.UseNewPM = !CGOpts.LegacyPassManager;
1640   Conf.DebugPassManager = CGOpts.DebugPassManager;
1641   Conf.RemarksWithHotness = CGOpts.DiagnosticsWithHotness;
1642   Conf.RemarksFilename = CGOpts.OptRecordFile;
1643   Conf.RemarksPasses = CGOpts.OptRecordPasses;
1644   Conf.RemarksFormat = CGOpts.OptRecordFormat;
1645   Conf.SplitDwarfFile = CGOpts.SplitDwarfFile;
1646   Conf.SplitDwarfOutput = CGOpts.SplitDwarfOutput;
1647   switch (Action) {
1648   case Backend_EmitNothing:
1649     Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1650       return false;
1651     };
1652     break;
1653   case Backend_EmitLL:
1654     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1655       M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1656       return false;
1657     };
1658     break;
1659   case Backend_EmitBC:
1660     Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1661       WriteBitcodeToFile(*M, *OS, CGOpts.EmitLLVMUseLists);
1662       return false;
1663     };
1664     break;
1665   default:
1666     Conf.CGFileType = getCodeGenFileType(Action);
1667     break;
1668   }
1669   if (Error E =
1670           thinBackend(Conf, -1, AddStream, *M, *CombinedIndex, ImportList,
1671                       ModuleToDefinedGVSummaries[M->getModuleIdentifier()],
1672                       /* ModuleMap */ nullptr, CGOpts.CmdArgs)) {
1673     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1674       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1675     });
1676   }
1677 }
1678 
1679 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
1680                               const HeaderSearchOptions &HeaderOpts,
1681                               const CodeGenOptions &CGOpts,
1682                               const clang::TargetOptions &TOpts,
1683                               const LangOptions &LOpts,
1684                               StringRef TDesc, Module *M,
1685                               BackendAction Action,
1686                               std::unique_ptr<raw_pwrite_stream> OS) {
1687 
1688   llvm::TimeTraceScope TimeScope("Backend");
1689 
1690   std::unique_ptr<llvm::Module> EmptyModule;
1691   if (!CGOpts.ThinLTOIndexFile.empty()) {
1692     // If we are performing a ThinLTO importing compile, load the function index
1693     // into memory and pass it into runThinLTOBackend, which will run the
1694     // function importer and invoke LTO passes.
1695     std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
1696     if (Error E = llvm::getModuleSummaryIndexForFile(
1697                       CGOpts.ThinLTOIndexFile,
1698                       /*IgnoreEmptyThinLTOIndexFile*/ true)
1699                       .moveInto(CombinedIndex)) {
1700       logAllUnhandledErrors(std::move(E), errs(),
1701                             "Error loading index file '" +
1702                             CGOpts.ThinLTOIndexFile + "': ");
1703       return;
1704     }
1705 
1706     // A null CombinedIndex means we should skip ThinLTO compilation
1707     // (LLVM will optionally ignore empty index files, returning null instead
1708     // of an error).
1709     if (CombinedIndex) {
1710       if (!CombinedIndex->skipModuleByDistributedBackend()) {
1711         runThinLTOBackend(Diags, CombinedIndex.get(), M, HeaderOpts, CGOpts,
1712                           TOpts, LOpts, std::move(OS), CGOpts.SampleProfileFile,
1713                           CGOpts.ProfileRemappingFile, Action);
1714         return;
1715       }
1716       // Distributed indexing detected that nothing from the module is needed
1717       // for the final linking. So we can skip the compilation. We sill need to
1718       // output an empty object file to make sure that a linker does not fail
1719       // trying to read it. Also for some features, like CFI, we must skip
1720       // the compilation as CombinedIndex does not contain all required
1721       // information.
1722       EmptyModule = std::make_unique<llvm::Module>("empty", M->getContext());
1723       EmptyModule->setTargetTriple(M->getTargetTriple());
1724       M = EmptyModule.get();
1725     }
1726   }
1727 
1728   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
1729 
1730   if (CGOpts.LegacyPassManager)
1731     AsmHelper.EmitAssemblyWithLegacyPassManager(Action, std::move(OS));
1732   else
1733     AsmHelper.EmitAssembly(Action, std::move(OS));
1734 
1735   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1736   // DataLayout.
1737   if (AsmHelper.TM) {
1738     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1739     if (DLDesc != TDesc) {
1740       unsigned DiagID = Diags.getCustomDiagID(
1741           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1742                                     "expected target description '%1'");
1743       Diags.Report(DiagID) << DLDesc << TDesc;
1744     }
1745   }
1746 }
1747 
1748 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1749 // __LLVM,__bitcode section.
1750 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1751                          llvm::MemoryBufferRef Buf) {
1752   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1753     return;
1754   llvm::embedBitcodeInModule(
1755       *M, Buf, CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker,
1756       CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode,
1757       CGOpts.CmdArgs);
1758 }
1759 
1760 void clang::EmbedObject(llvm::Module *M, const CodeGenOptions &CGOpts,
1761                         DiagnosticsEngine &Diags) {
1762   if (CGOpts.OffloadObjects.empty())
1763     return;
1764 
1765   for (StringRef OffloadObject : CGOpts.OffloadObjects) {
1766     if (OffloadObject.count(',') != 1)
1767       Diags.Report(Diags.getCustomDiagID(
1768           DiagnosticsEngine::Error, "Invalid string pair for embedding '%0'"))
1769           << OffloadObject;
1770     auto FilenameAndSection = OffloadObject.split(',');
1771     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ObjectOrErr =
1772         llvm::MemoryBuffer::getFileOrSTDIN(FilenameAndSection.first);
1773     if (std::error_code EC = ObjectOrErr.getError()) {
1774       auto DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1775                                           "could not open '%0' for embedding");
1776       Diags.Report(DiagID) << FilenameAndSection.first;
1777       return;
1778     }
1779 
1780     SmallString<128> SectionName(
1781         {".llvm.offloading.", FilenameAndSection.second});
1782     llvm::embedBufferInModule(*M, **ObjectOrErr, SectionName);
1783   }
1784 }
1785