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 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/CodeGen/CommandFlags.def"
20 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
21 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
22 #include "llvm/CodeGen/MIRParser/MIRParser.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/CodeGen/TargetSubtargetInfo.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/Transforms/Utils/Cloning.h"
56 // General options for llc. Other pass-specific options are specified
57 // within the corresponding llc passes, and target-specific options
58 // and back-end code generation options are specified with the target machine.
60 static cl::opt<std::string>
61 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
63 static cl::opt<std::string>
64 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
66 static cl::opt<std::string>
67 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
69 static cl::opt<unsigned>
70 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
72 cl::desc("Repeat compilation N times for timing"));
75 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
76 cl::desc("Disable integrated assembler"));
79 PreserveComments("preserve-as-comments", cl::Hidden,
80 cl::desc("Preserve Comments in outputted assembly"),
83 // Determine optimization level.
86 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
92 static cl::opt<std::string>
93 TargetTriple("mtriple", cl::desc("Override target triple for module"));
95 static cl::opt<std::string> SplitDwarfFile(
98 "Specify the name of the .dwo file to encode in the DWARF output"));
100 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
101 cl::desc("Do not verify input module"));
103 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
104 cl::desc("Disable simplify-libcalls"));
106 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
107 cl::desc("Show encoding in .s output"));
109 static cl::opt<bool> EnableDwarfDirectory(
110 "enable-dwarf-directory", cl::Hidden,
111 cl::desc("Use .file directives with an explicit directory."));
113 static cl::opt<bool> AsmVerbose("asm-verbose",
114 cl::desc("Add comments to directives."),
118 CompileTwice("compile-twice", cl::Hidden,
119 cl::desc("Run everything twice, re-using the same pass "
120 "manager and verify the result is the same."),
123 static cl::opt<bool> DiscardValueNames(
124 "discard-value-names",
125 cl::desc("Discard names from Value (other than GlobalValue)."),
126 cl::init(false), cl::Hidden);
128 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
130 static cl::opt<bool> PassRemarksWithHotness(
131 "pass-remarks-with-hotness",
132 cl::desc("With PGO, include profile count in optimization remarks"),
135 static cl::opt<unsigned> PassRemarksHotnessThreshold(
136 "pass-remarks-hotness-threshold",
137 cl::desc("Minimum profile count required for an optimization remark to be output"),
140 static cl::opt<std::string>
141 RemarksFilename("pass-remarks-output",
142 cl::desc("YAML output filename for pass remarks"),
143 cl::value_desc("filename"));
146 static ManagedStatic<std::vector<std::string>> RunPassNames;
148 struct RunPassOption {
149 void operator=(const std::string &Val) const {
152 SmallVector<StringRef, 8> PassNames;
153 StringRef(Val).split(PassNames, ',', -1, false);
154 for (auto PassName : PassNames)
155 RunPassNames->push_back(PassName);
160 static RunPassOption RunPassOpt;
162 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
164 cl::desc("Run compiler only for specified passes (comma separated list)"),
165 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
167 static int compileModule(char **, LLVMContext &);
169 static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
171 const char *ProgName) {
172 // If we don't yet have an output filename, make one.
173 if (OutputFilename.empty()) {
174 if (InputFilename == "-")
175 OutputFilename = "-";
177 // If InputFilename ends in .bc or .ll, remove it.
178 StringRef IFN = InputFilename;
179 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
180 OutputFilename = IFN.drop_back(3);
181 else if (IFN.endswith(".mir"))
182 OutputFilename = IFN.drop_back(4);
184 OutputFilename = IFN;
187 case TargetMachine::CGFT_AssemblyFile:
188 if (TargetName[0] == 'c') {
189 if (TargetName[1] == 0)
190 OutputFilename += ".cbe.c";
191 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
192 OutputFilename += ".cpp";
194 OutputFilename += ".s";
196 OutputFilename += ".s";
198 case TargetMachine::CGFT_ObjectFile:
199 if (OS == Triple::Win32)
200 OutputFilename += ".obj";
202 OutputFilename += ".o";
204 case TargetMachine::CGFT_Null:
205 OutputFilename += ".null";
211 // Decide if we need "binary" output.
214 case TargetMachine::CGFT_AssemblyFile:
216 case TargetMachine::CGFT_ObjectFile:
217 case TargetMachine::CGFT_Null:
224 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
226 OpenFlags |= sys::fs::F_Text;
227 auto FDOut = llvm::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
229 errs() << EC.message() << '\n';
236 struct LLCDiagnosticHandler : public DiagnosticHandler {
238 LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
239 bool handleDiagnostics(const DiagnosticInfo &DI) override {
240 if (DI.getSeverity() == DS_Error)
243 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
244 if (!Remark->isEnabled())
247 DiagnosticPrinterRawOStream DP(errs());
248 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
255 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
256 unsigned LocCookie) {
257 bool *HasError = static_cast<bool *>(Context);
258 if (SMD.getKind() == SourceMgr::DK_Error)
261 SMD.print(nullptr, errs());
263 // For testing purposes, we print the LocCookie here.
265 errs() << "note: !srcloc = " << LocCookie << "\n";
268 // main - Entry point for the llc compiler.
270 int main(int argc, char **argv) {
271 sys::PrintStackTraceOnErrorSignal(argv[0]);
272 PrettyStackTraceProgram X(argc, argv);
274 // Enable debug stream buffering.
275 EnableDebugBuffering = true;
278 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
280 // Initialize targets first, so that --version shows registered targets.
281 InitializeAllTargets();
282 InitializeAllTargetMCs();
283 InitializeAllAsmPrinters();
284 InitializeAllAsmParsers();
286 // Initialize codegen and IR passes used by llc so that the -print-after,
287 // -print-before, and -stop-after options work.
288 PassRegistry *Registry = PassRegistry::getPassRegistry();
289 initializeCore(*Registry);
290 initializeCodeGen(*Registry);
291 initializeLoopStrengthReducePass(*Registry);
292 initializeLowerIntrinsicsPass(*Registry);
293 initializeEntryExitInstrumenterPass(*Registry);
294 initializePostInlineEntryExitInstrumenterPass(*Registry);
295 initializeUnreachableBlockElimLegacyPassPass(*Registry);
296 initializeConstantHoistingLegacyPassPass(*Registry);
297 initializeScalarOpts(*Registry);
298 initializeVectorization(*Registry);
299 initializeScalarizeMaskedMemIntrinPass(*Registry);
300 initializeExpandReductionsPass(*Registry);
302 // Initialize debugging passes.
303 initializeScavengerTestPass(*Registry);
305 // Register the target printer for --version.
306 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
308 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
310 Context.setDiscardValueNames(DiscardValueNames);
312 // Set a diagnostic handler that doesn't exit on the first error
313 bool HasError = false;
314 Context.setDiagnosticHandler(
315 llvm::make_unique<LLCDiagnosticHandler>(&HasError));
316 Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
318 if (PassRemarksWithHotness)
319 Context.setDiagnosticsHotnessRequested(true);
321 if (PassRemarksHotnessThreshold)
322 Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold);
324 std::unique_ptr<ToolOutputFile> YamlFile;
325 if (RemarksFilename != "") {
328 llvm::make_unique<ToolOutputFile>(RemarksFilename, EC, sys::fs::F_None);
330 errs() << EC.message() << '\n';
333 Context.setDiagnosticsOutputFile(
334 llvm::make_unique<yaml::Output>(YamlFile->os()));
337 if (InputLanguage != "" && InputLanguage != "ir" &&
338 InputLanguage != "mir") {
339 errs() << argv[0] << "Input language must be '', 'IR' or 'MIR'\n";
343 // Compile the module TimeCompilations times to give better compile time
345 for (unsigned I = TimeCompilations; I; --I)
346 if (int RetVal = compileModule(argv, Context))
354 static bool addPass(PassManagerBase &PM, const char *argv0,
355 StringRef PassName, TargetPassConfig &TPC) {
356 if (PassName == "none")
359 const PassRegistry *PR = PassRegistry::getPassRegistry();
360 const PassInfo *PI = PR->getPassInfo(PassName);
362 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
367 if (PI->getNormalCtor())
368 P = PI->getNormalCtor()();
370 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
373 std::string Banner = std::string("After ") + std::string(P->getPassName());
375 TPC.printAndVerify(Banner);
380 static int compileModule(char **argv, LLVMContext &Context) {
381 // Load the module to be compiled...
383 std::unique_ptr<Module> M;
384 std::unique_ptr<MIRParser> MIR;
387 bool SkipModule = MCPU == "help" ||
388 (!MAttrs.empty() && MAttrs.front() == "help");
390 // If user just wants to list available options, skip module loading
392 if (InputLanguage == "mir" ||
393 (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
394 MIR = createMIRParserFromFile(InputFilename, Err, Context);
396 M = MIR->parseIRModule();
398 M = parseIRFile(InputFilename, Err, Context);
400 Err.print(argv[0], errs());
404 // Verify module immediately to catch problems before doInitialization() is
405 // called on any passes.
406 if (!NoVerify && verifyModule(*M, &errs())) {
407 errs() << argv[0] << ": " << InputFilename
408 << ": error: input module is broken!\n";
412 // If we are supposed to override the target triple, do so now.
413 if (!TargetTriple.empty())
414 M->setTargetTriple(Triple::normalize(TargetTriple));
415 TheTriple = Triple(M->getTargetTriple());
417 TheTriple = Triple(Triple::normalize(TargetTriple));
420 if (TheTriple.getTriple().empty())
421 TheTriple.setTriple(sys::getDefaultTargetTriple());
423 // Get the target specific parser.
425 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
428 errs() << argv[0] << ": " << Error;
432 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
434 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
437 errs() << argv[0] << ": invalid optimization level.\n";
440 case '0': OLvl = CodeGenOpt::None; break;
441 case '1': OLvl = CodeGenOpt::Less; break;
442 case '2': OLvl = CodeGenOpt::Default; break;
443 case '3': OLvl = CodeGenOpt::Aggressive; break;
446 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
447 Options.DisableIntegratedAS = NoIntegratedAssembler;
448 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
449 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
450 Options.MCOptions.AsmVerbose = AsmVerbose;
451 Options.MCOptions.PreserveAsmComments = PreserveComments;
452 Options.MCOptions.IASSearchPaths = IncludeDirs;
453 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
455 std::unique_ptr<TargetMachine> Target(TheTarget->createTargetMachine(
456 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, getRelocModel(),
457 getCodeModel(), OLvl));
459 assert(Target && "Could not allocate target machine!");
461 // If we don't have a module then just exit now. We do this down
462 // here since the CPU/Feature help is underneath the target machine
467 assert(M && "Should have exited if we didn't have a module!");
468 if (FloatABIForCalls != FloatABI::Default)
469 Options.FloatABIType = FloatABIForCalls;
471 // Figure out where we are going to send the output.
472 std::unique_ptr<ToolOutputFile> Out =
473 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
476 // Build up all of the passes that we want to do to the module.
477 legacy::PassManager PM;
479 // Add an appropriate TargetLibraryInfo pass for the module's triple.
480 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
482 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
483 if (DisableSimplifyLibCalls)
484 TLII.disableAllFunctions();
485 PM.add(new TargetLibraryInfoWrapperPass(TLII));
487 // Add the target data from the target machine, if it exists, or the module.
488 M->setDataLayout(Target->createDataLayout());
490 // Override function attributes based on CPUStr, FeaturesStr, and command line
492 setFunctionAttributes(CPUStr, FeaturesStr, *M);
494 if (RelaxAll.getNumOccurrences() > 0 &&
495 FileType != TargetMachine::CGFT_ObjectFile)
497 << ": warning: ignoring -mc-relax-all because filetype != obj";
500 raw_pwrite_stream *OS = &Out->os();
502 // Manually do the buffering rather than using buffer_ostream,
503 // so we can memcmp the contents in CompileTwice mode
504 SmallVector<char, 0> Buffer;
505 std::unique_ptr<raw_svector_ostream> BOS;
506 if ((FileType != TargetMachine::CGFT_AssemblyFile &&
507 !Out->os().supportsSeeking()) ||
509 BOS = make_unique<raw_svector_ostream>(Buffer);
513 const char *argv0 = argv[0];
514 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
515 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
517 // Construct a custom pass pipeline that starts after instruction
519 if (!RunPassNames->empty()) {
521 errs() << argv0 << ": run-pass is for .mir file only.\n";
524 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
525 if (TPC.hasLimitedCodeGenPipeline()) {
526 errs() << argv0 << ": run-pass cannot be used with "
527 << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
531 TPC.setDisableVerify(NoVerify);
534 TPC.printAndVerify("");
535 for (const std::string &RunPassName : *RunPassNames) {
536 if (addPass(PM, argv0, RunPassName, TPC))
539 TPC.setInitialized();
540 PM.add(createPrintMIRPass(*OS));
541 PM.add(createFreeMachineFunctionPass());
542 } else if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, MMI)) {
543 errs() << argv0 << ": target does not support generation of this"
549 assert(MMI && "Forgot to create MMI?");
550 if (MIR->parseMachineFunctions(*M, *MMI))
554 // Before executing passes, print the final values of the LLVM options.
555 cl::PrintOptionValues();
557 // If requested, run the pass manager over the same module again,
558 // to catch any bugs due to persistent state in the passes. Note that
559 // opt has the same functionality, so it may be worth abstracting this out
561 SmallVector<char, 0> CompileTwiceBuffer;
563 std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
565 CompileTwiceBuffer = Buffer;
572 ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
576 // Compare the two outputs and make sure they're the same
578 if (Buffer.size() != CompileTwiceBuffer.size() ||
579 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
582 << "Running the pass manager twice changed the output.\n"
583 "Writing the result of the second run to the specified output\n"
584 "To generate the one-run comparison binary, just run without\n"
585 "the compile-twice option\n";