10b57cec5SDimitry Andric //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // This is the llc code generator driver. It provides a convenient 100b57cec5SDimitry Andric // command-line interface for generating native assembly-language code 110b57cec5SDimitry Andric // or C code, given LLVM bitcode. 120b57cec5SDimitry Andric // 130b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 140b57cec5SDimitry Andric 150b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 160b57cec5SDimitry Andric #include "llvm/ADT/Triple.h" 170b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 180b57cec5SDimitry Andric #include "llvm/CodeGen/CommandFlags.inc" 190b57cec5SDimitry Andric #include "llvm/CodeGen/LinkAllAsmWriterComponents.h" 200b57cec5SDimitry Andric #include "llvm/CodeGen/LinkAllCodegenComponents.h" 210b57cec5SDimitry Andric #include "llvm/CodeGen/MIRParser/MIRParser.h" 220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h" 230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h" 240b57cec5SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h" 250b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h" 260b57cec5SDimitry Andric #include "llvm/IR/AutoUpgrade.h" 270b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h" 280b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h" 290b57cec5SDimitry Andric #include "llvm/IR/DiagnosticPrinter.h" 300b57cec5SDimitry Andric #include "llvm/IR/IRPrintingPasses.h" 310b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h" 320b57cec5SDimitry Andric #include "llvm/IR/LegacyPassManager.h" 330b57cec5SDimitry Andric #include "llvm/IR/Module.h" 340b57cec5SDimitry Andric #include "llvm/IR/RemarkStreamer.h" 350b57cec5SDimitry Andric #include "llvm/IR/Verifier.h" 360b57cec5SDimitry Andric #include "llvm/IRReader/IRReader.h" 37*480093f4SDimitry Andric #include "llvm/InitializePasses.h" 380b57cec5SDimitry Andric #include "llvm/MC/SubtargetFeature.h" 390b57cec5SDimitry Andric #include "llvm/Pass.h" 400b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h" 410b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 420b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h" 430b57cec5SDimitry Andric #include "llvm/Support/FormattedStream.h" 440b57cec5SDimitry Andric #include "llvm/Support/Host.h" 450b57cec5SDimitry Andric #include "llvm/Support/InitLLVM.h" 460b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h" 470b57cec5SDimitry Andric #include "llvm/Support/PluginLoader.h" 480b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h" 490b57cec5SDimitry Andric #include "llvm/Support/TargetRegistry.h" 500b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h" 510b57cec5SDimitry Andric #include "llvm/Support/ToolOutputFile.h" 520b57cec5SDimitry Andric #include "llvm/Support/WithColor.h" 530b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h" 540b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h" 550b57cec5SDimitry Andric #include <memory> 560b57cec5SDimitry Andric using namespace llvm; 570b57cec5SDimitry Andric 580b57cec5SDimitry Andric // General options for llc. Other pass-specific options are specified 590b57cec5SDimitry Andric // within the corresponding llc passes, and target-specific options 600b57cec5SDimitry Andric // and back-end code generation options are specified with the target machine. 610b57cec5SDimitry Andric // 620b57cec5SDimitry Andric static cl::opt<std::string> 630b57cec5SDimitry Andric InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 640b57cec5SDimitry Andric 650b57cec5SDimitry Andric static cl::opt<std::string> 660b57cec5SDimitry Andric InputLanguage("x", cl::desc("Input language ('ir' or 'mir')")); 670b57cec5SDimitry Andric 680b57cec5SDimitry Andric static cl::opt<std::string> 690b57cec5SDimitry Andric OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 700b57cec5SDimitry Andric 710b57cec5SDimitry Andric static cl::opt<std::string> 720b57cec5SDimitry Andric SplitDwarfOutputFile("split-dwarf-output", 730b57cec5SDimitry Andric cl::desc(".dwo output filename"), 740b57cec5SDimitry Andric cl::value_desc("filename")); 750b57cec5SDimitry Andric 760b57cec5SDimitry Andric static cl::opt<unsigned> 770b57cec5SDimitry Andric TimeCompilations("time-compilations", cl::Hidden, cl::init(1u), 780b57cec5SDimitry Andric cl::value_desc("N"), 790b57cec5SDimitry Andric cl::desc("Repeat compilation N times for timing")); 800b57cec5SDimitry Andric 810b57cec5SDimitry Andric static cl::opt<bool> 820b57cec5SDimitry Andric NoIntegratedAssembler("no-integrated-as", cl::Hidden, 830b57cec5SDimitry Andric cl::desc("Disable integrated assembler")); 840b57cec5SDimitry Andric 850b57cec5SDimitry Andric static cl::opt<bool> 860b57cec5SDimitry Andric PreserveComments("preserve-as-comments", cl::Hidden, 870b57cec5SDimitry Andric cl::desc("Preserve Comments in outputted assembly"), 880b57cec5SDimitry Andric cl::init(true)); 890b57cec5SDimitry Andric 900b57cec5SDimitry Andric // Determine optimization level. 910b57cec5SDimitry Andric static cl::opt<char> 920b57cec5SDimitry Andric OptLevel("O", 930b57cec5SDimitry Andric cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 940b57cec5SDimitry Andric "(default = '-O2')"), 950b57cec5SDimitry Andric cl::Prefix, 960b57cec5SDimitry Andric cl::ZeroOrMore, 970b57cec5SDimitry Andric cl::init(' ')); 980b57cec5SDimitry Andric 990b57cec5SDimitry Andric static cl::opt<std::string> 1000b57cec5SDimitry Andric TargetTriple("mtriple", cl::desc("Override target triple for module")); 1010b57cec5SDimitry Andric 1020b57cec5SDimitry Andric static cl::opt<std::string> SplitDwarfFile( 1030b57cec5SDimitry Andric "split-dwarf-file", 1040b57cec5SDimitry Andric cl::desc( 1050b57cec5SDimitry Andric "Specify the name of the .dwo file to encode in the DWARF output")); 1060b57cec5SDimitry Andric 1070b57cec5SDimitry Andric static cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 1080b57cec5SDimitry Andric cl::desc("Do not verify input module")); 1090b57cec5SDimitry Andric 1100b57cec5SDimitry Andric static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls", 1110b57cec5SDimitry Andric cl::desc("Disable simplify-libcalls")); 1120b57cec5SDimitry Andric 1130b57cec5SDimitry Andric static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, 1140b57cec5SDimitry Andric cl::desc("Show encoding in .s output")); 1150b57cec5SDimitry Andric 1160b57cec5SDimitry Andric static cl::opt<bool> EnableDwarfDirectory( 1170b57cec5SDimitry Andric "enable-dwarf-directory", cl::Hidden, 1180b57cec5SDimitry Andric cl::desc("Use .file directives with an explicit directory.")); 1190b57cec5SDimitry Andric 1200b57cec5SDimitry Andric static cl::opt<bool> AsmVerbose("asm-verbose", 1210b57cec5SDimitry Andric cl::desc("Add comments to directives."), 1220b57cec5SDimitry Andric cl::init(true)); 1230b57cec5SDimitry Andric 1240b57cec5SDimitry Andric static cl::opt<bool> 1250b57cec5SDimitry Andric CompileTwice("compile-twice", cl::Hidden, 1260b57cec5SDimitry Andric cl::desc("Run everything twice, re-using the same pass " 1270b57cec5SDimitry Andric "manager and verify the result is the same."), 1280b57cec5SDimitry Andric cl::init(false)); 1290b57cec5SDimitry Andric 1300b57cec5SDimitry Andric static cl::opt<bool> DiscardValueNames( 1310b57cec5SDimitry Andric "discard-value-names", 1320b57cec5SDimitry Andric cl::desc("Discard names from Value (other than GlobalValue)."), 1330b57cec5SDimitry Andric cl::init(false), cl::Hidden); 1340b57cec5SDimitry Andric 1350b57cec5SDimitry Andric static cl::list<std::string> IncludeDirs("I", cl::desc("include search path")); 1360b57cec5SDimitry Andric 1370b57cec5SDimitry Andric static cl::opt<bool> RemarksWithHotness( 1380b57cec5SDimitry Andric "pass-remarks-with-hotness", 1390b57cec5SDimitry Andric cl::desc("With PGO, include profile count in optimization remarks"), 1400b57cec5SDimitry Andric cl::Hidden); 1410b57cec5SDimitry Andric 1420b57cec5SDimitry Andric static cl::opt<unsigned> 1430b57cec5SDimitry Andric RemarksHotnessThreshold("pass-remarks-hotness-threshold", 1440b57cec5SDimitry Andric cl::desc("Minimum profile count required for " 1450b57cec5SDimitry Andric "an optimization remark to be output"), 1460b57cec5SDimitry Andric cl::Hidden); 1470b57cec5SDimitry Andric 1480b57cec5SDimitry Andric static cl::opt<std::string> 1490b57cec5SDimitry Andric RemarksFilename("pass-remarks-output", 1500b57cec5SDimitry Andric cl::desc("Output filename for pass remarks"), 1510b57cec5SDimitry Andric cl::value_desc("filename")); 1520b57cec5SDimitry Andric 1530b57cec5SDimitry Andric static cl::opt<std::string> 1540b57cec5SDimitry Andric RemarksPasses("pass-remarks-filter", 1550b57cec5SDimitry Andric cl::desc("Only record optimization remarks from passes whose " 1560b57cec5SDimitry Andric "names match the given regular expression"), 1570b57cec5SDimitry Andric cl::value_desc("regex")); 1580b57cec5SDimitry Andric 1590b57cec5SDimitry Andric static cl::opt<std::string> RemarksFormat( 1600b57cec5SDimitry Andric "pass-remarks-format", 1610b57cec5SDimitry Andric cl::desc("The format used for serializing remarks (default: YAML)"), 1620b57cec5SDimitry Andric cl::value_desc("format"), cl::init("yaml")); 1630b57cec5SDimitry Andric 1640b57cec5SDimitry Andric namespace { 1650b57cec5SDimitry Andric static ManagedStatic<std::vector<std::string>> RunPassNames; 1660b57cec5SDimitry Andric 1670b57cec5SDimitry Andric struct RunPassOption { 1680b57cec5SDimitry Andric void operator=(const std::string &Val) const { 1690b57cec5SDimitry Andric if (Val.empty()) 1700b57cec5SDimitry Andric return; 1710b57cec5SDimitry Andric SmallVector<StringRef, 8> PassNames; 1720b57cec5SDimitry Andric StringRef(Val).split(PassNames, ',', -1, false); 1730b57cec5SDimitry Andric for (auto PassName : PassNames) 1740b57cec5SDimitry Andric RunPassNames->push_back(PassName); 1750b57cec5SDimitry Andric } 1760b57cec5SDimitry Andric }; 1770b57cec5SDimitry Andric } 1780b57cec5SDimitry Andric 1790b57cec5SDimitry Andric static RunPassOption RunPassOpt; 1800b57cec5SDimitry Andric 1810b57cec5SDimitry Andric static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass( 1820b57cec5SDimitry Andric "run-pass", 1830b57cec5SDimitry Andric cl::desc("Run compiler only for specified passes (comma separated list)"), 1840b57cec5SDimitry Andric cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt)); 1850b57cec5SDimitry Andric 1860b57cec5SDimitry Andric static int compileModule(char **, LLVMContext &); 1870b57cec5SDimitry Andric 1880b57cec5SDimitry Andric static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName, 1890b57cec5SDimitry Andric Triple::OSType OS, 1900b57cec5SDimitry Andric const char *ProgName) { 1910b57cec5SDimitry Andric // If we don't yet have an output filename, make one. 1920b57cec5SDimitry Andric if (OutputFilename.empty()) { 1930b57cec5SDimitry Andric if (InputFilename == "-") 1940b57cec5SDimitry Andric OutputFilename = "-"; 1950b57cec5SDimitry Andric else { 1960b57cec5SDimitry Andric // If InputFilename ends in .bc or .ll, remove it. 1970b57cec5SDimitry Andric StringRef IFN = InputFilename; 1980b57cec5SDimitry Andric if (IFN.endswith(".bc") || IFN.endswith(".ll")) 1990b57cec5SDimitry Andric OutputFilename = IFN.drop_back(3); 2000b57cec5SDimitry Andric else if (IFN.endswith(".mir")) 2010b57cec5SDimitry Andric OutputFilename = IFN.drop_back(4); 2020b57cec5SDimitry Andric else 2030b57cec5SDimitry Andric OutputFilename = IFN; 2040b57cec5SDimitry Andric 2050b57cec5SDimitry Andric switch (FileType) { 206*480093f4SDimitry Andric case CGFT_AssemblyFile: 2070b57cec5SDimitry Andric if (TargetName[0] == 'c') { 2080b57cec5SDimitry Andric if (TargetName[1] == 0) 2090b57cec5SDimitry Andric OutputFilename += ".cbe.c"; 2100b57cec5SDimitry Andric else if (TargetName[1] == 'p' && TargetName[2] == 'p') 2110b57cec5SDimitry Andric OutputFilename += ".cpp"; 2120b57cec5SDimitry Andric else 2130b57cec5SDimitry Andric OutputFilename += ".s"; 2140b57cec5SDimitry Andric } else 2150b57cec5SDimitry Andric OutputFilename += ".s"; 2160b57cec5SDimitry Andric break; 217*480093f4SDimitry Andric case CGFT_ObjectFile: 2180b57cec5SDimitry Andric if (OS == Triple::Win32) 2190b57cec5SDimitry Andric OutputFilename += ".obj"; 2200b57cec5SDimitry Andric else 2210b57cec5SDimitry Andric OutputFilename += ".o"; 2220b57cec5SDimitry Andric break; 223*480093f4SDimitry Andric case CGFT_Null: 2240b57cec5SDimitry Andric OutputFilename += ".null"; 2250b57cec5SDimitry Andric break; 2260b57cec5SDimitry Andric } 2270b57cec5SDimitry Andric } 2280b57cec5SDimitry Andric } 2290b57cec5SDimitry Andric 2300b57cec5SDimitry Andric // Decide if we need "binary" output. 2310b57cec5SDimitry Andric bool Binary = false; 2320b57cec5SDimitry Andric switch (FileType) { 233*480093f4SDimitry Andric case CGFT_AssemblyFile: 2340b57cec5SDimitry Andric break; 235*480093f4SDimitry Andric case CGFT_ObjectFile: 236*480093f4SDimitry Andric case CGFT_Null: 2370b57cec5SDimitry Andric Binary = true; 2380b57cec5SDimitry Andric break; 2390b57cec5SDimitry Andric } 2400b57cec5SDimitry Andric 2410b57cec5SDimitry Andric // Open the file. 2420b57cec5SDimitry Andric std::error_code EC; 2438bcb0991SDimitry Andric sys::fs::OpenFlags OpenFlags = sys::fs::OF_None; 2440b57cec5SDimitry Andric if (!Binary) 2458bcb0991SDimitry Andric OpenFlags |= sys::fs::OF_Text; 2468bcb0991SDimitry Andric auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags); 2470b57cec5SDimitry Andric if (EC) { 2480b57cec5SDimitry Andric WithColor::error() << EC.message() << '\n'; 2490b57cec5SDimitry Andric return nullptr; 2500b57cec5SDimitry Andric } 2510b57cec5SDimitry Andric 2520b57cec5SDimitry Andric return FDOut; 2530b57cec5SDimitry Andric } 2540b57cec5SDimitry Andric 2550b57cec5SDimitry Andric struct LLCDiagnosticHandler : public DiagnosticHandler { 2560b57cec5SDimitry Andric bool *HasError; 2570b57cec5SDimitry Andric LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {} 2580b57cec5SDimitry Andric bool handleDiagnostics(const DiagnosticInfo &DI) override { 2590b57cec5SDimitry Andric if (DI.getSeverity() == DS_Error) 2600b57cec5SDimitry Andric *HasError = true; 2610b57cec5SDimitry Andric 2620b57cec5SDimitry Andric if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI)) 2630b57cec5SDimitry Andric if (!Remark->isEnabled()) 2640b57cec5SDimitry Andric return true; 2650b57cec5SDimitry Andric 2660b57cec5SDimitry Andric DiagnosticPrinterRawOStream DP(errs()); 2670b57cec5SDimitry Andric errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": "; 2680b57cec5SDimitry Andric DI.print(DP); 2690b57cec5SDimitry Andric errs() << "\n"; 2700b57cec5SDimitry Andric return true; 2710b57cec5SDimitry Andric } 2720b57cec5SDimitry Andric }; 2730b57cec5SDimitry Andric 2740b57cec5SDimitry Andric static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context, 2750b57cec5SDimitry Andric unsigned LocCookie) { 2760b57cec5SDimitry Andric bool *HasError = static_cast<bool *>(Context); 2770b57cec5SDimitry Andric if (SMD.getKind() == SourceMgr::DK_Error) 2780b57cec5SDimitry Andric *HasError = true; 2790b57cec5SDimitry Andric 2800b57cec5SDimitry Andric SMD.print(nullptr, errs()); 2810b57cec5SDimitry Andric 2820b57cec5SDimitry Andric // For testing purposes, we print the LocCookie here. 2830b57cec5SDimitry Andric if (LocCookie) 2840b57cec5SDimitry Andric WithColor::note() << "!srcloc = " << LocCookie << "\n"; 2850b57cec5SDimitry Andric } 2860b57cec5SDimitry Andric 2870b57cec5SDimitry Andric // main - Entry point for the llc compiler. 2880b57cec5SDimitry Andric // 2890b57cec5SDimitry Andric int main(int argc, char **argv) { 2900b57cec5SDimitry Andric InitLLVM X(argc, argv); 2910b57cec5SDimitry Andric 2920b57cec5SDimitry Andric // Enable debug stream buffering. 2930b57cec5SDimitry Andric EnableDebugBuffering = true; 2940b57cec5SDimitry Andric 2950b57cec5SDimitry Andric LLVMContext Context; 2960b57cec5SDimitry Andric 2970b57cec5SDimitry Andric // Initialize targets first, so that --version shows registered targets. 2980b57cec5SDimitry Andric InitializeAllTargets(); 2990b57cec5SDimitry Andric InitializeAllTargetMCs(); 3000b57cec5SDimitry Andric InitializeAllAsmPrinters(); 3010b57cec5SDimitry Andric InitializeAllAsmParsers(); 3020b57cec5SDimitry Andric 3030b57cec5SDimitry Andric // Initialize codegen and IR passes used by llc so that the -print-after, 3040b57cec5SDimitry Andric // -print-before, and -stop-after options work. 3050b57cec5SDimitry Andric PassRegistry *Registry = PassRegistry::getPassRegistry(); 3060b57cec5SDimitry Andric initializeCore(*Registry); 3070b57cec5SDimitry Andric initializeCodeGen(*Registry); 3080b57cec5SDimitry Andric initializeLoopStrengthReducePass(*Registry); 3090b57cec5SDimitry Andric initializeLowerIntrinsicsPass(*Registry); 3100b57cec5SDimitry Andric initializeEntryExitInstrumenterPass(*Registry); 3110b57cec5SDimitry Andric initializePostInlineEntryExitInstrumenterPass(*Registry); 3120b57cec5SDimitry Andric initializeUnreachableBlockElimLegacyPassPass(*Registry); 3130b57cec5SDimitry Andric initializeConstantHoistingLegacyPassPass(*Registry); 3140b57cec5SDimitry Andric initializeScalarOpts(*Registry); 3150b57cec5SDimitry Andric initializeVectorization(*Registry); 3160b57cec5SDimitry Andric initializeScalarizeMaskedMemIntrinPass(*Registry); 3170b57cec5SDimitry Andric initializeExpandReductionsPass(*Registry); 3180b57cec5SDimitry Andric initializeHardwareLoopsPass(*Registry); 3190b57cec5SDimitry Andric 3200b57cec5SDimitry Andric // Initialize debugging passes. 3210b57cec5SDimitry Andric initializeScavengerTestPass(*Registry); 3220b57cec5SDimitry Andric 3230b57cec5SDimitry Andric // Register the target printer for --version. 3240b57cec5SDimitry Andric cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 3250b57cec5SDimitry Andric 3260b57cec5SDimitry Andric cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 3270b57cec5SDimitry Andric 3280b57cec5SDimitry Andric Context.setDiscardValueNames(DiscardValueNames); 3290b57cec5SDimitry Andric 3300b57cec5SDimitry Andric // Set a diagnostic handler that doesn't exit on the first error 3310b57cec5SDimitry Andric bool HasError = false; 3320b57cec5SDimitry Andric Context.setDiagnosticHandler( 3338bcb0991SDimitry Andric std::make_unique<LLCDiagnosticHandler>(&HasError)); 3340b57cec5SDimitry Andric Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError); 3350b57cec5SDimitry Andric 3360b57cec5SDimitry Andric Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr = 3370b57cec5SDimitry Andric setupOptimizationRemarks(Context, RemarksFilename, RemarksPasses, 3380b57cec5SDimitry Andric RemarksFormat, RemarksWithHotness, 3390b57cec5SDimitry Andric RemarksHotnessThreshold); 3400b57cec5SDimitry Andric if (Error E = RemarksFileOrErr.takeError()) { 3410b57cec5SDimitry Andric WithColor::error(errs(), argv[0]) << toString(std::move(E)) << '\n'; 3420b57cec5SDimitry Andric return 1; 3430b57cec5SDimitry Andric } 3440b57cec5SDimitry Andric std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr); 3450b57cec5SDimitry Andric 3460b57cec5SDimitry Andric if (InputLanguage != "" && InputLanguage != "ir" && 3470b57cec5SDimitry Andric InputLanguage != "mir") { 3480b57cec5SDimitry Andric WithColor::error(errs(), argv[0]) 3490b57cec5SDimitry Andric << "input language must be '', 'IR' or 'MIR'\n"; 3500b57cec5SDimitry Andric return 1; 3510b57cec5SDimitry Andric } 3520b57cec5SDimitry Andric 3530b57cec5SDimitry Andric // Compile the module TimeCompilations times to give better compile time 3540b57cec5SDimitry Andric // metrics. 3550b57cec5SDimitry Andric for (unsigned I = TimeCompilations; I; --I) 3560b57cec5SDimitry Andric if (int RetVal = compileModule(argv, Context)) 3570b57cec5SDimitry Andric return RetVal; 3580b57cec5SDimitry Andric 3590b57cec5SDimitry Andric if (RemarksFile) 3600b57cec5SDimitry Andric RemarksFile->keep(); 3610b57cec5SDimitry Andric return 0; 3620b57cec5SDimitry Andric } 3630b57cec5SDimitry Andric 3640b57cec5SDimitry Andric static bool addPass(PassManagerBase &PM, const char *argv0, 3650b57cec5SDimitry Andric StringRef PassName, TargetPassConfig &TPC) { 3660b57cec5SDimitry Andric if (PassName == "none") 3670b57cec5SDimitry Andric return false; 3680b57cec5SDimitry Andric 3690b57cec5SDimitry Andric const PassRegistry *PR = PassRegistry::getPassRegistry(); 3700b57cec5SDimitry Andric const PassInfo *PI = PR->getPassInfo(PassName); 3710b57cec5SDimitry Andric if (!PI) { 3720b57cec5SDimitry Andric WithColor::error(errs(), argv0) 3730b57cec5SDimitry Andric << "run-pass " << PassName << " is not registered.\n"; 3740b57cec5SDimitry Andric return true; 3750b57cec5SDimitry Andric } 3760b57cec5SDimitry Andric 3770b57cec5SDimitry Andric Pass *P; 3780b57cec5SDimitry Andric if (PI->getNormalCtor()) 3790b57cec5SDimitry Andric P = PI->getNormalCtor()(); 3800b57cec5SDimitry Andric else { 3810b57cec5SDimitry Andric WithColor::error(errs(), argv0) 3820b57cec5SDimitry Andric << "cannot create pass: " << PI->getPassName() << "\n"; 3830b57cec5SDimitry Andric return true; 3840b57cec5SDimitry Andric } 3850b57cec5SDimitry Andric std::string Banner = std::string("After ") + std::string(P->getPassName()); 3860b57cec5SDimitry Andric PM.add(P); 3870b57cec5SDimitry Andric TPC.printAndVerify(Banner); 3880b57cec5SDimitry Andric 3890b57cec5SDimitry Andric return false; 3900b57cec5SDimitry Andric } 3910b57cec5SDimitry Andric 3920b57cec5SDimitry Andric static int compileModule(char **argv, LLVMContext &Context) { 3930b57cec5SDimitry Andric // Load the module to be compiled... 3940b57cec5SDimitry Andric SMDiagnostic Err; 3950b57cec5SDimitry Andric std::unique_ptr<Module> M; 3960b57cec5SDimitry Andric std::unique_ptr<MIRParser> MIR; 3970b57cec5SDimitry Andric Triple TheTriple; 398*480093f4SDimitry Andric std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr(); 399*480093f4SDimitry Andric 400*480093f4SDimitry Andric // Set attributes on functions as loaded from MIR from command line arguments. 401*480093f4SDimitry Andric auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) { 402*480093f4SDimitry Andric setFunctionAttributes(CPUStr, FeaturesStr, F); 403*480093f4SDimitry Andric }; 4040b57cec5SDimitry Andric 4050b57cec5SDimitry Andric bool SkipModule = MCPU == "help" || 4060b57cec5SDimitry Andric (!MAttrs.empty() && MAttrs.front() == "help"); 4070b57cec5SDimitry Andric 4080b57cec5SDimitry Andric // If user just wants to list available options, skip module loading 4090b57cec5SDimitry Andric if (!SkipModule) { 4100b57cec5SDimitry Andric if (InputLanguage == "mir" || 4110b57cec5SDimitry Andric (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) { 412*480093f4SDimitry Andric MIR = createMIRParserFromFile(InputFilename, Err, Context, 413*480093f4SDimitry Andric setMIRFunctionAttributes); 4140b57cec5SDimitry Andric if (MIR) 4150b57cec5SDimitry Andric M = MIR->parseIRModule(); 4160b57cec5SDimitry Andric } else 4170b57cec5SDimitry Andric M = parseIRFile(InputFilename, Err, Context, false); 4180b57cec5SDimitry Andric if (!M) { 4190b57cec5SDimitry Andric Err.print(argv[0], WithColor::error(errs(), argv[0])); 4200b57cec5SDimitry Andric return 1; 4210b57cec5SDimitry Andric } 4220b57cec5SDimitry Andric 4230b57cec5SDimitry Andric // If we are supposed to override the target triple, do so now. 4240b57cec5SDimitry Andric if (!TargetTriple.empty()) 4250b57cec5SDimitry Andric M->setTargetTriple(Triple::normalize(TargetTriple)); 4260b57cec5SDimitry Andric TheTriple = Triple(M->getTargetTriple()); 4270b57cec5SDimitry Andric } else { 4280b57cec5SDimitry Andric TheTriple = Triple(Triple::normalize(TargetTriple)); 4290b57cec5SDimitry Andric } 4300b57cec5SDimitry Andric 4310b57cec5SDimitry Andric if (TheTriple.getTriple().empty()) 4320b57cec5SDimitry Andric TheTriple.setTriple(sys::getDefaultTargetTriple()); 4330b57cec5SDimitry Andric 4340b57cec5SDimitry Andric // Get the target specific parser. 4350b57cec5SDimitry Andric std::string Error; 4360b57cec5SDimitry Andric const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 4370b57cec5SDimitry Andric Error); 4380b57cec5SDimitry Andric if (!TheTarget) { 4390b57cec5SDimitry Andric WithColor::error(errs(), argv[0]) << Error; 4400b57cec5SDimitry Andric return 1; 4410b57cec5SDimitry Andric } 4420b57cec5SDimitry Andric 4430b57cec5SDimitry Andric CodeGenOpt::Level OLvl = CodeGenOpt::Default; 4440b57cec5SDimitry Andric switch (OptLevel) { 4450b57cec5SDimitry Andric default: 4460b57cec5SDimitry Andric WithColor::error(errs(), argv[0]) << "invalid optimization level.\n"; 4470b57cec5SDimitry Andric return 1; 4480b57cec5SDimitry Andric case ' ': break; 4490b57cec5SDimitry Andric case '0': OLvl = CodeGenOpt::None; break; 4500b57cec5SDimitry Andric case '1': OLvl = CodeGenOpt::Less; break; 4510b57cec5SDimitry Andric case '2': OLvl = CodeGenOpt::Default; break; 4520b57cec5SDimitry Andric case '3': OLvl = CodeGenOpt::Aggressive; break; 4530b57cec5SDimitry Andric } 4540b57cec5SDimitry Andric 4550b57cec5SDimitry Andric TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); 4560b57cec5SDimitry Andric Options.DisableIntegratedAS = NoIntegratedAssembler; 4570b57cec5SDimitry Andric Options.MCOptions.ShowMCEncoding = ShowMCEncoding; 4580b57cec5SDimitry Andric Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory; 4590b57cec5SDimitry Andric Options.MCOptions.AsmVerbose = AsmVerbose; 4600b57cec5SDimitry Andric Options.MCOptions.PreserveAsmComments = PreserveComments; 4610b57cec5SDimitry Andric Options.MCOptions.IASSearchPaths = IncludeDirs; 4620b57cec5SDimitry Andric Options.MCOptions.SplitDwarfFile = SplitDwarfFile; 4630b57cec5SDimitry Andric 4640b57cec5SDimitry Andric std::unique_ptr<TargetMachine> Target(TheTarget->createTargetMachine( 4650b57cec5SDimitry Andric TheTriple.getTriple(), CPUStr, FeaturesStr, Options, getRelocModel(), 4660b57cec5SDimitry Andric getCodeModel(), OLvl)); 4670b57cec5SDimitry Andric 4680b57cec5SDimitry Andric assert(Target && "Could not allocate target machine!"); 4690b57cec5SDimitry Andric 4700b57cec5SDimitry Andric // If we don't have a module then just exit now. We do this down 4710b57cec5SDimitry Andric // here since the CPU/Feature help is underneath the target machine 4720b57cec5SDimitry Andric // creation. 4730b57cec5SDimitry Andric if (SkipModule) 4740b57cec5SDimitry Andric return 0; 4750b57cec5SDimitry Andric 4760b57cec5SDimitry Andric assert(M && "Should have exited if we didn't have a module!"); 4770b57cec5SDimitry Andric if (FloatABIForCalls != FloatABI::Default) 4780b57cec5SDimitry Andric Options.FloatABIType = FloatABIForCalls; 4790b57cec5SDimitry Andric 4800b57cec5SDimitry Andric // Figure out where we are going to send the output. 4810b57cec5SDimitry Andric std::unique_ptr<ToolOutputFile> Out = 4820b57cec5SDimitry Andric GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]); 4830b57cec5SDimitry Andric if (!Out) return 1; 4840b57cec5SDimitry Andric 4850b57cec5SDimitry Andric std::unique_ptr<ToolOutputFile> DwoOut; 4860b57cec5SDimitry Andric if (!SplitDwarfOutputFile.empty()) { 4870b57cec5SDimitry Andric std::error_code EC; 4888bcb0991SDimitry Andric DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC, 4898bcb0991SDimitry Andric sys::fs::OF_None); 4900b57cec5SDimitry Andric if (EC) { 4910b57cec5SDimitry Andric WithColor::error(errs(), argv[0]) << EC.message() << '\n'; 4920b57cec5SDimitry Andric return 1; 4930b57cec5SDimitry Andric } 4940b57cec5SDimitry Andric } 4950b57cec5SDimitry Andric 4960b57cec5SDimitry Andric // Build up all of the passes that we want to do to the module. 4970b57cec5SDimitry Andric legacy::PassManager PM; 4980b57cec5SDimitry Andric 4990b57cec5SDimitry Andric // Add an appropriate TargetLibraryInfo pass for the module's triple. 5000b57cec5SDimitry Andric TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple())); 5010b57cec5SDimitry Andric 5020b57cec5SDimitry Andric // The -disable-simplify-libcalls flag actually disables all builtin optzns. 5030b57cec5SDimitry Andric if (DisableSimplifyLibCalls) 5040b57cec5SDimitry Andric TLII.disableAllFunctions(); 5050b57cec5SDimitry Andric PM.add(new TargetLibraryInfoWrapperPass(TLII)); 5060b57cec5SDimitry Andric 5070b57cec5SDimitry Andric // Add the target data from the target machine, if it exists, or the module. 5080b57cec5SDimitry Andric M->setDataLayout(Target->createDataLayout()); 5090b57cec5SDimitry Andric 5100b57cec5SDimitry Andric // This needs to be done after setting datalayout since it calls verifier 5110b57cec5SDimitry Andric // to check debug info whereas verifier relies on correct datalayout. 5120b57cec5SDimitry Andric UpgradeDebugInfo(*M); 5130b57cec5SDimitry Andric 5140b57cec5SDimitry Andric // Verify module immediately to catch problems before doInitialization() is 5150b57cec5SDimitry Andric // called on any passes. 5160b57cec5SDimitry Andric if (!NoVerify && verifyModule(*M, &errs())) { 5170b57cec5SDimitry Andric std::string Prefix = 5180b57cec5SDimitry Andric (Twine(argv[0]) + Twine(": ") + Twine(InputFilename)).str(); 5190b57cec5SDimitry Andric WithColor::error(errs(), Prefix) << "input module is broken!\n"; 5200b57cec5SDimitry Andric return 1; 5210b57cec5SDimitry Andric } 5220b57cec5SDimitry Andric 5230b57cec5SDimitry Andric // Override function attributes based on CPUStr, FeaturesStr, and command line 5240b57cec5SDimitry Andric // flags. 5250b57cec5SDimitry Andric setFunctionAttributes(CPUStr, FeaturesStr, *M); 5260b57cec5SDimitry Andric 5270b57cec5SDimitry Andric if (RelaxAll.getNumOccurrences() > 0 && 528*480093f4SDimitry Andric FileType != CGFT_ObjectFile) 5290b57cec5SDimitry Andric WithColor::warning(errs(), argv[0]) 5300b57cec5SDimitry Andric << ": warning: ignoring -mc-relax-all because filetype != obj"; 5310b57cec5SDimitry Andric 5320b57cec5SDimitry Andric { 5330b57cec5SDimitry Andric raw_pwrite_stream *OS = &Out->os(); 5340b57cec5SDimitry Andric 5350b57cec5SDimitry Andric // Manually do the buffering rather than using buffer_ostream, 5360b57cec5SDimitry Andric // so we can memcmp the contents in CompileTwice mode 5370b57cec5SDimitry Andric SmallVector<char, 0> Buffer; 5380b57cec5SDimitry Andric std::unique_ptr<raw_svector_ostream> BOS; 539*480093f4SDimitry Andric if ((FileType != CGFT_AssemblyFile && 5400b57cec5SDimitry Andric !Out->os().supportsSeeking()) || 5410b57cec5SDimitry Andric CompileTwice) { 5428bcb0991SDimitry Andric BOS = std::make_unique<raw_svector_ostream>(Buffer); 5430b57cec5SDimitry Andric OS = BOS.get(); 5440b57cec5SDimitry Andric } 5450b57cec5SDimitry Andric 5460b57cec5SDimitry Andric const char *argv0 = argv[0]; 5470b57cec5SDimitry Andric LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine &>(*Target); 5488bcb0991SDimitry Andric MachineModuleInfoWrapperPass *MMIWP = 5498bcb0991SDimitry Andric new MachineModuleInfoWrapperPass(&LLVMTM); 5500b57cec5SDimitry Andric 5510b57cec5SDimitry Andric // Construct a custom pass pipeline that starts after instruction 5520b57cec5SDimitry Andric // selection. 5530b57cec5SDimitry Andric if (!RunPassNames->empty()) { 5540b57cec5SDimitry Andric if (!MIR) { 5550b57cec5SDimitry Andric WithColor::warning(errs(), argv[0]) 5560b57cec5SDimitry Andric << "run-pass is for .mir file only.\n"; 5570b57cec5SDimitry Andric return 1; 5580b57cec5SDimitry Andric } 5590b57cec5SDimitry Andric TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM); 5600b57cec5SDimitry Andric if (TPC.hasLimitedCodeGenPipeline()) { 5610b57cec5SDimitry Andric WithColor::warning(errs(), argv[0]) 5620b57cec5SDimitry Andric << "run-pass cannot be used with " 5630b57cec5SDimitry Andric << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n"; 5640b57cec5SDimitry Andric return 1; 5650b57cec5SDimitry Andric } 5660b57cec5SDimitry Andric 5670b57cec5SDimitry Andric TPC.setDisableVerify(NoVerify); 5680b57cec5SDimitry Andric PM.add(&TPC); 5698bcb0991SDimitry Andric PM.add(MMIWP); 5700b57cec5SDimitry Andric TPC.printAndVerify(""); 5710b57cec5SDimitry Andric for (const std::string &RunPassName : *RunPassNames) { 5720b57cec5SDimitry Andric if (addPass(PM, argv0, RunPassName, TPC)) 5730b57cec5SDimitry Andric return 1; 5740b57cec5SDimitry Andric } 5750b57cec5SDimitry Andric TPC.setInitialized(); 5760b57cec5SDimitry Andric PM.add(createPrintMIRPass(*OS)); 5770b57cec5SDimitry Andric PM.add(createFreeMachineFunctionPass()); 5780b57cec5SDimitry Andric } else if (Target->addPassesToEmitFile(PM, *OS, 5790b57cec5SDimitry Andric DwoOut ? &DwoOut->os() : nullptr, 5808bcb0991SDimitry Andric FileType, NoVerify, MMIWP)) { 5810b57cec5SDimitry Andric WithColor::warning(errs(), argv[0]) 5820b57cec5SDimitry Andric << "target does not support generation of this" 5830b57cec5SDimitry Andric << " file type!\n"; 5840b57cec5SDimitry Andric return 1; 5850b57cec5SDimitry Andric } 5860b57cec5SDimitry Andric 5870b57cec5SDimitry Andric if (MIR) { 5888bcb0991SDimitry Andric assert(MMIWP && "Forgot to create MMIWP?"); 5898bcb0991SDimitry Andric if (MIR->parseMachineFunctions(*M, MMIWP->getMMI())) 5900b57cec5SDimitry Andric return 1; 5910b57cec5SDimitry Andric } 5920b57cec5SDimitry Andric 5930b57cec5SDimitry Andric // Before executing passes, print the final values of the LLVM options. 5940b57cec5SDimitry Andric cl::PrintOptionValues(); 5950b57cec5SDimitry Andric 5960b57cec5SDimitry Andric // If requested, run the pass manager over the same module again, 5970b57cec5SDimitry Andric // to catch any bugs due to persistent state in the passes. Note that 5980b57cec5SDimitry Andric // opt has the same functionality, so it may be worth abstracting this out 5990b57cec5SDimitry Andric // in the future. 6000b57cec5SDimitry Andric SmallVector<char, 0> CompileTwiceBuffer; 6010b57cec5SDimitry Andric if (CompileTwice) { 6020b57cec5SDimitry Andric std::unique_ptr<Module> M2(llvm::CloneModule(*M)); 6030b57cec5SDimitry Andric PM.run(*M2); 6040b57cec5SDimitry Andric CompileTwiceBuffer = Buffer; 6050b57cec5SDimitry Andric Buffer.clear(); 6060b57cec5SDimitry Andric } 6070b57cec5SDimitry Andric 6080b57cec5SDimitry Andric PM.run(*M); 6090b57cec5SDimitry Andric 6100b57cec5SDimitry Andric auto HasError = 6110b57cec5SDimitry Andric ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError; 6120b57cec5SDimitry Andric if (*HasError) 6130b57cec5SDimitry Andric return 1; 6140b57cec5SDimitry Andric 6150b57cec5SDimitry Andric // Compare the two outputs and make sure they're the same 6160b57cec5SDimitry Andric if (CompileTwice) { 6170b57cec5SDimitry Andric if (Buffer.size() != CompileTwiceBuffer.size() || 6180b57cec5SDimitry Andric (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) != 6190b57cec5SDimitry Andric 0)) { 6200b57cec5SDimitry Andric errs() 6210b57cec5SDimitry Andric << "Running the pass manager twice changed the output.\n" 6220b57cec5SDimitry Andric "Writing the result of the second run to the specified output\n" 6230b57cec5SDimitry Andric "To generate the one-run comparison binary, just run without\n" 6240b57cec5SDimitry Andric "the compile-twice option\n"; 6250b57cec5SDimitry Andric Out->os() << Buffer; 6260b57cec5SDimitry Andric Out->keep(); 6270b57cec5SDimitry Andric return 1; 6280b57cec5SDimitry Andric } 6290b57cec5SDimitry Andric } 6300b57cec5SDimitry Andric 6310b57cec5SDimitry Andric if (BOS) { 6320b57cec5SDimitry Andric Out->os() << Buffer; 6330b57cec5SDimitry Andric } 6340b57cec5SDimitry Andric } 6350b57cec5SDimitry Andric 6360b57cec5SDimitry Andric // Declare success. 6370b57cec5SDimitry Andric Out->keep(); 6380b57cec5SDimitry Andric if (DwoOut) 6390b57cec5SDimitry Andric DwoOut->keep(); 6400b57cec5SDimitry Andric 6410b57cec5SDimitry Andric return 0; 6420b57cec5SDimitry Andric } 643