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     PMBuilder.Inliner = createFunctionInliningPass(
322         CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize);
323   }
324 
325   PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
326   PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
327   PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
328   PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
329   PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
330 
331   PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
332   PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
333   PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
334   PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
335   PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
336 
337   MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
338 
339   if (TM)
340     TM->adjustPassManager(PMBuilder);
341 
342   PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
343                          addAddDiscriminatorsPass);
344 
345   // In ObjC ARC mode, add the main ARC optimization passes.
346   if (LangOpts.ObjCAutoRefCount) {
347     PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
348                            addObjCARCExpandPass);
349     PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
350                            addObjCARCAPElimPass);
351     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
352                            addObjCARCOptPass);
353   }
354 
355   if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
356     PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
357                            addBoundsCheckingPass);
358     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
359                            addBoundsCheckingPass);
360   }
361 
362   if (CodeGenOpts.SanitizeCoverageType ||
363       CodeGenOpts.SanitizeCoverageIndirectCalls ||
364       CodeGenOpts.SanitizeCoverageTraceCmp) {
365     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
366                            addSanitizerCoveragePass);
367     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
368                            addSanitizerCoveragePass);
369   }
370 
371   if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
372     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
373                            addAddressSanitizerPasses);
374     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
375                            addAddressSanitizerPasses);
376   }
377 
378   if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
379     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
380                            addKernelAddressSanitizerPasses);
381     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
382                            addKernelAddressSanitizerPasses);
383   }
384 
385   if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
386     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
387                            addMemorySanitizerPass);
388     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
389                            addMemorySanitizerPass);
390   }
391 
392   if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
393     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
394                            addThreadSanitizerPass);
395     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
396                            addThreadSanitizerPass);
397   }
398 
399   if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
400     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
401                            addDataFlowSanitizerPass);
402     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
403                            addDataFlowSanitizerPass);
404   }
405 
406   if (LangOpts.CoroutinesTS)
407     addCoroutinePassesToExtensionPoints(PMBuilder);
408 
409   if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
410     PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
411                            addEfficiencySanitizerPass);
412     PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
413                            addEfficiencySanitizerPass);
414   }
415 
416   // Set up the per-function pass manager.
417   FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
418   if (CodeGenOpts.VerifyModule)
419     FPM.add(createVerifierPass());
420 
421   // Set up the per-module pass manager.
422   if (!CodeGenOpts.RewriteMapFiles.empty())
423     addSymbolRewriterPass(CodeGenOpts, &MPM);
424 
425   if (!CodeGenOpts.DisableGCov &&
426       (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
427     // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
428     // LLVM's -default-gcov-version flag is set to something invalid.
429     GCOVOptions Options;
430     Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
431     Options.EmitData = CodeGenOpts.EmitGcovArcs;
432     memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
433     Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
434     Options.NoRedZone = CodeGenOpts.DisableRedZone;
435     Options.FunctionNamesInData =
436         !CodeGenOpts.CoverageNoFunctionNamesInData;
437     Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
438     MPM.add(createGCOVProfilerPass(Options));
439     if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
440       MPM.add(createStripSymbolsPass(true));
441   }
442 
443   if (CodeGenOpts.hasProfileClangInstr()) {
444     InstrProfOptions Options;
445     Options.NoRedZone = CodeGenOpts.DisableRedZone;
446     Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
447     MPM.add(createInstrProfilingLegacyPass(Options));
448   }
449   if (CodeGenOpts.hasProfileIRInstr()) {
450     PMBuilder.EnablePGOInstrGen = true;
451     if (!CodeGenOpts.InstrProfileOutput.empty())
452       PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
453     else
454       PMBuilder.PGOInstrGen = DefaultProfileGenName;
455   }
456   if (CodeGenOpts.hasProfileIRUse())
457     PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
458 
459   if (!CodeGenOpts.SampleProfileFile.empty())
460     PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
461 
462   PMBuilder.populateFunctionPassManager(FPM);
463   PMBuilder.populateModulePassManager(MPM);
464 }
465 
466 void EmitAssemblyHelper::setCommandLineOpts() {
467   SmallVector<const char *, 16> BackendArgs;
468   BackendArgs.push_back("clang"); // Fake program name.
469   if (!CodeGenOpts.DebugPass.empty()) {
470     BackendArgs.push_back("-debug-pass");
471     BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
472   }
473   if (!CodeGenOpts.LimitFloatPrecision.empty()) {
474     BackendArgs.push_back("-limit-float-precision");
475     BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
476   }
477   for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
478     BackendArgs.push_back(BackendOption.c_str());
479   BackendArgs.push_back(nullptr);
480   llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
481                                     BackendArgs.data());
482 }
483 
484 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
485   // Create the TargetMachine for generating code.
486   std::string Error;
487   std::string Triple = TheModule->getTargetTriple();
488   const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
489   if (!TheTarget) {
490     if (MustCreateTM)
491       Diags.Report(diag::err_fe_unable_to_create_target) << Error;
492     return;
493   }
494 
495   unsigned CodeModel =
496     llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
497       .Case("small", llvm::CodeModel::Small)
498       .Case("kernel", llvm::CodeModel::Kernel)
499       .Case("medium", llvm::CodeModel::Medium)
500       .Case("large", llvm::CodeModel::Large)
501       .Case("default", llvm::CodeModel::Default)
502       .Default(~0u);
503   assert(CodeModel != ~0u && "invalid code model!");
504   llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
505 
506   std::string FeaturesStr =
507       llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
508 
509   // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
510   llvm::Optional<llvm::Reloc::Model> RM;
511   RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
512            .Case("static", llvm::Reloc::Static)
513            .Case("pic", llvm::Reloc::PIC_)
514            .Case("ropi", llvm::Reloc::ROPI)
515            .Case("rwpi", llvm::Reloc::RWPI)
516            .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
517            .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
518   assert(RM.hasValue() && "invalid PIC model!");
519 
520   CodeGenOpt::Level OptLevel;
521   switch (CodeGenOpts.OptimizationLevel) {
522   default:
523     llvm_unreachable("Invalid optimization level!");
524   case 0:
525     OptLevel = CodeGenOpt::None;
526     break;
527   case 1:
528     OptLevel = CodeGenOpt::Less;
529     break;
530   case 2:
531     OptLevel = CodeGenOpt::Default;
532     break; // O2/Os/Oz
533   case 3:
534     OptLevel = CodeGenOpt::Aggressive;
535     break;
536   }
537 
538   llvm::TargetOptions Options;
539 
540   Options.ThreadModel =
541     llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
542       .Case("posix", llvm::ThreadModel::POSIX)
543       .Case("single", llvm::ThreadModel::Single);
544 
545   // Set float ABI type.
546   assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
547           CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
548          "Invalid Floating Point ABI!");
549   Options.FloatABIType =
550       llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
551           .Case("soft", llvm::FloatABI::Soft)
552           .Case("softfp", llvm::FloatABI::Soft)
553           .Case("hard", llvm::FloatABI::Hard)
554           .Default(llvm::FloatABI::Default);
555 
556   // Set FP fusion mode.
557   switch (CodeGenOpts.getFPContractMode()) {
558   case CodeGenOptions::FPC_Off:
559     Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
560     break;
561   case CodeGenOptions::FPC_On:
562     Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
563     break;
564   case CodeGenOptions::FPC_Fast:
565     Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
566     break;
567   }
568 
569   Options.UseInitArray = CodeGenOpts.UseInitArray;
570   Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
571   Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
572   Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
573 
574   // Set EABI version.
575   Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
576                             .Case("4", llvm::EABI::EABI4)
577                             .Case("5", llvm::EABI::EABI5)
578                             .Case("gnu", llvm::EABI::GNU)
579                             .Default(llvm::EABI::Default);
580 
581   if (LangOpts.SjLjExceptions)
582     Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
583 
584   Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
585   Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
586   Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
587   Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
588   Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
589   Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
590   Options.FunctionSections = CodeGenOpts.FunctionSections;
591   Options.DataSections = CodeGenOpts.DataSections;
592   Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
593   Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
594   Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
595 
596   Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
597   Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
598   Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
599   Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
600   Options.MCOptions.MCIncrementalLinkerCompatible =
601       CodeGenOpts.IncrementalLinkerCompatible;
602   Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
603   Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
604   Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
605   Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
606   Options.MCOptions.ABIName = TargetOpts.ABI;
607   for (const auto &Entry : HSOpts.UserEntries)
608     if (!Entry.IsFramework &&
609         (Entry.Group == frontend::IncludeDirGroup::Quoted ||
610          Entry.Group == frontend::IncludeDirGroup::Angled ||
611          Entry.Group == frontend::IncludeDirGroup::System))
612       Options.MCOptions.IASSearchPaths.push_back(
613           Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
614 
615   TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
616                                           Options, RM, CM, OptLevel));
617 }
618 
619 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
620                                        BackendAction Action,
621                                        raw_pwrite_stream &OS) {
622   // Add LibraryInfo.
623   llvm::Triple TargetTriple(TheModule->getTargetTriple());
624   std::unique_ptr<TargetLibraryInfoImpl> TLII(
625       createTLII(TargetTriple, CodeGenOpts));
626   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
627 
628   // Normal mode, emit a .s or .o file by running the code generator. Note,
629   // this also adds codegenerator level optimization passes.
630   TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
631   if (Action == Backend_EmitObj)
632     CGFT = TargetMachine::CGFT_ObjectFile;
633   else if (Action == Backend_EmitMCNull)
634     CGFT = TargetMachine::CGFT_Null;
635   else
636     assert(Action == Backend_EmitAssembly && "Invalid action!");
637 
638   // Add ObjC ARC final-cleanup optimizations. This is done as part of the
639   // "codegen" passes so that it isn't run multiple times when there is
640   // inlining happening.
641   if (CodeGenOpts.OptimizationLevel > 0)
642     CodeGenPasses.add(createObjCARCContractPass());
643 
644   if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
645                               /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
646     Diags.Report(diag::err_fe_unable_to_interface_with_target);
647     return false;
648   }
649 
650   return true;
651 }
652 
653 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
654                                       std::unique_ptr<raw_pwrite_stream> OS) {
655   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
656 
657   setCommandLineOpts();
658 
659   bool UsesCodeGen = (Action != Backend_EmitNothing &&
660                       Action != Backend_EmitBC &&
661                       Action != Backend_EmitLL);
662   CreateTargetMachine(UsesCodeGen);
663 
664   if (UsesCodeGen && !TM)
665     return;
666   if (TM)
667     TheModule->setDataLayout(TM->createDataLayout());
668 
669   legacy::PassManager PerModulePasses;
670   PerModulePasses.add(
671       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
672 
673   legacy::FunctionPassManager PerFunctionPasses(TheModule);
674   PerFunctionPasses.add(
675       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
676 
677   CreatePasses(PerModulePasses, PerFunctionPasses);
678 
679   legacy::PassManager CodeGenPasses;
680   CodeGenPasses.add(
681       createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
682 
683   switch (Action) {
684   case Backend_EmitNothing:
685     break;
686 
687   case Backend_EmitBC:
688     if (CodeGenOpts.EmitSummaryIndex)
689       PerModulePasses.add(createWriteThinLTOBitcodePass(*OS));
690     else
691       PerModulePasses.add(
692           createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
693     break;
694 
695   case Backend_EmitLL:
696     PerModulePasses.add(
697         createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
698     break;
699 
700   default:
701     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
702       return;
703   }
704 
705   // Before executing passes, print the final values of the LLVM options.
706   cl::PrintOptionValues();
707 
708   // Run passes. For now we do all passes at once, but eventually we
709   // would like to have the option of streaming code generation.
710 
711   {
712     PrettyStackTraceString CrashInfo("Per-function optimization");
713 
714     PerFunctionPasses.doInitialization();
715     for (Function &F : *TheModule)
716       if (!F.isDeclaration())
717         PerFunctionPasses.run(F);
718     PerFunctionPasses.doFinalization();
719   }
720 
721   {
722     PrettyStackTraceString CrashInfo("Per-module optimization passes");
723     PerModulePasses.run(*TheModule);
724   }
725 
726   {
727     PrettyStackTraceString CrashInfo("Code generation");
728     CodeGenPasses.run(*TheModule);
729   }
730 }
731 
732 static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
733   switch (Opts.OptimizationLevel) {
734   default:
735     llvm_unreachable("Invalid optimization level!");
736 
737   case 1:
738     return PassBuilder::O1;
739 
740   case 2:
741     switch (Opts.OptimizeSize) {
742     default:
743       llvm_unreachable("Invalide optimization level for size!");
744 
745     case 0:
746       return PassBuilder::O2;
747 
748     case 1:
749       return PassBuilder::Os;
750 
751     case 2:
752       return PassBuilder::Oz;
753     }
754 
755   case 3:
756     return PassBuilder::O3;
757   }
758 }
759 
760 /// A clean version of `EmitAssembly` that uses the new pass manager.
761 ///
762 /// Not all features are currently supported in this system, but where
763 /// necessary it falls back to the legacy pass manager to at least provide
764 /// basic functionality.
765 ///
766 /// This API is planned to have its functionality finished and then to replace
767 /// `EmitAssembly` at some point in the future when the default switches.
768 void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
769     BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
770   TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
771   setCommandLineOpts();
772 
773   // The new pass manager always makes a target machine available to passes
774   // during construction.
775   CreateTargetMachine(/*MustCreateTM*/ true);
776   if (!TM)
777     // This will already be diagnosed, just bail.
778     return;
779   TheModule->setDataLayout(TM->createDataLayout());
780 
781   PGOOptions PGOOpt;
782 
783   // -fprofile-generate.
784   PGOOpt.RunProfileGen = CodeGenOpts.hasProfileIRInstr();
785   if (PGOOpt.RunProfileGen)
786     PGOOpt.ProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ?
787       DefaultProfileGenName : CodeGenOpts.InstrProfileOutput;
788 
789   // -fprofile-use.
790   if (CodeGenOpts.hasProfileIRUse())
791     PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath;
792 
793   // Only pass a PGO options struct if -fprofile-generate or
794   // -fprofile-use were passed on the cmdline.
795   PassBuilder PB(TM.get(),
796     (PGOOpt.RunProfileGen ||
797       !PGOOpt.ProfileUseFile.empty()) ?
798         Optional<PGOOptions>(PGOOpt) : None);
799 
800   LoopAnalysisManager LAM;
801   FunctionAnalysisManager FAM;
802   CGSCCAnalysisManager CGAM;
803   ModuleAnalysisManager MAM;
804 
805   // Register the AA manager first so that our version is the one used.
806   FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
807 
808   // Register all the basic analyses with the managers.
809   PB.registerModuleAnalyses(MAM);
810   PB.registerCGSCCAnalyses(CGAM);
811   PB.registerFunctionAnalyses(FAM);
812   PB.registerLoopAnalyses(LAM);
813   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
814 
815   ModulePassManager MPM;
816 
817   if (!CodeGenOpts.DisableLLVMPasses) {
818     if (CodeGenOpts.OptimizationLevel == 0) {
819       // Build a minimal pipeline based on the semantics required by Clang,
820       // which is just that always inlining occurs.
821       MPM.addPass(AlwaysInlinerPass());
822     } else {
823       // Otherwise, use the default pass pipeline. We also have to map our
824       // optimization levels into one of the distinct levels used to configure
825       // the pipeline.
826       PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
827 
828       MPM = PB.buildPerModuleDefaultPipeline(Level);
829     }
830   }
831 
832   // FIXME: We still use the legacy pass manager to do code generation. We
833   // create that pass manager here and use it as needed below.
834   legacy::PassManager CodeGenPasses;
835   bool NeedCodeGen = false;
836 
837   // Append any output we need to the pass manager.
838   switch (Action) {
839   case Backend_EmitNothing:
840     break;
841 
842   case Backend_EmitBC:
843     MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
844                                   CodeGenOpts.EmitSummaryIndex,
845                                   CodeGenOpts.EmitSummaryIndex));
846     break;
847 
848   case Backend_EmitLL:
849     MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
850     break;
851 
852   case Backend_EmitAssembly:
853   case Backend_EmitMCNull:
854   case Backend_EmitObj:
855     NeedCodeGen = true;
856     CodeGenPasses.add(
857         createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
858     if (!AddEmitPasses(CodeGenPasses, Action, *OS))
859       // FIXME: Should we handle this error differently?
860       return;
861     break;
862   }
863 
864   // Before executing passes, print the final values of the LLVM options.
865   cl::PrintOptionValues();
866 
867   // Now that we have all of the passes ready, run them.
868   {
869     PrettyStackTraceString CrashInfo("Optimizer");
870     MPM.run(*TheModule, MAM);
871   }
872 
873   // Now if needed, run the legacy PM for codegen.
874   if (NeedCodeGen) {
875     PrettyStackTraceString CrashInfo("Code generation");
876     CodeGenPasses.run(*TheModule);
877   }
878 }
879 
880 Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
881   Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
882   if (!BMsOrErr)
883     return BMsOrErr.takeError();
884 
885   // The bitcode file may contain multiple modules, we want the one with a
886   // summary.
887   for (BitcodeModule &BM : *BMsOrErr) {
888     Expected<bool> HasSummary = BM.hasSummary();
889     if (HasSummary && *HasSummary)
890       return BM;
891   }
892 
893   return make_error<StringError>("Could not find module summary",
894                                  inconvertibleErrorCode());
895 }
896 
897 static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
898                               std::unique_ptr<raw_pwrite_stream> OS,
899                               std::string SampleProfile) {
900   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
901       ModuleToDefinedGVSummaries;
902   CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
903 
904   // We can simply import the values mentioned in the combined index, since
905   // we should only invoke this using the individual indexes written out
906   // via a WriteIndexesThinBackend.
907   FunctionImporter::ImportMapTy ImportList;
908   for (auto &GlobalList : *CombinedIndex) {
909     auto GUID = GlobalList.first;
910     assert(GlobalList.second.size() == 1 &&
911            "Expected individual combined index to have one summary per GUID");
912     auto &Summary = GlobalList.second[0];
913     // Skip the summaries for the importing module. These are included to
914     // e.g. record required linkage changes.
915     if (Summary->modulePath() == M->getModuleIdentifier())
916       continue;
917     // Doesn't matter what value we plug in to the map, just needs an entry
918     // to provoke importing by thinBackend.
919     ImportList[Summary->modulePath()][GUID] = 1;
920   }
921 
922   std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
923   MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
924 
925   for (auto &I : ImportList) {
926     ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
927         llvm::MemoryBuffer::getFile(I.first());
928     if (!MBOrErr) {
929       errs() << "Error loading imported file '" << I.first()
930              << "': " << MBOrErr.getError().message() << "\n";
931       return;
932     }
933 
934     Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
935     if (!BMOrErr) {
936       handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
937         errs() << "Error loading imported file '" << I.first()
938                << "': " << EIB.message() << '\n';
939       });
940       return;
941     }
942     ModuleMap.insert({I.first(), *BMOrErr});
943 
944     OwnedImports.push_back(std::move(*MBOrErr));
945   }
946   auto AddStream = [&](size_t Task) {
947     return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
948   };
949   lto::Config Conf;
950   Conf.SampleProfile = SampleProfile;
951   if (Error E = thinBackend(
952           Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
953           ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
954     handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
955       errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
956     });
957   }
958 }
959 
960 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
961                               const HeaderSearchOptions &HeaderOpts,
962                               const CodeGenOptions &CGOpts,
963                               const clang::TargetOptions &TOpts,
964                               const LangOptions &LOpts,
965                               const llvm::DataLayout &TDesc, Module *M,
966                               BackendAction Action,
967                               std::unique_ptr<raw_pwrite_stream> OS) {
968   if (!CGOpts.ThinLTOIndexFile.empty()) {
969     // If we are performing a ThinLTO importing compile, load the function index
970     // into memory and pass it into runThinLTOBackend, which will run the
971     // function importer and invoke LTO passes.
972     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
973         llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
974     if (!IndexOrErr) {
975       logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
976                             "Error loading index file '" +
977                             CGOpts.ThinLTOIndexFile + "': ");
978       return;
979     }
980     std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
981     // A null CombinedIndex means we should skip ThinLTO compilation
982     // (LLVM will optionally ignore empty index files, returning null instead
983     // of an error).
984     bool DoThinLTOBackend = CombinedIndex != nullptr;
985     if (DoThinLTOBackend) {
986       runThinLTOBackend(CombinedIndex.get(), M, std::move(OS),
987                         CGOpts.SampleProfileFile);
988       return;
989     }
990   }
991 
992   EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
993 
994   if (CGOpts.ExperimentalNewPassManager)
995     AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
996   else
997     AsmHelper.EmitAssembly(Action, std::move(OS));
998 
999   // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1000   // DataLayout.
1001   if (AsmHelper.TM) {
1002     std::string DLDesc = M->getDataLayout().getStringRepresentation();
1003     if (DLDesc != TDesc.getStringRepresentation()) {
1004       unsigned DiagID = Diags.getCustomDiagID(
1005           DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1006                                     "expected target description '%1'");
1007       Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
1008     }
1009   }
1010 }
1011 
1012 static const char* getSectionNameForBitcode(const Triple &T) {
1013   switch (T.getObjectFormat()) {
1014   case Triple::MachO:
1015     return "__LLVM,__bitcode";
1016   case Triple::COFF:
1017   case Triple::ELF:
1018   case Triple::Wasm:
1019   case Triple::UnknownObjectFormat:
1020     return ".llvmbc";
1021   }
1022   llvm_unreachable("Unimplemented ObjectFormatType");
1023 }
1024 
1025 static const char* getSectionNameForCommandline(const Triple &T) {
1026   switch (T.getObjectFormat()) {
1027   case Triple::MachO:
1028     return "__LLVM,__cmdline";
1029   case Triple::COFF:
1030   case Triple::ELF:
1031   case Triple::Wasm:
1032   case Triple::UnknownObjectFormat:
1033     return ".llvmcmd";
1034   }
1035   llvm_unreachable("Unimplemented ObjectFormatType");
1036 }
1037 
1038 // With -fembed-bitcode, save a copy of the llvm IR as data in the
1039 // __LLVM,__bitcode section.
1040 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1041                          llvm::MemoryBufferRef Buf) {
1042   if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1043     return;
1044 
1045   // Save llvm.compiler.used and remote it.
1046   SmallVector<Constant*, 2> UsedArray;
1047   SmallSet<GlobalValue*, 4> UsedGlobals;
1048   Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1049   GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1050   for (auto *GV : UsedGlobals) {
1051     if (GV->getName() != "llvm.embedded.module" &&
1052         GV->getName() != "llvm.cmdline")
1053       UsedArray.push_back(
1054           ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1055   }
1056   if (Used)
1057     Used->eraseFromParent();
1058 
1059   // Embed the bitcode for the llvm module.
1060   std::string Data;
1061   ArrayRef<uint8_t> ModuleData;
1062   Triple T(M->getTargetTriple());
1063   // Create a constant that contains the bitcode.
1064   // In case of embedding a marker, ignore the input Buf and use the empty
1065   // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1066   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1067     if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1068                    (const unsigned char *)Buf.getBufferEnd())) {
1069       // If the input is LLVM Assembly, bitcode is produced by serializing
1070       // the module. Use-lists order need to be perserved in this case.
1071       llvm::raw_string_ostream OS(Data);
1072       llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1073       ModuleData =
1074           ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1075     } else
1076       // If the input is LLVM bitcode, write the input byte stream directly.
1077       ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1078                                      Buf.getBufferSize());
1079   }
1080   llvm::Constant *ModuleConstant =
1081       llvm::ConstantDataArray::get(M->getContext(), ModuleData);
1082   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1083       *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
1084       ModuleConstant);
1085   GV->setSection(getSectionNameForBitcode(T));
1086   UsedArray.push_back(
1087       ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1088   if (llvm::GlobalVariable *Old =
1089           M->getGlobalVariable("llvm.embedded.module", true)) {
1090     assert(Old->hasOneUse() &&
1091            "llvm.embedded.module can only be used once in llvm.compiler.used");
1092     GV->takeName(Old);
1093     Old->eraseFromParent();
1094   } else {
1095     GV->setName("llvm.embedded.module");
1096   }
1097 
1098   // Skip if only bitcode needs to be embedded.
1099   if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1100     // Embed command-line options.
1101     ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
1102                               CGOpts.CmdArgs.size());
1103     llvm::Constant *CmdConstant =
1104       llvm::ConstantDataArray::get(M->getContext(), CmdData);
1105     GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1106                                   llvm::GlobalValue::PrivateLinkage,
1107                                   CmdConstant);
1108     GV->setSection(getSectionNameForCommandline(T));
1109     UsedArray.push_back(
1110         ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1111     if (llvm::GlobalVariable *Old =
1112             M->getGlobalVariable("llvm.cmdline", true)) {
1113       assert(Old->hasOneUse() &&
1114              "llvm.cmdline can only be used once in llvm.compiler.used");
1115       GV->takeName(Old);
1116       Old->eraseFromParent();
1117     } else {
1118       GV->setName("llvm.cmdline");
1119     }
1120   }
1121 
1122   if (UsedArray.empty())
1123     return;
1124 
1125   // Recreate llvm.compiler.used.
1126   ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1127   auto *NewUsed = new GlobalVariable(
1128       *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1129       llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1130   NewUsed->setSection("llvm.metadata");
1131 }
1132