LLVMTargetMachine.cpp 11 KB

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