llc.cpp revision 37ed9c199ca639565f6ce88105f9e39e898d82d0
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/Triple.h" 18#include "llvm/CodeGen/CommandFlags.h" 19#include "llvm/CodeGen/LinkAllAsmWriterComponents.h" 20#include "llvm/CodeGen/LinkAllCodegenComponents.h" 21#include "llvm/IR/DataLayout.h" 22#include "llvm/IR/IRPrintingPasses.h" 23#include "llvm/IR/LLVMContext.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/FileSystem.h" 32#include "llvm/Support/FormattedStream.h" 33#include "llvm/Support/Host.h" 34#include "llvm/Support/ManagedStatic.h" 35#include "llvm/Support/PluginLoader.h" 36#include "llvm/Support/PrettyStackTrace.h" 37#include "llvm/Support/Signals.h" 38#include "llvm/Support/SourceMgr.h" 39#include "llvm/Support/TargetRegistry.h" 40#include "llvm/Support/TargetSelect.h" 41#include "llvm/Support/ToolOutputFile.h" 42#include "llvm/Target/TargetLibraryInfo.h" 43#include "llvm/Target/TargetMachine.h" 44#include "llvm/Target/TargetSubtargetInfo.h" 45#include <memory> 46using namespace llvm; 47 48// General options for llc. Other pass-specific options are specified 49// within the corresponding llc passes, and target-specific options 50// and back-end code generation options are specified with the target machine. 51// 52static cl::opt<std::string> 53InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); 54 55static cl::opt<std::string> 56OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); 57 58static cl::opt<unsigned> 59TimeCompilations("time-compilations", cl::Hidden, cl::init(1u), 60 cl::value_desc("N"), 61 cl::desc("Repeat compilation N times for timing")); 62 63static cl::opt<bool> 64NoIntegratedAssembler("no-integrated-as", cl::Hidden, 65 cl::desc("Disable integrated assembler")); 66 67// Determine optimization level. 68static cl::opt<char> 69OptLevel("O", 70 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] " 71 "(default = '-O2')"), 72 cl::Prefix, 73 cl::ZeroOrMore, 74 cl::init(' ')); 75 76static cl::opt<std::string> 77TargetTriple("mtriple", cl::desc("Override target triple for module")); 78 79static cl::opt<bool> NoVerify("disable-verify", cl::Hidden, 80 cl::desc("Do not verify input module")); 81 82static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls", 83 cl::desc("Disable simplify-libcalls")); 84 85static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, 86 cl::desc("Show encoding in .s output")); 87 88static cl::opt<bool> EnableDwarfDirectory( 89 "enable-dwarf-directory", cl::Hidden, 90 cl::desc("Use .file directives with an explicit directory.")); 91 92static cl::opt<bool> AsmVerbose("asm-verbose", 93 cl::desc("Add comments to directives."), 94 cl::init(true)); 95 96static int compileModule(char **, LLVMContext &); 97 98static tool_output_file *GetOutputStream(const char *TargetName, 99 Triple::OSType OS, 100 const char *ProgName) { 101 // If we don't yet have an output filename, make one. 102 if (OutputFilename.empty()) { 103 if (InputFilename == "-") 104 OutputFilename = "-"; 105 else { 106 // If InputFilename ends in .bc or .ll, remove it. 107 StringRef IFN = InputFilename; 108 if (IFN.endswith(".bc") || IFN.endswith(".ll")) 109 OutputFilename = IFN.drop_back(3); 110 else 111 OutputFilename = IFN; 112 113 switch (FileType) { 114 case TargetMachine::CGFT_AssemblyFile: 115 if (TargetName[0] == 'c') { 116 if (TargetName[1] == 0) 117 OutputFilename += ".cbe.c"; 118 else if (TargetName[1] == 'p' && TargetName[2] == 'p') 119 OutputFilename += ".cpp"; 120 else 121 OutputFilename += ".s"; 122 } else 123 OutputFilename += ".s"; 124 break; 125 case TargetMachine::CGFT_ObjectFile: 126 if (OS == Triple::Win32) 127 OutputFilename += ".obj"; 128 else 129 OutputFilename += ".o"; 130 break; 131 case TargetMachine::CGFT_Null: 132 OutputFilename += ".null"; 133 break; 134 } 135 } 136 } 137 138 // Decide if we need "binary" output. 139 bool Binary = false; 140 switch (FileType) { 141 case TargetMachine::CGFT_AssemblyFile: 142 break; 143 case TargetMachine::CGFT_ObjectFile: 144 case TargetMachine::CGFT_Null: 145 Binary = true; 146 break; 147 } 148 149 // Open the file. 150 std::error_code EC; 151 sys::fs::OpenFlags OpenFlags = sys::fs::F_None; 152 if (!Binary) 153 OpenFlags |= sys::fs::F_Text; 154 tool_output_file *FDOut = new tool_output_file(OutputFilename, EC, OpenFlags); 155 if (EC) { 156 errs() << EC.message() << '\n'; 157 delete FDOut; 158 return nullptr; 159 } 160 161 return FDOut; 162} 163 164// main - Entry point for the llc compiler. 165// 166int main(int argc, char **argv) { 167 sys::PrintStackTraceOnErrorSignal(); 168 PrettyStackTraceProgram X(argc, argv); 169 170 // Enable debug stream buffering. 171 EnableDebugBuffering = true; 172 173 LLVMContext &Context = getGlobalContext(); 174 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 175 176 // Initialize targets first, so that --version shows registered targets. 177 InitializeAllTargets(); 178 InitializeAllTargetMCs(); 179 InitializeAllAsmPrinters(); 180 InitializeAllAsmParsers(); 181 182 // Initialize codegen and IR passes used by llc so that the -print-after, 183 // -print-before, and -stop-after options work. 184 PassRegistry *Registry = PassRegistry::getPassRegistry(); 185 initializeCore(*Registry); 186 initializeCodeGen(*Registry); 187 initializeLoopStrengthReducePass(*Registry); 188 initializeLowerIntrinsicsPass(*Registry); 189 initializeUnreachableBlockElimPass(*Registry); 190 191 // Register the target printer for --version. 192 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 193 194 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); 195 196 // Compile the module TimeCompilations times to give better compile time 197 // metrics. 198 for (unsigned I = TimeCompilations; I; --I) 199 if (int RetVal = compileModule(argv, Context)) 200 return RetVal; 201 return 0; 202} 203 204static int compileModule(char **argv, LLVMContext &Context) { 205 // Load the module to be compiled... 206 SMDiagnostic Err; 207 std::unique_ptr<Module> M; 208 Module *mod = nullptr; 209 Triple TheTriple; 210 211 bool SkipModule = MCPU == "help" || 212 (!MAttrs.empty() && MAttrs.front() == "help"); 213 214 // If user asked for the 'native' CPU, autodetect here. If autodection fails, 215 // this will set the CPU to an empty string which tells the target to 216 // pick a basic default. 217 if (MCPU == "native") 218 MCPU = sys::getHostCPUName(); 219 220 // If user just wants to list available options, skip module loading 221 if (!SkipModule) { 222 M = parseIRFile(InputFilename, Err, Context); 223 mod = M.get(); 224 if (mod == nullptr) { 225 Err.print(argv[0], errs()); 226 return 1; 227 } 228 229 // If we are supposed to override the target triple, do so now. 230 if (!TargetTriple.empty()) 231 mod->setTargetTriple(Triple::normalize(TargetTriple)); 232 TheTriple = Triple(mod->getTargetTriple()); 233 } else { 234 TheTriple = Triple(Triple::normalize(TargetTriple)); 235 } 236 237 if (TheTriple.getTriple().empty()) 238 TheTriple.setTriple(sys::getDefaultTargetTriple()); 239 240 // Get the target specific parser. 241 std::string Error; 242 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 243 Error); 244 if (!TheTarget) { 245 errs() << argv[0] << ": " << Error; 246 return 1; 247 } 248 249 // Package up features to be passed to target/subtarget 250 std::string FeaturesStr; 251 if (MAttrs.size()) { 252 SubtargetFeatures Features; 253 for (unsigned i = 0; i != MAttrs.size(); ++i) 254 Features.AddFeature(MAttrs[i]); 255 FeaturesStr = Features.getString(); 256 } 257 258 CodeGenOpt::Level OLvl = CodeGenOpt::Default; 259 switch (OptLevel) { 260 default: 261 errs() << argv[0] << ": invalid optimization level.\n"; 262 return 1; 263 case ' ': break; 264 case '0': OLvl = CodeGenOpt::None; break; 265 case '1': OLvl = CodeGenOpt::Less; break; 266 case '2': OLvl = CodeGenOpt::Default; break; 267 case '3': OLvl = CodeGenOpt::Aggressive; break; 268 } 269 270 TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); 271 Options.DisableIntegratedAS = NoIntegratedAssembler; 272 Options.MCOptions.ShowMCEncoding = ShowMCEncoding; 273 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory; 274 Options.MCOptions.AsmVerbose = AsmVerbose; 275 276 std::unique_ptr<TargetMachine> target( 277 TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr, 278 Options, RelocModel, CMModel, OLvl)); 279 assert(target.get() && "Could not allocate target machine!"); 280 281 // If we don't have a module then just exit now. We do this down 282 // here since the CPU/Feature help is underneath the target machine 283 // creation. 284 if (SkipModule) 285 return 0; 286 287 assert(mod && "Should have exited if we didn't have a module!"); 288 TargetMachine &Target = *target.get(); 289 290 if (GenerateSoftFloatCalls) 291 FloatABIForCalls = FloatABI::Soft; 292 293 // Figure out where we are going to send the output. 294 std::unique_ptr<tool_output_file> Out( 295 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0])); 296 if (!Out) return 1; 297 298 // Build up all of the passes that we want to do to the module. 299 PassManager PM; 300 301 // Add an appropriate TargetLibraryInfo pass for the module's triple. 302 TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple); 303 if (DisableSimplifyLibCalls) 304 TLI->disableAllFunctions(); 305 PM.add(TLI); 306 307 // Add the target data from the target machine, if it exists, or the module. 308 if (const DataLayout *DL = Target.getSubtargetImpl()->getDataLayout()) 309 mod->setDataLayout(DL); 310 PM.add(new DataLayoutPass()); 311 312 if (RelaxAll.getNumOccurrences() > 0 && 313 FileType != TargetMachine::CGFT_ObjectFile) 314 errs() << argv[0] 315 << ": warning: ignoring -mc-relax-all because filetype != obj"; 316 317 { 318 formatted_raw_ostream FOS(Out->os()); 319 320 AnalysisID StartAfterID = nullptr; 321 AnalysisID StopAfterID = nullptr; 322 const PassRegistry *PR = PassRegistry::getPassRegistry(); 323 if (!StartAfter.empty()) { 324 const PassInfo *PI = PR->getPassInfo(StartAfter); 325 if (!PI) { 326 errs() << argv[0] << ": start-after pass is not registered.\n"; 327 return 1; 328 } 329 StartAfterID = PI->getTypeInfo(); 330 } 331 if (!StopAfter.empty()) { 332 const PassInfo *PI = PR->getPassInfo(StopAfter); 333 if (!PI) { 334 errs() << argv[0] << ": stop-after pass is not registered.\n"; 335 return 1; 336 } 337 StopAfterID = PI->getTypeInfo(); 338 } 339 340 // Ask the target to add backend passes as necessary. 341 if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify, 342 StartAfterID, StopAfterID)) { 343 errs() << argv[0] << ": target does not support generation of this" 344 << " file type!\n"; 345 return 1; 346 } 347 348 // Before executing passes, print the final values of the LLVM options. 349 cl::PrintOptionValues(); 350 351 PM.run(*mod); 352 } 353 354 // Declare success. 355 Out->keep(); 356 357 return 0; 358} 359