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