llc.cpp revision 12c74dc2c2ee306f60fb39a9b2a43000e23addcc
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/IR/LLVMContext.h" 18#include "llvm/ADT/Triple.h" 19#include "llvm/Assembly/PrintModulePass.h" 20#include "llvm/CodeGen/CommandFlags.h" 21#include "llvm/CodeGen/LinkAllAsmWriterComponents.h" 22#include "llvm/CodeGen/LinkAllCodegenComponents.h" 23#include "llvm/IR/DataLayout.h" 24#include "llvm/IR/Module.h" 25#include "llvm/IRReader/IRReader.h" 26#include "llvm/MC/SubtargetFeature.h" 27#include "llvm/Pass.h" 28#include "llvm/PassManager.h" 29#include "llvm/Support/CommandLine.h" 30#include "llvm/Support/Debug.h" 31#include "llvm/Support/FormattedStream.h" 32#include "llvm/Support/Host.h" 33#include "llvm/Support/ManagedStatic.h" 34#include "llvm/Support/PluginLoader.h" 35#include "llvm/Support/PrettyStackTrace.h" 36#include "llvm/Support/Signals.h" 37#include "llvm/Support/SourceMgr.h" 38#include "llvm/Support/TargetRegistry.h" 39#include "llvm/Support/TargetSelect.h" 40#include "llvm/Support/ToolOutputFile.h" 41#include "llvm/Target/TargetLibraryInfo.h" 42#include "llvm/Target/TargetMachine.h" 43#include <memory> 44using namespace llvm; 45 46// General options for llc. Other pass-specific options are specified 47// within the corresponding llc passes, and target-specific options 48// and back-end code generation options are specified with the target machine. 49// 50static cl::opt<std::string> 51InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 52 53static cl::opt<std::string> 54OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 55 56static cl::opt<unsigned> 57TimeCompilations("time-compilations", cl::Hidden, cl::init(1u), 58 cl::value_desc("N"), 59 cl::desc("Repeat compilation N times for timing")); 60 61// Determine optimization level. 62static cl::opt<char> 63OptLevel("O", 64 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 65 "(default = '-O2')"), 66 cl::Prefix, 67 cl::ZeroOrMore, 68 cl::init(' ')); 69 70static cl::opt<std::string> 71TargetTriple("mtriple", cl::desc("Override target triple for module")); 72 73cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 74 cl::desc("Do not verify input module")); 75 76cl::opt<bool> 77DisableSimplifyLibCalls("disable-simplify-libcalls", 78 cl::desc("Disable simplify-libcalls"), 79 cl::init(false)); 80 81static int compileModule(char**, LLVMContext&); 82 83// GetFileNameRoot - Helper function to get the basename of a filename. 84static inline std::string 85GetFileNameRoot(const std::string &InputFilename) { 86 std::string IFN = InputFilename; 87 std::string outputFilename; 88 int Len = IFN.length(); 89 if ((Len > 2) && 90 IFN[Len-3] == '.' && 91 ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') || 92 (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) { 93 outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/ 94 } else { 95 outputFilename = IFN; 96 } 97 return outputFilename; 98} 99 100static tool_output_file *GetOutputStream(const char *TargetName, 101 Triple::OSType OS, 102 const char *ProgName) { 103 // If we don't yet have an output filename, make one. 104 if (OutputFilename.empty()) { 105 if (InputFilename == "-") 106 OutputFilename = "-"; 107 else { 108 OutputFilename = GetFileNameRoot(InputFilename); 109 110 switch (FileType) { 111 case TargetMachine::CGFT_AssemblyFile: 112 if (TargetName[0] == 'c') { 113 if (TargetName[1] == 0) 114 OutputFilename += ".cbe.c"; 115 else if (TargetName[1] == 'p' && TargetName[2] == 'p') 116 OutputFilename += ".cpp"; 117 else 118 OutputFilename += ".s"; 119 } else 120 OutputFilename += ".s"; 121 break; 122 case TargetMachine::CGFT_ObjectFile: 123 if (OS == Triple::Win32) 124 OutputFilename += ".obj"; 125 else 126 OutputFilename += ".o"; 127 break; 128 case TargetMachine::CGFT_Null: 129 OutputFilename += ".null"; 130 break; 131 } 132 } 133 } 134 135 // Decide if we need "binary" output. 136 bool Binary = false; 137 switch (FileType) { 138 case TargetMachine::CGFT_AssemblyFile: 139 break; 140 case TargetMachine::CGFT_ObjectFile: 141 case TargetMachine::CGFT_Null: 142 Binary = true; 143 break; 144 } 145 146 // Open the file. 147 std::string error; 148 unsigned OpenFlags = 0; 149 if (Binary) OpenFlags |= raw_fd_ostream::F_Binary; 150 tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error, 151 OpenFlags); 152 if (!error.empty()) { 153 errs() << error << '\n'; 154 delete FDOut; 155 return 0; 156 } 157 158 return FDOut; 159} 160 161// main - Entry point for the llc compiler. 162// 163int main(int argc, char **argv) { 164 sys::PrintStackTraceOnErrorSignal(); 165 PrettyStackTraceProgram X(argc, argv); 166 167 // Enable debug stream buffering. 168 EnableDebugBuffering = true; 169 170 LLVMContext &Context = getGlobalContext(); 171 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 172 173 // Initialize targets first, so that --version shows registered targets. 174 InitializeAllTargets(); 175 InitializeAllTargetMCs(); 176 InitializeAllAsmPrinters(); 177 InitializeAllAsmParsers(); 178 179 // Initialize codegen and IR passes used by llc so that the -print-after, 180 // -print-before, and -stop-after options work. 181 PassRegistry *Registry = PassRegistry::getPassRegistry(); 182 initializeCore(*Registry); 183 initializeCodeGen(*Registry); 184 initializeLoopStrengthReducePass(*Registry); 185 initializeLowerIntrinsicsPass(*Registry); 186 initializeUnreachableBlockElimPass(*Registry); 187 188 // Register the target printer for --version. 189 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 190 191 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 192 193 // Compile the module TimeCompilations times to give better compile time 194 // metrics. 195 for (unsigned I = TimeCompilations; I; --I) 196 if (int RetVal = compileModule(argv, Context)) 197 return RetVal; 198 return 0; 199} 200 201static int compileModule(char **argv, LLVMContext &Context) { 202 // Load the module to be compiled... 203 SMDiagnostic Err; 204 OwningPtr<Module> M; 205 Module *mod = 0; 206 Triple TheTriple; 207 208 bool SkipModule = MCPU == "help" || 209 (!MAttrs.empty() && MAttrs.front() == "help"); 210 211 // If user just wants to list available options, skip module loading 212 if (!SkipModule) { 213 M.reset(ParseIRFile(InputFilename, Err, Context)); 214 mod = M.get(); 215 if (mod == 0) { 216 Err.print(argv[0], errs()); 217 return 1; 218 } 219 220 // If we are supposed to override the target triple, do so now. 221 if (!TargetTriple.empty()) 222 mod->setTargetTriple(Triple::normalize(TargetTriple)); 223 TheTriple = Triple(mod->getTargetTriple()); 224 } else { 225 TheTriple = Triple(Triple::normalize(TargetTriple)); 226 } 227 228 if (TheTriple.getTriple().empty()) 229 TheTriple.setTriple(sys::getDefaultTargetTriple()); 230 231 // Get the target specific parser. 232 std::string Error; 233 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 234 Error); 235 if (!TheTarget) { 236 errs() << argv[0] << ": " << Error; 237 return 1; 238 } 239 240 // Package up features to be passed to target/subtarget 241 std::string FeaturesStr; 242 if (MAttrs.size()) { 243 SubtargetFeatures Features; 244 for (unsigned i = 0; i != MAttrs.size(); ++i) 245 Features.AddFeature(MAttrs[i]); 246 FeaturesStr = Features.getString(); 247 } 248 249 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 250 switch (OptLevel) { 251 default: 252 errs() << argv[0] << ": invalid optimization level.\n"; 253 return 1; 254 case ' ': break; 255 case '0': OLvl = CodeGenOpt::None; break; 256 case '1': OLvl = CodeGenOpt::Less; break; 257 case '2': OLvl = CodeGenOpt::Default; break; 258 case '3': OLvl = CodeGenOpt::Aggressive; break; 259 } 260 261 TargetOptions Options; 262 Options.LessPreciseFPMADOption = EnableFPMAD; 263 Options.NoFramePointerElim = DisableFPElim; 264 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf; 265 Options.AllowFPOpFusion = FuseFPOps; 266 Options.UnsafeFPMath = EnableUnsafeFPMath; 267 Options.NoInfsFPMath = EnableNoInfsFPMath; 268 Options.NoNaNsFPMath = EnableNoNaNsFPMath; 269 Options.HonorSignDependentRoundingFPMathOption = 270 EnableHonorSignDependentRoundingFPMath; 271 Options.UseSoftFloat = GenerateSoftFloatCalls; 272 if (FloatABIForCalls != FloatABI::Default) 273 Options.FloatABIType = FloatABIForCalls; 274 Options.NoZerosInBSS = DontPlaceZerosInBSS; 275 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt; 276 Options.DisableTailCalls = DisableTailCalls; 277 Options.StackAlignmentOverride = OverrideStackAlignment; 278 Options.RealignStack = EnableRealignStack; 279 Options.TrapFuncName = TrapFuncName; 280 Options.PositionIndependentExecutable = EnablePIE; 281 Options.EnableSegmentedStacks = SegmentedStacks; 282 Options.UseInitArray = UseInitArray; 283 Options.SSPBufferSize = SSPBufferSize; 284 285 OwningPtr<TargetMachine> 286 target(TheTarget->createTargetMachine(TheTriple.getTriple(), 287 MCPU, FeaturesStr, Options, 288 RelocModel, CMModel, OLvl)); 289 assert(target.get() && "Could not allocate target machine!"); 290 assert(mod && "Should have exited after outputting help!"); 291 TargetMachine &Target = *target.get(); 292 293 if (DisableDotLoc) 294 Target.setMCUseLoc(false); 295 296 if (DisableCFI) 297 Target.setMCUseCFI(false); 298 299 if (EnableDwarfDirectory) 300 Target.setMCUseDwarfDirectory(true); 301 302 if (GenerateSoftFloatCalls) 303 FloatABIForCalls = FloatABI::Soft; 304 305 // Disable .loc support for older OS X versions. 306 if (TheTriple.isMacOSX() && 307 TheTriple.isMacOSXVersionLT(10, 6)) 308 Target.setMCUseLoc(false); 309 310 // Figure out where we are going to send the output. 311 OwningPtr<tool_output_file> Out 312 (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0])); 313 if (!Out) return 1; 314 315 // Build up all of the passes that we want to do to the module. 316 PassManager PM; 317 318 // Add an appropriate TargetLibraryInfo pass for the module's triple. 319 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple); 320 if (DisableSimplifyLibCalls) 321 TLI->disableAllFunctions(); 322 PM.add(TLI); 323 324 // Add intenal analysis passes from the target machine. 325 Target.addAnalysisPasses(PM); 326 327 // Add the target data from the target machine, if it exists, or the module. 328 if (const DataLayout *TD = Target.getDataLayout()) 329 PM.add(new DataLayout(*TD)); 330 else 331 PM.add(new DataLayout(mod)); 332 333 // Override default to generate verbose assembly. 334 Target.setAsmVerbosityDefault(true); 335 336 if (RelaxAll) { 337 if (FileType != TargetMachine::CGFT_ObjectFile) 338 errs() << argv[0] 339 << ": warning: ignoring -mc-relax-all because filetype != obj"; 340 else 341 Target.setMCRelaxAll(true); 342 } 343 344 { 345 formatted_raw_ostream FOS(Out->os()); 346 347 AnalysisID StartAfterID = 0; 348 AnalysisID StopAfterID = 0; 349 const PassRegistry *PR = PassRegistry::getPassRegistry(); 350 if (!StartAfter.empty()) { 351 const PassInfo *PI = PR->getPassInfo(StartAfter); 352 if (!PI) { 353 errs() << argv[0] << ": start-after pass is not registered.\n"; 354 return 1; 355 } 356 StartAfterID = PI->getTypeInfo(); 357 } 358 if (!StopAfter.empty()) { 359 const PassInfo *PI = PR->getPassInfo(StopAfter); 360 if (!PI) { 361 errs() << argv[0] << ": stop-after pass is not registered.\n"; 362 return 1; 363 } 364 StopAfterID = PI->getTypeInfo(); 365 } 366 367 // Ask the target to add backend passes as necessary. 368 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify, 369 StartAfterID, StopAfterID)) { 370 errs() << argv[0] << ": target does not support generation of this" 371 << " file type!\n"; 372 return 1; 373 } 374 375 // Before executing passes, print the final values of the LLVM options. 376 cl::PrintOptionValues(); 377 378 PM.run(*mod); 379 } 380 381 // Declare success. 382 Out->keep(); 383 384 return 0; 385} 386