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/Analysis/Passes.h" 16 #include "llvm/CodeGen/AsmPrinter.h" 17 #include "llvm/CodeGen/BasicTTIImpl.h" 18 #include "llvm/CodeGen/MachineFunctionAnalysis.h" 19 #include "llvm/CodeGen/MachineModuleInfo.h" 20 #include "llvm/CodeGen/Passes.h" 21 #include "llvm/CodeGen/TargetPassConfig.h" 22 #include "llvm/IR/IRPrintingPasses.h" 23 #include "llvm/IR/LegacyPassManager.h" 24 #include "llvm/IR/Verifier.h" 25 #include "llvm/MC/MCAsmInfo.h" 26 #include "llvm/MC/MCContext.h" 27 #include "llvm/MC/MCInstrInfo.h" 28 #include "llvm/MC/MCStreamer.h" 29 #include "llvm/MC/MCSubtargetInfo.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/FormattedStream.h" 33 #include "llvm/Support/TargetRegistry.h" 34 #include "llvm/Target/TargetLoweringObjectFile.h" 35 #include "llvm/Target/TargetOptions.h" 36 #include "llvm/Transforms/Scalar.h" 37 using namespace llvm; 38 39 // Enable or disable FastISel. Both options are needed, because 40 // FastISel is enabled by default with -fast, and we wish to be 41 // able to enable or disable fast-isel independently from -O0. 42 static cl::opt<cl::boolOrDefault> 43 EnableFastISelOption("fast-isel", cl::Hidden, 44 cl::desc("Enable the \"fast\" instruction selector")); 45 46 static cl::opt<bool> 47 EnableGlobalISel("global-isel", cl::Hidden, cl::init(false), 48 cl::desc("Enable the \"global\" instruction selector")); 49 50 void LLVMTargetMachine::initAsmInfo() { 51 MRI = TheTarget.createMCRegInfo(getTargetTriple().str()); 52 MII = TheTarget.createMCInstrInfo(); 53 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due 54 // to some backends having subtarget feature dependent module level 55 // code generation. This is similar to the hack in the AsmPrinter for 56 // module level assembly etc. 57 STI = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(), 58 getTargetFeatureString()); 59 60 MCAsmInfo *TmpAsmInfo = 61 TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str()); 62 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0, 63 // and if the old one gets included then MCAsmInfo will be NULL and 64 // we'll crash later. 65 // Provide the user with a useful error message about what's wrong. 66 assert(TmpAsmInfo && "MCAsmInfo not initialized. " 67 "Make sure you include the correct TargetSelect.h" 68 "and that InitializeAllTargetMCs() is being invoked!"); 69 70 if (Options.DisableIntegratedAS) 71 TmpAsmInfo->setUseIntegratedAssembler(false); 72 73 if (Options.CompressDebugSections) 74 TmpAsmInfo->setCompressDebugSections(DebugCompressionType::DCT_ZlibGnu); 75 76 TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations); 77 78 if (Options.ExceptionModel != ExceptionHandling::None) 79 TmpAsmInfo->setExceptionsType(Options.ExceptionModel); 80 81 AsmInfo = TmpAsmInfo; 82 } 83 84 LLVMTargetMachine::LLVMTargetMachine(const Target &T, 85 StringRef DataLayoutString, 86 const Triple &TT, StringRef CPU, 87 StringRef FS, TargetOptions Options, 88 Reloc::Model RM, CodeModel::Model CM, 89 CodeGenOpt::Level OL) 90 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) { 91 CodeGenInfo = T.createMCCodeGenInfo(TT.str(), RM, CM, OL); 92 } 93 94 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() { 95 return TargetIRAnalysis([this](const Function &F) { 96 return TargetTransformInfo(BasicTTIImpl(this, F)); 97 }); 98 } 99 100 MachineModuleInfo & 101 LLVMTargetMachine::addMachineModuleInfo(PassManagerBase &PM) const { 102 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(), 103 *getMCRegisterInfo(), 104 getObjFileLowering()); 105 PM.add(MMI); 106 return *MMI; 107 } 108 109 void LLVMTargetMachine::addMachineFunctionAnalysis(PassManagerBase &PM, 110 MachineFunctionInitializer *MFInitializer) const { 111 PM.add(new MachineFunctionAnalysis(*this, MFInitializer)); 112 } 113 114 /// addPassesToX helper drives creation and initialization of TargetPassConfig. 115 static MCContext * 116 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM, 117 bool DisableVerify, AnalysisID StartBefore, 118 AnalysisID StartAfter, AnalysisID StopAfter, 119 MachineFunctionInitializer *MFInitializer = nullptr) { 120 121 // When in emulated TLS mode, add the LowerEmuTLS pass. 122 if (TM->Options.EmulatedTLS) 123 PM.add(createLowerEmuTLSPass(TM)); 124 125 PM.add(createPreISelIntrinsicLoweringPass()); 126 127 // Add internal analysis passes from the target machine. 128 PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); 129 130 // Targets may override createPassConfig to provide a target-specific 131 // subclass. 132 TargetPassConfig *PassConfig = TM->createPassConfig(PM); 133 PassConfig->setStartStopPasses(StartBefore, StartAfter, StopAfter); 134 135 // Set PassConfig options provided by TargetMachine. 136 PassConfig->setDisableVerify(DisableVerify); 137 138 PM.add(PassConfig); 139 140 PassConfig->addIRPasses(); 141 142 PassConfig->addCodeGenPrepare(); 143 144 PassConfig->addPassesToHandleExceptions(); 145 146 PassConfig->addISelPrepare(); 147 148 MachineModuleInfo &MMI = TM->addMachineModuleInfo(PM); 149 TM->addMachineFunctionAnalysis(PM, MFInitializer); 150 151 // Enable FastISel with -fast, but allow that to be overridden. 152 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE); 153 if (EnableFastISelOption == cl::BOU_TRUE || 154 (TM->getOptLevel() == CodeGenOpt::None && 155 TM->getO0WantsFastISel())) 156 TM->setFastISel(true); 157 158 // Ask the target for an isel. 159 if (LLVM_UNLIKELY(EnableGlobalISel)) { 160 if (PassConfig->addIRTranslator()) 161 return nullptr; 162 163 // Before running the register bank selector, ask the target if it 164 // wants to run some passes. 165 PassConfig->addPreRegBankSelect(); 166 167 if (PassConfig->addRegBankSelect()) 168 return nullptr; 169 170 } else if (PassConfig->addInstSelector()) 171 return nullptr; 172 173 PassConfig->addMachinePasses(); 174 175 PassConfig->setInitialized(); 176 177 return &MMI.getContext(); 178 } 179 180 bool LLVMTargetMachine::addPassesToEmitFile( 181 PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType, 182 bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter, 183 AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) { 184 // Add common CodeGen passes. 185 MCContext *Context = 186 addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter, 187 StopAfter, MFInitializer); 188 if (!Context) 189 return true; 190 191 if (StopAfter) { 192 PM.add(createPrintMIRPass(errs())); 193 return false; 194 } 195 196 if (Options.MCOptions.MCSaveTempLabels) 197 Context->setAllowTemporaryLabels(false); 198 199 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 200 const MCAsmInfo &MAI = *getMCAsmInfo(); 201 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 202 const MCInstrInfo &MII = *getMCInstrInfo(); 203 204 std::unique_ptr<MCStreamer> AsmStreamer; 205 206 switch (FileType) { 207 case CGFT_AssemblyFile: { 208 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter( 209 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI); 210 211 // Create a code emitter if asked to show the encoding. 212 MCCodeEmitter *MCE = nullptr; 213 if (Options.MCOptions.ShowMCEncoding) 214 MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context); 215 216 MCAsmBackend *MAB = 217 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU); 218 auto FOut = llvm::make_unique<formatted_raw_ostream>(Out); 219 MCStreamer *S = getTarget().createAsmStreamer( 220 *Context, std::move(FOut), Options.MCOptions.AsmVerbose, 221 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB, 222 Options.MCOptions.ShowMCInst); 223 AsmStreamer.reset(S); 224 break; 225 } 226 case CGFT_ObjectFile: { 227 // Create the code emitter for the target if it exists. If not, .o file 228 // emission fails. 229 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context); 230 MCAsmBackend *MAB = 231 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU); 232 if (!MCE || !MAB) 233 return true; 234 235 // Don't waste memory on names of temp labels. 236 Context->setUseNamesOnTempLabels(false); 237 238 Triple T(getTargetTriple().str()); 239 AsmStreamer.reset(getTarget().createMCObjectStreamer( 240 T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll, 241 Options.MCOptions.MCIncrementalLinkerCompatible, 242 /*DWARFMustBeAtTheEnd*/ true)); 243 break; 244 } 245 case CGFT_Null: 246 // The Null output is intended for use for performance analysis and testing, 247 // not real users. 248 AsmStreamer.reset(getTarget().createNullStreamer(*Context)); 249 break; 250 } 251 252 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 253 FunctionPass *Printer = 254 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 255 if (!Printer) 256 return true; 257 258 PM.add(Printer); 259 260 return false; 261 } 262 263 /// addPassesToEmitMC - Add passes to the specified pass manager to get 264 /// machine code emitted with the MCJIT. This method returns true if machine 265 /// code is not supported. It fills the MCContext Ctx pointer which can be 266 /// used to build custom MCStreamer. 267 /// 268 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, 269 raw_pwrite_stream &Out, 270 bool DisableVerify) { 271 // Add common CodeGen passes. 272 Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr, 273 nullptr); 274 if (!Ctx) 275 return true; 276 277 if (Options.MCOptions.MCSaveTempLabels) 278 Ctx->setAllowTemporaryLabels(false); 279 280 // Create the code emitter for the target if it exists. If not, .o file 281 // emission fails. 282 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 283 MCCodeEmitter *MCE = 284 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx); 285 MCAsmBackend *MAB = 286 getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU); 287 if (!MCE || !MAB) 288 return true; 289 290 const Triple &T = getTargetTriple(); 291 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 292 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer( 293 T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll, 294 Options.MCOptions.MCIncrementalLinkerCompatible, 295 /*DWARFMustBeAtTheEnd*/ true)); 296 297 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 298 FunctionPass *Printer = 299 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 300 if (!Printer) 301 return true; 302 303 PM.add(Printer); 304 305 return false; // success! 306 } 307