1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the LLVMTargetMachine class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/Analysis/Passes.h" 14 #include "llvm/CodeGen/AsmPrinter.h" 15 #include "llvm/CodeGen/BasicTTIImpl.h" 16 #include "llvm/CodeGen/MachineModuleInfo.h" 17 #include "llvm/CodeGen/Passes.h" 18 #include "llvm/CodeGen/TargetPassConfig.h" 19 #include "llvm/IR/LegacyPassManager.h" 20 #include "llvm/MC/MCAsmBackend.h" 21 #include "llvm/MC/MCAsmInfo.h" 22 #include "llvm/MC/MCCodeEmitter.h" 23 #include "llvm/MC/MCContext.h" 24 #include "llvm/MC/MCInstrInfo.h" 25 #include "llvm/MC/MCObjectWriter.h" 26 #include "llvm/MC/MCStreamer.h" 27 #include "llvm/MC/MCSubtargetInfo.h" 28 #include "llvm/MC/TargetRegistry.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/FormattedStream.h" 32 #include "llvm/Target/TargetLoweringObjectFile.h" 33 #include "llvm/Target/TargetMachine.h" 34 #include "llvm/Target/TargetOptions.h" 35 using namespace llvm; 36 37 static cl::opt<bool> EnableTrapUnreachable("trap-unreachable", 38 cl::Hidden, cl::ZeroOrMore, cl::init(false), 39 cl::desc("Enable generating trap for unreachable")); 40 41 void LLVMTargetMachine::initAsmInfo() { 42 MRI.reset(TheTarget.createMCRegInfo(getTargetTriple().str())); 43 assert(MRI && "Unable to create reg info"); 44 MII.reset(TheTarget.createMCInstrInfo()); 45 assert(MII && "Unable to create instruction info"); 46 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due 47 // to some backends having subtarget feature dependent module level 48 // code generation. This is similar to the hack in the AsmPrinter for 49 // module level assembly etc. 50 STI.reset(TheTarget.createMCSubtargetInfo( 51 getTargetTriple().str(), getTargetCPU(), getTargetFeatureString())); 52 assert(STI && "Unable to create subtarget info"); 53 54 MCAsmInfo *TmpAsmInfo = TheTarget.createMCAsmInfo( 55 *MRI, getTargetTriple().str(), Options.MCOptions); 56 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0, 57 // and if the old one gets included then MCAsmInfo will be NULL and 58 // we'll crash later. 59 // Provide the user with a useful error message about what's wrong. 60 assert(TmpAsmInfo && "MCAsmInfo not initialized. " 61 "Make sure you include the correct TargetSelect.h" 62 "and that InitializeAllTargetMCs() is being invoked!"); 63 64 if (Options.BinutilsVersion.first > 0) 65 TmpAsmInfo->setBinutilsVersion(Options.BinutilsVersion); 66 67 if (Options.DisableIntegratedAS) { 68 TmpAsmInfo->setUseIntegratedAssembler(false); 69 // If there is explict option disable integratedAS, we can't use it for 70 // inlineasm either. 71 TmpAsmInfo->setParseInlineAsmUsingAsmParser(false); 72 } 73 74 TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments); 75 76 TmpAsmInfo->setCompressDebugSections(Options.CompressDebugSections); 77 78 TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations); 79 80 if (Options.ExceptionModel != ExceptionHandling::None) 81 TmpAsmInfo->setExceptionsType(Options.ExceptionModel); 82 83 AsmInfo.reset(TmpAsmInfo); 84 } 85 86 LLVMTargetMachine::LLVMTargetMachine(const Target &T, 87 StringRef DataLayoutString, 88 const Triple &TT, StringRef CPU, 89 StringRef FS, const TargetOptions &Options, 90 Reloc::Model RM, CodeModel::Model CM, 91 CodeGenOpt::Level OL) 92 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) { 93 this->RM = RM; 94 this->CMModel = CM; 95 this->OptLevel = OL; 96 97 if (EnableTrapUnreachable) 98 this->Options.TrapUnreachable = true; 99 } 100 101 TargetTransformInfo 102 LLVMTargetMachine::getTargetTransformInfo(const Function &F) { 103 return TargetTransformInfo(BasicTTIImpl(this, F)); 104 } 105 106 /// addPassesToX helper drives creation and initialization of TargetPassConfig. 107 static TargetPassConfig * 108 addPassesToGenerateCode(LLVMTargetMachine &TM, PassManagerBase &PM, 109 bool DisableVerify, 110 MachineModuleInfoWrapperPass &MMIWP) { 111 // Targets may override createPassConfig to provide a target-specific 112 // subclass. 113 TargetPassConfig *PassConfig = TM.createPassConfig(PM); 114 // Set PassConfig options provided by TargetMachine. 115 PassConfig->setDisableVerify(DisableVerify); 116 PM.add(PassConfig); 117 PM.add(&MMIWP); 118 119 if (PassConfig->addISelPasses()) 120 return nullptr; 121 PassConfig->addMachinePasses(); 122 PassConfig->setInitialized(); 123 return PassConfig; 124 } 125 126 bool LLVMTargetMachine::addAsmPrinter(PassManagerBase &PM, 127 raw_pwrite_stream &Out, 128 raw_pwrite_stream *DwoOut, 129 CodeGenFileType FileType, 130 MCContext &Context) { 131 Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr = 132 createMCStreamer(Out, DwoOut, FileType, Context); 133 if (auto Err = MCStreamerOrErr.takeError()) 134 return true; 135 136 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 137 FunctionPass *Printer = 138 getTarget().createAsmPrinter(*this, std::move(*MCStreamerOrErr)); 139 if (!Printer) 140 return true; 141 142 PM.add(Printer); 143 return false; 144 } 145 146 Expected<std::unique_ptr<MCStreamer>> LLVMTargetMachine::createMCStreamer( 147 raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType, 148 MCContext &Context) { 149 if (Options.MCOptions.MCSaveTempLabels) 150 Context.setAllowTemporaryLabels(false); 151 152 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 153 const MCAsmInfo &MAI = *getMCAsmInfo(); 154 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 155 const MCInstrInfo &MII = *getMCInstrInfo(); 156 157 std::unique_ptr<MCStreamer> AsmStreamer; 158 159 switch (FileType) { 160 case CGFT_AssemblyFile: { 161 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter( 162 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI); 163 164 // Create a code emitter if asked to show the encoding. 165 std::unique_ptr<MCCodeEmitter> MCE; 166 if (Options.MCOptions.ShowMCEncoding) 167 MCE.reset(getTarget().createMCCodeEmitter(MII, MRI, Context)); 168 169 std::unique_ptr<MCAsmBackend> MAB( 170 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions)); 171 auto FOut = std::make_unique<formatted_raw_ostream>(Out); 172 MCStreamer *S = getTarget().createAsmStreamer( 173 Context, std::move(FOut), Options.MCOptions.AsmVerbose, 174 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, std::move(MCE), 175 std::move(MAB), Options.MCOptions.ShowMCInst); 176 AsmStreamer.reset(S); 177 break; 178 } 179 case CGFT_ObjectFile: { 180 // Create the code emitter for the target if it exists. If not, .o file 181 // emission fails. 182 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context); 183 if (!MCE) 184 return make_error<StringError>("createMCCodeEmitter failed", 185 inconvertibleErrorCode()); 186 MCAsmBackend *MAB = 187 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions); 188 if (!MAB) 189 return make_error<StringError>("createMCAsmBackend failed", 190 inconvertibleErrorCode()); 191 192 Triple T(getTargetTriple().str()); 193 AsmStreamer.reset(getTarget().createMCObjectStreamer( 194 T, Context, std::unique_ptr<MCAsmBackend>(MAB), 195 DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut) 196 : MAB->createObjectWriter(Out), 197 std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll, 198 Options.MCOptions.MCIncrementalLinkerCompatible, 199 /*DWARFMustBeAtTheEnd*/ true)); 200 break; 201 } 202 case CGFT_Null: 203 // The Null output is intended for use for performance analysis and testing, 204 // not real users. 205 AsmStreamer.reset(getTarget().createNullStreamer(Context)); 206 break; 207 } 208 209 return std::move(AsmStreamer); 210 } 211 212 bool LLVMTargetMachine::addPassesToEmitFile( 213 PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, 214 CodeGenFileType FileType, bool DisableVerify, 215 MachineModuleInfoWrapperPass *MMIWP) { 216 // Add common CodeGen passes. 217 if (!MMIWP) 218 MMIWP = new MachineModuleInfoWrapperPass(this); 219 TargetPassConfig *PassConfig = 220 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP); 221 if (!PassConfig) 222 return true; 223 224 if (TargetPassConfig::willCompleteCodeGenPipeline()) { 225 if (addAsmPrinter(PM, Out, DwoOut, FileType, MMIWP->getMMI().getContext())) 226 return true; 227 } else { 228 // MIR printing is redundant with -filetype=null. 229 if (FileType != CGFT_Null) 230 PM.add(createPrintMIRPass(Out)); 231 } 232 233 PM.add(createFreeMachineFunctionPass()); 234 return false; 235 } 236 237 /// addPassesToEmitMC - Add passes to the specified pass manager to get 238 /// machine code emitted with the MCJIT. This method returns true if machine 239 /// code is not supported. It fills the MCContext Ctx pointer which can be 240 /// used to build custom MCStreamer. 241 /// 242 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, 243 raw_pwrite_stream &Out, 244 bool DisableVerify) { 245 // Add common CodeGen passes. 246 MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(this); 247 TargetPassConfig *PassConfig = 248 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP); 249 if (!PassConfig) 250 return true; 251 assert(TargetPassConfig::willCompleteCodeGenPipeline() && 252 "Cannot emit MC with limited codegen pipeline"); 253 254 Ctx = &MMIWP->getMMI().getContext(); 255 if (Options.MCOptions.MCSaveTempLabels) 256 Ctx->setAllowTemporaryLabels(false); 257 258 // Create the code emitter for the target if it exists. If not, .o file 259 // emission fails. 260 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 261 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 262 MCCodeEmitter *MCE = 263 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx); 264 MCAsmBackend *MAB = 265 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions); 266 if (!MCE || !MAB) 267 return true; 268 269 const Triple &T = getTargetTriple(); 270 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer( 271 T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out), 272 std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll, 273 Options.MCOptions.MCIncrementalLinkerCompatible, 274 /*DWARFMustBeAtTheEnd*/ true)); 275 276 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 277 FunctionPass *Printer = 278 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 279 if (!Printer) 280 return true; 281 282 PM.add(Printer); 283 PM.add(createFreeMachineFunctionPass()); 284 285 return false; // success! 286 } 287