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