LLVMTargetMachine.cpp 10 KB

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