LLVMTargetMachine.cpp revision d6889ceb21f6478604547c55963539a7ecc8449f
1//===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===// 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 file implements the LLVMTargetMachine class. 11// 12//===----------------------------------------------------------------------===// 13 14#include "llvm/Target/TargetMachine.h" 15#include "llvm/PassManager.h" 16#include "llvm/Pass.h" 17#include "llvm/Assembly/PrintModulePass.h" 18#include "llvm/CodeGen/AsmPrinter.h" 19#include "llvm/CodeGen/Passes.h" 20#include "llvm/CodeGen/GCStrategy.h" 21#include "llvm/CodeGen/MachineFunctionAnalysis.h" 22#include "llvm/Target/TargetOptions.h" 23#include "llvm/MC/MCAsmInfo.h" 24#include "llvm/MC/MCContext.h" 25#include "llvm/MC/MCStreamer.h" 26#include "llvm/Target/TargetData.h" 27#include "llvm/Target/TargetRegistry.h" 28#include "llvm/Transforms/Scalar.h" 29#include "llvm/ADT/OwningPtr.h" 30#include "llvm/Support/CommandLine.h" 31#include "llvm/Support/Debug.h" 32#include "llvm/Support/FormattedStream.h" 33using namespace llvm; 34 35namespace llvm { 36 bool EnableFastISel; 37} 38 39static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden, 40 cl::desc("Disable Post Regalloc")); 41static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden, 42 cl::desc("Disable branch folding")); 43static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, 44 cl::desc("Disable tail duplication")); 45static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden, 46 cl::desc("Disable pre-register allocation tail duplication")); 47static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden, 48 cl::desc("Disable code placement")); 49static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, 50 cl::desc("Disable Stack Slot Coloring")); 51static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, 52 cl::desc("Disable Machine LICM")); 53static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, 54 cl::desc("Disable Machine Sinking")); 55static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, 56 cl::desc("Disable Loop Strength Reduction Pass")); 57static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, 58 cl::desc("Disable Codegen Prepare")); 59static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, 60 cl::desc("Print LLVM IR produced by the loop-reduce pass")); 61static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, 62 cl::desc("Print LLVM IR input to isel pass")); 63static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, 64 cl::desc("Dump garbage collector data")); 65static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden, 66 cl::desc("Verify generated machine code"), 67 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL)); 68 69static cl::opt<cl::boolOrDefault> 70AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), 71 cl::init(cl::BOU_UNSET)); 72 73static bool getVerboseAsm() { 74 switch (AsmVerbose) { 75 default: 76 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault(); 77 case cl::BOU_TRUE: return true; 78 case cl::BOU_FALSE: return false; 79 } 80} 81 82// Enable or disable FastISel. Both options are needed, because 83// FastISel is enabled by default with -fast, and we wish to be 84// able to enable or disable fast-isel independently from -O0. 85static cl::opt<cl::boolOrDefault> 86EnableFastISelOption("fast-isel", cl::Hidden, 87 cl::desc("Enable the \"fast\" instruction selector")); 88 89// Enable or disable an experimental optimization to split GEPs 90// and run a special GVN pass which does not examine loads, in 91// an effort to factor out redundancy implicit in complex GEPs. 92static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden, 93 cl::desc("Split GEPs and run no-load GVN")); 94 95LLVMTargetMachine::LLVMTargetMachine(const Target &T, 96 const std::string &TargetTriple) 97 : TargetMachine(T) { 98 AsmInfo = T.createAsmInfo(TargetTriple); 99} 100 101// Set the default code model for the JIT for a generic target. 102// FIXME: Is small right here? or .is64Bit() ? Large : Small? 103void 104LLVMTargetMachine::setCodeModelForJIT() { 105 setCodeModel(CodeModel::Small); 106} 107 108// Set the default code model for static compilation for a generic target. 109void 110LLVMTargetMachine::setCodeModelForStatic() { 111 setCodeModel(CodeModel::Small); 112} 113 114TargetMachine::CodeGenFileType 115LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM, 116 formatted_raw_ostream &Out, 117 CodeGenFileType FileType, 118 CodeGenOpt::Level OptLevel) { 119 // Add common CodeGen passes. 120 if (addCommonCodeGenPasses(PM, OptLevel)) 121 return CGFT_ErrorOccurred; 122 123 OwningPtr<MCContext> Context(new MCContext()); 124 OwningPtr<MCStreamer> AsmStreamer; 125 126 formatted_raw_ostream *LegacyOutput; 127 switch (FileType) { 128 default: return CGFT_ErrorOccurred; 129 case CGFT_AssemblyFile: 130 AsmStreamer.reset(createAsmStreamer(*Context, Out, *getMCAsmInfo(), 131 getTargetData()->isLittleEndian(), 132 getVerboseAsm(), /*instprinter*/0, 133 /*codeemitter*/0)); 134 // Set the AsmPrinter's "O" to the output file. 135 LegacyOutput = &Out; 136 break; 137 case CGFT_ObjectFile: { 138 // Create the code emitter for the target if it exists. If not, .o file 139 // emission fails. 140 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this); 141 if (MCE == 0) 142 return CGFT_ErrorOccurred; 143 144 AsmStreamer.reset(createMachOStreamer(*Context, Out, MCE)); 145 146 // Any output to the asmprinter's "O" stream is bad and needs to be fixed, 147 // force it to come out stderr. 148 // FIXME: this is horrible and leaks, eventually remove the raw_ostream from 149 // asmprinter. 150 LegacyOutput = new formatted_raw_ostream(errs()); 151 break; 152 } 153 } 154 155 // Create the AsmPrinter, which takes ownership of Context and AsmStreamer 156 // if successful. 157 FunctionPass *Printer = 158 getTarget().createAsmPrinter(*LegacyOutput, *this, *Context, *AsmStreamer, 159 getMCAsmInfo()); 160 if (Printer == 0) 161 return CGFT_ErrorOccurred; 162 163 // If successful, createAsmPrinter took ownership of AsmStreamer and Context. 164 Context.take(); AsmStreamer.take(); 165 166 PM.add(Printer); 167 168 // Make sure the code model is set. 169 setCodeModelForStatic(); 170 PM.add(createGCInfoDeleter()); 171 return FileType; 172} 173 174/// addPassesToEmitMachineCode - Add passes to the specified pass manager to 175/// get machine code emitted. This uses a JITCodeEmitter object to handle 176/// actually outputting the machine code and resolving things like the address 177/// of functions. This method should returns true if machine code emission is 178/// not supported. 179/// 180bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM, 181 JITCodeEmitter &JCE, 182 CodeGenOpt::Level OptLevel) { 183 // Make sure the code model is set. 184 setCodeModelForJIT(); 185 186 // Add common CodeGen passes. 187 if (addCommonCodeGenPasses(PM, OptLevel)) 188 return true; 189 190 addCodeEmitter(PM, OptLevel, JCE); 191 PM.add(createGCInfoDeleter()); 192 193 return false; // success! 194} 195 196static void printAndVerify(PassManagerBase &PM, 197 const char *Banner, 198 bool allowDoubleDefs = false) { 199 if (PrintMachineCode) 200 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 201 202 if (VerifyMachineCode) 203 PM.add(createMachineVerifierPass(allowDoubleDefs)); 204} 205 206/// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both 207/// emitting to assembly files or machine code output. 208/// 209bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM, 210 CodeGenOpt::Level OptLevel) { 211 // Standard LLVM-Level Passes. 212 213 // Optionally, tun split-GEPs and no-load GVN. 214 if (EnableSplitGEPGVN) { 215 PM.add(createGEPSplitterPass()); 216 PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true)); 217 } 218 219 // Run loop strength reduction before anything else. 220 if (OptLevel != CodeGenOpt::None && !DisableLSR) { 221 PM.add(createLoopStrengthReducePass(getTargetLowering())); 222 if (PrintLSR) 223 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs())); 224 } 225 226 // Turn exception handling constructs into something the code generators can 227 // handle. 228 switch (getMCAsmInfo()->getExceptionHandlingType()) 229 { 230 case ExceptionHandling::SjLj: 231 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 232 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 233 // catch info can get misplaced when a selector ends up more than one block 234 // removed from the parent invoke(s). This could happen when a landing 235 // pad is shared by multiple invokes and is also a target of a normal 236 // edge from elsewhere. 237 PM.add(createSjLjEHPass(getTargetLowering())); 238 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None)); 239 break; 240 case ExceptionHandling::Dwarf: 241 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None)); 242 break; 243 case ExceptionHandling::None: 244 PM.add(createLowerInvokePass(getTargetLowering())); 245 break; 246 } 247 248 PM.add(createGCLoweringPass()); 249 250 // Make sure that no unreachable blocks are instruction selected. 251 PM.add(createUnreachableBlockEliminationPass()); 252 253 if (OptLevel != CodeGenOpt::None && !DisableCGP) 254 PM.add(createCodeGenPreparePass(getTargetLowering())); 255 256 PM.add(createStackProtectorPass(getTargetLowering())); 257 258 if (PrintISelInput) 259 PM.add(createPrintFunctionPass("\n\n" 260 "*** Final LLVM Code input to ISel ***\n", 261 &dbgs())); 262 263 // Standard Lower-Level Passes. 264 265 // Set up a MachineFunction for the rest of CodeGen to work on. 266 PM.add(new MachineFunctionAnalysis(*this, OptLevel)); 267 268 // Enable FastISel with -fast, but allow that to be overridden. 269 if (EnableFastISelOption == cl::BOU_TRUE || 270 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE)) 271 EnableFastISel = true; 272 273 // Ask the target for an isel. 274 if (addInstSelector(PM, OptLevel)) 275 return true; 276 277 // Print the instruction selected machine code... 278 printAndVerify(PM, "After Instruction Selection", 279 /* allowDoubleDefs= */ true); 280 281 if (OptLevel != CodeGenOpt::None) { 282 PM.add(createOptimizeExtsPass()); 283 if (!DisableMachineLICM) 284 PM.add(createMachineLICMPass()); 285 if (!DisableMachineSink) 286 PM.add(createMachineSinkingPass()); 287 printAndVerify(PM, "After MachineLICM and MachineSinking", 288 /* allowDoubleDefs= */ true); 289 } 290 291 // Pre-ra tail duplication. 292 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) { 293 PM.add(createTailDuplicatePass(true)); 294 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate", 295 /* allowDoubleDefs= */ true); 296 } 297 298 // Run pre-ra passes. 299 if (addPreRegAlloc(PM, OptLevel)) 300 printAndVerify(PM, "After PreRegAlloc passes", 301 /* allowDoubleDefs= */ true); 302 303 // Perform register allocation. 304 PM.add(createRegisterAllocator()); 305 printAndVerify(PM, "After Register Allocation"); 306 307 // Perform stack slot coloring. 308 if (OptLevel != CodeGenOpt::None && !DisableSSC) { 309 // FIXME: Re-enable coloring with register when it's capable of adding 310 // kill markers. 311 PM.add(createStackSlotColoringPass(false)); 312 printAndVerify(PM, "After StackSlotColoring"); 313 } 314 315 // Run post-ra passes. 316 if (addPostRegAlloc(PM, OptLevel)) 317 printAndVerify(PM, "After PostRegAlloc passes"); 318 319 PM.add(createLowerSubregsPass()); 320 printAndVerify(PM, "After LowerSubregs"); 321 322 // Insert prolog/epilog code. Eliminate abstract frame index references... 323 PM.add(createPrologEpilogCodeInserter()); 324 printAndVerify(PM, "After PrologEpilogCodeInserter"); 325 326 // Run pre-sched2 passes. 327 if (addPreSched2(PM, OptLevel)) 328 printAndVerify(PM, "After PreSched2 passes"); 329 330 // Second pass scheduler. 331 if (OptLevel != CodeGenOpt::None && !DisablePostRA) { 332 PM.add(createPostRAScheduler(OptLevel)); 333 printAndVerify(PM, "After PostRAScheduler"); 334 } 335 336 // Branch folding must be run after regalloc and prolog/epilog insertion. 337 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) { 338 PM.add(createBranchFoldingPass(getEnableTailMergeDefault())); 339 printAndVerify(PM, "After BranchFolding"); 340 } 341 342 // Tail duplication. 343 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) { 344 PM.add(createTailDuplicatePass(false)); 345 printAndVerify(PM, "After TailDuplicate"); 346 } 347 348 PM.add(createGCMachineCodeAnalysisPass()); 349 350 if (PrintGCInfo) 351 PM.add(createGCInfoPrinter(dbgs())); 352 353 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) { 354 PM.add(createCodePlacementOptPass()); 355 printAndVerify(PM, "After CodePlacementOpt"); 356 } 357 358 if (addPreEmitPass(PM, OptLevel)) 359 printAndVerify(PM, "After PreEmit passes"); 360 361 return false; 362} 363