1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/CodeGen/BackendUtil.h"
11 #include "clang/Basic/Diagnostic.h"
12 #include "clang/Basic/LangOptions.h"
13 #include "clang/Basic/TargetOptions.h"
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/Utils.h"
17 #include "clang/Lex/HeaderSearchOptions.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeReader.h"
25 #include "llvm/Bitcode/BitcodeWriter.h"
26 #include "llvm/Bitcode/BitcodeWriterPass.h"
27 #include "llvm/CodeGen/RegAllocRegistry.h"
28 #include "llvm/CodeGen/SchedulerRegistry.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSummaryIndex.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/LTO/LTOBackend.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/SubtargetFeature.h"
38 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
39 #include "llvm/Passes/PassBuilder.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/PrettyStackTrace.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Target/TargetSubtargetInfo.h"
49 #include "llvm/Transforms/Coroutines.h"
50 #include "llvm/Transforms/IPO.h"
51 #include "llvm/Transforms/IPO/AlwaysInliner.h"
52 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 #include "llvm/Transforms/Instrumentation.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 #include "llvm/Transforms/Scalar.h"
56 #include "llvm/Transforms/Scalar/GVN.h"
57 #include "llvm/Transforms/Utils/SymbolRewriter.h"
58 #include <memory>
59 using namespace clang;
60 using namespace llvm;
61 
62 namespace {
63 
64 // Default filename used for profile generation.
65 static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
66 
67 class EmitAssemblyHelper {
68   DiagnosticsEngine &Diags;
69   const HeaderSearchOptions &HSOpts;
70   const CodeGenOptions &CodeGenOpts;
71   const clang::TargetOptions &TargetOpts;
72   const LangOptions &LangOpts;
73   Module *TheModule;
74 
75   Timer CodeGenerationTime;
76 
77   std::unique_ptr<raw_pwrite_stream> OS;
78 
79   TargetIRAnalysis getTargetIRAnalysis() const {
80     if (TM)
81       return TM->getTargetIRAnalysis();
82 
83     return TargetIRAnalysis();
84   }
85 
86   /// Set LLVM command line options passed through -backend-option.
87   void setCommandLineOpts();
88 
89   void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
90 
91   /// Generates the TargetMachine.
92   /// Leaves TM unchanged if it is unable to create the target machine.
93   /// Some of our clang tests specify triples which are not built
94   /// into clang. This is okay because these tests check the generated
95   /// IR, and they require DataLayout which depends on the triple.
96   /// In this case, we allow this method to fail and not report an error.
97   /// When MustCreateTM is used, we print an error if we are unable to load
98   /// the requested target.
99   void CreateTargetMachine(bool MustCreateTM);
100 
101   /// Add passes necessary to emit assembly or LLVM IR.
102   ///
103   /// \return True on success.
104   bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
105                      raw_pwrite_stream &OS);
106 
107 public:
108   EmitAssemblyHelper(DiagnosticsEngine &_Diags,
109                      const HeaderSearchOptions &HeaderSearchOpts,
110                      const CodeGenOptions &CGOpts,
111                      const clang::TargetOptions &TOpts,
112                      const LangOptions &LOpts, Module *M)
113       : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
114         TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
115         CodeGenerationTime("codegen", "Code Generation Time") {}
116 
117   ~EmitAssemblyHelper() {
118     if (CodeGenOpts.DisableFree)
119       BuryPointer(std::move(TM));
120   }
121 
122   std::unique_ptr<TargetMachine> TM;
123 
124   void EmitAssembly(BackendAction Action,
125                     std::unique_ptr<raw_pwrite_stream> OS);
126 
127   void EmitAssemblyWithNewPassManager(BackendAction Action,
128                                       std::unique_ptr<raw_pwrite_stream> OS);
129 };
130 
131 // We need this wrapper to access LangOpts and CGOpts from extension functions
132 // that we add to the PassManagerBuilder.
133 class PassManagerBuilderWrapper : public PassManagerBuilder {
134 public:
135   PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
136                             const LangOptions &LangOpts)
137       : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
138   const CodeGenOptions &getCGOpts() const { return CGOpts; }
139   const LangOptions &getLangOpts() const { return LangOpts; }
140 private:
141   const CodeGenOptions &CGOpts;
142   const LangOptions &LangOpts;
143 };
144 
145 }
146 
147 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
148   if (Builder.OptLevel > 0)
149     PM.add(createObjCARCAPElimPass());
150 }
151 
152 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
153   if (Builder.OptLevel > 0)
154     PM.add(createObjCARCExpandPass());
155 }
156 
157 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
158   if (Builder.OptLevel > 0)
159     PM.add(createObjCARCOptPass());
160 }
161 
162 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
163                                      legacy::PassManagerBase &PM) {
164   PM.add(createAddDiscriminatorsPass());
165 }
166 
167 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
168                                   legacy::PassManagerBase &PM) {
169   PM.add(createBoundsCheckingPass());
170 }
171 
172 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
173                                      legacy::PassManagerBase &PM) {
174   const PassManagerBuilderWrapper &BuilderWrapper =
175       static_cast<const PassManagerBuilderWrapper&>(Builder);
176   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
177   SanitizerCoverageOptions Opts;
178   Opts.CoverageType =
179       static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
180   Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
181   Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
182   Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
183   Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
184   Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
185   Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
186   Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
187   Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
188   PM.add(createSanitizerCoverageModulePass(Opts));
189 }
190 
191 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
192                                       legacy::PassManagerBase &PM) {
193   const PassManagerBuilderWrapper &BuilderWrapper =
194       static_cast<const PassManagerBuilderWrapper&>(Builder);
195   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
196   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
197   bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
198   PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
199                                             UseAfterScope));
200   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
201 }
202 
203 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
204                                             legacy::PassManagerBase &PM) {
205   PM.add(createAddressSanitizerFunctionPass(
206       /*CompileKernel*/ true,
207       /*Recover*/ true, /*UseAfterScope*/ false));
208   PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
209                                           /*Recover*/true));
210 }
211 
212 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
213                                    legacy::PassManagerBase &PM) {
214   const PassManagerBuilderWrapper &BuilderWrapper =
215       static_cast<const PassManagerBuilderWrapper&>(Builder);
216   const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
217   int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
218   bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
219   PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
220 
221   // MemorySanitizer inserts complex instrumentation that mostly follows
222   // the logic of the original code, but operates on "shadow" values.
223   // It can benefit from re-running some general purpose optimization passes.
224   if (Builder.OptLevel > 0) {
225     PM.add(createEarlyCSEPass());
226     PM.add(createReassociatePass());
227     PM.add(createLICMPass());
228     PM.add(createGVNPass());
229     PM.add(createInstructionCombiningPass());
230     PM.add(createDeadStoreEliminationPass());
231   }
232 }
233 
234 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
235                                    legacy::PassManagerBase &PM) {
236   PM.add(createThreadSanitizerPass());
237 }
238 
239 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
240                                      legacy::PassManagerBase &PM) {
241   const PassManagerBuilderWrapper &BuilderWrapper =
242       static_cast<const PassManagerBuilderWrapper&>(Builder);
243   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
244   PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
245 }
246 
247 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
248                                        legacy::PassManagerBase &PM) {
249   const PassManagerBuilderWrapper &BuilderWrapper =
250       static_cast<const PassManagerBuilderWrapper&>(Builder);
251   const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
252   EfficiencySanitizerOptions Opts;
253   if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
254     Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
255   else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
256     Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
257   PM.add(createEfficiencySanitizerPass(Opts));
258 }
259 
260 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
261                                          const CodeGenOptions &CodeGenOpts) {
262   TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
263   if (!CodeGenOpts.SimplifyLibCalls)
264     TLII->disableAllFunctions();
265   else {
266     // Disable individual libc/libm calls in TargetLibraryInfo.
267     LibFunc F;
268     for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
269       if (TLII->getLibFunc(FuncName, F))
270         TLII->setUnavailable(F);
271   }
272 
273   switch (CodeGenOpts.getVecLib()) {
274   case CodeGenOptions::Accelerate:
275     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
276     break;
277   case CodeGenOptions::SVML:
278     TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
279     break;
280   default:
281     break;
282   }
283   return TLII;
284 }
285 
286 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
287                                   legacy::PassManager *MPM) {
288   llvm::SymbolRewriter::RewriteDescriptorList DL;
289 
290   llvm::SymbolRewriter::RewriteMapParser MapParser;
291   for (const auto &MapFile : Opts.RewriteMapFiles)
292     MapParser.parse(MapFile, &DL);
293 
294   MPM->add(createRewriteSymbolsPass(DL));
295 }
296 
297 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
298                                       legacy::FunctionPassManager &FPM) {
299   // Handle disabling of all LLVM passes, where we want to preserve the
300   // internal module before any optimization.
301   if (CodeGenOpts.DisableLLVMPasses)
302     return;
303 
304   PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
305 
306   // Figure out TargetLibraryInfo.  This needs to be added to MPM and FPM
307   // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
308   // are inserted before PMBuilder ones - they'd get the default-constructed
309   // TLI with an unknown target otherwise.
310   Triple TargetTriple(TheModule->getTargetTriple());
311   std::unique_ptr<TargetLibraryInfoImpl> TLII(
312       createTLII(TargetTriple, CodeGenOpts));
313 
314   // At O0 and O1 we only run the always inliner which is more efficient. At
315   // higher optimization levels we run the normal inliner.
316   if (CodeGenOpts.OptimizationLevel <= 1) {
317     bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
318                                      !CodeGenOpts.DisableLifetimeMarkers);
319     PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
320   } else {
321     // We do not want to inline hot callsites for SamplePGO module-summary build
322     // because profile annotation will happen again in ThinLTO backend, and we
323     // want the IR of the hot path to match the profile.
324     PMBuilder.Inliner = createFunctionInliningPass(
325         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
326         (!CodeGenOpts.SampleProfileFile.empty() &&
327          CodeGenOpts.EmitSummaryIndex));
328   }
329 
330   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
331   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
332   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
333   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
334   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
335 
336   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
337   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
338   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
339   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
340   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
341 
342   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
343 
344   if (TM)
345     TM->adjustPassManager(PMBuilder);
346 
347   if (CodeGenOpts.DebugInfoForProfiling ||
348       !CodeGenOpts.SampleProfileFile.empty())
349     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
350                            addAddDiscriminatorsPass);
351 
352   // In ObjC ARC mode, add the main ARC optimization passes.
353   if (LangOpts.ObjCAutoRefCount) {
354     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
355                            addObjCARCExpandPass);
356     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
357                            addObjCARCAPElimPass);
358     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
359                            addObjCARCOptPass);
360   }
361 
362   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
363     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
364                            addBoundsCheckingPass);
365     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
366                            addBoundsCheckingPass);
367   }
368 
369   if (CodeGenOpts.SanitizeCoverageType ||
370       CodeGenOpts.SanitizeCoverageIndirectCalls ||
371       CodeGenOpts.SanitizeCoverageTraceCmp) {
372     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
373                            addSanitizerCoveragePass);
374     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
375                            addSanitizerCoveragePass);
376   }
377 
378   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
379     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
380                            addAddressSanitizerPasses);
381     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
382                            addAddressSanitizerPasses);
383   }
384 
385   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
386     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
387                            addKernelAddressSanitizerPasses);
388     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
389                            addKernelAddressSanitizerPasses);
390   }
391 
392   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
393     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
394                            addMemorySanitizerPass);
395     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
396                            addMemorySanitizerPass);
397   }
398 
399   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
400     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
401                            addThreadSanitizerPass);
402     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
403                            addThreadSanitizerPass);
404   }
405 
406   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
407     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
408                            addDataFlowSanitizerPass);
409     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
410                            addDataFlowSanitizerPass);
411   }
412 
413   if (LangOpts.CoroutinesTS)
414     addCoroutinePassesToExtensionPoints(PMBuilder);
415 
416   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
417     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
418                            addEfficiencySanitizerPass);
419     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
420                            addEfficiencySanitizerPass);
421   }
422 
423   // Set up the per-function pass manager.
424   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
425   if (CodeGenOpts.VerifyModule)
426     FPM.add(createVerifierPass());
427 
428   // Set up the per-module pass manager.
429   if (!CodeGenOpts.RewriteMapFiles.empty())
430     addSymbolRewriterPass(CodeGenOpts, &MPM);
431 
432   if (!CodeGenOpts.DisableGCov &&
433       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
434     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
435     // LLVM's -default-gcov-version flag is set to something invalid.
436     GCOVOptions Options;
437     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
438     Options.EmitData = CodeGenOpts.EmitGcovArcs;
439     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
440     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
441     Options.NoRedZone = CodeGenOpts.DisableRedZone;
442     Options.FunctionNamesInData =
443         !CodeGenOpts.CoverageNoFunctionNamesInData;
444     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
445     MPM.add(createGCOVProfilerPass(Options));
446     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
447       MPM.add(createStripSymbolsPass(true));
448   }
449 
450   if (CodeGenOpts.hasProfileClangInstr()) {
451     InstrProfOptions Options;
452     Options.NoRedZone = CodeGenOpts.DisableRedZone;
453     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
454     MPM.add(createInstrProfilingLegacyPass(Options));
455   }
456   if (CodeGenOpts.hasProfileIRInstr()) {
457     PMBuilder.EnablePGOInstrGen = true;
458     if (!CodeGenOpts.InstrProfileOutput.empty())
459       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
460     else
461       PMBuilder.PGOInstrGen = DefaultProfileGenName;
462   }
463   if (CodeGenOpts.hasProfileIRUse())
464     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
465 
466   if (!CodeGenOpts.SampleProfileFile.empty())
467     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
468 
469   PMBuilder.populateFunctionPassManager(FPM);
470   PMBuilder.populateModulePassManager(MPM);
471 }
472 
473 void EmitAssemblyHelper::setCommandLineOpts() {
474   SmallVector<const char *, 16> BackendArgs;
475   BackendArgs.push_back("clang"); // Fake program name.
476   if (!CodeGenOpts.DebugPass.empty()) {
477     BackendArgs.push_back("-debug-pass");
478     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
479   }
480   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
481     BackendArgs.push_back("-limit-float-precision");
482     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
483   }
484   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
485     BackendArgs.push_back(BackendOption.c_str());
486   BackendArgs.push_back(nullptr);
487   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
488                                     BackendArgs.data());
489 }
490 
491 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
492   // Create the TargetMachine for generating code.
493   std::string Error;
494   std::string Triple = TheModule->getTargetTriple();
495   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
496   if (!TheTarget) {
497     if (MustCreateTM)
498       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
499     return;
500   }
501 
502   unsigned CodeModel =
503     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
504       .Case("small", llvm::CodeModel::Small)
505       .Case("kernel", llvm::CodeModel::Kernel)
506       .Case("medium", llvm::CodeModel::Medium)
507       .Case("large", llvm::CodeModel::Large)
508       .Case("default", llvm::CodeModel::Default)
509       .Default(~0u);
510   assert(CodeModel != ~0u && "invalid code model!");
511   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
512 
513   std::string FeaturesStr =
514       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
515 
516   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
517   llvm::Optional<llvm::Reloc::Model> RM;
518   RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
519            .Case("static", llvm::Reloc::Static)
520            .Case("pic", llvm::Reloc::PIC_)
521            .Case("ropi", llvm::Reloc::ROPI)
522            .Case("rwpi", llvm::Reloc::RWPI)
523            .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
524            .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
525   assert(RM.hasValue() && "invalid PIC model!");
526 
527   CodeGenOpt::Level OptLevel;
528   switch (CodeGenOpts.OptimizationLevel) {
529   default:
530     llvm_unreachable("Invalid optimization level!");
531   case 0:
532     OptLevel = CodeGenOpt::None;
533     break;
534   case 1:
535     OptLevel = CodeGenOpt::Less;
536     break;
537   case 2:
538     OptLevel = CodeGenOpt::Default;
539     break; // O2/Os/Oz
540   case 3:
541     OptLevel = CodeGenOpt::Aggressive;
542     break;
543   }
544 
545   llvm::TargetOptions Options;
546 
547   Options.ThreadModel =
548     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
549       .Case("posix", llvm::ThreadModel::POSIX)
550       .Case("single", llvm::ThreadModel::Single);
551 
552   // Set float ABI type.
553   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
554           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
555          "Invalid Floating Point ABI!");
556   Options.FloatABIType =
557       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
558           .Case("soft", llvm::FloatABI::Soft)
559           .Case("softfp", llvm::FloatABI::Soft)
560           .Case("hard", llvm::FloatABI::Hard)
561           .Default(llvm::FloatABI::Default);
562 
563   // Set FP fusion mode.
564   switch (CodeGenOpts.getFPContractMode()) {
565   case CodeGenOptions::FPC_Off:
566     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
567     break;
568   case CodeGenOptions::FPC_On:
569     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
570     break;
571   case CodeGenOptions::FPC_Fast:
572     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
573     break;
574   }
575 
576   Options.UseInitArray = CodeGenOpts.UseInitArray;
577   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
578   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
579   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
580 
581   // Set EABI version.
582   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
583                             .Case("4", llvm::EABI::EABI4)
584                             .Case("5", llvm::EABI::EABI5)
585                             .Case("gnu", llvm::EABI::GNU)
586                             .Default(llvm::EABI::Default);
587 
588   if (LangOpts.SjLjExceptions)
589     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
590 
591   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
592   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
593   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
594   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
595   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
596   Options.FunctionSections = CodeGenOpts.FunctionSections;
597   Options.DataSections = CodeGenOpts.DataSections;
598   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
599   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
600   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
601 
602   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
603   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
604   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
605   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
606   Options.MCOptions.MCIncrementalLinkerCompatible =
607       CodeGenOpts.IncrementalLinkerCompatible;
608   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
609   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
610   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
611   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
612   Options.MCOptions.ABIName = TargetOpts.ABI;
613   for (const auto &Entry : HSOpts.UserEntries)
614     if (!Entry.IsFramework &&
615         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
616          Entry.Group == frontend::IncludeDirGroup::Angled ||
617          Entry.Group == frontend::IncludeDirGroup::System))
618       Options.MCOptions.IASSearchPaths.push_back(
619           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
620 
621   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
622                                           Options, RM, CM, OptLevel));
623 }
624 
625 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
626                                        BackendAction Action,
627                                        raw_pwrite_stream &OS) {
628   // Add LibraryInfo.
629   llvm::Triple TargetTriple(TheModule->getTargetTriple());
630   std::unique_ptr<TargetLibraryInfoImpl> TLII(
631       createTLII(TargetTriple, CodeGenOpts));
632   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
633 
634   // Normal mode, emit a .s or .o file by running the code generator. Note,
635   // this also adds codegenerator level optimization passes.
636   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
637   if (Action == Backend_EmitObj)
638     CGFT = TargetMachine::CGFT_ObjectFile;
639   else if (Action == Backend_EmitMCNull)
640     CGFT = TargetMachine::CGFT_Null;
641   else
642     assert(Action == Backend_EmitAssembly && "Invalid action!");
643 
644   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
645   // "codegen" passes so that it isn't run multiple times when there is
646   // inlining happening.
647   if (CodeGenOpts.OptimizationLevel > 0)
648     CodeGenPasses.add(createObjCARCContractPass());
649 
650   if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
651                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
652     Diags.Report(diag::err_fe_unable_to_interface_with_target);
653     return false;
654   }
655 
656   return true;
657 }
658 
659 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
660                                       std::unique_ptr<raw_pwrite_stream> OS) {
661   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
662 
663   setCommandLineOpts();
664 
665   bool UsesCodeGen = (Action != Backend_EmitNothing &&
666                       Action != Backend_EmitBC &&
667                       Action != Backend_EmitLL);
668   CreateTargetMachine(UsesCodeGen);
669 
670   if (UsesCodeGen && !TM)
671     return;
672   if (TM)
673     TheModule->setDataLayout(TM->createDataLayout());
674 
675   legacy::PassManager PerModulePasses;
676   PerModulePasses.add(
677       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
678 
679   legacy::FunctionPassManager PerFunctionPasses(TheModule);
680   PerFunctionPasses.add(
681       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
682 
683   CreatePasses(PerModulePasses, PerFunctionPasses);
684 
685   legacy::PassManager CodeGenPasses;
686   CodeGenPasses.add(
687       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
688 
689   switch (Action) {
690   case Backend_EmitNothing:
691     break;
692 
693   case Backend_EmitBC:
694     if (CodeGenOpts.EmitSummaryIndex)
695       PerModulePasses.add(createWriteThinLTOBitcodePass(*OS));
696     else
697       PerModulePasses.add(
698           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
699     break;
700 
701   case Backend_EmitLL:
702     PerModulePasses.add(
703         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
704     break;
705 
706   default:
707     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
708       return;
709   }
710 
711   // Before executing passes, print the final values of the LLVM options.
712   cl::PrintOptionValues();
713 
714   // Run passes. For now we do all passes at once, but eventually we
715   // would like to have the option of streaming code generation.
716 
717   {
718     PrettyStackTraceString CrashInfo("Per-function optimization");
719 
720     PerFunctionPasses.doInitialization();
721     for (Function &F : *TheModule)
722       if (!F.isDeclaration())
723         PerFunctionPasses.run(F);
724     PerFunctionPasses.doFinalization();
725   }
726 
727   {
728     PrettyStackTraceString CrashInfo("Per-module optimization passes");
729     PerModulePasses.run(*TheModule);
730   }
731 
732   {
733     PrettyStackTraceString CrashInfo("Code generation");
734     CodeGenPasses.run(*TheModule);
735   }
736 }
737 
738 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
739   switch (Opts.OptimizationLevel) {
740   default:
741     llvm_unreachable("Invalid optimization level!");
742 
743   case 1:
744     return PassBuilder::O1;
745 
746   case 2:
747     switch (Opts.OptimizeSize) {
748     default:
749       llvm_unreachable("Invalide optimization level for size!");
750 
751     case 0:
752       return PassBuilder::O2;
753 
754     case 1:
755       return PassBuilder::Os;
756 
757     case 2:
758       return PassBuilder::Oz;
759     }
760 
761   case 3:
762     return PassBuilder::O3;
763   }
764 }
765 
766 /// A clean version of `EmitAssembly` that uses the new pass manager.
767 ///
768 /// Not all features are currently supported in this system, but where
769 /// necessary it falls back to the legacy pass manager to at least provide
770 /// basic functionality.
771 ///
772 /// This API is planned to have its functionality finished and then to replace
773 /// `EmitAssembly` at some point in the future when the default switches.
774 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
775     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
776   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
777   setCommandLineOpts();
778 
779   // The new pass manager always makes a target machine available to passes
780   // during construction.
781   CreateTargetMachine(/*MustCreateTM*/ true);
782   if (!TM)
783     // This will already be diagnosed, just bail.
784     return;
785   TheModule->setDataLayout(TM->createDataLayout());
786 
787   PGOOptions PGOOpt;
788 
789   // -fprofile-generate.
790   PGOOpt.RunProfileGen = CodeGenOpts.hasProfileIRInstr();
791   if (PGOOpt.RunProfileGen)
792     PGOOpt.ProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ?
793       DefaultProfileGenName : CodeGenOpts.InstrProfileOutput;
794 
795   // -fprofile-use.
796   if (CodeGenOpts.hasProfileIRUse())
797     PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath;
798 
799   // Only pass a PGO options struct if -fprofile-generate or
800   // -fprofile-use were passed on the cmdline.
801   PassBuilder PB(TM.get(),
802     (PGOOpt.RunProfileGen ||
803       !PGOOpt.ProfileUseFile.empty()) ?
804         Optional<PGOOptions>(PGOOpt) : None);
805 
806   LoopAnalysisManager LAM;
807   FunctionAnalysisManager FAM;
808   CGSCCAnalysisManager CGAM;
809   ModuleAnalysisManager MAM;
810 
811   // Register the AA manager first so that our version is the one used.
812   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
813 
814   // Register all the basic analyses with the managers.
815   PB.registerModuleAnalyses(MAM);
816   PB.registerCGSCCAnalyses(CGAM);
817   PB.registerFunctionAnalyses(FAM);
818   PB.registerLoopAnalyses(LAM);
819   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
820 
821   ModulePassManager MPM;
822 
823   if (!CodeGenOpts.DisableLLVMPasses) {
824     if (CodeGenOpts.OptimizationLevel == 0) {
825       // Build a minimal pipeline based on the semantics required by Clang,
826       // which is just that always inlining occurs.
827       MPM.addPass(AlwaysInlinerPass());
828     } else {
829       // Otherwise, use the default pass pipeline. We also have to map our
830       // optimization levels into one of the distinct levels used to configure
831       // the pipeline.
832       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
833 
834       MPM = PB.buildPerModuleDefaultPipeline(Level);
835     }
836   }
837 
838   // FIXME: We still use the legacy pass manager to do code generation. We
839   // create that pass manager here and use it as needed below.
840   legacy::PassManager CodeGenPasses;
841   bool NeedCodeGen = false;
842 
843   // Append any output we need to the pass manager.
844   switch (Action) {
845   case Backend_EmitNothing:
846     break;
847 
848   case Backend_EmitBC:
849     MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
850                                   CodeGenOpts.EmitSummaryIndex,
851                                   CodeGenOpts.EmitSummaryIndex));
852     break;
853 
854   case Backend_EmitLL:
855     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
856     break;
857 
858   case Backend_EmitAssembly:
859   case Backend_EmitMCNull:
860   case Backend_EmitObj:
861     NeedCodeGen = true;
862     CodeGenPasses.add(
863         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
864     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
865       // FIXME: Should we handle this error differently?
866       return;
867     break;
868   }
869 
870   // Before executing passes, print the final values of the LLVM options.
871   cl::PrintOptionValues();
872 
873   // Now that we have all of the passes ready, run them.
874   {
875     PrettyStackTraceString CrashInfo("Optimizer");
876     MPM.run(*TheModule, MAM);
877   }
878 
879   // Now if needed, run the legacy PM for codegen.
880   if (NeedCodeGen) {
881     PrettyStackTraceString CrashInfo("Code generation");
882     CodeGenPasses.run(*TheModule);
883   }
884 }
885 
886 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
887   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
888   if (!BMsOrErr)
889     return BMsOrErr.takeError();
890 
891   // The bitcode file may contain multiple modules, we want the one with a
892   // summary.
893   for (BitcodeModule &BM : *BMsOrErr) {
894     Expected<bool> HasSummary = BM.hasSummary();
895     if (HasSummary && *HasSummary)
896       return BM;
897   }
898 
899   return make_error<StringError>("Could not find module summary",
900                                  inconvertibleErrorCode());
901 }
902 
903 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
904                               std::unique_ptr<raw_pwrite_stream> OS,
905                               std::string SampleProfile) {
906   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
907       ModuleToDefinedGVSummaries;
908   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
909 
910   // We can simply import the values mentioned in the combined index, since
911   // we should only invoke this using the individual indexes written out
912   // via a WriteIndexesThinBackend.
913   FunctionImporter::ImportMapTy ImportList;
914   for (auto &GlobalList : *CombinedIndex) {
915     auto GUID = GlobalList.first;
916     assert(GlobalList.second.size() == 1 &&
917            "Expected individual combined index to have one summary per GUID");
918     auto &Summary = GlobalList.second[0];
919     // Skip the summaries for the importing module. These are included to
920     // e.g. record required linkage changes.
921     if (Summary->modulePath() == M->getModuleIdentifier())
922       continue;
923     // Doesn't matter what value we plug in to the map, just needs an entry
924     // to provoke importing by thinBackend.
925     ImportList[Summary->modulePath()][GUID] = 1;
926   }
927 
928   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
929   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
930 
931   for (auto &I : ImportList) {
932     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
933         llvm::MemoryBuffer::getFile(I.first());
934     if (!MBOrErr) {
935       errs() << "Error loading imported file '" << I.first()
936              << "': " << MBOrErr.getError().message() << "\n";
937       return;
938     }
939 
940     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
941     if (!BMOrErr) {
942       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
943         errs() << "Error loading imported file '" << I.first()
944                << "': " << EIB.message() << '\n';
945       });
946       return;
947     }
948     ModuleMap.insert({I.first(), *BMOrErr});
949 
950     OwnedImports.push_back(std::move(*MBOrErr));
951   }
952   auto AddStream = [&](size_t Task) {
953     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
954   };
955   lto::Config Conf;
956   Conf.SampleProfile = std::move(SampleProfile);
957   if (Error E = thinBackend(
958           Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
959           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
960     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
961       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
962     });
963   }
964 }
965 
966 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
967                               const HeaderSearchOptions &HeaderOpts,
968                               const CodeGenOptions &CGOpts,
969                               const clang::TargetOptions &TOpts,
970                               const LangOptions &LOpts,
971                               const llvm::DataLayout &TDesc, Module *M,
972                               BackendAction Action,
973                               std::unique_ptr<raw_pwrite_stream> OS) {
974   if (!CGOpts.ThinLTOIndexFile.empty()) {
975     // If we are performing a ThinLTO importing compile, load the function index
976     // into memory and pass it into runThinLTOBackend, which will run the
977     // function importer and invoke LTO passes.
978     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
979         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
980     if (!IndexOrErr) {
981       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
982                             "Error loading index file '" +
983                             CGOpts.ThinLTOIndexFile + "': ");
984       return;
985     }
986     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
987     // A null CombinedIndex means we should skip ThinLTO compilation
988     // (LLVM will optionally ignore empty index files, returning null instead
989     // of an error).
990     bool DoThinLTOBackend = CombinedIndex != nullptr;
991     if (DoThinLTOBackend) {
992       runThinLTOBackend(CombinedIndex.get(), M, std::move(OS),
993                         CGOpts.SampleProfileFile);
994       return;
995     }
996   }
997 
998   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
999 
1000   if (CGOpts.ExperimentalNewPassManager)
1001     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1002   else
1003     AsmHelper.EmitAssembly(Action, std::move(OS));
1004 
1005   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1006   // DataLayout.
1007   if (AsmHelper.TM) {
1008     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1009     if (DLDesc != TDesc.getStringRepresentation()) {
1010       unsigned DiagID = Diags.getCustomDiagID(
1011           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1012                                     "expected target description '%1'");
1013       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1014     }
1015   }
1016 }
1017 
1018 static const char* getSectionNameForBitcode(const Triple &T) {
1019   switch (T.getObjectFormat()) {
1020   case Triple::MachO:
1021     return "__LLVM,__bitcode";
1022   case Triple::COFF:
1023   case Triple::ELF:
1024   case Triple::Wasm:
1025   case Triple::UnknownObjectFormat:
1026     return ".llvmbc";
1027   }
1028   llvm_unreachable("Unimplemented ObjectFormatType");
1029 }
1030 
1031 static const char* getSectionNameForCommandline(const Triple &T) {
1032   switch (T.getObjectFormat()) {
1033   case Triple::MachO:
1034     return "__LLVM,__cmdline";
1035   case Triple::COFF:
1036   case Triple::ELF:
1037   case Triple::Wasm:
1038   case Triple::UnknownObjectFormat:
1039     return ".llvmcmd";
1040   }
1041   llvm_unreachable("Unimplemented ObjectFormatType");
1042 }
1043 
1044 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1045 // __LLVM,__bitcode section.
1046 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1047                          llvm::MemoryBufferRef Buf) {
1048   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1049     return;
1050 
1051   // Save llvm.compiler.used and remote it.
1052   SmallVector<Constant*, 2> UsedArray;
1053   SmallSet<GlobalValue*, 4> UsedGlobals;
1054   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1055   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1056   for (auto *GV : UsedGlobals) {
1057     if (GV->getName() != "llvm.embedded.module" &&
1058         GV->getName() != "llvm.cmdline")
1059       UsedArray.push_back(
1060           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1061   }
1062   if (Used)
1063     Used->eraseFromParent();
1064 
1065   // Embed the bitcode for the llvm module.
1066   std::string Data;
1067   ArrayRef<uint8_t> ModuleData;
1068   Triple T(M->getTargetTriple());
1069   // Create a constant that contains the bitcode.
1070   // In case of embedding a marker, ignore the input Buf and use the empty
1071   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1072   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1073     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1074                    (const unsigned char *)Buf.getBufferEnd())) {
1075       // If the input is LLVM Assembly, bitcode is produced by serializing
1076       // the module. Use-lists order need to be perserved in this case.
1077       llvm::raw_string_ostream OS(Data);
1078       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1079       ModuleData =
1080           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1081     } else
1082       // If the input is LLVM bitcode, write the input byte stream directly.
1083       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1084                                      Buf.getBufferSize());
1085   }
1086   llvm::Constant *ModuleConstant =
1087       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1088   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1089       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1090       ModuleConstant);
1091   GV->setSection(getSectionNameForBitcode(T));
1092   UsedArray.push_back(
1093       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1094   if (llvm::GlobalVariable *Old =
1095           M->getGlobalVariable("llvm.embedded.module", true)) {
1096     assert(Old->hasOneUse() &&
1097            "llvm.embedded.module can only be used once in llvm.compiler.used");
1098     GV->takeName(Old);
1099     Old->eraseFromParent();
1100   } else {
1101     GV->setName("llvm.embedded.module");
1102   }
1103 
1104   // Skip if only bitcode needs to be embedded.
1105   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1106     // Embed command-line options.
1107     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1108                               CGOpts.CmdArgs.size());
1109     llvm::Constant *CmdConstant =
1110       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1111     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1112                                   llvm::GlobalValue::PrivateLinkage,
1113                                   CmdConstant);
1114     GV->setSection(getSectionNameForCommandline(T));
1115     UsedArray.push_back(
1116         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1117     if (llvm::GlobalVariable *Old =
1118             M->getGlobalVariable("llvm.cmdline", true)) {
1119       assert(Old->hasOneUse() &&
1120              "llvm.cmdline can only be used once in llvm.compiler.used");
1121       GV->takeName(Old);
1122       Old->eraseFromParent();
1123     } else {
1124       GV->setName("llvm.cmdline");
1125     }
1126   }
1127 
1128   if (UsedArray.empty())
1129     return;
1130 
1131   // Recreate llvm.compiler.used.
1132   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1133   auto *NewUsed = new GlobalVariable(
1134       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1135       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1136   NewUsed->setSection("llvm.metadata");
1137 }
1138