1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 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. 13 // 14 //===----------------------------------------------------------------------===// 15 16 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" 54 #include <memory> 55 using namespace llvm; 56 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. 60 // 61 static cl::opt<std::string> 62 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 63 64 static cl::opt<std::string> 65 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 66 67 static cl::opt<unsigned> 68 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u), 69 cl::value_desc("N"), 70 cl::desc("Repeat compilation N times for timing")); 71 72 static cl::opt<bool> 73 NoIntegratedAssembler("no-integrated-as", cl::Hidden, 74 cl::desc("Disable integrated assembler")); 75 76 static cl::opt<bool> 77 PreserveComments("preserve-as-comments", cl::Hidden, 78 cl::desc("Preserve Comments in outputted assembly"), 79 cl::init(true)); 80 81 // Determine optimization level. 82 static cl::opt<char> 83 OptLevel("O", 84 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 85 "(default = '-O2')"), 86 cl::Prefix, 87 cl::ZeroOrMore, 88 cl::init(' ')); 89 90 static cl::opt<std::string> 91 TargetTriple("mtriple", cl::desc("Override target triple for module")); 92 93 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 94 cl::desc("Do not verify input module")); 95 96 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls", 97 cl::desc("Disable simplify-libcalls")); 98 99 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, 100 cl::desc("Show encoding in .s output")); 101 102 static cl::opt<bool> EnableDwarfDirectory( 103 "enable-dwarf-directory", cl::Hidden, 104 cl::desc("Use .file directives with an explicit directory.")); 105 106 static cl::opt<bool> AsmVerbose("asm-verbose", 107 cl::desc("Add comments to directives."), 108 cl::init(true)); 109 110 static cl::opt<bool> 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."), 114 cl::init(false)); 115 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); 120 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("")); 124 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("")); 128 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("")); 132 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("")); 136 137 namespace { 138 static ManagedStatic<std::vector<std::string>> RunPassNames; 139 140 struct RunPassOption { 141 void operator=(const std::string &Val) const { 142 if (Val.empty()) 143 return; 144 SmallVector<StringRef, 8> PassNames; 145 StringRef(Val).split(PassNames, ',', -1, false); 146 for (auto PassName : PassNames) 147 RunPassNames->push_back(PassName); 148 } 149 }; 150 } 151 152 static RunPassOption RunPassOpt; 153 154 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass( 155 "run-pass", 156 cl::desc("Run compiler only for specified passes (comma separated list)"), 157 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt)); 158 159 static int compileModule(char **, LLVMContext &); 160 161 static std::unique_ptr<tool_output_file> 162 GetOutputStream(const char *TargetName, Triple::OSType OS, 163 const char *ProgName) { 164 // If we don't yet have an output filename, make one. 165 if (OutputFilename.empty()) { 166 if (InputFilename == "-") 167 OutputFilename = "-"; 168 else { 169 // If InputFilename ends in .bc or .ll, remove it. 170 StringRef IFN = InputFilename; 171 if (IFN.endswith(".bc") || IFN.endswith(".ll")) 172 OutputFilename = IFN.drop_back(3); 173 else if (IFN.endswith(".mir")) 174 OutputFilename = IFN.drop_back(4); 175 else 176 OutputFilename = IFN; 177 178 switch (FileType) { 179 case TargetMachine::CGFT_AssemblyFile: 180 if (TargetName[0] == 'c') { 181 if (TargetName[1] == 0) 182 OutputFilename += ".cbe.c"; 183 else if (TargetName[1] == 'p' && TargetName[2] == 'p') 184 OutputFilename += ".cpp"; 185 else 186 OutputFilename += ".s"; 187 } else 188 OutputFilename += ".s"; 189 break; 190 case TargetMachine::CGFT_ObjectFile: 191 if (OS == Triple::Win32) 192 OutputFilename += ".obj"; 193 else 194 OutputFilename += ".o"; 195 break; 196 case TargetMachine::CGFT_Null: 197 OutputFilename += ".null"; 198 break; 199 } 200 } 201 } 202 203 // Decide if we need "binary" output. 204 bool Binary = false; 205 switch (FileType) { 206 case TargetMachine::CGFT_AssemblyFile: 207 break; 208 case TargetMachine::CGFT_ObjectFile: 209 case TargetMachine::CGFT_Null: 210 Binary = true; 211 break; 212 } 213 214 // Open the file. 215 std::error_code EC; 216 sys::fs::OpenFlags OpenFlags = sys::fs::F_None; 217 if (!Binary) 218 OpenFlags |= sys::fs::F_Text; 219 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC, 220 OpenFlags); 221 if (EC) { 222 errs() << EC.message() << '\n'; 223 return nullptr; 224 } 225 226 return FDOut; 227 } 228 229 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) { 230 bool *HasError = static_cast<bool *>(Context); 231 if (DI.getSeverity() == DS_Error) 232 *HasError = true; 233 234 DiagnosticPrinterRawOStream DP(errs()); 235 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": "; 236 DI.print(DP); 237 errs() << "\n"; 238 } 239 240 // main - Entry point for the llc compiler. 241 // 242 int main(int argc, char **argv) { 243 sys::PrintStackTraceOnErrorSignal(argv[0]); 244 PrettyStackTraceProgram X(argc, argv); 245 246 // Enable debug stream buffering. 247 EnableDebugBuffering = true; 248 249 LLVMContext Context; 250 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 251 252 // Initialize targets first, so that --version shows registered targets. 253 InitializeAllTargets(); 254 InitializeAllTargetMCs(); 255 InitializeAllAsmPrinters(); 256 InitializeAllAsmParsers(); 257 258 // Initialize codegen and IR passes used by llc so that the -print-after, 259 // -print-before, and -stop-after options work. 260 PassRegistry *Registry = PassRegistry::getPassRegistry(); 261 initializeCore(*Registry); 262 initializeCodeGen(*Registry); 263 initializeLoopStrengthReducePass(*Registry); 264 initializeLowerIntrinsicsPass(*Registry); 265 initializeCountingFunctionInserterPass(*Registry); 266 initializeUnreachableBlockElimLegacyPassPass(*Registry); 267 initializeConstantHoistingLegacyPassPass(*Registry); 268 269 // Register the target printer for --version. 270 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 271 272 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 273 274 Context.setDiscardValueNames(DiscardValueNames); 275 276 // Set a diagnostic handler that doesn't exit on the first error 277 bool HasError = false; 278 Context.setDiagnosticHandler(DiagnosticHandler, &HasError); 279 280 // Compile the module TimeCompilations times to give better compile time 281 // metrics. 282 for (unsigned I = TimeCompilations; I; --I) 283 if (int RetVal = compileModule(argv, Context)) 284 return RetVal; 285 return 0; 286 } 287 288 static bool addPass(PassManagerBase &PM, const char *argv0, 289 StringRef PassName, TargetPassConfig &TPC) { 290 if (PassName == "none") 291 return false; 292 293 const PassRegistry *PR = PassRegistry::getPassRegistry(); 294 const PassInfo *PI = PR->getPassInfo(PassName); 295 if (!PI) { 296 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n"; 297 return true; 298 } 299 300 Pass *P; 301 if (PI->getTargetMachineCtor()) 302 P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>()); 303 else if (PI->getNormalCtor()) 304 P = PI->getNormalCtor()(); 305 else { 306 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n"; 307 return true; 308 } 309 std::string Banner = std::string("After ") + std::string(P->getPassName()); 310 PM.add(P); 311 TPC.printAndVerify(Banner); 312 313 return false; 314 } 315 316 static AnalysisID getPassID(const char *argv0, const char *OptionName, 317 StringRef PassName) { 318 if (PassName.empty()) 319 return nullptr; 320 321 const PassRegistry &PR = *PassRegistry::getPassRegistry(); 322 const PassInfo *PI = PR.getPassInfo(PassName); 323 if (!PI) { 324 errs() << argv0 << ": " << OptionName << " pass is not registered.\n"; 325 exit(1); 326 } 327 return PI->getTypeInfo(); 328 } 329 330 static int compileModule(char **argv, LLVMContext &Context) { 331 // Load the module to be compiled... 332 SMDiagnostic Err; 333 std::unique_ptr<Module> M; 334 std::unique_ptr<MIRParser> MIR; 335 Triple TheTriple; 336 337 bool SkipModule = MCPU == "help" || 338 (!MAttrs.empty() && MAttrs.front() == "help"); 339 340 // If user just wants to list available options, skip module loading 341 if (!SkipModule) { 342 if (StringRef(InputFilename).endswith_lower(".mir")) { 343 MIR = createMIRParserFromFile(InputFilename, Err, Context); 344 if (MIR) 345 M = MIR->parseLLVMModule(); 346 } else 347 M = parseIRFile(InputFilename, Err, Context); 348 if (!M) { 349 Err.print(argv[0], errs()); 350 return 1; 351 } 352 353 // Verify module immediately to catch problems before doInitialization() is 354 // called on any passes. 355 if (!NoVerify && verifyModule(*M, &errs())) { 356 errs() << argv[0] << ": " << InputFilename 357 << ": error: input module is broken!\n"; 358 return 1; 359 } 360 361 // If we are supposed to override the target triple, do so now. 362 if (!TargetTriple.empty()) 363 M->setTargetTriple(Triple::normalize(TargetTriple)); 364 TheTriple = Triple(M->getTargetTriple()); 365 } else { 366 TheTriple = Triple(Triple::normalize(TargetTriple)); 367 } 368 369 if (TheTriple.getTriple().empty()) 370 TheTriple.setTriple(sys::getDefaultTargetTriple()); 371 372 // Get the target specific parser. 373 std::string Error; 374 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 375 Error); 376 if (!TheTarget) { 377 errs() << argv[0] << ": " << Error; 378 return 1; 379 } 380 381 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr(); 382 383 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 384 switch (OptLevel) { 385 default: 386 errs() << argv[0] << ": invalid optimization level.\n"; 387 return 1; 388 case ' ': break; 389 case '0': OLvl = CodeGenOpt::None; break; 390 case '1': OLvl = CodeGenOpt::Less; break; 391 case '2': OLvl = CodeGenOpt::Default; break; 392 case '3': OLvl = CodeGenOpt::Aggressive; break; 393 } 394 395 TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); 396 Options.DisableIntegratedAS = NoIntegratedAssembler; 397 Options.MCOptions.ShowMCEncoding = ShowMCEncoding; 398 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory; 399 Options.MCOptions.AsmVerbose = AsmVerbose; 400 Options.MCOptions.PreserveAsmComments = PreserveComments; 401 402 std::unique_ptr<TargetMachine> Target( 403 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr, 404 Options, getRelocModel(), CMModel, OLvl)); 405 406 assert(Target && "Could not allocate target machine!"); 407 408 // If we don't have a module then just exit now. We do this down 409 // here since the CPU/Feature help is underneath the target machine 410 // creation. 411 if (SkipModule) 412 return 0; 413 414 assert(M && "Should have exited if we didn't have a module!"); 415 if (FloatABIForCalls != FloatABI::Default) 416 Options.FloatABIType = FloatABIForCalls; 417 418 // Figure out where we are going to send the output. 419 std::unique_ptr<tool_output_file> Out = 420 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]); 421 if (!Out) return 1; 422 423 // Build up all of the passes that we want to do to the module. 424 legacy::PassManager PM; 425 426 // Add an appropriate TargetLibraryInfo pass for the module's triple. 427 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple())); 428 429 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 430 if (DisableSimplifyLibCalls) 431 TLII.disableAllFunctions(); 432 PM.add(new TargetLibraryInfoWrapperPass(TLII)); 433 434 // Add the target data from the target machine, if it exists, or the module. 435 M->setDataLayout(Target->createDataLayout()); 436 437 // Override function attributes based on CPUStr, FeaturesStr, and command line 438 // flags. 439 setFunctionAttributes(CPUStr, FeaturesStr, *M); 440 441 if (RelaxAll.getNumOccurrences() > 0 && 442 FileType != TargetMachine::CGFT_ObjectFile) 443 errs() << argv[0] 444 << ": warning: ignoring -mc-relax-all because filetype != obj"; 445 446 { 447 raw_pwrite_stream *OS = &Out->os(); 448 449 // Manually do the buffering rather than using buffer_ostream, 450 // so we can memcmp the contents in CompileTwice mode 451 SmallVector<char, 0> Buffer; 452 std::unique_ptr<raw_svector_ostream> BOS; 453 if ((FileType != TargetMachine::CGFT_AssemblyFile && 454 !Out->os().supportsSeeking()) || 455 CompileTwice) { 456 BOS = make_unique<raw_svector_ostream>(Buffer); 457 OS = BOS.get(); 458 } 459 460 if (!RunPassNames->empty()) { 461 if (!StartAfter.empty() || !StopAfter.empty() || !StartBefore.empty() || 462 !StopBefore.empty()) { 463 errs() << argv[0] << ": start-after and/or stop-after passes are " 464 "redundant when run-pass is specified.\n"; 465 return 1; 466 } 467 if (!MIR) { 468 errs() << argv[0] << ": run-pass needs a .mir input.\n"; 469 return 1; 470 } 471 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target); 472 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM); 473 PM.add(&TPC); 474 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM); 475 MMI->setMachineFunctionInitializer(MIR.get()); 476 PM.add(MMI); 477 TPC.printAndVerify(""); 478 479 for (const std::string &RunPassName : *RunPassNames) { 480 if (addPass(PM, argv[0], RunPassName, TPC)) 481 return 1; 482 } 483 PM.add(createPrintMIRPass(*OS)); 484 } else { 485 const char *argv0 = argv[0]; 486 AnalysisID StartBeforeID = getPassID(argv0, "start-before", StartBefore); 487 AnalysisID StartAfterID = getPassID(argv0, "start-after", StartAfter); 488 AnalysisID StopAfterID = getPassID(argv0, "stop-after", StopAfter); 489 AnalysisID StopBeforeID = getPassID(argv0, "stop-before", StopBefore); 490 491 if (StartBeforeID && StartAfterID) { 492 errs() << argv[0] << ": -start-before and -start-after specified!\n"; 493 return 1; 494 } 495 if (StopBeforeID && StopAfterID) { 496 errs() << argv[0] << ": -stop-before and -stop-after specified!\n"; 497 return 1; 498 } 499 500 // Ask the target to add backend passes as necessary. 501 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, 502 StartBeforeID, StartAfterID, StopBeforeID, 503 StopAfterID, MIR.get())) { 504 errs() << argv[0] << ": target does not support generation of this" 505 << " file type!\n"; 506 return 1; 507 } 508 } 509 510 // Before executing passes, print the final values of the LLVM options. 511 cl::PrintOptionValues(); 512 513 // If requested, run the pass manager over the same module again, 514 // to catch any bugs due to persistent state in the passes. Note that 515 // opt has the same functionality, so it may be worth abstracting this out 516 // in the future. 517 SmallVector<char, 0> CompileTwiceBuffer; 518 if (CompileTwice) { 519 std::unique_ptr<Module> M2(llvm::CloneModule(M.get())); 520 PM.run(*M2); 521 CompileTwiceBuffer = Buffer; 522 Buffer.clear(); 523 } 524 525 PM.run(*M); 526 527 auto HasError = *static_cast<bool *>(Context.getDiagnosticContext()); 528 if (HasError) 529 return 1; 530 531 // Compare the two outputs and make sure they're the same 532 if (CompileTwice) { 533 if (Buffer.size() != CompileTwiceBuffer.size() || 534 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) != 535 0)) { 536 errs() 537 << "Running the pass manager twice changed the output.\n" 538 "Writing the result of the second run to the specified output\n" 539 "To generate the one-run comparison binary, just run without\n" 540 "the compile-twice option\n"; 541 Out->os() << Buffer; 542 Out->keep(); 543 return 1; 544 } 545 } 546 547 if (BOS) { 548 Out->os() << Buffer; 549 } 550 } 551 552 // Declare success. 553 Out->keep(); 554 555 return 0; 556 } 557