1 //===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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 "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeWriterPass.h"
23 #include "llvm/Bitcode/ReaderWriter.h"
24 #include "llvm/CodeGen/RegAllocRegistry.h"
25 #include "llvm/CodeGen/SchedulerRegistry.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/ModuleSummaryIndex.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/MC/SubtargetFeature.h"
33 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/Timer.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
42 #include "llvm/Transforms/IPO.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
44 #include "llvm/Transforms/Instrumentation.h"
45 #include "llvm/Transforms/ObjCARC.h"
46 #include "llvm/Transforms/Scalar.h"
47 #include "llvm/Transforms/Scalar/GVN.h"
48 #include "llvm/Transforms/Utils/SymbolRewriter.h"
50 using namespace clang;
55 class EmitAssemblyHelper {
56 DiagnosticsEngine &Diags;
57 const CodeGenOptions &CodeGenOpts;
58 const clang::TargetOptions &TargetOpts;
59 const LangOptions &LangOpts;
62 Timer CodeGenerationTime;
64 std::unique_ptr<raw_pwrite_stream> OS;
67 TargetIRAnalysis getTargetIRAnalysis() const {
69 return TM->getTargetIRAnalysis();
71 return TargetIRAnalysis();
74 /// Set LLVM command line options passed through -backend-option.
75 void setCommandLineOpts();
77 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM,
78 ModuleSummaryIndex *ModuleSummary);
80 /// Generates the TargetMachine.
81 /// Leaves TM unchanged if it is unable to create the target machine.
82 /// Some of our clang tests specify triples which are not built
83 /// into clang. This is okay because these tests check the generated
84 /// IR, and they require DataLayout which depends on the triple.
85 /// In this case, we allow this method to fail and not report an error.
86 /// When MustCreateTM is used, we print an error if we are unable to load
87 /// the requested target.
88 void CreateTargetMachine(bool MustCreateTM);
90 /// Add passes necessary to emit assembly or LLVM IR.
92 /// \return True on success.
93 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
94 raw_pwrite_stream &OS);
97 EmitAssemblyHelper(DiagnosticsEngine &_Diags, const CodeGenOptions &CGOpts,
98 const clang::TargetOptions &TOpts,
99 const LangOptions &LOpts, Module *M)
100 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
101 TheModule(M), CodeGenerationTime("Code Generation Time") {}
103 ~EmitAssemblyHelper() {
104 if (CodeGenOpts.DisableFree)
105 BuryPointer(std::move(TM));
108 std::unique_ptr<TargetMachine> TM;
110 void EmitAssembly(BackendAction Action,
111 std::unique_ptr<raw_pwrite_stream> OS);
114 // We need this wrapper to access LangOpts and CGOpts from extension functions
115 // that we add to the PassManagerBuilder.
116 class PassManagerBuilderWrapper : public PassManagerBuilder {
118 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
119 const LangOptions &LangOpts)
120 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
121 const CodeGenOptions &getCGOpts() const { return CGOpts; }
122 const LangOptions &getLangOpts() const { return LangOpts; }
124 const CodeGenOptions &CGOpts;
125 const LangOptions &LangOpts;
130 static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
131 if (Builder.OptLevel > 0)
132 PM.add(createObjCARCAPElimPass());
135 static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
136 if (Builder.OptLevel > 0)
137 PM.add(createObjCARCExpandPass());
140 static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
141 if (Builder.OptLevel > 0)
142 PM.add(createObjCARCOptPass());
145 static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
146 legacy::PassManagerBase &PM) {
147 PM.add(createAddDiscriminatorsPass());
150 static void addCleanupPassesForSampleProfiler(
151 const PassManagerBuilder &Builder, legacy::PassManagerBase &PM) {
152 // instcombine is needed before sample profile annotation because it converts
153 // certain function calls to be inlinable. simplifycfg and sroa are needed
154 // before instcombine for necessary preparation. E.g. load store is eliminated
155 // properly so that instcombine will not introduce unecessary liverange.
156 PM.add(createCFGSimplificationPass());
157 PM.add(createSROAPass());
158 PM.add(createInstructionCombiningPass());
161 static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
162 legacy::PassManagerBase &PM) {
163 PM.add(createBoundsCheckingPass());
166 static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
167 legacy::PassManagerBase &PM) {
168 const PassManagerBuilderWrapper &BuilderWrapper =
169 static_cast<const PassManagerBuilderWrapper&>(Builder);
170 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
171 SanitizerCoverageOptions Opts;
173 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
174 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
175 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
176 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
177 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
178 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
179 PM.add(createSanitizerCoverageModulePass(Opts));
182 static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
183 legacy::PassManagerBase &PM) {
184 const PassManagerBuilderWrapper &BuilderWrapper =
185 static_cast<const PassManagerBuilderWrapper&>(Builder);
186 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
187 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
188 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
189 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
191 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/false, Recover));
194 static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
195 legacy::PassManagerBase &PM) {
196 PM.add(createAddressSanitizerFunctionPass(
197 /*CompileKernel*/ true,
198 /*Recover*/ true, /*UseAfterScope*/ false));
199 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
203 static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
204 legacy::PassManagerBase &PM) {
205 const PassManagerBuilderWrapper &BuilderWrapper =
206 static_cast<const PassManagerBuilderWrapper&>(Builder);
207 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
208 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
210 // MemorySanitizer inserts complex instrumentation that mostly follows
211 // the logic of the original code, but operates on "shadow" values.
212 // It can benefit from re-running some general purpose optimization passes.
213 if (Builder.OptLevel > 0) {
214 PM.add(createEarlyCSEPass());
215 PM.add(createReassociatePass());
216 PM.add(createLICMPass());
217 PM.add(createGVNPass());
218 PM.add(createInstructionCombiningPass());
219 PM.add(createDeadStoreEliminationPass());
223 static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
224 legacy::PassManagerBase &PM) {
225 PM.add(createThreadSanitizerPass());
228 static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
229 legacy::PassManagerBase &PM) {
230 const PassManagerBuilderWrapper &BuilderWrapper =
231 static_cast<const PassManagerBuilderWrapper&>(Builder);
232 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
233 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
236 static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
237 legacy::PassManagerBase &PM) {
238 const PassManagerBuilderWrapper &BuilderWrapper =
239 static_cast<const PassManagerBuilderWrapper&>(Builder);
240 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
241 EfficiencySanitizerOptions Opts;
242 if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
243 Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
244 else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
245 Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
246 PM.add(createEfficiencySanitizerPass(Opts));
249 static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
250 const CodeGenOptions &CodeGenOpts) {
251 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
252 if (!CodeGenOpts.SimplifyLibCalls)
253 TLII->disableAllFunctions();
255 // Disable individual libc/libm calls in TargetLibraryInfo.
257 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
258 if (TLII->getLibFunc(FuncName, F))
259 TLII->setUnavailable(F);
262 switch (CodeGenOpts.getVecLib()) {
263 case CodeGenOptions::Accelerate:
264 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
272 static void addSymbolRewriterPass(const CodeGenOptions &Opts,
273 legacy::PassManager *MPM) {
274 llvm::SymbolRewriter::RewriteDescriptorList DL;
276 llvm::SymbolRewriter::RewriteMapParser MapParser;
277 for (const auto &MapFile : Opts.RewriteMapFiles)
278 MapParser.parse(MapFile, &DL);
280 MPM->add(createRewriteSymbolsPass(DL));
283 void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
284 legacy::FunctionPassManager &FPM,
285 ModuleSummaryIndex *ModuleSummary) {
286 if (CodeGenOpts.DisableLLVMPasses)
289 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
290 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
292 // Handle disabling of LLVM optimization, where we want to preserve the
293 // internal module before any optimization.
294 if (CodeGenOpts.DisableLLVMOpts) {
296 Inlining = CodeGenOpts.NoInlining;
299 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
301 // Figure out TargetLibraryInfo.
302 Triple TargetTriple(TheModule->getTargetTriple());
303 PMBuilder.LibraryInfo = createTLII(TargetTriple, CodeGenOpts);
306 case CodeGenOptions::NoInlining:
308 case CodeGenOptions::NormalInlining:
309 case CodeGenOptions::OnlyHintInlining: {
311 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
314 case CodeGenOptions::OnlyAlwaysInlining:
315 // Respect always_inline.
317 // Do not insert lifetime intrinsics at -O0.
318 PMBuilder.Inliner = createAlwaysInlinerPass(false);
320 PMBuilder.Inliner = createAlwaysInlinerPass();
324 PMBuilder.OptLevel = OptLevel;
325 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
326 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
327 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
328 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
330 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
331 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
332 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
333 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
334 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
336 // If we are performing a ThinLTO importing compile, invoke the LTO
337 // pipeline and pass down the in-memory module summary index.
339 PMBuilder.ModuleSummary = ModuleSummary;
340 PMBuilder.populateThinLTOPassManager(MPM);
344 // Add target-specific passes that need to run as early as possible.
346 PMBuilder.addExtension(
347 PassManagerBuilder::EP_EarlyAsPossible,
348 [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
349 TM->addEarlyAsPossiblePasses(PM);
352 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
353 addAddDiscriminatorsPass);
355 // In ObjC ARC mode, add the main ARC optimization passes.
356 if (LangOpts.ObjCAutoRefCount) {
357 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
358 addObjCARCExpandPass);
359 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
360 addObjCARCAPElimPass);
361 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
365 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
366 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
367 addBoundsCheckingPass);
368 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
369 addBoundsCheckingPass);
372 if (CodeGenOpts.SanitizeCoverageType ||
373 CodeGenOpts.SanitizeCoverageIndirectCalls ||
374 CodeGenOpts.SanitizeCoverageTraceCmp) {
375 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
376 addSanitizerCoveragePass);
377 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
378 addSanitizerCoveragePass);
381 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
382 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
383 addAddressSanitizerPasses);
384 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
385 addAddressSanitizerPasses);
388 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
389 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
390 addKernelAddressSanitizerPasses);
391 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
392 addKernelAddressSanitizerPasses);
395 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
396 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
397 addMemorySanitizerPass);
398 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
399 addMemorySanitizerPass);
402 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
403 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
404 addThreadSanitizerPass);
405 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
406 addThreadSanitizerPass);
409 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
410 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
411 addDataFlowSanitizerPass);
412 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
413 addDataFlowSanitizerPass);
416 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
417 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
418 addEfficiencySanitizerPass);
419 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
420 addEfficiencySanitizerPass);
423 // Set up the per-function pass manager.
424 if (CodeGenOpts.VerifyModule)
425 FPM.add(createVerifierPass());
427 // Set up the per-module pass manager.
428 if (!CodeGenOpts.RewriteMapFiles.empty())
429 addSymbolRewriterPass(CodeGenOpts, &MPM);
431 if (!CodeGenOpts.DisableGCov &&
432 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
433 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
434 // LLVM's -default-gcov-version flag is set to something invalid.
436 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
437 Options.EmitData = CodeGenOpts.EmitGcovArcs;
438 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
439 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
440 Options.NoRedZone = CodeGenOpts.DisableRedZone;
441 Options.FunctionNamesInData =
442 !CodeGenOpts.CoverageNoFunctionNamesInData;
443 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
444 MPM.add(createGCOVProfilerPass(Options));
445 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
446 MPM.add(createStripSymbolsPass(true));
449 if (CodeGenOpts.hasProfileClangInstr()) {
450 InstrProfOptions Options;
451 Options.NoRedZone = CodeGenOpts.DisableRedZone;
452 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
453 MPM.add(createInstrProfilingLegacyPass(Options));
455 if (CodeGenOpts.hasProfileIRInstr()) {
456 if (!CodeGenOpts.InstrProfileOutput.empty())
457 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
459 PMBuilder.PGOInstrGen = "default.profraw";
461 if (CodeGenOpts.hasProfileIRUse())
462 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
464 if (!CodeGenOpts.SampleProfileFile.empty()) {
465 MPM.add(createPruneEHPass());
466 MPM.add(createSampleProfileLoaderPass(CodeGenOpts.SampleProfileFile));
467 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
468 addCleanupPassesForSampleProfiler);
471 PMBuilder.populateFunctionPassManager(FPM);
472 PMBuilder.populateModulePassManager(MPM);
475 void EmitAssemblyHelper::setCommandLineOpts() {
476 SmallVector<const char *, 16> BackendArgs;
477 BackendArgs.push_back("clang"); // Fake program name.
478 if (!CodeGenOpts.DebugPass.empty()) {
479 BackendArgs.push_back("-debug-pass");
480 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
482 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
483 BackendArgs.push_back("-limit-float-precision");
484 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
486 for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
487 BackendArgs.push_back(BackendOption.c_str());
488 BackendArgs.push_back(nullptr);
489 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
493 void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
494 // Create the TargetMachine for generating code.
496 std::string Triple = TheModule->getTargetTriple();
497 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
500 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
505 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
506 .Case("small", llvm::CodeModel::Small)
507 .Case("kernel", llvm::CodeModel::Kernel)
508 .Case("medium", llvm::CodeModel::Medium)
509 .Case("large", llvm::CodeModel::Large)
510 .Case("default", llvm::CodeModel::Default)
512 assert(CodeModel != ~0u && "invalid code model!");
513 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
515 std::string FeaturesStr =
516 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
518 // Keep this synced with the equivalent code in tools/driver/cc1as_main.cpp.
519 llvm::Optional<llvm::Reloc::Model> RM;
520 if (CodeGenOpts.RelocationModel == "static") {
521 RM = llvm::Reloc::Static;
522 } else if (CodeGenOpts.RelocationModel == "pic") {
523 RM = llvm::Reloc::PIC_;
525 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
526 "Invalid PIC model!");
527 RM = llvm::Reloc::DynamicNoPIC;
530 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
531 switch (CodeGenOpts.OptimizationLevel) {
533 case 0: OptLevel = CodeGenOpt::None; break;
534 case 3: OptLevel = CodeGenOpt::Aggressive; break;
537 llvm::TargetOptions Options;
539 if (!TargetOpts.Reciprocals.empty())
540 Options.Reciprocals = TargetRecip(TargetOpts.Reciprocals);
542 Options.ThreadModel =
543 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
544 .Case("posix", llvm::ThreadModel::POSIX)
545 .Case("single", llvm::ThreadModel::Single);
547 // Set float ABI type.
548 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
549 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
550 "Invalid Floating Point ABI!");
551 Options.FloatABIType =
552 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
553 .Case("soft", llvm::FloatABI::Soft)
554 .Case("softfp", llvm::FloatABI::Soft)
555 .Case("hard", llvm::FloatABI::Hard)
556 .Default(llvm::FloatABI::Default);
558 // Set FP fusion mode.
559 switch (CodeGenOpts.getFPContractMode()) {
560 case CodeGenOptions::FPC_Off:
561 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
563 case CodeGenOptions::FPC_On:
564 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
566 case CodeGenOptions::FPC_Fast:
567 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
571 Options.UseInitArray = CodeGenOpts.UseInitArray;
572 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
573 Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
574 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
577 Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
578 .Case("4", llvm::EABI::EABI4)
579 .Case("5", llvm::EABI::EABI5)
580 .Case("gnu", llvm::EABI::GNU)
581 .Default(llvm::EABI::Default);
583 if (LangOpts.SjLjExceptions)
584 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
586 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
587 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
588 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
589 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
590 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
591 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
592 Options.FunctionSections = CodeGenOpts.FunctionSections;
593 Options.DataSections = CodeGenOpts.DataSections;
594 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
595 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
596 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
598 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
599 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
600 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
601 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
602 Options.MCOptions.MCIncrementalLinkerCompatible =
603 CodeGenOpts.IncrementalLinkerCompatible;
604 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
605 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
606 Options.MCOptions.ABIName = TargetOpts.ABI;
608 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
609 Options, RM, CM, OptLevel));
612 bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
613 BackendAction Action,
614 raw_pwrite_stream &OS) {
616 llvm::Triple TargetTriple(TheModule->getTargetTriple());
617 std::unique_ptr<TargetLibraryInfoImpl> TLII(
618 createTLII(TargetTriple, CodeGenOpts));
619 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
621 // Normal mode, emit a .s or .o file by running the code generator. Note,
622 // this also adds codegenerator level optimization passes.
623 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
624 if (Action == Backend_EmitObj)
625 CGFT = TargetMachine::CGFT_ObjectFile;
626 else if (Action == Backend_EmitMCNull)
627 CGFT = TargetMachine::CGFT_Null;
629 assert(Action == Backend_EmitAssembly && "Invalid action!");
631 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
632 // "codegen" passes so that it isn't run multiple times when there is
633 // inlining happening.
634 if (CodeGenOpts.OptimizationLevel > 0)
635 CodeGenPasses.add(createObjCARCContractPass());
637 if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
638 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
639 Diags.Report(diag::err_fe_unable_to_interface_with_target);
646 void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
647 std::unique_ptr<raw_pwrite_stream> OS) {
648 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
650 setCommandLineOpts();
652 bool UsesCodeGen = (Action != Backend_EmitNothing &&
653 Action != Backend_EmitBC &&
654 Action != Backend_EmitLL);
655 CreateTargetMachine(UsesCodeGen);
657 if (UsesCodeGen && !TM)
660 TheModule->setDataLayout(TM->createDataLayout());
662 // If we are performing a ThinLTO importing compile, load the function
663 // index into memory and pass it into CreatePasses, which will add it
664 // to the PassManagerBuilder and invoke LTO passes.
665 std::unique_ptr<ModuleSummaryIndex> ModuleSummary;
666 if (!CodeGenOpts.ThinLTOIndexFile.empty()) {
667 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
668 llvm::getModuleSummaryIndexForFile(
669 CodeGenOpts.ThinLTOIndexFile, [&](const DiagnosticInfo &DI) {
670 TheModule->getContext().diagnose(DI);
672 if (std::error_code EC = IndexOrErr.getError()) {
673 std::string Error = EC.message();
674 errs() << "Error loading index file '" << CodeGenOpts.ThinLTOIndexFile
675 << "': " << Error << "\n";
678 ModuleSummary = std::move(IndexOrErr.get());
679 assert(ModuleSummary && "Expected non-empty module summary index");
682 legacy::PassManager PerModulePasses;
684 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
686 legacy::FunctionPassManager PerFunctionPasses(TheModule);
687 PerFunctionPasses.add(
688 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
690 CreatePasses(PerModulePasses, PerFunctionPasses, ModuleSummary.get());
692 legacy::PassManager CodeGenPasses;
694 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
697 case Backend_EmitNothing:
701 PerModulePasses.add(createBitcodeWriterPass(
702 *OS, CodeGenOpts.EmitLLVMUseLists, CodeGenOpts.EmitSummaryIndex,
703 CodeGenOpts.EmitSummaryIndex));
708 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
712 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
716 // Before executing passes, print the final values of the LLVM options.
717 cl::PrintOptionValues();
719 // Run passes. For now we do all passes at once, but eventually we
720 // would like to have the option of streaming code generation.
723 PrettyStackTraceString CrashInfo("Per-function optimization");
725 PerFunctionPasses.doInitialization();
726 for (Function &F : *TheModule)
727 if (!F.isDeclaration())
728 PerFunctionPasses.run(F);
729 PerFunctionPasses.doFinalization();
733 PrettyStackTraceString CrashInfo("Per-module optimization passes");
734 PerModulePasses.run(*TheModule);
738 PrettyStackTraceString CrashInfo("Code generation");
739 CodeGenPasses.run(*TheModule);
743 void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
744 const CodeGenOptions &CGOpts,
745 const clang::TargetOptions &TOpts,
746 const LangOptions &LOpts, const llvm::DataLayout &TDesc,
747 Module *M, BackendAction Action,
748 std::unique_ptr<raw_pwrite_stream> OS) {
749 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
751 AsmHelper.EmitAssembly(Action, std::move(OS));
753 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
756 std::string DLDesc = M->getDataLayout().getStringRepresentation();
757 if (DLDesc != TDesc.getStringRepresentation()) {
758 unsigned DiagID = Diags.getCustomDiagID(
759 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
760 "expected target description '%1'");
761 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
766 static const char* getSectionNameForBitcode(const Triple &T) {
767 switch (T.getObjectFormat()) {
769 return "__LLVM,__bitcode";
772 case Triple::UnknownObjectFormat:
775 llvm_unreachable("Unimplemented ObjectFormatType");
778 static const char* getSectionNameForCommandline(const Triple &T) {
779 switch (T.getObjectFormat()) {
781 return "__LLVM,__cmdline";
784 case Triple::UnknownObjectFormat:
787 llvm_unreachable("Unimplemented ObjectFormatType");
790 // With -fembed-bitcode, save a copy of the llvm IR as data in the
791 // __LLVM,__bitcode section.
792 void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
793 llvm::MemoryBufferRef Buf) {
794 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
797 // Save llvm.compiler.used and remote it.
798 SmallVector<Constant*, 2> UsedArray;
799 SmallSet<GlobalValue*, 4> UsedGlobals;
800 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
801 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
802 for (auto *GV : UsedGlobals) {
803 if (GV->getName() != "llvm.embedded.module" &&
804 GV->getName() != "llvm.cmdline")
806 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
809 Used->eraseFromParent();
811 // Embed the bitcode for the llvm module.
813 ArrayRef<uint8_t> ModuleData;
814 Triple T(M->getTargetTriple());
815 // Create a constant that contains the bitcode.
816 // In case of embedding a marker, ignore the input Buf and use the empty
817 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
818 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
819 if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
820 (const unsigned char *)Buf.getBufferEnd())) {
821 // If the input is LLVM Assembly, bitcode is produced by serializing
822 // the module. Use-lists order need to be perserved in this case.
823 llvm::raw_string_ostream OS(Data);
824 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
826 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
828 // If the input is LLVM bitcode, write the input byte stream directly.
829 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
830 Buf.getBufferSize());
832 llvm::Constant *ModuleConstant =
833 llvm::ConstantDataArray::get(M->getContext(), ModuleData);
834 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
835 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
837 GV->setSection(getSectionNameForBitcode(T));
839 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
840 if (llvm::GlobalVariable *Old =
841 M->getGlobalVariable("llvm.embedded.module", true)) {
842 assert(Old->hasOneUse() &&
843 "llvm.embedded.module can only be used once in llvm.compiler.used");
845 Old->eraseFromParent();
847 GV->setName("llvm.embedded.module");
850 // Skip if only bitcode needs to be embedded.
851 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
852 // Embed command-line options.
853 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
854 CGOpts.CmdArgs.size());
855 llvm::Constant *CmdConstant =
856 llvm::ConstantDataArray::get(M->getContext(), CmdData);
857 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
858 llvm::GlobalValue::PrivateLinkage,
860 GV->setSection(getSectionNameForCommandline(T));
862 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
863 if (llvm::GlobalVariable *Old =
864 M->getGlobalVariable("llvm.cmdline", true)) {
865 assert(Old->hasOneUse() &&
866 "llvm.cmdline can only be used once in llvm.compiler.used");
868 Old->eraseFromParent();
870 GV->setName("llvm.cmdline");
874 if (UsedArray.empty())
877 // Recreate llvm.compiler.used.
878 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
879 auto *NewUsed = new GlobalVariable(
880 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
881 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
882 NewUsed->setSection("llvm.metadata");