llc.cpp revision 206274
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#include "llvm/LLVMContext.h" 17#include "llvm/Module.h" 18#include "llvm/PassManager.h" 19#include "llvm/Pass.h" 20#include "llvm/ADT/Triple.h" 21#include "llvm/Analysis/Verifier.h" 22#include "llvm/Support/IRReader.h" 23#include "llvm/CodeGen/LinkAllAsmWriterComponents.h" 24#include "llvm/CodeGen/LinkAllCodegenComponents.h" 25#include "llvm/Config/config.h" 26#include "llvm/Support/CommandLine.h" 27#include "llvm/Support/Debug.h" 28#include "llvm/Support/FormattedStream.h" 29#include "llvm/Support/ManagedStatic.h" 30#include "llvm/Support/PluginLoader.h" 31#include "llvm/Support/PrettyStackTrace.h" 32#include "llvm/System/Host.h" 33#include "llvm/System/Signals.h" 34#include "llvm/Target/SubtargetFeature.h" 35#include "llvm/Target/TargetData.h" 36#include "llvm/Target/TargetMachine.h" 37#include "llvm/Target/TargetRegistry.h" 38#include "llvm/Target/TargetSelect.h" 39#include <memory> 40using namespace llvm; 41 42// General options for llc. Other pass-specific options are specified 43// within the corresponding llc passes, and target-specific options 44// and back-end code generation options are specified with the target machine. 45// 46static cl::opt<std::string> 47InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 48 49static cl::opt<std::string> 50OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 51 52static cl::opt<bool> 53Force("f", cl::desc("Enable binary output on terminals")); 54 55// Determine optimization level. 56static cl::opt<char> 57OptLevel("O", 58 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 59 "(default = '-O2')"), 60 cl::Prefix, 61 cl::ZeroOrMore, 62 cl::init(' ')); 63 64static cl::opt<std::string> 65TargetTriple("mtriple", cl::desc("Override target triple for module")); 66 67static cl::opt<std::string> 68MArch("march", cl::desc("Architecture to generate code for (see --version)")); 69 70static cl::opt<std::string> 71MCPU("mcpu", 72 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 73 cl::value_desc("cpu-name"), 74 cl::init("")); 75 76static cl::list<std::string> 77MAttrs("mattr", 78 cl::CommaSeparated, 79 cl::desc("Target specific attributes (-mattr=help for details)"), 80 cl::value_desc("a1,+a2,-a3,...")); 81 82cl::opt<TargetMachine::CodeGenFileType> 83FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile), 84 cl::desc("Choose a file type (not all types are supported by all targets):"), 85 cl::values( 86 clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm", 87 "Emit an assembly ('.s') file"), 88 clEnumValN(TargetMachine::CGFT_ObjectFile, "obj", 89 "Emit a native object ('.o') file [experimental]"), 90 clEnumValN(TargetMachine::CGFT_Null, "null", 91 "Emit nothing, for performance testing"), 92 clEnumValEnd)); 93 94cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 95 cl::desc("Do not verify input module")); 96 97 98static cl::opt<bool> 99DisableRedZone("disable-red-zone", 100 cl::desc("Do not emit code that uses the red zone."), 101 cl::init(false)); 102 103static cl::opt<bool> 104NoImplicitFloats("no-implicit-float", 105 cl::desc("Don't generate implicit floating point instructions (x86-only)"), 106 cl::init(false)); 107 108// GetFileNameRoot - Helper function to get the basename of a filename. 109static inline std::string 110GetFileNameRoot(const std::string &InputFilename) { 111 std::string IFN = InputFilename; 112 std::string outputFilename; 113 int Len = IFN.length(); 114 if ((Len > 2) && 115 IFN[Len-3] == '.' && 116 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') || 117 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) { 118 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ 119 } else { 120 outputFilename = IFN; 121 } 122 return outputFilename; 123} 124 125static formatted_raw_ostream *GetOutputStream(const char *TargetName, 126 const char *ProgName) { 127 if (OutputFilename != "") { 128 if (OutputFilename == "-") 129 return &fouts(); 130 131 // Make sure that the Out file gets unlinked from the disk if we get a 132 // SIGINT 133 sys::RemoveFileOnSignal(sys::Path(OutputFilename)); 134 135 std::string error; 136 raw_fd_ostream *FDOut = 137 new raw_fd_ostream(OutputFilename.c_str(), error, 138 raw_fd_ostream::F_Binary); 139 if (!error.empty()) { 140 errs() << error << '\n'; 141 delete FDOut; 142 return 0; 143 } 144 formatted_raw_ostream *Out = 145 new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM); 146 147 return Out; 148 } 149 150 if (InputFilename == "-") { 151 OutputFilename = "-"; 152 return &fouts(); 153 } 154 155 OutputFilename = GetFileNameRoot(InputFilename); 156 157 bool Binary = false; 158 switch (FileType) { 159 default: assert(0 && "Unknown file type"); 160 case TargetMachine::CGFT_AssemblyFile: 161 if (TargetName[0] == 'c') { 162 if (TargetName[1] == 0) 163 OutputFilename += ".cbe.c"; 164 else if (TargetName[1] == 'p' && TargetName[2] == 'p') 165 OutputFilename += ".cpp"; 166 else 167 OutputFilename += ".s"; 168 } else 169 OutputFilename += ".s"; 170 break; 171 case TargetMachine::CGFT_ObjectFile: 172 OutputFilename += ".o"; 173 Binary = true; 174 break; 175 case TargetMachine::CGFT_Null: 176 OutputFilename += ".null"; 177 Binary = true; 178 break; 179 } 180 181 // Make sure that the Out file gets unlinked from the disk if we get a 182 // SIGINT 183 sys::RemoveFileOnSignal(sys::Path(OutputFilename)); 184 185 std::string error; 186 unsigned OpenFlags = 0; 187 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary; 188 raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error, 189 OpenFlags); 190 if (!error.empty()) { 191 errs() << error << '\n'; 192 delete FDOut; 193 return 0; 194 } 195 196 formatted_raw_ostream *Out = 197 new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM); 198 199 return Out; 200} 201 202// main - Entry point for the llc compiler. 203// 204int main(int argc, char **argv) { 205 sys::PrintStackTraceOnErrorSignal(); 206 PrettyStackTraceProgram X(argc, argv); 207 208 // Enable debug stream buffering. 209 EnableDebugBuffering = true; 210 211 LLVMContext &Context = getGlobalContext(); 212 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 213 214 // Initialize targets first, so that --version shows registered targets. 215 InitializeAllTargets(); 216 InitializeAllAsmPrinters(); 217 InitializeAllAsmParsers(); 218 219 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 220 221 // Load the module to be compiled... 222 SMDiagnostic Err; 223 std::auto_ptr<Module> M; 224 225 M.reset(ParseIRFile(InputFilename, Err, Context)); 226 if (M.get() == 0) { 227 Err.Print(argv[0], errs()); 228 return 1; 229 } 230 Module &mod = *M.get(); 231 232 // If we are supposed to override the target triple, do so now. 233 if (!TargetTriple.empty()) 234 mod.setTargetTriple(TargetTriple); 235 236 Triple TheTriple(mod.getTargetTriple()); 237 if (TheTriple.getTriple().empty()) 238 TheTriple.setTriple(sys::getHostTriple()); 239 240 // Allocate target machine. First, check whether the user has explicitly 241 // specified an architecture to compile for. If so we have to look it up by 242 // name, because it might be a backend that has no mapping to a target triple. 243 const Target *TheTarget = 0; 244 if (!MArch.empty()) { 245 for (TargetRegistry::iterator it = TargetRegistry::begin(), 246 ie = TargetRegistry::end(); it != ie; ++it) { 247 if (MArch == it->getName()) { 248 TheTarget = &*it; 249 break; 250 } 251 } 252 253 if (!TheTarget) { 254 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n"; 255 return 1; 256 } 257 258 // Adjust the triple to match (if known), otherwise stick with the 259 // module/host triple. 260 Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch); 261 if (Type != Triple::UnknownArch) 262 TheTriple.setArch(Type); 263 } else { 264 std::string Err; 265 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err); 266 if (TheTarget == 0) { 267 errs() << argv[0] << ": error auto-selecting target for module '" 268 << Err << "'. Please use the -march option to explicitly " 269 << "pick a target.\n"; 270 return 1; 271 } 272 } 273 274 // Package up features to be passed to target/subtarget 275 std::string FeaturesStr; 276 if (MCPU.size() || MAttrs.size()) { 277 SubtargetFeatures Features; 278 Features.setCPU(MCPU); 279 for (unsigned i = 0; i != MAttrs.size(); ++i) 280 Features.AddFeature(MAttrs[i]); 281 FeaturesStr = Features.getString(); 282 } 283 284 std::auto_ptr<TargetMachine> 285 target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr)); 286 assert(target.get() && "Could not allocate target machine!"); 287 TargetMachine &Target = *target.get(); 288 289 // Figure out where we are going to send the output... 290 formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(), argv[0]); 291 if (Out == 0) return 1; 292 293 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 294 switch (OptLevel) { 295 default: 296 errs() << argv[0] << ": invalid optimization level.\n"; 297 return 1; 298 case ' ': break; 299 case '0': OLvl = CodeGenOpt::None; break; 300 case '1': OLvl = CodeGenOpt::Less; break; 301 case '2': OLvl = CodeGenOpt::Default; break; 302 case '3': OLvl = CodeGenOpt::Aggressive; break; 303 } 304 305 // Request that addPassesToEmitFile run the Verifier after running 306 // passes which modify the IR. 307#ifndef NDEBUG 308 bool DisableVerify = false; 309#else 310 bool DisableVerify = true; 311#endif 312 313 // If this target requires addPassesToEmitWholeFile, do it now. This is 314 // used by strange things like the C backend. 315 if (Target.WantsWholeFile()) { 316 PassManager PM; 317 318 // Add the target data from the target machine, if it exists, or the module. 319 if (const TargetData *TD = Target.getTargetData()) 320 PM.add(new TargetData(*TD)); 321 else 322 PM.add(new TargetData(&mod)); 323 324 if (!NoVerify) 325 PM.add(createVerifierPass()); 326 327 // Ask the target to add backend passes as necessary. 328 if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, OLvl, 329 DisableVerify)) { 330 errs() << argv[0] << ": target does not support generation of this" 331 << " file type!\n"; 332 if (Out != &fouts()) delete Out; 333 // And the Out file is empty and useless, so remove it now. 334 sys::Path(OutputFilename).eraseFromDisk(); 335 return 1; 336 } 337 PM.run(mod); 338 } else { 339 // Build up all of the passes that we want to do to the module. 340 FunctionPassManager Passes(M.get()); 341 342 // Add the target data from the target machine, if it exists, or the module. 343 if (const TargetData *TD = Target.getTargetData()) 344 Passes.add(new TargetData(*TD)); 345 else 346 Passes.add(new TargetData(&mod)); 347 348#ifndef NDEBUG 349 if (!NoVerify) 350 Passes.add(createVerifierPass()); 351#endif 352 353 // Override default to generate verbose assembly. 354 Target.setAsmVerbosityDefault(true); 355 356 if (Target.addPassesToEmitFile(Passes, *Out, FileType, OLvl, 357 DisableVerify)) { 358 errs() << argv[0] << ": target does not support generation of this" 359 << " file type!\n"; 360 if (Out != &fouts()) delete Out; 361 // And the Out file is empty and useless, so remove it now. 362 sys::Path(OutputFilename).eraseFromDisk(); 363 return 1; 364 } 365 366 Passes.doInitialization(); 367 368 // Run our queue of passes all at once now, efficiently. 369 // TODO: this could lazily stream functions out of the module. 370 for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I) 371 if (!I->isDeclaration()) { 372 if (DisableRedZone) 373 I->addFnAttr(Attribute::NoRedZone); 374 if (NoImplicitFloats) 375 I->addFnAttr(Attribute::NoImplicitFloat); 376 Passes.run(*I); 377 } 378 379 Passes.doFinalization(); 380 } 381 382 // Delete the ostream if it's not a stdout stream 383 if (Out != &fouts()) delete Out; 384 385 return 0; 386} 387