1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This is the llc code generator driver. It provides a convenient
10 // command-line interface for generating native assembly-language code
11 // or C code, given LLVM bitcode.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/TargetLibraryInfo.h"
18 #include "llvm/CodeGen/CommandFlags.inc"
19 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
20 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
21 #include "llvm/CodeGen/MIRParser/MIRParser.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/IR/AutoUpgrade.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/RemarkStreamer.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/IRReader/IRReader.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/ManagedStatic.h"
47 #include "llvm/Support/PluginLoader.h"
48 #include "llvm/Support/SourceMgr.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/WithColor.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Transforms/Utils/Cloning.h"
58 // General options for llc. Other pass-specific options are specified
59 // within the corresponding llc passes, and target-specific options
60 // and back-end code generation options are specified with the target machine.
62 static cl::opt<std::string>
63 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
65 static cl::opt<std::string>
66 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
68 static cl::opt<std::string>
69 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
71 static cl::opt<std::string>
72 SplitDwarfOutputFile("split-dwarf-output",
73 cl::desc(".dwo output filename"),
74 cl::value_desc("filename"));
76 static cl::opt<unsigned>
77 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
79 cl::desc("Repeat compilation N times for timing"));
82 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
83 cl::desc("Disable integrated assembler"));
86 PreserveComments("preserve-as-comments", cl::Hidden,
87 cl::desc("Preserve Comments in outputted assembly"),
90 // Determine optimization level.
93 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
99 static cl::opt<std::string>
100 TargetTriple("mtriple", cl::desc("Override target triple for module"));
102 static cl::opt<std::string> SplitDwarfFile(
105 "Specify the name of the .dwo file to encode in the DWARF output"));
107 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
108 cl::desc("Do not verify input module"));
110 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
111 cl::desc("Disable simplify-libcalls"));
113 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
114 cl::desc("Show encoding in .s output"));
116 static cl::opt<bool> EnableDwarfDirectory(
117 "enable-dwarf-directory", cl::Hidden,
118 cl::desc("Use .file directives with an explicit directory."));
120 static cl::opt<bool> AsmVerbose("asm-verbose",
121 cl::desc("Add comments to directives."),
125 CompileTwice("compile-twice", cl::Hidden,
126 cl::desc("Run everything twice, re-using the same pass "
127 "manager and verify the result is the same."),
130 static cl::opt<bool> DiscardValueNames(
131 "discard-value-names",
132 cl::desc("Discard names from Value (other than GlobalValue)."),
133 cl::init(false), cl::Hidden);
135 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
137 static cl::opt<bool> RemarksWithHotness(
138 "pass-remarks-with-hotness",
139 cl::desc("With PGO, include profile count in optimization remarks"),
142 static cl::opt<unsigned>
143 RemarksHotnessThreshold("pass-remarks-hotness-threshold",
144 cl::desc("Minimum profile count required for "
145 "an optimization remark to be output"),
148 static cl::opt<std::string>
149 RemarksFilename("pass-remarks-output",
150 cl::desc("Output filename for pass remarks"),
151 cl::value_desc("filename"));
153 static cl::opt<std::string>
154 RemarksPasses("pass-remarks-filter",
155 cl::desc("Only record optimization remarks from passes whose "
156 "names match the given regular expression"),
157 cl::value_desc("regex"));
159 static cl::opt<std::string> RemarksFormat(
160 "pass-remarks-format",
161 cl::desc("The format used for serializing remarks (default: YAML)"),
162 cl::value_desc("format"), cl::init("yaml"));
165 static ManagedStatic<std::vector<std::string>> RunPassNames;
167 struct RunPassOption {
168 void operator=(const std::string &Val) const {
171 SmallVector<StringRef, 8> PassNames;
172 StringRef(Val).split(PassNames, ',', -1, false);
173 for (auto PassName : PassNames)
174 RunPassNames->push_back(PassName);
179 static RunPassOption RunPassOpt;
181 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
183 cl::desc("Run compiler only for specified passes (comma separated list)"),
184 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
186 static int compileModule(char **, LLVMContext &);
188 static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
190 const char *ProgName) {
191 // If we don't yet have an output filename, make one.
192 if (OutputFilename.empty()) {
193 if (InputFilename == "-")
194 OutputFilename = "-";
196 // If InputFilename ends in .bc or .ll, remove it.
197 StringRef IFN = InputFilename;
198 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
199 OutputFilename = IFN.drop_back(3);
200 else if (IFN.endswith(".mir"))
201 OutputFilename = IFN.drop_back(4);
203 OutputFilename = IFN;
206 case TargetMachine::CGFT_AssemblyFile:
207 if (TargetName[0] == 'c') {
208 if (TargetName[1] == 0)
209 OutputFilename += ".cbe.c";
210 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
211 OutputFilename += ".cpp";
213 OutputFilename += ".s";
215 OutputFilename += ".s";
217 case TargetMachine::CGFT_ObjectFile:
218 if (OS == Triple::Win32)
219 OutputFilename += ".obj";
221 OutputFilename += ".o";
223 case TargetMachine::CGFT_Null:
224 OutputFilename += ".null";
230 // Decide if we need "binary" output.
233 case TargetMachine::CGFT_AssemblyFile:
235 case TargetMachine::CGFT_ObjectFile:
236 case TargetMachine::CGFT_Null:
243 sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;
245 OpenFlags |= sys::fs::OF_Text;
246 auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
248 WithColor::error() << EC.message() << '\n';
255 struct LLCDiagnosticHandler : public DiagnosticHandler {
257 LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
258 bool handleDiagnostics(const DiagnosticInfo &DI) override {
259 if (DI.getSeverity() == DS_Error)
262 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
263 if (!Remark->isEnabled())
266 DiagnosticPrinterRawOStream DP(errs());
267 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
274 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
275 unsigned LocCookie) {
276 bool *HasError = static_cast<bool *>(Context);
277 if (SMD.getKind() == SourceMgr::DK_Error)
280 SMD.print(nullptr, errs());
282 // For testing purposes, we print the LocCookie here.
284 WithColor::note() << "!srcloc = " << LocCookie << "\n";
287 // main - Entry point for the llc compiler.
289 int main(int argc, char **argv) {
290 InitLLVM X(argc, argv);
292 // Enable debug stream buffering.
293 EnableDebugBuffering = true;
297 // Initialize targets first, so that --version shows registered targets.
298 InitializeAllTargets();
299 InitializeAllTargetMCs();
300 InitializeAllAsmPrinters();
301 InitializeAllAsmParsers();
303 // Initialize codegen and IR passes used by llc so that the -print-after,
304 // -print-before, and -stop-after options work.
305 PassRegistry *Registry = PassRegistry::getPassRegistry();
306 initializeCore(*Registry);
307 initializeCodeGen(*Registry);
308 initializeLoopStrengthReducePass(*Registry);
309 initializeLowerIntrinsicsPass(*Registry);
310 initializeEntryExitInstrumenterPass(*Registry);
311 initializePostInlineEntryExitInstrumenterPass(*Registry);
312 initializeUnreachableBlockElimLegacyPassPass(*Registry);
313 initializeConstantHoistingLegacyPassPass(*Registry);
314 initializeScalarOpts(*Registry);
315 initializeVectorization(*Registry);
316 initializeScalarizeMaskedMemIntrinPass(*Registry);
317 initializeExpandReductionsPass(*Registry);
318 initializeHardwareLoopsPass(*Registry);
320 // Initialize debugging passes.
321 initializeScavengerTestPass(*Registry);
323 // Register the target printer for --version.
324 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
326 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
328 Context.setDiscardValueNames(DiscardValueNames);
330 // Set a diagnostic handler that doesn't exit on the first error
331 bool HasError = false;
332 Context.setDiagnosticHandler(
333 std::make_unique<LLCDiagnosticHandler>(&HasError));
334 Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
336 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
337 setupOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
338 RemarksFormat, RemarksWithHotness,
339 RemarksHotnessThreshold);
340 if (Error E = RemarksFileOrErr.takeError()) {
341 WithColor::error(errs(), argv[0]) << toString(std::move(E)) << '\n';
344 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
346 if (InputLanguage != "" && InputLanguage != "ir" &&
347 InputLanguage != "mir") {
348 WithColor::error(errs(), argv[0])
349 << "input language must be '', 'IR' or 'MIR'\n";
353 // Compile the module TimeCompilations times to give better compile time
355 for (unsigned I = TimeCompilations; I; --I)
356 if (int RetVal = compileModule(argv, Context))
364 static bool addPass(PassManagerBase &PM, const char *argv0,
365 StringRef PassName, TargetPassConfig &TPC) {
366 if (PassName == "none")
369 const PassRegistry *PR = PassRegistry::getPassRegistry();
370 const PassInfo *PI = PR->getPassInfo(PassName);
372 WithColor::error(errs(), argv0)
373 << "run-pass " << PassName << " is not registered.\n";
378 if (PI->getNormalCtor())
379 P = PI->getNormalCtor()();
381 WithColor::error(errs(), argv0)
382 << "cannot create pass: " << PI->getPassName() << "\n";
385 std::string Banner = std::string("After ") + std::string(P->getPassName());
387 TPC.printAndVerify(Banner);
392 static int compileModule(char **argv, LLVMContext &Context) {
393 // Load the module to be compiled...
395 std::unique_ptr<Module> M;
396 std::unique_ptr<MIRParser> MIR;
399 bool SkipModule = MCPU == "help" ||
400 (!MAttrs.empty() && MAttrs.front() == "help");
402 // If user just wants to list available options, skip module loading
404 if (InputLanguage == "mir" ||
405 (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
406 MIR = createMIRParserFromFile(InputFilename, Err, Context);
408 M = MIR->parseIRModule();
410 M = parseIRFile(InputFilename, Err, Context, false);
412 Err.print(argv[0], WithColor::error(errs(), argv[0]));
416 // If we are supposed to override the target triple, do so now.
417 if (!TargetTriple.empty())
418 M->setTargetTriple(Triple::normalize(TargetTriple));
419 TheTriple = Triple(M->getTargetTriple());
421 TheTriple = Triple(Triple::normalize(TargetTriple));
424 if (TheTriple.getTriple().empty())
425 TheTriple.setTriple(sys::getDefaultTargetTriple());
427 // Get the target specific parser.
429 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
432 WithColor::error(errs(), argv[0]) << Error;
436 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
438 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
441 WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
444 case '0': OLvl = CodeGenOpt::None; break;
445 case '1': OLvl = CodeGenOpt::Less; break;
446 case '2': OLvl = CodeGenOpt::Default; break;
447 case '3': OLvl = CodeGenOpt::Aggressive; break;
450 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
451 Options.DisableIntegratedAS = NoIntegratedAssembler;
452 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
453 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
454 Options.MCOptions.AsmVerbose = AsmVerbose;
455 Options.MCOptions.PreserveAsmComments = PreserveComments;
456 Options.MCOptions.IASSearchPaths = IncludeDirs;
457 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
459 std::unique_ptr<TargetMachine> Target(TheTarget->createTargetMachine(
460 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, getRelocModel(),
461 getCodeModel(), OLvl));
463 assert(Target && "Could not allocate target machine!");
465 // If we don't have a module then just exit now. We do this down
466 // here since the CPU/Feature help is underneath the target machine
471 assert(M && "Should have exited if we didn't have a module!");
472 if (FloatABIForCalls != FloatABI::Default)
473 Options.FloatABIType = FloatABIForCalls;
475 // Figure out where we are going to send the output.
476 std::unique_ptr<ToolOutputFile> Out =
477 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
480 std::unique_ptr<ToolOutputFile> DwoOut;
481 if (!SplitDwarfOutputFile.empty()) {
483 DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
486 WithColor::error(errs(), argv[0]) << EC.message() << '\n';
491 // Build up all of the passes that we want to do to the module.
492 legacy::PassManager PM;
494 // Add an appropriate TargetLibraryInfo pass for the module's triple.
495 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
497 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
498 if (DisableSimplifyLibCalls)
499 TLII.disableAllFunctions();
500 PM.add(new TargetLibraryInfoWrapperPass(TLII));
502 // Add the target data from the target machine, if it exists, or the module.
503 M->setDataLayout(Target->createDataLayout());
505 // This needs to be done after setting datalayout since it calls verifier
506 // to check debug info whereas verifier relies on correct datalayout.
507 UpgradeDebugInfo(*M);
509 // Verify module immediately to catch problems before doInitialization() is
510 // called on any passes.
511 if (!NoVerify && verifyModule(*M, &errs())) {
513 (Twine(argv[0]) + Twine(": ") + Twine(InputFilename)).str();
514 WithColor::error(errs(), Prefix) << "input module is broken!\n";
518 // Override function attributes based on CPUStr, FeaturesStr, and command line
520 setFunctionAttributes(CPUStr, FeaturesStr, *M);
522 if (RelaxAll.getNumOccurrences() > 0 &&
523 FileType != TargetMachine::CGFT_ObjectFile)
524 WithColor::warning(errs(), argv[0])
525 << ": warning: ignoring -mc-relax-all because filetype != obj";
528 raw_pwrite_stream *OS = &Out->os();
530 // Manually do the buffering rather than using buffer_ostream,
531 // so we can memcmp the contents in CompileTwice mode
532 SmallVector<char, 0> Buffer;
533 std::unique_ptr<raw_svector_ostream> BOS;
534 if ((FileType != TargetMachine::CGFT_AssemblyFile &&
535 !Out->os().supportsSeeking()) ||
537 BOS = std::make_unique<raw_svector_ostream>(Buffer);
541 const char *argv0 = argv[0];
542 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target);
543 MachineModuleInfoWrapperPass *MMIWP =
544 new MachineModuleInfoWrapperPass(&LLVMTM);
546 // Construct a custom pass pipeline that starts after instruction
548 if (!RunPassNames->empty()) {
550 WithColor::warning(errs(), argv[0])
551 << "run-pass is for .mir file only.\n";
554 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
555 if (TPC.hasLimitedCodeGenPipeline()) {
556 WithColor::warning(errs(), argv[0])
557 << "run-pass cannot be used with "
558 << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
562 TPC.setDisableVerify(NoVerify);
565 TPC.printAndVerify("");
566 for (const std::string &RunPassName : *RunPassNames) {
567 if (addPass(PM, argv0, RunPassName, TPC))
570 TPC.setInitialized();
571 PM.add(createPrintMIRPass(*OS));
572 PM.add(createFreeMachineFunctionPass());
573 } else if (Target->addPassesToEmitFile(PM, *OS,
574 DwoOut ? &DwoOut->os() : nullptr,
575 FileType, NoVerify, MMIWP)) {
576 WithColor::warning(errs(), argv[0])
577 << "target does not support generation of this"
583 assert(MMIWP && "Forgot to create MMIWP?");
584 if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))
588 // Before executing passes, print the final values of the LLVM options.
589 cl::PrintOptionValues();
591 // If requested, run the pass manager over the same module again,
592 // to catch any bugs due to persistent state in the passes. Note that
593 // opt has the same functionality, so it may be worth abstracting this out
595 SmallVector<char, 0> CompileTwiceBuffer;
597 std::unique_ptr<Module> M2(llvm::CloneModule(*M));
599 CompileTwiceBuffer = Buffer;
606 ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
610 // Compare the two outputs and make sure they're the same
612 if (Buffer.size() != CompileTwiceBuffer.size() ||
613 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
616 << "Running the pass manager twice changed the output.\n"
617 "Writing the result of the second run to the specified output\n"
618 "To generate the one-run comparison binary, just run without\n"
619 "the compile-twice option\n";