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 268 // Register the target printer for --version. 269 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 270 271 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 272 273 Context.setDiscardValueNames(DiscardValueNames); 274 275 // Set a diagnostic handler that doesn't exit on the first error 276 bool HasError = false; 277 Context.setDiagnosticHandler(DiagnosticHandler, &HasError); 278 279 // Compile the module TimeCompilations times to give better compile time 280 // metrics. 281 for (unsigned I = TimeCompilations; I; --I) 282 if (int RetVal = compileModule(argv, Context)) 283 return RetVal; 284 return 0; 285 } 286 287 static bool addPass(PassManagerBase &PM, const char *argv0, 288 StringRef PassName, TargetPassConfig &TPC) { 289 if (PassName == "none") 290 return false; 291 292 const PassRegistry *PR = PassRegistry::getPassRegistry(); 293 const PassInfo *PI = PR->getPassInfo(PassName); 294 if (!PI) { 295 errs() << argv0 << ": run-pass " << PassName << " is not registered.\n"; 296 return true; 297 } 298 299 Pass *P; 300 if (PI->getTargetMachineCtor()) 301 P = PI->getTargetMachineCtor()(&TPC.getTM<TargetMachine>()); 302 else if (PI->getNormalCtor()) 303 P = PI->getNormalCtor()(); 304 else { 305 errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n"; 306 return true; 307 } 308 std::string Banner = std::string("After ") + std::string(P->getPassName()); 309 PM.add(P); 310 TPC.printAndVerify(Banner); 311 312 return false; 313 } 314 315 static AnalysisID getPassID(const char *argv0, const char *OptionName, 316 StringRef PassName) { 317 if (PassName.empty()) 318 return nullptr; 319 320 const PassRegistry &PR = *PassRegistry::getPassRegistry(); 321 const PassInfo *PI = PR.getPassInfo(PassName); 322 if (!PI) { 323 errs() << argv0 << ": " << OptionName << " pass is not registered.\n"; 324 exit(1); 325 } 326 return PI->getTypeInfo(); 327 } 328 329 static int compileModule(char **argv, LLVMContext &Context) { 330 // Load the module to be compiled... 331 SMDiagnostic Err; 332 std::unique_ptr<Module> M; 333 std::unique_ptr<MIRParser> MIR; 334 Triple TheTriple; 335 336 bool SkipModule = MCPU == "help" || 337 (!MAttrs.empty() && MAttrs.front() == "help"); 338 339 // If user just wants to list available options, skip module loading 340 if (!SkipModule) { 341 if (StringRef(InputFilename).endswith_lower(".mir")) { 342 MIR = createMIRParserFromFile(InputFilename, Err, Context); 343 if (MIR) 344 M = MIR->parseLLVMModule(); 345 } else 346 M = parseIRFile(InputFilename, Err, Context); 347 if (!M) { 348 Err.print(argv[0], errs()); 349 return 1; 350 } 351 352 // Verify module immediately to catch problems before doInitialization() is 353 // called on any passes. 354 if (!NoVerify && verifyModule(*M, &errs())) { 355 errs() << argv[0] << ": " << InputFilename 356 << ": error: input module is broken!\n"; 357 return 1; 358 } 359 360 // If we are supposed to override the target triple, do so now. 361 if (!TargetTriple.empty()) 362 M->setTargetTriple(Triple::normalize(TargetTriple)); 363 TheTriple = Triple(M->getTargetTriple()); 364 } else { 365 TheTriple = Triple(Triple::normalize(TargetTriple)); 366 } 367 368 if (TheTriple.getTriple().empty()) 369 TheTriple.setTriple(sys::getDefaultTargetTriple()); 370 371 // Get the target specific parser. 372 std::string Error; 373 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 374 Error); 375 if (!TheTarget) { 376 errs() << argv[0] << ": " << Error; 377 return 1; 378 } 379 380 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr(); 381 382 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 383 switch (OptLevel) { 384 default: 385 errs() << argv[0] << ": invalid optimization level.\n"; 386 return 1; 387 case ' ': break; 388 case '0': OLvl = CodeGenOpt::None; break; 389 case '1': OLvl = CodeGenOpt::Less; break; 390 case '2': OLvl = CodeGenOpt::Default; break; 391 case '3': OLvl = CodeGenOpt::Aggressive; break; 392 } 393 394 TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); 395 Options.DisableIntegratedAS = NoIntegratedAssembler; 396 Options.MCOptions.ShowMCEncoding = ShowMCEncoding; 397 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory; 398 Options.MCOptions.AsmVerbose = AsmVerbose; 399 Options.MCOptions.PreserveAsmComments = PreserveComments; 400 401 std::unique_ptr<TargetMachine> Target( 402 TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr, 403 Options, getRelocModel(), CMModel, OLvl)); 404 405 assert(Target && "Could not allocate target machine!"); 406 407 // If we don't have a module then just exit now. We do this down 408 // here since the CPU/Feature help is underneath the target machine 409 // creation. 410 if (SkipModule) 411 return 0; 412 413 assert(M && "Should have exited if we didn't have a module!"); 414 if (FloatABIForCalls != FloatABI::Default) 415 Options.FloatABIType = FloatABIForCalls; 416 417 // Figure out where we are going to send the output. 418 std::unique_ptr<tool_output_file> Out = 419 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]); 420 if (!Out) return 1; 421 422 // Build up all of the passes that we want to do to the module. 423 legacy::PassManager PM; 424 425 // Add an appropriate TargetLibraryInfo pass for the module's triple. 426 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple())); 427 428 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 429 if (DisableSimplifyLibCalls) 430 TLII.disableAllFunctions(); 431 PM.add(new TargetLibraryInfoWrapperPass(TLII)); 432 433 // Add the target data from the target machine, if it exists, or the module. 434 M->setDataLayout(Target->createDataLayout()); 435 436 // Override function attributes based on CPUStr, FeaturesStr, and command line 437 // flags. 438 setFunctionAttributes(CPUStr, FeaturesStr, *M); 439 440 if (RelaxAll.getNumOccurrences() > 0 && 441 FileType != TargetMachine::CGFT_ObjectFile) 442 errs() << argv[0] 443 << ": warning: ignoring -mc-relax-all because filetype != obj"; 444 445 { 446 raw_pwrite_stream *OS = &Out->os(); 447 448 // Manually do the buffering rather than using buffer_ostream, 449 // so we can memcmp the contents in CompileTwice mode 450 SmallVector<char, 0> Buffer; 451 std::unique_ptr<raw_svector_ostream> BOS; 452 if ((FileType != TargetMachine::CGFT_AssemblyFile && 453 !Out->os().supportsSeeking()) || 454 CompileTwice) { 455 BOS = make_unique<raw_svector_ostream>(Buffer); 456 OS = BOS.get(); 457 } 458 459 if (!RunPassNames->empty()) { 460 if (!StartAfter.empty() || !StopAfter.empty() || !StartBefore.empty() || 461 !StopBefore.empty()) { 462 errs() << argv[0] << ": start-after and/or stop-after passes are " 463 "redundant when run-pass is specified.\n"; 464 return 1; 465 } 466 if (!MIR) { 467 errs() << argv[0] << ": run-pass needs a .mir input.\n"; 468 return 1; 469 } 470 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target); 471 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM); 472 PM.add(&TPC); 473 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM); 474 MMI->setMachineFunctionInitializer(MIR.get()); 475 PM.add(MMI); 476 TPC.printAndVerify(""); 477 478 for (const std::string &RunPassName : *RunPassNames) { 479 if (addPass(PM, argv[0], RunPassName, TPC)) 480 return 1; 481 } 482 PM.add(createPrintMIRPass(*OS)); 483 } else { 484 const char *argv0 = argv[0]; 485 AnalysisID StartBeforeID = getPassID(argv0, "start-before", StartBefore); 486 AnalysisID StartAfterID = getPassID(argv0, "start-after", StartAfter); 487 AnalysisID StopAfterID = getPassID(argv0, "stop-after", StopAfter); 488 AnalysisID StopBeforeID = getPassID(argv0, "stop-before", StopBefore); 489 490 if (StartBeforeID && StartAfterID) { 491 errs() << argv[0] << ": -start-before and -start-after specified!\n"; 492 return 1; 493 } 494 if (StopBeforeID && StopAfterID) { 495 errs() << argv[0] << ": -stop-before and -stop-after specified!\n"; 496 return 1; 497 } 498 499 // Ask the target to add backend passes as necessary. 500 if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify, 501 StartBeforeID, StartAfterID, StopBeforeID, 502 StopAfterID, MIR.get())) { 503 errs() << argv[0] << ": target does not support generation of this" 504 << " file type!\n"; 505 return 1; 506 } 507 } 508 509 // Before executing passes, print the final values of the LLVM options. 510 cl::PrintOptionValues(); 511 512 // If requested, run the pass manager over the same module again, 513 // to catch any bugs due to persistent state in the passes. Note that 514 // opt has the same functionality, so it may be worth abstracting this out 515 // in the future. 516 SmallVector<char, 0> CompileTwiceBuffer; 517 if (CompileTwice) { 518 std::unique_ptr<Module> M2(llvm::CloneModule(M.get())); 519 PM.run(*M2); 520 CompileTwiceBuffer = Buffer; 521 Buffer.clear(); 522 } 523 524 PM.run(*M); 525 526 auto HasError = *static_cast<bool *>(Context.getDiagnosticContext()); 527 if (HasError) 528 return 1; 529 530 // Compare the two outputs and make sure they're the same 531 if (CompileTwice) { 532 if (Buffer.size() != CompileTwiceBuffer.size() || 533 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) != 534 0)) { 535 errs() 536 << "Running the pass manager twice changed the output.\n" 537 "Writing the result of the second run to the specified output\n" 538 "To generate the one-run comparison binary, just run without\n" 539 "the compile-twice option\n"; 540 Out->os() << Buffer; 541 Out->keep(); 542 return 1; 543 } 544 } 545 546 if (BOS) { 547 Out->os() << Buffer; 548 } 549 } 550 551 // Declare success. 552 Out->keep(); 553 554 return 0; 555 } 556