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 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
67 static cl::opt<unsigned>
68 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
70 cl::desc("Repeat compilation N times for timing"));
73 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
74 cl::desc("Disable integrated assembler"));
77 PreserveComments("preserve-as-comments", cl::Hidden,
78 cl::desc("Preserve Comments in outputted assembly"),
81 // Determine optimization level.
84 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
90 static cl::opt<std::string>
91 TargetTriple("mtriple", cl::desc("Override target triple for module"));
93 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
94 cl::desc("Do not verify input module"));
96 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
97 cl::desc("Disable simplify-libcalls"));
99 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
100 cl::desc("Show encoding in .s output"));
102 static cl::opt<bool> EnableDwarfDirectory(
103 "enable-dwarf-directory", cl::Hidden,
104 cl::desc("Use .file directives with an explicit directory."));
106 static cl::opt<bool> AsmVerbose("asm-verbose",
107 cl::desc("Add comments to directives."),
111 CompileTwice("compile-twice", cl::Hidden,
112 cl::desc("Run everything twice, re-using the same pass "
113 "manager and verify the result is the same."),
116 static cl::opt<bool> DiscardValueNames(
117 "discard-value-names",
118 cl::desc("Discard names from Value (other than GlobalValue)."),
119 cl::init(false), cl::Hidden);
121 static cl::opt<std::string> StopBefore("stop-before",
122 cl::desc("Stop compilation before a specific pass"),
123 cl::value_desc("pass-name"), cl::init(""));
125 static cl::opt<std::string> StopAfter("stop-after",
126 cl::desc("Stop compilation after a specific pass"),
127 cl::value_desc("pass-name"), cl::init(""));
129 static cl::opt<std::string> StartBefore("start-before",
130 cl::desc("Resume compilation before a specific pass"),
131 cl::value_desc("pass-name"), cl::init(""));
133 static cl::opt<std::string> StartAfter("start-after",
134 cl::desc("Resume compilation after a specific pass"),
135 cl::value_desc("pass-name"), cl::init(""));
137 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
139 static cl::opt<bool> PassRemarksWithHotness(
140 "pass-remarks-with-hotness",
141 cl::desc("With PGO, include profile count in optimization remarks"),
144 static cl::opt<std::string>
145 RemarksFilename("pass-remarks-output",
146 cl::desc("YAML output filename for pass remarks"),
147 cl::value_desc("filename"));
150 static ManagedStatic<std::vector<std::string>> RunPassNames;
152 struct RunPassOption {
153 void operator=(const std::string &Val) const {
156 SmallVector<StringRef, 8> PassNames;
157 StringRef(Val).split(PassNames, ',', -1, false);
158 for (auto PassName : PassNames)
159 RunPassNames->push_back(PassName);
164 static RunPassOption RunPassOpt;
166 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
168 cl::desc("Run compiler only for specified passes (comma separated list)"),
169 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
171 static int compileModule(char **, LLVMContext &);
173 static std::unique_ptr<tool_output_file>
174 GetOutputStream(const char *TargetName, Triple::OSType OS,
175 const char *ProgName) {
176 // If we don't yet have an output filename, make one.
177 if (OutputFilename.empty()) {
178 if (InputFilename == "-")
179 OutputFilename = "-";
181 // If InputFilename ends in .bc or .ll, remove it.
182 StringRef IFN = InputFilename;
183 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
184 OutputFilename = IFN.drop_back(3);
185 else if (IFN.endswith(".mir"))
186 OutputFilename = IFN.drop_back(4);
188 OutputFilename = IFN;
191 case TargetMachine::CGFT_AssemblyFile:
192 if (TargetName[0] == 'c') {
193 if (TargetName[1] == 0)
194 OutputFilename += ".cbe.c";
195 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
196 OutputFilename += ".cpp";
198 OutputFilename += ".s";
200 OutputFilename += ".s";
202 case TargetMachine::CGFT_ObjectFile:
203 if (OS == Triple::Win32)
204 OutputFilename += ".obj";
206 OutputFilename += ".o";
208 case TargetMachine::CGFT_Null:
209 OutputFilename += ".null";
215 // Decide if we need "binary" output.
218 case TargetMachine::CGFT_AssemblyFile:
220 case TargetMachine::CGFT_ObjectFile:
221 case TargetMachine::CGFT_Null:
228 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
230 OpenFlags |= sys::fs::F_Text;
231 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
234 errs() << EC.message() << '\n';
241 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
242 bool *HasError = static_cast<bool *>(Context);
243 if (DI.getSeverity() == DS_Error)
246 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
247 if (!Remark->isEnabled())
250 DiagnosticPrinterRawOStream DP(errs());
251 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
256 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
257 unsigned LocCookie) {
258 bool *HasError = static_cast<bool *>(Context);
259 if (SMD.getKind() == SourceMgr::DK_Error)
262 SMD.print(nullptr, errs());
264 // For testing purposes, we print the LocCookie here.
266 errs() << "note: !srcloc = " << LocCookie << "\n";
269 // main - Entry point for the llc compiler.
271 int main(int argc, char **argv) {
272 sys::PrintStackTraceOnErrorSignal(argv[0]);
273 PrettyStackTraceProgram X(argc, argv);
275 // Enable debug stream buffering.
276 EnableDebugBuffering = true;
279 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
281 // Initialize targets first, so that --version shows registered targets.
282 InitializeAllTargets();
283 InitializeAllTargetMCs();
284 InitializeAllAsmPrinters();
285 InitializeAllAsmParsers();
287 // Initialize codegen and IR passes used by llc so that the -print-after,
288 // -print-before, and -stop-after options work.
289 PassRegistry *Registry = PassRegistry::getPassRegistry();
290 initializeCore(*Registry);
291 initializeCodeGen(*Registry);
292 initializeLoopStrengthReducePass(*Registry);
293 initializeLowerIntrinsicsPass(*Registry);
294 initializeCountingFunctionInserterPass(*Registry);
295 initializeUnreachableBlockElimLegacyPassPass(*Registry);
296 initializeConstantHoistingLegacyPassPass(*Registry);
297 initializeScalarOpts(*Registry);
298 initializeVectorization(*Registry);
300 // Register the target printer for --version.
301 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
303 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
305 Context.setDiscardValueNames(DiscardValueNames);
307 // Set a diagnostic handler that doesn't exit on the first error
308 bool HasError = false;
309 Context.setDiagnosticHandler(DiagnosticHandler, &HasError);
310 Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
312 if (PassRemarksWithHotness)
313 Context.setDiagnosticHotnessRequested(true);
315 std::unique_ptr<tool_output_file> YamlFile;
316 if (RemarksFilename != "") {
318 YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC,
321 errs() << EC.message() << '\n';
324 Context.setDiagnosticsOutputFile(
325 llvm::make_unique<yaml::Output>(YamlFile->os()));
328 // Compile the module TimeCompilations times to give better compile time
330 for (unsigned I = TimeCompilations; I; --I)
331 if (int RetVal = compileModule(argv, Context))
339 static bool addPass(PassManagerBase &PM, const char *argv0,
340 StringRef PassName, TargetPassConfig &TPC) {
341 if (PassName == "none")
344 const PassRegistry *PR = PassRegistry::getPassRegistry();
345 const PassInfo *PI = PR->getPassInfo(PassName);
347 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
352 if (PI->getTargetMachineCtor())
353 P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>());
354 else if (PI->getNormalCtor())
355 P = PI->getNormalCtor()();
357 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
360 std::string Banner = std::string("After ") + std::string(P->getPassName());
362 TPC.printAndVerify(Banner);
367 static AnalysisID getPassID(const char *argv0, const char *OptionName,
368 StringRef PassName) {
369 if (PassName.empty())
372 const PassRegistry &PR = *PassRegistry::getPassRegistry();
373 const PassInfo *PI = PR.getPassInfo(PassName);
375 errs() << argv0 << ": " << OptionName << " pass is not registered.\n";
378 return PI->getTypeInfo();
381 static int compileModule(char **argv, LLVMContext &Context) {
382 // Load the module to be compiled...
384 std::unique_ptr<Module> M;
385 std::unique_ptr<MIRParser> MIR;
388 bool SkipModule = MCPU == "help" ||
389 (!MAttrs.empty() && MAttrs.front() == "help");
391 // If user just wants to list available options, skip module loading
393 if (StringRef(InputFilename).endswith_lower(".mir")) {
394 MIR = createMIRParserFromFile(InputFilename, Err, Context);
396 M = MIR->parseLLVMModule();
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;
454 std::unique_ptr<TargetMachine> Target(
455 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
456 Options, getRelocModel(), CMModel, OLvl));
458 assert(Target && "Could not allocate target machine!");
460 // If we don't have a module then just exit now. We do this down
461 // here since the CPU/Feature help is underneath the target machine
466 assert(M && "Should have exited if we didn't have a module!");
467 if (FloatABIForCalls != FloatABI::Default)
468 Options.FloatABIType = FloatABIForCalls;
470 // Figure out where we are going to send the output.
471 std::unique_ptr<tool_output_file> Out =
472 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
475 // Build up all of the passes that we want to do to the module.
476 legacy::PassManager PM;
478 // Add an appropriate TargetLibraryInfo pass for the module's triple.
479 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
481 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
482 if (DisableSimplifyLibCalls)
483 TLII.disableAllFunctions();
484 PM.add(new TargetLibraryInfoWrapperPass(TLII));
486 // Add the target data from the target machine, if it exists, or the module.
487 M->setDataLayout(Target->createDataLayout());
489 // Override function attributes based on CPUStr, FeaturesStr, and command line
491 setFunctionAttributes(CPUStr, FeaturesStr, *M);
493 if (RelaxAll.getNumOccurrences() > 0 &&
494 FileType != TargetMachine::CGFT_ObjectFile)
496 << ": warning: ignoring -mc-relax-all because filetype != obj";
499 raw_pwrite_stream *OS = &Out->os();
501 // Manually do the buffering rather than using buffer_ostream,
502 // so we can memcmp the contents in CompileTwice mode
503 SmallVector<char, 0> Buffer;
504 std::unique_ptr<raw_svector_ostream> BOS;
505 if ((FileType != TargetMachine::CGFT_AssemblyFile &&
506 !Out->os().supportsSeeking()) ||
508 BOS = make_unique<raw_svector_ostream>(Buffer);
512 if (!RunPassNames->empty()) {
513 if (!StartAfter.empty() || !StopAfter.empty() || !StartBefore.empty() ||
514 !StopBefore.empty()) {
515 errs() << argv[0] << ": start-after and/or stop-after passes are "
516 "redundant when run-pass is specified.\n";
520 errs() << argv[0] << ": run-pass needs a .mir input.\n";
523 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
524 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
526 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
527 MMI->setMachineFunctionInitializer(MIR.get());
529 TPC.printAndVerify("");
531 for (const std::string &RunPassName : *RunPassNames) {
532 if (addPass(PM, argv[0], RunPassName, TPC))
535 PM.add(createPrintMIRPass(*OS));
537 const char *argv0 = argv[0];
538 AnalysisID StartBeforeID = getPassID(argv0, "start-before", StartBefore);
539 AnalysisID StartAfterID = getPassID(argv0, "start-after", StartAfter);
540 AnalysisID StopAfterID = getPassID(argv0, "stop-after", StopAfter);
541 AnalysisID StopBeforeID = getPassID(argv0, "stop-before", StopBefore);
543 if (StartBeforeID && StartAfterID) {
544 errs() << argv[0] << ": -start-before and -start-after specified!\n";
547 if (StopBeforeID && StopAfterID) {
548 errs() << argv[0] << ": -stop-before and -stop-after specified!\n";
552 // Ask the target to add backend passes as necessary.
553 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify,
554 StartBeforeID, StartAfterID, StopBeforeID,
555 StopAfterID, MIR.get())) {
556 errs() << argv[0] << ": target does not support generation of this"
562 // Before executing passes, print the final values of the LLVM options.
563 cl::PrintOptionValues();
565 // If requested, run the pass manager over the same module again,
566 // to catch any bugs due to persistent state in the passes. Note that
567 // opt has the same functionality, so it may be worth abstracting this out
569 SmallVector<char, 0> CompileTwiceBuffer;
571 std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
573 CompileTwiceBuffer = Buffer;
579 auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
583 // Compare the two outputs and make sure they're the same
585 if (Buffer.size() != CompileTwiceBuffer.size() ||
586 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
589 << "Running the pass manager twice changed the output.\n"
590 "Writing the result of the second run to the specified output\n"
591 "To generate the one-run comparison binary, just run without\n"
592 "the compile-twice option\n";