llc.cpp revision 99dca4fde746eb76253e737cca166261c767412d
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 52// Determine optimization level. 53static cl::opt<char> 54OptLevel("O", 55 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 56 "(default = '-O2')"), 57 cl::Prefix, 58 cl::ZeroOrMore, 59 cl::init(' ')); 60 61static cl::opt<std::string> 62TargetTriple("mtriple", cl::desc("Override target triple for module")); 63 64static cl::opt<std::string> 65MArch("march", cl::desc("Architecture to generate code for (see --version)")); 66 67static cl::opt<std::string> 68MCPU("mcpu", 69 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 70 cl::value_desc("cpu-name"), 71 cl::init("")); 72 73static cl::list<std::string> 74MAttrs("mattr", 75 cl::CommaSeparated, 76 cl::desc("Target specific attributes (-mattr=help for details)"), 77 cl::value_desc("a1,+a2,-a3,...")); 78 79cl::opt<TargetMachine::CodeGenFileType> 80FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile), 81 cl::desc("Choose a file type (not all types are supported by all targets):"), 82 cl::values( 83 clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm", 84 "Emit an assembly ('.s') file"), 85 clEnumValN(TargetMachine::CGFT_ObjectFile, "obj", 86 "Emit a native object ('.o') file [experimental]"), 87 clEnumValN(TargetMachine::CGFT_Null, "null", 88 "Emit nothing, for performance testing"), 89 clEnumValEnd)); 90 91cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 92 cl::desc("Do not verify input module")); 93 94 95static cl::opt<bool> 96DisableRedZone("disable-red-zone", 97 cl::desc("Do not emit code that uses the red zone."), 98 cl::init(false)); 99 100static cl::opt<bool> 101NoImplicitFloats("no-implicit-float", 102 cl::desc("Don't generate implicit floating point instructions (x86-only)"), 103 cl::init(false)); 104 105// GetFileNameRoot - Helper function to get the basename of a filename. 106static inline std::string 107GetFileNameRoot(const std::string &InputFilename) { 108 std::string IFN = InputFilename; 109 std::string outputFilename; 110 int Len = IFN.length(); 111 if ((Len > 2) && 112 IFN[Len-3] == '.' && 113 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') || 114 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) { 115 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ 116 } else { 117 outputFilename = IFN; 118 } 119 return outputFilename; 120} 121 122static formatted_raw_ostream *GetOutputStream(const char *TargetName, 123 Triple::OSType OS, 124 const char *ProgName) { 125 if (OutputFilename != "") { 126 if (OutputFilename == "-") 127 return &fouts(); 128 129 // Make sure that the Out file gets unlinked from the disk if we get a 130 // SIGINT 131 sys::RemoveFileOnSignal(sys::Path(OutputFilename)); 132 133 std::string error; 134 raw_fd_ostream *FDOut = 135 new raw_fd_ostream(OutputFilename.c_str(), error, 136 raw_fd_ostream::F_Binary); 137 if (!error.empty()) { 138 errs() << error << '\n'; 139 delete FDOut; 140 return 0; 141 } 142 formatted_raw_ostream *Out = 143 new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM); 144 145 return Out; 146 } 147 148 if (InputFilename == "-") { 149 OutputFilename = "-"; 150 return &fouts(); 151 } 152 153 OutputFilename = GetFileNameRoot(InputFilename); 154 155 bool Binary = false; 156 switch (FileType) { 157 default: assert(0 && "Unknown file type"); 158 case TargetMachine::CGFT_AssemblyFile: 159 if (TargetName[0] == 'c') { 160 if (TargetName[1] == 0) 161 OutputFilename += ".cbe.c"; 162 else if (TargetName[1] == 'p' && TargetName[2] == 'p') 163 OutputFilename += ".cpp"; 164 else 165 OutputFilename += ".s"; 166 } else 167 OutputFilename += ".s"; 168 break; 169 case TargetMachine::CGFT_ObjectFile: 170 if (OS == Triple::Win32) 171 OutputFilename += ".obj"; 172 else 173 OutputFilename += ".o"; 174 Binary = true; 175 break; 176 case TargetMachine::CGFT_Null: 177 OutputFilename += ".null"; 178 Binary = true; 179 break; 180 } 181 182 // Make sure that the Out file gets unlinked from the disk if we get a 183 // SIGINT 184 sys::RemoveFileOnSignal(sys::Path(OutputFilename)); 185 186 std::string error; 187 unsigned OpenFlags = 0; 188 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary; 189 raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error, 190 OpenFlags); 191 if (!error.empty()) { 192 errs() << error << '\n'; 193 delete FDOut; 194 return 0; 195 } 196 197 formatted_raw_ostream *Out = 198 new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM); 199 200 return Out; 201} 202 203// main - Entry point for the llc compiler. 204// 205int main(int argc, char **argv) { 206 sys::PrintStackTraceOnErrorSignal(); 207 PrettyStackTraceProgram X(argc, argv); 208 209 // Enable debug stream buffering. 210 EnableDebugBuffering = true; 211 212 LLVMContext &Context = getGlobalContext(); 213 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 214 215 // Initialize targets first, so that --version shows registered targets. 216 InitializeAllTargets(); 217 InitializeAllAsmPrinters(); 218 InitializeAllAsmParsers(); 219 220 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 221 222 // Load the module to be compiled... 223 SMDiagnostic Err; 224 std::auto_ptr<Module> M; 225 226 M.reset(ParseIRFile(InputFilename, Err, Context)); 227 if (M.get() == 0) { 228 Err.Print(argv[0], errs()); 229 return 1; 230 } 231 Module &mod = *M.get(); 232 233 // If we are supposed to override the target triple, do so now. 234 if (!TargetTriple.empty()) 235 mod.setTargetTriple(TargetTriple); 236 237 Triple TheTriple(mod.getTargetTriple()); 238 if (TheTriple.getTriple().empty()) 239 TheTriple.setTriple(sys::getHostTriple()); 240 241 // Allocate target machine. First, check whether the user has explicitly 242 // specified an architecture to compile for. If so we have to look it up by 243 // name, because it might be a backend that has no mapping to a target triple. 244 const Target *TheTarget = 0; 245 if (!MArch.empty()) { 246 for (TargetRegistry::iterator it = TargetRegistry::begin(), 247 ie = TargetRegistry::end(); it != ie; ++it) { 248 if (MArch == it->getName()) { 249 TheTarget = &*it; 250 break; 251 } 252 } 253 254 if (!TheTarget) { 255 errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n"; 256 return 1; 257 } 258 259 // Adjust the triple to match (if known), otherwise stick with the 260 // module/host triple. 261 Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch); 262 if (Type != Triple::UnknownArch) 263 TheTriple.setArch(Type); 264 } else { 265 std::string Err; 266 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err); 267 if (TheTarget == 0) { 268 errs() << argv[0] << ": error auto-selecting target for module '" 269 << Err << "'. Please use the -march option to explicitly " 270 << "pick a target.\n"; 271 return 1; 272 } 273 } 274 275 // Package up features to be passed to target/subtarget 276 std::string FeaturesStr; 277 if (MCPU.size() || MAttrs.size()) { 278 SubtargetFeatures Features; 279 Features.setCPU(MCPU); 280 for (unsigned i = 0; i != MAttrs.size(); ++i) 281 Features.AddFeature(MAttrs[i]); 282 FeaturesStr = Features.getString(); 283 } 284 285 std::auto_ptr<TargetMachine> 286 target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr)); 287 assert(target.get() && "Could not allocate target machine!"); 288 TargetMachine &Target = *target.get(); 289 290 // Figure out where we are going to send the output... 291 formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(), 292 TheTriple.getOS(), argv[0]); 293 if (Out == 0) return 1; 294 295 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 296 switch (OptLevel) { 297 default: 298 errs() << argv[0] << ": invalid optimization level.\n"; 299 return 1; 300 case ' ': break; 301 case '0': OLvl = CodeGenOpt::None; break; 302 case '1': OLvl = CodeGenOpt::Less; break; 303 case '2': OLvl = CodeGenOpt::Default; break; 304 case '3': OLvl = CodeGenOpt::Aggressive; break; 305 } 306 307 // Request that addPassesToEmitFile run the Verifier after running 308 // passes which modify the IR. 309#ifndef NDEBUG 310 bool DisableVerify = false; 311#else 312 bool DisableVerify = true; 313#endif 314 315 // Build up all of the passes that we want to do to the module. 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 // Override default to generate verbose assembly. 328 Target.setAsmVerbosityDefault(true); 329 330 // Ask the target to add backend passes as necessary. 331 if (Target.addPassesToEmitFile(PM, *Out, FileType, OLvl, 332 DisableVerify)) { 333 errs() << argv[0] << ": target does not support generation of this" 334 << " file type!\n"; 335 if (Out != &fouts()) delete Out; 336 // And the Out file is empty and useless, so remove it now. 337 sys::Path(OutputFilename).eraseFromDisk(); 338 return 1; 339 } 340 341 PM.run(mod); 342 343 // Delete the ostream if it's not a stdout stream 344 if (Out != &fouts()) delete Out; 345 346 return 0; 347} 348