1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
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 // This is the llc code generator driver. It provides a convenient
11 // command-line interface for generating native assembly-language code
12 // or C code, given LLVM bitcode.
14 //===----------------------------------------------------------------------===//
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
22 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23 #include "llvm/CodeGen/MIRParser/MIRParser.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/TargetPassConfig.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/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/MC/SubtargetFeature.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/PluginLoader.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include "llvm/Transforms/Utils/Cloning.h"
57 // General options for llc. Other pass-specific options are specified
58 // within the corresponding llc passes, and target-specific options
59 // and back-end code generation options are specified with the target machine.
61 static cl::opt<std::string>
62 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
64 static cl::opt<std::string>
65 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
67 static cl::opt<std::string>
68 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
70 static cl::opt<unsigned>
71 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
73 cl::desc("Repeat compilation N times for timing"));
76 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
77 cl::desc("Disable integrated assembler"));
80 PreserveComments("preserve-as-comments", cl::Hidden,
81 cl::desc("Preserve Comments in outputted assembly"),
84 // Determine optimization level.
87 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
93 static cl::opt<std::string>
94 TargetTriple("mtriple", cl::desc("Override target triple for module"));
96 static cl::opt<std::string> SplitDwarfFile(
99 "Specify the name of the .dwo file to encode in the DWARF output"));
101 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
102 cl::desc("Do not verify input module"));
104 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
105 cl::desc("Disable simplify-libcalls"));
107 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
108 cl::desc("Show encoding in .s output"));
110 static cl::opt<bool> EnableDwarfDirectory(
111 "enable-dwarf-directory", cl::Hidden,
112 cl::desc("Use .file directives with an explicit directory."));
114 static cl::opt<bool> AsmVerbose("asm-verbose",
115 cl::desc("Add comments to directives."),
119 CompileTwice("compile-twice", cl::Hidden,
120 cl::desc("Run everything twice, re-using the same pass "
121 "manager and verify the result is the same."),
124 static cl::opt<bool> DiscardValueNames(
125 "discard-value-names",
126 cl::desc("Discard names from Value (other than GlobalValue)."),
127 cl::init(false), cl::Hidden);
129 static cl::opt<std::string> StopBefore("stop-before",
130 cl::desc("Stop compilation before a specific pass"),
131 cl::value_desc("pass-name"), cl::init(""));
133 static cl::opt<std::string> StopAfter("stop-after",
134 cl::desc("Stop compilation after a specific pass"),
135 cl::value_desc("pass-name"), cl::init(""));
137 static cl::opt<std::string> StartBefore("start-before",
138 cl::desc("Resume compilation before a specific pass"),
139 cl::value_desc("pass-name"), cl::init(""));
141 static cl::opt<std::string> StartAfter("start-after",
142 cl::desc("Resume compilation after a specific pass"),
143 cl::value_desc("pass-name"), cl::init(""));
145 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
147 static cl::opt<bool> PassRemarksWithHotness(
148 "pass-remarks-with-hotness",
149 cl::desc("With PGO, include profile count in optimization remarks"),
152 static cl::opt<unsigned> PassRemarksHotnessThreshold(
153 "pass-remarks-hotness-threshold",
154 cl::desc("Minimum profile count required for an optimization remark to be output"),
157 static cl::opt<std::string>
158 RemarksFilename("pass-remarks-output",
159 cl::desc("YAML output filename for pass remarks"),
160 cl::value_desc("filename"));
163 static ManagedStatic<std::vector<std::string>> RunPassNames;
165 struct RunPassOption {
166 void operator=(const std::string &Val) const {
169 SmallVector<StringRef, 8> PassNames;
170 StringRef(Val).split(PassNames, ',', -1, false);
171 for (auto PassName : PassNames)
172 RunPassNames->push_back(PassName);
177 static RunPassOption RunPassOpt;
179 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
181 cl::desc("Run compiler only for specified passes (comma separated list)"),
182 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
184 static int compileModule(char **, LLVMContext &);
186 static std::unique_ptr<tool_output_file>
187 GetOutputStream(const char *TargetName, Triple::OSType OS,
188 const char *ProgName) {
189 // If we don't yet have an output filename, make one.
190 if (OutputFilename.empty()) {
191 if (InputFilename == "-")
192 OutputFilename = "-";
194 // If InputFilename ends in .bc or .ll, remove it.
195 StringRef IFN = InputFilename;
196 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
197 OutputFilename = IFN.drop_back(3);
198 else if (IFN.endswith(".mir"))
199 OutputFilename = IFN.drop_back(4);
201 OutputFilename = IFN;
204 case TargetMachine::CGFT_AssemblyFile:
205 if (TargetName[0] == 'c') {
206 if (TargetName[1] == 0)
207 OutputFilename += ".cbe.c";
208 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
209 OutputFilename += ".cpp";
211 OutputFilename += ".s";
213 OutputFilename += ".s";
215 case TargetMachine::CGFT_ObjectFile:
216 if (OS == Triple::Win32)
217 OutputFilename += ".obj";
219 OutputFilename += ".o";
221 case TargetMachine::CGFT_Null:
222 OutputFilename += ".null";
228 // Decide if we need "binary" output.
231 case TargetMachine::CGFT_AssemblyFile:
233 case TargetMachine::CGFT_ObjectFile:
234 case TargetMachine::CGFT_Null:
241 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
243 OpenFlags |= sys::fs::F_Text;
244 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
247 errs() << EC.message() << '\n';
254 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
255 bool *HasError = static_cast<bool *>(Context);
256 if (DI.getSeverity() == DS_Error)
259 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
260 if (!Remark->isEnabled())
263 DiagnosticPrinterRawOStream DP(errs());
264 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
269 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
270 unsigned LocCookie) {
271 bool *HasError = static_cast<bool *>(Context);
272 if (SMD.getKind() == SourceMgr::DK_Error)
275 SMD.print(nullptr, errs());
277 // For testing purposes, we print the LocCookie here.
279 errs() << "note: !srcloc = " << LocCookie << "\n";
282 // main - Entry point for the llc compiler.
284 int main(int argc, char **argv) {
285 sys::PrintStackTraceOnErrorSignal(argv[0]);
286 PrettyStackTraceProgram X(argc, argv);
288 // Enable debug stream buffering.
289 EnableDebugBuffering = true;
292 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
294 // Initialize targets first, so that --version shows registered targets.
295 InitializeAllTargets();
296 InitializeAllTargetMCs();
297 InitializeAllAsmPrinters();
298 InitializeAllAsmParsers();
300 // Initialize codegen and IR passes used by llc so that the -print-after,
301 // -print-before, and -stop-after options work.
302 PassRegistry *Registry = PassRegistry::getPassRegistry();
303 initializeCore(*Registry);
304 initializeCodeGen(*Registry);
305 initializeLoopStrengthReducePass(*Registry);
306 initializeLowerIntrinsicsPass(*Registry);
307 initializeCountingFunctionInserterPass(*Registry);
308 initializeUnreachableBlockElimLegacyPassPass(*Registry);
309 initializeConstantHoistingLegacyPassPass(*Registry);
310 initializeScalarOpts(*Registry);
311 initializeVectorization(*Registry);
312 initializeScalarizeMaskedMemIntrinPass(*Registry);
313 initializeExpandReductionsPass(*Registry);
315 // Initialize debugging passes.
316 initializeScavengerTestPass(*Registry);
318 // Register the target printer for --version.
319 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
321 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
323 Context.setDiscardValueNames(DiscardValueNames);
325 // Set a diagnostic handler that doesn't exit on the first error
326 bool HasError = false;
327 Context.setDiagnosticHandler(DiagnosticHandler, &HasError);
328 Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
330 if (PassRemarksWithHotness)
331 Context.setDiagnosticsHotnessRequested(true);
333 if (PassRemarksHotnessThreshold)
334 Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold);
336 std::unique_ptr<tool_output_file> YamlFile;
337 if (RemarksFilename != "") {
339 YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC,
342 errs() << EC.message() << '\n';
345 Context.setDiagnosticsOutputFile(
346 llvm::make_unique<yaml::Output>(YamlFile->os()));
349 if (InputLanguage != "" && InputLanguage != "ir" &&
350 InputLanguage != "mir") {
351 errs() << argv[0] << "Input language must be '', 'IR' or 'MIR'\n";
355 // Compile the module TimeCompilations times to give better compile time
357 for (unsigned I = TimeCompilations; I; --I)
358 if (int RetVal = compileModule(argv, Context))
366 static bool addPass(PassManagerBase &PM, const char *argv0,
367 StringRef PassName, TargetPassConfig &TPC) {
368 if (PassName == "none")
371 const PassRegistry *PR = PassRegistry::getPassRegistry();
372 const PassInfo *PI = PR->getPassInfo(PassName);
374 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
379 if (PI->getNormalCtor())
380 P = PI->getNormalCtor()();
382 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
385 std::string Banner = std::string("After ") + std::string(P->getPassName());
387 TPC.printAndVerify(Banner);
392 static AnalysisID getPassID(const char *argv0, const char *OptionName,
393 StringRef PassName) {
394 if (PassName.empty())
397 const PassRegistry &PR = *PassRegistry::getPassRegistry();
398 const PassInfo *PI = PR.getPassInfo(PassName);
400 errs() << argv0 << ": " << OptionName << " pass is not registered.\n";
403 return PI->getTypeInfo();
406 static int compileModule(char **argv, LLVMContext &Context) {
407 // Load the module to be compiled...
409 std::unique_ptr<Module> M;
410 std::unique_ptr<MIRParser> MIR;
413 bool SkipModule = MCPU == "help" ||
414 (!MAttrs.empty() && MAttrs.front() == "help");
416 // If user just wants to list available options, skip module loading
418 if (InputLanguage == "mir" ||
419 (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
420 MIR = createMIRParserFromFile(InputFilename, Err, Context);
422 M = MIR->parseIRModule();
424 M = parseIRFile(InputFilename, Err, Context);
426 Err.print(argv[0], errs());
430 // Verify module immediately to catch problems before doInitialization() is
431 // called on any passes.
432 if (!NoVerify && verifyModule(*M, &errs())) {
433 errs() << argv[0] << ": " << InputFilename
434 << ": error: input module is broken!\n";
438 // If we are supposed to override the target triple, do so now.
439 if (!TargetTriple.empty())
440 M->setTargetTriple(Triple::normalize(TargetTriple));
441 TheTriple = Triple(M->getTargetTriple());
443 TheTriple = Triple(Triple::normalize(TargetTriple));
446 if (TheTriple.getTriple().empty())
447 TheTriple.setTriple(sys::getDefaultTargetTriple());
449 // Get the target specific parser.
451 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
454 errs() << argv[0] << ": " << Error;
458 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
460 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
463 errs() << argv[0] << ": invalid optimization level.\n";
466 case '0': OLvl = CodeGenOpt::None; break;
467 case '1': OLvl = CodeGenOpt::Less; break;
468 case '2': OLvl = CodeGenOpt::Default; break;
469 case '3': OLvl = CodeGenOpt::Aggressive; break;
472 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
473 Options.DisableIntegratedAS = NoIntegratedAssembler;
474 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
475 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
476 Options.MCOptions.AsmVerbose = AsmVerbose;
477 Options.MCOptions.PreserveAsmComments = PreserveComments;
478 Options.MCOptions.IASSearchPaths = IncludeDirs;
479 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
481 std::unique_ptr<TargetMachine> Target(
482 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
483 Options, getRelocModel(), CMModel, OLvl));
485 assert(Target && "Could not allocate target machine!");
487 // If we don't have a module then just exit now. We do this down
488 // here since the CPU/Feature help is underneath the target machine
493 assert(M && "Should have exited if we didn't have a module!");
494 if (FloatABIForCalls != FloatABI::Default)
495 Options.FloatABIType = FloatABIForCalls;
497 // Figure out where we are going to send the output.
498 std::unique_ptr<tool_output_file> Out =
499 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
502 // Build up all of the passes that we want to do to the module.
503 legacy::PassManager PM;
505 // Add an appropriate TargetLibraryInfo pass for the module's triple.
506 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
508 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
509 if (DisableSimplifyLibCalls)
510 TLII.disableAllFunctions();
511 PM.add(new TargetLibraryInfoWrapperPass(TLII));
513 // Add the target data from the target machine, if it exists, or the module.
514 M->setDataLayout(Target->createDataLayout());
516 // Override function attributes based on CPUStr, FeaturesStr, and command line
518 setFunctionAttributes(CPUStr, FeaturesStr, *M);
520 if (RelaxAll.getNumOccurrences() > 0 &&
521 FileType != TargetMachine::CGFT_ObjectFile)
523 << ": warning: ignoring -mc-relax-all because filetype != obj";
526 raw_pwrite_stream *OS = &Out->os();
528 // Manually do the buffering rather than using buffer_ostream,
529 // so we can memcmp the contents in CompileTwice mode
530 SmallVector<char, 0> Buffer;
531 std::unique_ptr<raw_svector_ostream> BOS;
532 if ((FileType != TargetMachine::CGFT_AssemblyFile &&
533 !Out->os().supportsSeeking()) ||
535 BOS = make_unique<raw_svector_ostream>(Buffer);
539 const char *argv0 = argv[0];
540 AnalysisID StartBeforeID = getPassID(argv0, "start-before", StartBefore);
541 AnalysisID StartAfterID = getPassID(argv0, "start-after", StartAfter);
542 AnalysisID StopAfterID = getPassID(argv0, "stop-after", StopAfter);
543 AnalysisID StopBeforeID = getPassID(argv0, "stop-before", StopBefore);
544 if (StartBeforeID && StartAfterID) {
545 errs() << argv0 << ": -start-before and -start-after specified!\n";
548 if (StopBeforeID && StopAfterID) {
549 errs() << argv0 << ": -stop-before and -stop-after specified!\n";
554 // Construct a custom pass pipeline that starts after instruction
556 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
557 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
558 TPC.setDisableVerify(NoVerify);
560 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
561 if (MIR->parseMachineFunctions(*M, *MMI))
564 TPC.printAndVerify("");
566 if (!RunPassNames->empty()) {
567 if (!StartAfter.empty() || !StopAfter.empty() || !StartBefore.empty() ||
568 !StopBefore.empty()) {
569 errs() << argv0 << ": start-after and/or stop-after passes are "
570 "redundant when run-pass is specified.\n";
574 for (const std::string &RunPassName : *RunPassNames) {
575 if (addPass(PM, argv0, RunPassName, TPC))
579 TPC.setStartStopPasses(StartBeforeID, StartAfterID, StopBeforeID,
582 TPC.addMachinePasses();
584 TPC.setInitialized();
586 if (!StopBefore.empty() || !StopAfter.empty() || !RunPassNames->empty()) {
587 PM.add(createPrintMIRPass(*OS));
588 } else if (LLVMTM.addAsmPrinter(PM, *OS, FileType, MMI->getContext())) {
589 errs() << argv0 << ": target does not support generation of this"
593 PM.add(createFreeMachineFunctionPass());
594 } else if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify,
595 StartBeforeID, StartAfterID,
596 StopBeforeID, StopAfterID)) {
597 errs() << argv0 << ": target does not support generation of this"
602 // Before executing passes, print the final values of the LLVM options.
603 cl::PrintOptionValues();
605 // If requested, run the pass manager over the same module again,
606 // to catch any bugs due to persistent state in the passes. Note that
607 // opt has the same functionality, so it may be worth abstracting this out
609 SmallVector<char, 0> CompileTwiceBuffer;
611 std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
613 CompileTwiceBuffer = Buffer;
619 auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
623 // Compare the two outputs and make sure they're the same
625 if (Buffer.size() != CompileTwiceBuffer.size() ||
626 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
629 << "Running the pass manager twice changed the output.\n"
630 "Writing the result of the second run to the specified output\n"
631 "To generate the one-run comparison binary, just run without\n"
632 "the compile-twice option\n";