LLVMTargetMachine.cpp 12 KB

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