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/Support/CommandLine.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/FormattedStream.h" 31 #include "llvm/Support/TargetRegistry.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 MII.reset(TheTarget.createMCInstrInfo()); 44 // FIXME: Having an MCSubtargetInfo on the target machine is a hack due 45 // to some backends having subtarget feature dependent module level 46 // code generation. This is similar to the hack in the AsmPrinter for 47 // module level assembly etc. 48 STI.reset(TheTarget.createMCSubtargetInfo( 49 getTargetTriple().str(), getTargetCPU(), getTargetFeatureString())); 50 51 MCAsmInfo *TmpAsmInfo = TheTarget.createMCAsmInfo( 52 *MRI, getTargetTriple().str(), Options.MCOptions); 53 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0, 54 // and if the old one gets included then MCAsmInfo will be NULL and 55 // we'll crash later. 56 // Provide the user with a useful error message about what's wrong. 57 assert(TmpAsmInfo && "MCAsmInfo not initialized. " 58 "Make sure you include the correct TargetSelect.h" 59 "and that InitializeAllTargetMCs() is being invoked!"); 60 61 if (Options.DisableIntegratedAS) 62 TmpAsmInfo->setUseIntegratedAssembler(false); 63 64 TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments); 65 66 TmpAsmInfo->setCompressDebugSections(Options.CompressDebugSections); 67 68 TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations); 69 70 if (Options.ExceptionModel != ExceptionHandling::None) 71 TmpAsmInfo->setExceptionsType(Options.ExceptionModel); 72 73 AsmInfo.reset(TmpAsmInfo); 74 } 75 76 LLVMTargetMachine::LLVMTargetMachine(const Target &T, 77 StringRef DataLayoutString, 78 const Triple &TT, StringRef CPU, 79 StringRef FS, const TargetOptions &Options, 80 Reloc::Model RM, CodeModel::Model CM, 81 CodeGenOpt::Level OL) 82 : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) { 83 this->RM = RM; 84 this->CMModel = CM; 85 this->OptLevel = OL; 86 87 if (EnableTrapUnreachable) 88 this->Options.TrapUnreachable = true; 89 } 90 91 TargetTransformInfo 92 LLVMTargetMachine::getTargetTransformInfo(const Function &F) { 93 return TargetTransformInfo(BasicTTIImpl(this, F)); 94 } 95 96 /// addPassesToX helper drives creation and initialization of TargetPassConfig. 97 static TargetPassConfig * 98 addPassesToGenerateCode(LLVMTargetMachine &TM, PassManagerBase &PM, 99 bool DisableVerify, 100 MachineModuleInfoWrapperPass &MMIWP) { 101 // Targets may override createPassConfig to provide a target-specific 102 // subclass. 103 TargetPassConfig *PassConfig = TM.createPassConfig(PM); 104 // Set PassConfig options provided by TargetMachine. 105 PassConfig->setDisableVerify(DisableVerify); 106 PM.add(PassConfig); 107 PM.add(&MMIWP); 108 109 if (PassConfig->addISelPasses()) 110 return nullptr; 111 PassConfig->addMachinePasses(); 112 PassConfig->setInitialized(); 113 return PassConfig; 114 } 115 116 bool LLVMTargetMachine::addAsmPrinter(PassManagerBase &PM, 117 raw_pwrite_stream &Out, 118 raw_pwrite_stream *DwoOut, 119 CodeGenFileType FileType, 120 MCContext &Context) { 121 if (Options.MCOptions.MCSaveTempLabels) 122 Context.setAllowTemporaryLabels(false); 123 124 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 125 const MCAsmInfo &MAI = *getMCAsmInfo(); 126 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 127 const MCInstrInfo &MII = *getMCInstrInfo(); 128 129 std::unique_ptr<MCStreamer> AsmStreamer; 130 131 switch (FileType) { 132 case CGFT_AssemblyFile: { 133 MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter( 134 getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI); 135 136 // Create a code emitter if asked to show the encoding. 137 std::unique_ptr<MCCodeEmitter> MCE; 138 if (Options.MCOptions.ShowMCEncoding) 139 MCE.reset(getTarget().createMCCodeEmitter(MII, MRI, Context)); 140 141 std::unique_ptr<MCAsmBackend> MAB( 142 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions)); 143 auto FOut = std::make_unique<formatted_raw_ostream>(Out); 144 MCStreamer *S = getTarget().createAsmStreamer( 145 Context, std::move(FOut), Options.MCOptions.AsmVerbose, 146 Options.MCOptions.MCUseDwarfDirectory, InstPrinter, std::move(MCE), 147 std::move(MAB), Options.MCOptions.ShowMCInst); 148 AsmStreamer.reset(S); 149 break; 150 } 151 case CGFT_ObjectFile: { 152 // Create the code emitter for the target if it exists. If not, .o file 153 // emission fails. 154 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context); 155 MCAsmBackend *MAB = 156 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions); 157 if (!MCE || !MAB) 158 return true; 159 160 Triple T(getTargetTriple().str()); 161 AsmStreamer.reset(getTarget().createMCObjectStreamer( 162 T, Context, std::unique_ptr<MCAsmBackend>(MAB), 163 DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut) 164 : MAB->createObjectWriter(Out), 165 std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll, 166 Options.MCOptions.MCIncrementalLinkerCompatible, 167 /*DWARFMustBeAtTheEnd*/ true)); 168 break; 169 } 170 case CGFT_Null: 171 // The Null output is intended for use for performance analysis and testing, 172 // not real users. 173 AsmStreamer.reset(getTarget().createNullStreamer(Context)); 174 break; 175 } 176 177 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 178 FunctionPass *Printer = 179 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 180 if (!Printer) 181 return true; 182 183 PM.add(Printer); 184 return false; 185 } 186 187 bool LLVMTargetMachine::addPassesToEmitFile( 188 PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, 189 CodeGenFileType FileType, bool DisableVerify, 190 MachineModuleInfoWrapperPass *MMIWP) { 191 // Add common CodeGen passes. 192 if (!MMIWP) 193 MMIWP = new MachineModuleInfoWrapperPass(this); 194 TargetPassConfig *PassConfig = 195 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP); 196 if (!PassConfig) 197 return true; 198 199 if (!TargetPassConfig::willCompleteCodeGenPipeline()) { 200 if (this->getTargetTriple().isOSAIX()) { 201 // On AIX, we might manifest MCSymbols during SDAG lowering. For MIR 202 // testing to be meaningful, we need to ensure that the symbols created 203 // are MCSymbolXCOFF variants, which requires that 204 // the TargetLoweringObjectFile instance has been initialized. 205 MCContext &Ctx = MMIWP->getMMI().getContext(); 206 const_cast<TargetLoweringObjectFile &>(*this->getObjFileLowering()) 207 .Initialize(Ctx, *this); 208 } 209 PM.add(createPrintMIRPass(Out)); 210 } else if (addAsmPrinter(PM, Out, DwoOut, FileType, 211 MMIWP->getMMI().getContext())) 212 return true; 213 214 PM.add(createFreeMachineFunctionPass()); 215 return false; 216 } 217 218 /// addPassesToEmitMC - Add passes to the specified pass manager to get 219 /// machine code emitted with the MCJIT. This method returns true if machine 220 /// code is not supported. It fills the MCContext Ctx pointer which can be 221 /// used to build custom MCStreamer. 222 /// 223 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx, 224 raw_pwrite_stream &Out, 225 bool DisableVerify) { 226 // Add common CodeGen passes. 227 MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(this); 228 TargetPassConfig *PassConfig = 229 addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP); 230 if (!PassConfig) 231 return true; 232 assert(TargetPassConfig::willCompleteCodeGenPipeline() && 233 "Cannot emit MC with limited codegen pipeline"); 234 235 Ctx = &MMIWP->getMMI().getContext(); 236 if (Options.MCOptions.MCSaveTempLabels) 237 Ctx->setAllowTemporaryLabels(false); 238 239 // Create the code emitter for the target if it exists. If not, .o file 240 // emission fails. 241 const MCSubtargetInfo &STI = *getMCSubtargetInfo(); 242 const MCRegisterInfo &MRI = *getMCRegisterInfo(); 243 MCCodeEmitter *MCE = 244 getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx); 245 MCAsmBackend *MAB = 246 getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions); 247 if (!MCE || !MAB) 248 return true; 249 250 const Triple &T = getTargetTriple(); 251 std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer( 252 T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out), 253 std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll, 254 Options.MCOptions.MCIncrementalLinkerCompatible, 255 /*DWARFMustBeAtTheEnd*/ true)); 256 257 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 258 FunctionPass *Printer = 259 getTarget().createAsmPrinter(*this, std::move(AsmStreamer)); 260 if (!Printer) 261 return true; 262 263 PM.add(Printer); 264 PM.add(createFreeMachineFunctionPass()); 265 266 return false; // success! 267 } 268