[lit] Remove LitTestCase
[llvm-complete.git] / tools / llc / llc.cpp
blobae51eef9e9ccfa570237e313be55474872386e0a
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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/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/InitLLVM.h"
44 #include "llvm/Support/ManagedStatic.h"
45 #include "llvm/Support/PluginLoader.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Support/WithColor.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Transforms/Utils/Cloning.h"
53 #include <memory>
54 using namespace llvm;
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<std::string>
70 SplitDwarfOutputFile("split-dwarf-output",
71 cl::desc(".dwo output filename"),
72 cl::value_desc("filename"));
74 static cl::opt<unsigned>
75 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
76 cl::value_desc("N"),
77 cl::desc("Repeat compilation N times for timing"));
79 static cl::opt<bool>
80 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
81 cl::desc("Disable integrated assembler"));
83 static cl::opt<bool>
84 PreserveComments("preserve-as-comments", cl::Hidden,
85 cl::desc("Preserve Comments in outputted assembly"),
86 cl::init(true));
88 // Determine optimization level.
89 static cl::opt<char>
90 OptLevel("O",
91 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
92 "(default = '-O2')"),
93 cl::Prefix,
94 cl::ZeroOrMore,
95 cl::init(' '));
97 static cl::opt<std::string>
98 TargetTriple("mtriple", cl::desc("Override target triple for module"));
100 static cl::opt<std::string> SplitDwarfFile(
101 "split-dwarf-file",
102 cl::desc(
103 "Specify the name of the .dwo file to encode in the DWARF output"));
105 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
106 cl::desc("Do not verify input module"));
108 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
109 cl::desc("Disable simplify-libcalls"));
111 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
112 cl::desc("Show encoding in .s output"));
114 static cl::opt<bool> EnableDwarfDirectory(
115 "enable-dwarf-directory", cl::Hidden,
116 cl::desc("Use .file directives with an explicit directory."));
118 static cl::opt<bool> AsmVerbose("asm-verbose",
119 cl::desc("Add comments to directives."),
120 cl::init(true));
122 static cl::opt<bool>
123 CompileTwice("compile-twice", cl::Hidden,
124 cl::desc("Run everything twice, re-using the same pass "
125 "manager and verify the result is the same."),
126 cl::init(false));
128 static cl::opt<bool> DiscardValueNames(
129 "discard-value-names",
130 cl::desc("Discard names from Value (other than GlobalValue)."),
131 cl::init(false), cl::Hidden);
133 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
135 static cl::opt<bool> PassRemarksWithHotness(
136 "pass-remarks-with-hotness",
137 cl::desc("With PGO, include profile count in optimization remarks"),
138 cl::Hidden);
140 static cl::opt<unsigned> PassRemarksHotnessThreshold(
141 "pass-remarks-hotness-threshold",
142 cl::desc("Minimum profile count required for an optimization remark to be output"),
143 cl::Hidden);
145 static cl::opt<std::string>
146 RemarksFilename("pass-remarks-output",
147 cl::desc("YAML output filename for pass remarks"),
148 cl::value_desc("filename"));
150 namespace {
151 static ManagedStatic<std::vector<std::string>> RunPassNames;
153 struct RunPassOption {
154 void operator=(const std::string &Val) const {
155 if (Val.empty())
156 return;
157 SmallVector<StringRef, 8> PassNames;
158 StringRef(Val).split(PassNames, ',', -1, false);
159 for (auto PassName : PassNames)
160 RunPassNames->push_back(PassName);
165 static RunPassOption RunPassOpt;
167 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
168 "run-pass",
169 cl::desc("Run compiler only for specified passes (comma separated list)"),
170 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
172 static int compileModule(char **, LLVMContext &);
174 static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
175 Triple::OSType OS,
176 const char *ProgName) {
177 // If we don't yet have an output filename, make one.
178 if (OutputFilename.empty()) {
179 if (InputFilename == "-")
180 OutputFilename = "-";
181 else {
182 // If InputFilename ends in .bc or .ll, remove it.
183 StringRef IFN = InputFilename;
184 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
185 OutputFilename = IFN.drop_back(3);
186 else if (IFN.endswith(".mir"))
187 OutputFilename = IFN.drop_back(4);
188 else
189 OutputFilename = IFN;
191 switch (FileType) {
192 case TargetMachine::CGFT_AssemblyFile:
193 if (TargetName[0] == 'c') {
194 if (TargetName[1] == 0)
195 OutputFilename += ".cbe.c";
196 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
197 OutputFilename += ".cpp";
198 else
199 OutputFilename += ".s";
200 } else
201 OutputFilename += ".s";
202 break;
203 case TargetMachine::CGFT_ObjectFile:
204 if (OS == Triple::Win32)
205 OutputFilename += ".obj";
206 else
207 OutputFilename += ".o";
208 break;
209 case TargetMachine::CGFT_Null:
210 OutputFilename += ".null";
211 break;
216 // Decide if we need "binary" output.
217 bool Binary = false;
218 switch (FileType) {
219 case TargetMachine::CGFT_AssemblyFile:
220 break;
221 case TargetMachine::CGFT_ObjectFile:
222 case TargetMachine::CGFT_Null:
223 Binary = true;
224 break;
227 // Open the file.
228 std::error_code EC;
229 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
230 if (!Binary)
231 OpenFlags |= sys::fs::F_Text;
232 auto FDOut = llvm::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
233 if (EC) {
234 WithColor::error() << EC.message() << '\n';
235 return nullptr;
238 return FDOut;
241 struct LLCDiagnosticHandler : public DiagnosticHandler {
242 bool *HasError;
243 LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
244 bool handleDiagnostics(const DiagnosticInfo &DI) override {
245 if (DI.getSeverity() == DS_Error)
246 *HasError = true;
248 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
249 if (!Remark->isEnabled())
250 return true;
252 DiagnosticPrinterRawOStream DP(errs());
253 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
254 DI.print(DP);
255 errs() << "\n";
256 return true;
260 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
261 unsigned LocCookie) {
262 bool *HasError = static_cast<bool *>(Context);
263 if (SMD.getKind() == SourceMgr::DK_Error)
264 *HasError = true;
266 SMD.print(nullptr, errs());
268 // For testing purposes, we print the LocCookie here.
269 if (LocCookie)
270 WithColor::note() << "!srcloc = " << LocCookie << "\n";
273 // main - Entry point for the llc compiler.
275 int main(int argc, char **argv) {
276 InitLLVM X(argc, argv);
278 // Enable debug stream buffering.
279 EnableDebugBuffering = true;
281 LLVMContext Context;
283 // Initialize targets first, so that --version shows registered targets.
284 InitializeAllTargets();
285 InitializeAllTargetMCs();
286 InitializeAllAsmPrinters();
287 InitializeAllAsmParsers();
289 // Initialize codegen and IR passes used by llc so that the -print-after,
290 // -print-before, and -stop-after options work.
291 PassRegistry *Registry = PassRegistry::getPassRegistry();
292 initializeCore(*Registry);
293 initializeCodeGen(*Registry);
294 initializeLoopStrengthReducePass(*Registry);
295 initializeLowerIntrinsicsPass(*Registry);
296 initializeEntryExitInstrumenterPass(*Registry);
297 initializePostInlineEntryExitInstrumenterPass(*Registry);
298 initializeUnreachableBlockElimLegacyPassPass(*Registry);
299 initializeConstantHoistingLegacyPassPass(*Registry);
300 initializeScalarOpts(*Registry);
301 initializeVectorization(*Registry);
302 initializeScalarizeMaskedMemIntrinPass(*Registry);
303 initializeExpandReductionsPass(*Registry);
305 // Initialize debugging passes.
306 initializeScavengerTestPass(*Registry);
308 // Register the target printer for --version.
309 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
311 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
313 Context.setDiscardValueNames(DiscardValueNames);
315 // Set a diagnostic handler that doesn't exit on the first error
316 bool HasError = false;
317 Context.setDiagnosticHandler(
318 llvm::make_unique<LLCDiagnosticHandler>(&HasError));
319 Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
321 if (PassRemarksWithHotness)
322 Context.setDiagnosticsHotnessRequested(true);
324 if (PassRemarksHotnessThreshold)
325 Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold);
327 std::unique_ptr<ToolOutputFile> YamlFile;
328 if (RemarksFilename != "") {
329 std::error_code EC;
330 YamlFile =
331 llvm::make_unique<ToolOutputFile>(RemarksFilename, EC, sys::fs::F_None);
332 if (EC) {
333 WithColor::error(errs(), argv[0]) << EC.message() << '\n';
334 return 1;
336 Context.setDiagnosticsOutputFile(
337 llvm::make_unique<yaml::Output>(YamlFile->os()));
340 if (InputLanguage != "" && InputLanguage != "ir" &&
341 InputLanguage != "mir") {
342 WithColor::error(errs(), argv[0])
343 << "input language must be '', 'IR' or 'MIR'\n";
344 return 1;
347 // Compile the module TimeCompilations times to give better compile time
348 // metrics.
349 for (unsigned I = TimeCompilations; I; --I)
350 if (int RetVal = compileModule(argv, Context))
351 return RetVal;
353 if (YamlFile)
354 YamlFile->keep();
355 return 0;
358 static bool addPass(PassManagerBase &PM, const char *argv0,
359 StringRef PassName, TargetPassConfig &TPC) {
360 if (PassName == "none")
361 return false;
363 const PassRegistry *PR = PassRegistry::getPassRegistry();
364 const PassInfo *PI = PR->getPassInfo(PassName);
365 if (!PI) {
366 WithColor::error(errs(), argv0)
367 << "run-pass " << PassName << " is not registered.\n";
368 return true;
371 Pass *P;
372 if (PI->getNormalCtor())
373 P = PI->getNormalCtor()();
374 else {
375 WithColor::error(errs(), argv0)
376 << "cannot create pass: " << PI->getPassName() << "\n";
377 return true;
379 std::string Banner = std::string("After ") + std::string(P->getPassName());
380 PM.add(P);
381 TPC.printAndVerify(Banner);
383 return false;
386 static int compileModule(char **argv, LLVMContext &Context) {
387 // Load the module to be compiled...
388 SMDiagnostic Err;
389 std::unique_ptr<Module> M;
390 std::unique_ptr<MIRParser> MIR;
391 Triple TheTriple;
393 bool SkipModule = MCPU == "help" ||
394 (!MAttrs.empty() && MAttrs.front() == "help");
396 // If user just wants to list available options, skip module loading
397 if (!SkipModule) {
398 if (InputLanguage == "mir" ||
399 (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
400 MIR = createMIRParserFromFile(InputFilename, Err, Context);
401 if (MIR)
402 M = MIR->parseIRModule();
403 } else
404 M = parseIRFile(InputFilename, Err, Context, false);
405 if (!M) {
406 Err.print(argv[0], WithColor::error(errs(), argv[0]));
407 return 1;
410 // If we are supposed to override the target triple, do so now.
411 if (!TargetTriple.empty())
412 M->setTargetTriple(Triple::normalize(TargetTriple));
413 TheTriple = Triple(M->getTargetTriple());
414 } else {
415 TheTriple = Triple(Triple::normalize(TargetTriple));
418 if (TheTriple.getTriple().empty())
419 TheTriple.setTriple(sys::getDefaultTargetTriple());
421 // Get the target specific parser.
422 std::string Error;
423 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
424 Error);
425 if (!TheTarget) {
426 WithColor::error(errs(), argv[0]) << Error;
427 return 1;
430 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
432 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
433 switch (OptLevel) {
434 default:
435 WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
436 return 1;
437 case ' ': break;
438 case '0': OLvl = CodeGenOpt::None; break;
439 case '1': OLvl = CodeGenOpt::Less; break;
440 case '2': OLvl = CodeGenOpt::Default; break;
441 case '3': OLvl = CodeGenOpt::Aggressive; break;
444 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
445 Options.DisableIntegratedAS = NoIntegratedAssembler;
446 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
447 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
448 Options.MCOptions.AsmVerbose = AsmVerbose;
449 Options.MCOptions.PreserveAsmComments = PreserveComments;
450 Options.MCOptions.IASSearchPaths = IncludeDirs;
451 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
453 std::unique_ptr<TargetMachine> Target(TheTarget->createTargetMachine(
454 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, getRelocModel(),
455 getCodeModel(), OLvl));
457 assert(Target && "Could not allocate target machine!");
459 // If we don't have a module then just exit now. We do this down
460 // here since the CPU/Feature help is underneath the target machine
461 // creation.
462 if (SkipModule)
463 return 0;
465 assert(M && "Should have exited if we didn't have a module!");
466 if (FloatABIForCalls != FloatABI::Default)
467 Options.FloatABIType = FloatABIForCalls;
469 // Figure out where we are going to send the output.
470 std::unique_ptr<ToolOutputFile> Out =
471 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
472 if (!Out) return 1;
474 std::unique_ptr<ToolOutputFile> DwoOut;
475 if (!SplitDwarfOutputFile.empty()) {
476 std::error_code EC;
477 DwoOut = llvm::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
478 sys::fs::F_None);
479 if (EC) {
480 WithColor::error(errs(), argv[0]) << EC.message() << '\n';
481 return 1;
485 // Build up all of the passes that we want to do to the module.
486 legacy::PassManager PM;
488 // Add an appropriate TargetLibraryInfo pass for the module's triple.
489 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
491 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
492 if (DisableSimplifyLibCalls)
493 TLII.disableAllFunctions();
494 PM.add(new TargetLibraryInfoWrapperPass(TLII));
496 // Add the target data from the target machine, if it exists, or the module.
497 M->setDataLayout(Target->createDataLayout());
499 // This needs to be done after setting datalayout since it calls verifier
500 // to check debug info whereas verifier relies on correct datalayout.
501 UpgradeDebugInfo(*M);
503 // Verify module immediately to catch problems before doInitialization() is
504 // called on any passes.
505 if (!NoVerify && verifyModule(*M, &errs())) {
506 std::string Prefix =
507 (Twine(argv[0]) + Twine(": ") + Twine(InputFilename)).str();
508 WithColor::error(errs(), Prefix) << "input module is broken!\n";
509 return 1;
512 // Override function attributes based on CPUStr, FeaturesStr, and command line
513 // flags.
514 setFunctionAttributes(CPUStr, FeaturesStr, *M);
516 if (RelaxAll.getNumOccurrences() > 0 &&
517 FileType != TargetMachine::CGFT_ObjectFile)
518 WithColor::warning(errs(), argv[0])
519 << ": warning: ignoring -mc-relax-all because filetype != obj";
522 raw_pwrite_stream *OS = &Out->os();
524 // Manually do the buffering rather than using buffer_ostream,
525 // so we can memcmp the contents in CompileTwice mode
526 SmallVector<char, 0> Buffer;
527 std::unique_ptr<raw_svector_ostream> BOS;
528 if ((FileType != TargetMachine::CGFT_AssemblyFile &&
529 !Out->os().supportsSeeking()) ||
530 CompileTwice) {
531 BOS = make_unique<raw_svector_ostream>(Buffer);
532 OS = BOS.get();
535 const char *argv0 = argv[0];
536 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
537 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
539 // Construct a custom pass pipeline that starts after instruction
540 // selection.
541 if (!RunPassNames->empty()) {
542 if (!MIR) {
543 WithColor::warning(errs(), argv[0])
544 << "run-pass is for .mir file only.\n";
545 return 1;
547 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
548 if (TPC.hasLimitedCodeGenPipeline()) {
549 WithColor::warning(errs(), argv[0])
550 << "run-pass cannot be used with "
551 << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
552 return 1;
555 TPC.setDisableVerify(NoVerify);
556 PM.add(&TPC);
557 PM.add(MMI);
558 TPC.printAndVerify("");
559 for (const std::string &RunPassName : *RunPassNames) {
560 if (addPass(PM, argv0, RunPassName, TPC))
561 return 1;
563 TPC.setInitialized();
564 PM.add(createPrintMIRPass(*OS));
565 PM.add(createFreeMachineFunctionPass());
566 } else if (Target->addPassesToEmitFile(PM, *OS,
567 DwoOut ? &DwoOut->os() : nullptr,
568 FileType, NoVerify, MMI)) {
569 WithColor::warning(errs(), argv[0])
570 << "target does not support generation of this"
571 << " file type!\n";
572 return 1;
575 if (MIR) {
576 assert(MMI && "Forgot to create MMI?");
577 if (MIR->parseMachineFunctions(*M, *MMI))
578 return 1;
581 // Before executing passes, print the final values of the LLVM options.
582 cl::PrintOptionValues();
584 // If requested, run the pass manager over the same module again,
585 // to catch any bugs due to persistent state in the passes. Note that
586 // opt has the same functionality, so it may be worth abstracting this out
587 // in the future.
588 SmallVector<char, 0> CompileTwiceBuffer;
589 if (CompileTwice) {
590 std::unique_ptr<Module> M2(llvm::CloneModule(*M));
591 PM.run(*M2);
592 CompileTwiceBuffer = Buffer;
593 Buffer.clear();
596 PM.run(*M);
598 auto HasError =
599 ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
600 if (*HasError)
601 return 1;
603 // Compare the two outputs and make sure they're the same
604 if (CompileTwice) {
605 if (Buffer.size() != CompileTwiceBuffer.size() ||
606 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
607 0)) {
608 errs()
609 << "Running the pass manager twice changed the output.\n"
610 "Writing the result of the second run to the specified output\n"
611 "To generate the one-run comparison binary, just run without\n"
612 "the compile-twice option\n";
613 Out->os() << Buffer;
614 Out->keep();
615 return 1;
619 if (BOS) {
620 Out->os() << Buffer;
624 // Declare success.
625 Out->keep();
626 if (DwoOut)
627 DwoOut->keep();
629 return 0;