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 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path")); 138 139 static cl::opt<bool> PassRemarksWithHotness( 140 "pass-remarks-with-hotness", 141 cl::desc("With PGO, include profile count in optimization remarks"), 142 cl::Hidden); 143 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")); 148 149 namespace { 150 static ManagedStatic<std::vector<std::string>> RunPassNames; 151 152 struct RunPassOption { 153 void operator=(const std::string &Val) const { 154 if (Val.empty()) 155 return; 156 SmallVector<StringRef, 8> PassNames; 157 StringRef(Val).split(PassNames, ',', -1, false); 158 for (auto PassName : PassNames) 159 RunPassNames->push_back(PassName); 160 } 161 }; 162 } 163 164 static RunPassOption RunPassOpt; 165 166 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass( 167 "run-pass", 168 cl::desc("Run compiler only for specified passes (comma separated list)"), 169 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt)); 170 171 static int compileModule(char **, LLVMContext &); 172 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 = "-"; 180 else { 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); 187 else 188 OutputFilename = IFN; 189 190 switch (FileType) { 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"; 197 else 198 OutputFilename += ".s"; 199 } else 200 OutputFilename += ".s"; 201 break; 202 case TargetMachine::CGFT_ObjectFile: 203 if (OS == Triple::Win32) 204 OutputFilename += ".obj"; 205 else 206 OutputFilename += ".o"; 207 break; 208 case TargetMachine::CGFT_Null: 209 OutputFilename += ".null"; 210 break; 211 } 212 } 213 } 214 215 // Decide if we need "binary" output. 216 bool Binary = false; 217 switch (FileType) { 218 case TargetMachine::CGFT_AssemblyFile: 219 break; 220 case TargetMachine::CGFT_ObjectFile: 221 case TargetMachine::CGFT_Null: 222 Binary = true; 223 break; 224 } 225 226 // Open the file. 227 std::error_code EC; 228 sys::fs::OpenFlags OpenFlags = sys::fs::F_None; 229 if (!Binary) 230 OpenFlags |= sys::fs::F_Text; 231 auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC, 232 OpenFlags); 233 if (EC) { 234 errs() << EC.message() << '\n'; 235 return nullptr; 236 } 237 238 return FDOut; 239 } 240 241 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) { 242 bool *HasError = static_cast<bool *>(Context); 243 if (DI.getSeverity() == DS_Error) 244 *HasError = true; 245 246 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI)) 247 if (!Remark->isEnabled()) 248 return; 249 250 DiagnosticPrinterRawOStream DP(errs()); 251 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": "; 252 DI.print(DP); 253 errs() << "\n"; 254 } 255 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) 260 *HasError = true; 261 262 SMD.print(nullptr, errs()); 263 264 // For testing purposes, we print the LocCookie here. 265 if (LocCookie) 266 errs() << "note: !srcloc = " << LocCookie << "\n"; 267 } 268 269 // main - Entry point for the llc compiler. 270 // 271 int main(int argc, char **argv) { 272 sys::PrintStackTraceOnErrorSignal(argv[0]); 273 PrettyStackTraceProgram X(argc, argv); 274 275 // Enable debug stream buffering. 276 EnableDebugBuffering = true; 277 278 LLVMContext Context; 279 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 280 281 // Initialize targets first, so that --version shows registered targets. 282 InitializeAllTargets(); 283 InitializeAllTargetMCs(); 284 InitializeAllAsmPrinters(); 285 InitializeAllAsmParsers(); 286 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); 299 300 // Register the target printer for --version. 301 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 302 303 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 304 305 Context.setDiscardValueNames(DiscardValueNames); 306 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); 311 312 if (PassRemarksWithHotness) 313 Context.setDiagnosticHotnessRequested(true); 314 315 std::unique_ptr<tool_output_file> YamlFile; 316 if (RemarksFilename != "") { 317 std::error_code EC; 318 YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC, 319 sys::fs::F_None); 320 if (EC) { 321 errs() << EC.message() << '\n'; 322 return 1; 323 } 324 Context.setDiagnosticsOutputFile( 325 llvm::make_unique<yaml::Output>(YamlFile->os())); 326 } 327 328 // Compile the module TimeCompilations times to give better compile time 329 // metrics. 330 for (unsigned I = TimeCompilations; I; --I) 331 if (int RetVal = compileModule(argv, Context)) 332 return RetVal; 333 334 if (YamlFile) 335 YamlFile->keep(); 336 return 0; 337 } 338 339 static bool addPass(PassManagerBase &PM, const char *argv0, 340 StringRef PassName, TargetPassConfig &TPC) { 341 if (PassName == "none") 342 return false; 343 344 const PassRegistry *PR = PassRegistry::getPassRegistry(); 345 const PassInfo *PI = PR->getPassInfo(PassName); 346 if (!PI) { 347 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n"; 348 return true; 349 } 350 351 Pass *P; 352 if (PI->getTargetMachineCtor()) 353 P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>()); 354 else if (PI->getNormalCtor()) 355 P = PI->getNormalCtor()(); 356 else { 357 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n"; 358 return true; 359 } 360 std::string Banner = std::string("After ") + std::string(P->getPassName()); 361 PM.add(P); 362 TPC.printAndVerify(Banner); 363 364 return false; 365 } 366 367 static AnalysisID getPassID(const char *argv0, const char *OptionName, 368 StringRef PassName) { 369 if (PassName.empty()) 370 return nullptr; 371 372 const PassRegistry &PR = *PassRegistry::getPassRegistry(); 373 const PassInfo *PI = PR.getPassInfo(PassName); 374 if (!PI) { 375 errs() << argv0 << ": " << OptionName << " pass is not registered.\n"; 376 exit(1); 377 } 378 return PI->getTypeInfo(); 379 } 380 381 static int compileModule(char **argv, LLVMContext &Context) { 382 // Load the module to be compiled... 383 SMDiagnostic Err; 384 std::unique_ptr<Module> M; 385 std::unique_ptr<MIRParser> MIR; 386 Triple TheTriple; 387 388 bool SkipModule = MCPU == "help" || 389 (!MAttrs.empty() && MAttrs.front() == "help"); 390 391 // If user just wants to list available options, skip module loading 392 if (!SkipModule) { 393 if (StringRef(InputFilename).endswith_lower(".mir")) { 394 MIR = createMIRParserFromFile(InputFilename, Err, Context); 395 if (MIR) 396 M = MIR->parseLLVMModule(); 397 } else 398 M = parseIRFile(InputFilename, Err, Context); 399 if (!M) { 400 Err.print(argv[0], errs()); 401 return 1; 402 } 403 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"; 409 return 1; 410 } 411 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()); 416 } else { 417 TheTriple = Triple(Triple::normalize(TargetTriple)); 418 } 419 420 if (TheTriple.getTriple().empty()) 421 TheTriple.setTriple(sys::getDefaultTargetTriple()); 422 423 // Get the target specific parser. 424 std::string Error; 425 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 426 Error); 427 if (!TheTarget) { 428 errs() << argv[0] << ": " << Error; 429 return 1; 430 } 431 432 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr(); 433 434 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 435 switch (OptLevel) { 436 default: 437 errs() << argv[0] << ": invalid optimization level.\n"; 438 return 1; 439 case ' ': break; 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; 444 } 445 446 TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); 447 Options.DisableIntegratedAS = NoIntegratedAssembler; 448 Options.MCOptions.ShowMCEncoding = ShowMCEncoding; 449 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory; 450 Options.MCOptions.AsmVerbose = AsmVerbose; 451 Options.MCOptions.PreserveAsmComments = PreserveComments; 452 Options.MCOptions.IASSearchPaths = IncludeDirs; 453 454 std::unique_ptr<TargetMachine> Target( 455 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr, 456 Options, getRelocModel(), CMModel, OLvl)); 457 458 assert(Target && "Could not allocate target machine!"); 459 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 462 // creation. 463 if (SkipModule) 464 return 0; 465 466 assert(M && "Should have exited if we didn't have a module!"); 467 if (FloatABIForCalls != FloatABI::Default) 468 Options.FloatABIType = FloatABIForCalls; 469 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]); 473 if (!Out) return 1; 474 475 // Build up all of the passes that we want to do to the module. 476 legacy::PassManager PM; 477 478 // Add an appropriate TargetLibraryInfo pass for the module's triple. 479 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple())); 480 481 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 482 if (DisableSimplifyLibCalls) 483 TLII.disableAllFunctions(); 484 PM.add(new TargetLibraryInfoWrapperPass(TLII)); 485 486 // Add the target data from the target machine, if it exists, or the module. 487 M->setDataLayout(Target->createDataLayout()); 488 489 // Override function attributes based on CPUStr, FeaturesStr, and command line 490 // flags. 491 setFunctionAttributes(CPUStr, FeaturesStr, *M); 492 493 if (RelaxAll.getNumOccurrences() > 0 && 494 FileType != TargetMachine::CGFT_ObjectFile) 495 errs() << argv[0] 496 << ": warning: ignoring -mc-relax-all because filetype != obj"; 497 498 { 499 raw_pwrite_stream *OS = &Out->os(); 500 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()) || 507 CompileTwice) { 508 BOS = make_unique<raw_svector_ostream>(Buffer); 509 OS = BOS.get(); 510 } 511 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"; 517 return 1; 518 } 519 if (!MIR) { 520 errs() << argv[0] << ": run-pass needs a .mir input.\n"; 521 return 1; 522 } 523 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target); 524 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM); 525 PM.add(&TPC); 526 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM); 527 MMI->setMachineFunctionInitializer(MIR.get()); 528 PM.add(MMI); 529 TPC.printAndVerify(""); 530 531 for (const std::string &RunPassName : *RunPassNames) { 532 if (addPass(PM, argv[0], RunPassName, TPC)) 533 return 1; 534 } 535 PM.add(createPrintMIRPass(*OS)); 536 } else { 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); 542 543 if (StartBeforeID && StartAfterID) { 544 errs() << argv[0] << ": -start-before and -start-after specified!\n"; 545 return 1; 546 } 547 if (StopBeforeID && StopAfterID) { 548 errs() << argv[0] << ": -stop-before and -stop-after specified!\n"; 549 return 1; 550 } 551 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" 557 << " file type!\n"; 558 return 1; 559 } 560 } 561 562 // Before executing passes, print the final values of the LLVM options. 563 cl::PrintOptionValues(); 564 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 568 // in the future. 569 SmallVector<char, 0> CompileTwiceBuffer; 570 if (CompileTwice) { 571 std::unique_ptr<Module> M2(llvm::CloneModule(M.get())); 572 PM.run(*M2); 573 CompileTwiceBuffer = Buffer; 574 Buffer.clear(); 575 } 576 577 PM.run(*M); 578 579 auto HasError = *static_cast<bool *>(Context.getDiagnosticContext()); 580 if (HasError) 581 return 1; 582 583 // Compare the two outputs and make sure they're the same 584 if (CompileTwice) { 585 if (Buffer.size() != CompileTwiceBuffer.size() || 586 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) != 587 0)) { 588 errs() 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"; 593 Out->os() << Buffer; 594 Out->keep(); 595 return 1; 596 } 597 } 598 599 if (BOS) { 600 Out->os() << Buffer; 601 } 602 } 603 604 // Declare success. 605 Out->keep(); 606 607 return 0; 608 } 609