MIRParser.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
  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 class that parses the optional LLVM IR and machine
  10. // functions that are stored in MIR files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/MIRParser/MIRParser.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/StringMap.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/AsmParser/Parser.h"
  19. #include "llvm/AsmParser/SlotMapping.h"
  20. #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
  21. #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
  22. #include "llvm/CodeGen/MIRParser/MIParser.h"
  23. #include "llvm/CodeGen/MIRYamlMapping.h"
  24. #include "llvm/CodeGen/MachineConstantPool.h"
  25. #include "llvm/CodeGen/MachineFrameInfo.h"
  26. #include "llvm/CodeGen/MachineFunction.h"
  27. #include "llvm/CodeGen/MachineModuleInfo.h"
  28. #include "llvm/CodeGen/MachineRegisterInfo.h"
  29. #include "llvm/CodeGen/TargetFrameLowering.h"
  30. #include "llvm/IR/BasicBlock.h"
  31. #include "llvm/IR/DebugInfo.h"
  32. #include "llvm/IR/DiagnosticInfo.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/IR/LLVMContext.h"
  35. #include "llvm/IR/Module.h"
  36. #include "llvm/IR/ValueSymbolTable.h"
  37. #include "llvm/Support/LineIterator.h"
  38. #include "llvm/Support/MemoryBuffer.h"
  39. #include "llvm/Support/SMLoc.h"
  40. #include "llvm/Support/SourceMgr.h"
  41. #include "llvm/Support/YAMLTraits.h"
  42. #include "llvm/Target/TargetMachine.h"
  43. #include <memory>
  44. using namespace llvm;
  45. namespace llvm {
  46. /// This class implements the parsing of LLVM IR that's embedded inside a MIR
  47. /// file.
  48. class MIRParserImpl {
  49. SourceMgr SM;
  50. LLVMContext &Context;
  51. yaml::Input In;
  52. StringRef Filename;
  53. SlotMapping IRSlots;
  54. std::unique_ptr<PerTargetMIParsingState> Target;
  55. /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
  56. /// created and inserted into the given module when this is true.
  57. bool NoLLVMIR = false;
  58. /// True when a well formed MIR file does not contain any MIR/machine function
  59. /// parts.
  60. bool NoMIRDocuments = false;
  61. std::function<void(Function &)> ProcessIRFunction;
  62. public:
  63. MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
  64. LLVMContext &Context,
  65. std::function<void(Function &)> ProcessIRFunction);
  66. void reportDiagnostic(const SMDiagnostic &Diag);
  67. /// Report an error with the given message at unknown location.
  68. ///
  69. /// Always returns true.
  70. bool error(const Twine &Message);
  71. /// Report an error with the given message at the given location.
  72. ///
  73. /// Always returns true.
  74. bool error(SMLoc Loc, const Twine &Message);
  75. /// Report a given error with the location translated from the location in an
  76. /// embedded string literal to a location in the MIR file.
  77. ///
  78. /// Always returns true.
  79. bool error(const SMDiagnostic &Error, SMRange SourceRange);
  80. /// Try to parse the optional LLVM module and the machine functions in the MIR
  81. /// file.
  82. ///
  83. /// Return null if an error occurred.
  84. std::unique_ptr<Module>
  85. parseIRModule(DataLayoutCallbackTy DataLayoutCallback);
  86. /// Create an empty function with the given name.
  87. Function *createDummyFunction(StringRef Name, Module &M);
  88. bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI);
  89. /// Parse the machine function in the current YAML document.
  90. ///
  91. ///
  92. /// Return true if an error occurred.
  93. bool parseMachineFunction(Module &M, MachineModuleInfo &MMI);
  94. /// Initialize the machine function to the state that's described in the MIR
  95. /// file.
  96. ///
  97. /// Return true if error occurred.
  98. bool initializeMachineFunction(const yaml::MachineFunction &YamlMF,
  99. MachineFunction &MF);
  100. bool parseRegisterInfo(PerFunctionMIParsingState &PFS,
  101. const yaml::MachineFunction &YamlMF);
  102. bool setupRegisterInfo(const PerFunctionMIParsingState &PFS,
  103. const yaml::MachineFunction &YamlMF);
  104. bool initializeFrameInfo(PerFunctionMIParsingState &PFS,
  105. const yaml::MachineFunction &YamlMF);
  106. bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS,
  107. const yaml::MachineFunction &YamlMF);
  108. bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
  109. std::vector<CalleeSavedInfo> &CSIInfo,
  110. const yaml::StringValue &RegisterSource,
  111. bool IsRestored, int FrameIdx);
  112. template <typename T>
  113. bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
  114. const T &Object,
  115. int FrameIdx);
  116. bool initializeConstantPool(PerFunctionMIParsingState &PFS,
  117. MachineConstantPool &ConstantPool,
  118. const yaml::MachineFunction &YamlMF);
  119. bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
  120. const yaml::MachineJumpTable &YamlJTI);
  121. bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS,
  122. MachineFunction &MF,
  123. const yaml::MachineFunction &YMF);
  124. private:
  125. bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
  126. const yaml::StringValue &Source);
  127. bool parseMBBReference(PerFunctionMIParsingState &PFS,
  128. MachineBasicBlock *&MBB,
  129. const yaml::StringValue &Source);
  130. bool parseMachineMetadata(PerFunctionMIParsingState &PFS,
  131. const yaml::StringValue &Source);
  132. /// Return a MIR diagnostic converted from an MI string diagnostic.
  133. SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
  134. SMRange SourceRange);
  135. /// Return a MIR diagnostic converted from a diagnostic located in a YAML
  136. /// block scalar string.
  137. SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
  138. SMRange SourceRange);
  139. void computeFunctionProperties(MachineFunction &MF);
  140. void setupDebugValueTracking(MachineFunction &MF,
  141. PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF);
  142. };
  143. } // end namespace llvm
  144. static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
  145. reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
  146. }
  147. MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
  148. StringRef Filename, LLVMContext &Context,
  149. std::function<void(Function &)> Callback)
  150. : Context(Context),
  151. In(SM.getMemoryBuffer(SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))
  152. ->getBuffer(),
  153. nullptr, handleYAMLDiag, this),
  154. Filename(Filename), ProcessIRFunction(Callback) {
  155. In.setContext(&In);
  156. }
  157. bool MIRParserImpl::error(const Twine &Message) {
  158. Context.diagnose(DiagnosticInfoMIRParser(
  159. DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
  160. return true;
  161. }
  162. bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
  163. Context.diagnose(DiagnosticInfoMIRParser(
  164. DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
  165. return true;
  166. }
  167. bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
  168. assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
  169. reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
  170. return true;
  171. }
  172. void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
  173. DiagnosticSeverity Kind;
  174. switch (Diag.getKind()) {
  175. case SourceMgr::DK_Error:
  176. Kind = DS_Error;
  177. break;
  178. case SourceMgr::DK_Warning:
  179. Kind = DS_Warning;
  180. break;
  181. case SourceMgr::DK_Note:
  182. Kind = DS_Note;
  183. break;
  184. case SourceMgr::DK_Remark:
  185. llvm_unreachable("remark unexpected");
  186. break;
  187. }
  188. Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
  189. }
  190. std::unique_ptr<Module>
  191. MIRParserImpl::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
  192. if (!In.setCurrentDocument()) {
  193. if (In.error())
  194. return nullptr;
  195. // Create an empty module when the MIR file is empty.
  196. NoMIRDocuments = true;
  197. auto M = std::make_unique<Module>(Filename, Context);
  198. if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
  199. M->setDataLayout(*LayoutOverride);
  200. return M;
  201. }
  202. std::unique_ptr<Module> M;
  203. // Parse the block scalar manually so that we can return unique pointer
  204. // without having to go trough YAML traits.
  205. if (const auto *BSN =
  206. dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
  207. SMDiagnostic Error;
  208. M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
  209. Context, &IRSlots, DataLayoutCallback);
  210. if (!M) {
  211. reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
  212. return nullptr;
  213. }
  214. In.nextDocument();
  215. if (!In.setCurrentDocument())
  216. NoMIRDocuments = true;
  217. } else {
  218. // Create an new, empty module.
  219. M = std::make_unique<Module>(Filename, Context);
  220. if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple()))
  221. M->setDataLayout(*LayoutOverride);
  222. NoLLVMIR = true;
  223. }
  224. return M;
  225. }
  226. bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
  227. if (NoMIRDocuments)
  228. return false;
  229. // Parse the machine functions.
  230. do {
  231. if (parseMachineFunction(M, MMI))
  232. return true;
  233. In.nextDocument();
  234. } while (In.setCurrentDocument());
  235. return false;
  236. }
  237. Function *MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
  238. auto &Context = M.getContext();
  239. Function *F =
  240. Function::Create(FunctionType::get(Type::getVoidTy(Context), false),
  241. Function::ExternalLinkage, Name, M);
  242. BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
  243. new UnreachableInst(Context, BB);
  244. if (ProcessIRFunction)
  245. ProcessIRFunction(*F);
  246. return F;
  247. }
  248. bool MIRParserImpl::parseMachineFunction(Module &M, MachineModuleInfo &MMI) {
  249. // Parse the yaml.
  250. yaml::MachineFunction YamlMF;
  251. yaml::EmptyContext Ctx;
  252. const LLVMTargetMachine &TM = MMI.getTarget();
  253. YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
  254. TM.createDefaultFuncInfoYAML());
  255. yaml::yamlize(In, YamlMF, false, Ctx);
  256. if (In.error())
  257. return true;
  258. // Search for the corresponding IR function.
  259. StringRef FunctionName = YamlMF.Name;
  260. Function *F = M.getFunction(FunctionName);
  261. if (!F) {
  262. if (NoLLVMIR) {
  263. F = createDummyFunction(FunctionName, M);
  264. } else {
  265. return error(Twine("function '") + FunctionName +
  266. "' isn't defined in the provided LLVM IR");
  267. }
  268. }
  269. if (MMI.getMachineFunction(*F) != nullptr)
  270. return error(Twine("redefinition of machine function '") + FunctionName +
  271. "'");
  272. // Create the MachineFunction.
  273. MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
  274. if (initializeMachineFunction(YamlMF, MF))
  275. return true;
  276. return false;
  277. }
  278. static bool isSSA(const MachineFunction &MF) {
  279. const MachineRegisterInfo &MRI = MF.getRegInfo();
  280. for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
  281. Register Reg = Register::index2VirtReg(I);
  282. if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
  283. return false;
  284. // Subregister defs are invalid in SSA.
  285. const MachineOperand *RegDef = MRI.getOneDef(Reg);
  286. if (RegDef && RegDef->getSubReg() != 0)
  287. return false;
  288. }
  289. return true;
  290. }
  291. void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
  292. MachineFunctionProperties &Properties = MF.getProperties();
  293. bool HasPHI = false;
  294. bool HasInlineAsm = false;
  295. bool AllTiedOpsRewritten = true, HasTiedOps = false;
  296. for (const MachineBasicBlock &MBB : MF) {
  297. for (const MachineInstr &MI : MBB) {
  298. if (MI.isPHI())
  299. HasPHI = true;
  300. if (MI.isInlineAsm())
  301. HasInlineAsm = true;
  302. for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
  303. const MachineOperand &MO = MI.getOperand(I);
  304. if (!MO.isReg() || !MO.getReg())
  305. continue;
  306. unsigned DefIdx;
  307. if (MO.isUse() && MI.isRegTiedToDefOperand(I, &DefIdx)) {
  308. HasTiedOps = true;
  309. if (MO.getReg() != MI.getOperand(DefIdx).getReg())
  310. AllTiedOpsRewritten = false;
  311. }
  312. }
  313. }
  314. }
  315. if (!HasPHI)
  316. Properties.set(MachineFunctionProperties::Property::NoPHIs);
  317. MF.setHasInlineAsm(HasInlineAsm);
  318. if (HasTiedOps && AllTiedOpsRewritten)
  319. Properties.set(MachineFunctionProperties::Property::TiedOpsRewritten);
  320. if (isSSA(MF))
  321. Properties.set(MachineFunctionProperties::Property::IsSSA);
  322. else
  323. Properties.reset(MachineFunctionProperties::Property::IsSSA);
  324. const MachineRegisterInfo &MRI = MF.getRegInfo();
  325. if (MRI.getNumVirtRegs() == 0)
  326. Properties.set(MachineFunctionProperties::Property::NoVRegs);
  327. }
  328. bool MIRParserImpl::initializeCallSiteInfo(
  329. PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF) {
  330. MachineFunction &MF = PFS.MF;
  331. SMDiagnostic Error;
  332. const LLVMTargetMachine &TM = MF.getTarget();
  333. for (auto YamlCSInfo : YamlMF.CallSitesInfo) {
  334. yaml::CallSiteInfo::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
  335. if (MILoc.BlockNum >= MF.size())
  336. return error(Twine(MF.getName()) +
  337. Twine(" call instruction block out of range.") +
  338. " Unable to reference bb:" + Twine(MILoc.BlockNum));
  339. auto CallB = std::next(MF.begin(), MILoc.BlockNum);
  340. if (MILoc.Offset >= CallB->size())
  341. return error(Twine(MF.getName()) +
  342. Twine(" call instruction offset out of range.") +
  343. " Unable to reference instruction at bb: " +
  344. Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset));
  345. auto CallI = std::next(CallB->instr_begin(), MILoc.Offset);
  346. if (!CallI->isCall(MachineInstr::IgnoreBundle))
  347. return error(Twine(MF.getName()) +
  348. Twine(" call site info should reference call "
  349. "instruction. Instruction at bb:") +
  350. Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
  351. " is not a call instruction");
  352. MachineFunction::CallSiteInfo CSInfo;
  353. for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
  354. Register Reg;
  355. if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error))
  356. return error(Error, ArgRegPair.Reg.SourceRange);
  357. CSInfo.emplace_back(Reg, ArgRegPair.ArgNo);
  358. }
  359. if (TM.Options.EmitCallSiteInfo)
  360. MF.addCallArgsForwardingRegs(&*CallI, std::move(CSInfo));
  361. }
  362. if (YamlMF.CallSitesInfo.size() && !TM.Options.EmitCallSiteInfo)
  363. return error(Twine("Call site info provided but not used"));
  364. return false;
  365. }
  366. void MIRParserImpl::setupDebugValueTracking(
  367. MachineFunction &MF, PerFunctionMIParsingState &PFS,
  368. const yaml::MachineFunction &YamlMF) {
  369. // Compute the value of the "next instruction number" field.
  370. unsigned MaxInstrNum = 0;
  371. for (auto &MBB : MF)
  372. for (auto &MI : MBB)
  373. MaxInstrNum = std::max((unsigned)MI.peekDebugInstrNum(), MaxInstrNum);
  374. MF.setDebugInstrNumberingCount(MaxInstrNum);
  375. // Load any substitutions.
  376. for (auto &Sub : YamlMF.DebugValueSubstitutions) {
  377. MF.makeDebugValueSubstitution({Sub.SrcInst, Sub.SrcOp},
  378. {Sub.DstInst, Sub.DstOp}, Sub.Subreg);
  379. }
  380. }
  381. bool
  382. MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF,
  383. MachineFunction &MF) {
  384. // TODO: Recreate the machine function.
  385. if (Target) {
  386. // Avoid clearing state if we're using the same subtarget again.
  387. Target->setTarget(MF.getSubtarget());
  388. } else {
  389. Target.reset(new PerTargetMIParsingState(MF.getSubtarget()));
  390. }
  391. MF.setAlignment(YamlMF.Alignment.valueOrOne());
  392. MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
  393. MF.setHasWinCFI(YamlMF.HasWinCFI);
  394. if (YamlMF.Legalized)
  395. MF.getProperties().set(MachineFunctionProperties::Property::Legalized);
  396. if (YamlMF.RegBankSelected)
  397. MF.getProperties().set(
  398. MachineFunctionProperties::Property::RegBankSelected);
  399. if (YamlMF.Selected)
  400. MF.getProperties().set(MachineFunctionProperties::Property::Selected);
  401. if (YamlMF.FailedISel)
  402. MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
  403. if (YamlMF.FailsVerification)
  404. MF.getProperties().set(
  405. MachineFunctionProperties::Property::FailsVerification);
  406. if (YamlMF.TracksDebugUserValues)
  407. MF.getProperties().set(
  408. MachineFunctionProperties::Property::TracksDebugUserValues);
  409. PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
  410. if (parseRegisterInfo(PFS, YamlMF))
  411. return true;
  412. if (!YamlMF.Constants.empty()) {
  413. auto *ConstantPool = MF.getConstantPool();
  414. assert(ConstantPool && "Constant pool must be created");
  415. if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
  416. return true;
  417. }
  418. if (!YamlMF.MachineMetadataNodes.empty() &&
  419. parseMachineMetadataNodes(PFS, MF, YamlMF))
  420. return true;
  421. StringRef BlockStr = YamlMF.Body.Value.Value;
  422. SMDiagnostic Error;
  423. SourceMgr BlockSM;
  424. BlockSM.AddNewSourceBuffer(
  425. MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
  426. SMLoc());
  427. PFS.SM = &BlockSM;
  428. if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
  429. reportDiagnostic(
  430. diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
  431. return true;
  432. }
  433. // Check Basic Block Section Flags.
  434. if (MF.getTarget().getBBSectionsType() == BasicBlockSection::Labels) {
  435. MF.setBBSectionsType(BasicBlockSection::Labels);
  436. } else if (MF.hasBBSections()) {
  437. MF.assignBeginEndSections();
  438. }
  439. PFS.SM = &SM;
  440. // Initialize the frame information after creating all the MBBs so that the
  441. // MBB references in the frame information can be resolved.
  442. if (initializeFrameInfo(PFS, YamlMF))
  443. return true;
  444. // Initialize the jump table after creating all the MBBs so that the MBB
  445. // references can be resolved.
  446. if (!YamlMF.JumpTableInfo.Entries.empty() &&
  447. initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo))
  448. return true;
  449. // Parse the machine instructions after creating all of the MBBs so that the
  450. // parser can resolve the MBB references.
  451. StringRef InsnStr = YamlMF.Body.Value.Value;
  452. SourceMgr InsnSM;
  453. InsnSM.AddNewSourceBuffer(
  454. MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
  455. SMLoc());
  456. PFS.SM = &InsnSM;
  457. if (parseMachineInstructions(PFS, InsnStr, Error)) {
  458. reportDiagnostic(
  459. diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
  460. return true;
  461. }
  462. PFS.SM = &SM;
  463. if (setupRegisterInfo(PFS, YamlMF))
  464. return true;
  465. if (YamlMF.MachineFuncInfo) {
  466. const LLVMTargetMachine &TM = MF.getTarget();
  467. // Note this is called after the initial constructor of the
  468. // MachineFunctionInfo based on the MachineFunction, which may depend on the
  469. // IR.
  470. SMRange SrcRange;
  471. if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
  472. SrcRange)) {
  473. return error(Error, SrcRange);
  474. }
  475. }
  476. // Set the reserved registers after parsing MachineFuncInfo. The target may
  477. // have been recording information used to select the reserved registers
  478. // there.
  479. // FIXME: This is a temporary workaround until the reserved registers can be
  480. // serialized.
  481. MachineRegisterInfo &MRI = MF.getRegInfo();
  482. MRI.freezeReservedRegs(MF);
  483. computeFunctionProperties(MF);
  484. if (initializeCallSiteInfo(PFS, YamlMF))
  485. return false;
  486. setupDebugValueTracking(MF, PFS, YamlMF);
  487. MF.getSubtarget().mirFileLoaded(MF);
  488. MF.verify();
  489. return false;
  490. }
  491. bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
  492. const yaml::MachineFunction &YamlMF) {
  493. MachineFunction &MF = PFS.MF;
  494. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  495. assert(RegInfo.tracksLiveness());
  496. if (!YamlMF.TracksRegLiveness)
  497. RegInfo.invalidateLiveness();
  498. SMDiagnostic Error;
  499. // Parse the virtual register information.
  500. for (const auto &VReg : YamlMF.VirtualRegisters) {
  501. VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
  502. if (Info.Explicit)
  503. return error(VReg.ID.SourceRange.Start,
  504. Twine("redefinition of virtual register '%") +
  505. Twine(VReg.ID.Value) + "'");
  506. Info.Explicit = true;
  507. if (StringRef(VReg.Class.Value).equals("_")) {
  508. Info.Kind = VRegInfo::GENERIC;
  509. Info.D.RegBank = nullptr;
  510. } else {
  511. const auto *RC = Target->getRegClass(VReg.Class.Value);
  512. if (RC) {
  513. Info.Kind = VRegInfo::NORMAL;
  514. Info.D.RC = RC;
  515. } else {
  516. const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
  517. if (!RegBank)
  518. return error(
  519. VReg.Class.SourceRange.Start,
  520. Twine("use of undefined register class or register bank '") +
  521. VReg.Class.Value + "'");
  522. Info.Kind = VRegInfo::REGBANK;
  523. Info.D.RegBank = RegBank;
  524. }
  525. }
  526. if (!VReg.PreferredRegister.Value.empty()) {
  527. if (Info.Kind != VRegInfo::NORMAL)
  528. return error(VReg.Class.SourceRange.Start,
  529. Twine("preferred register can only be set for normal vregs"));
  530. if (parseRegisterReference(PFS, Info.PreferredReg,
  531. VReg.PreferredRegister.Value, Error))
  532. return error(Error, VReg.PreferredRegister.SourceRange);
  533. }
  534. }
  535. // Parse the liveins.
  536. for (const auto &LiveIn : YamlMF.LiveIns) {
  537. Register Reg;
  538. if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
  539. return error(Error, LiveIn.Register.SourceRange);
  540. Register VReg;
  541. if (!LiveIn.VirtualRegister.Value.empty()) {
  542. VRegInfo *Info;
  543. if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
  544. Error))
  545. return error(Error, LiveIn.VirtualRegister.SourceRange);
  546. VReg = Info->VReg;
  547. }
  548. RegInfo.addLiveIn(Reg, VReg);
  549. }
  550. // Parse the callee saved registers (Registers that will
  551. // be saved for the caller).
  552. if (YamlMF.CalleeSavedRegisters) {
  553. SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
  554. for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
  555. Register Reg;
  556. if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
  557. return error(Error, RegSource.SourceRange);
  558. CalleeSavedRegisters.push_back(Reg);
  559. }
  560. RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
  561. }
  562. return false;
  563. }
  564. bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
  565. const yaml::MachineFunction &YamlMF) {
  566. MachineFunction &MF = PFS.MF;
  567. MachineRegisterInfo &MRI = MF.getRegInfo();
  568. bool Error = false;
  569. // Create VRegs
  570. auto populateVRegInfo = [&] (const VRegInfo &Info, Twine Name) {
  571. Register Reg = Info.VReg;
  572. switch (Info.Kind) {
  573. case VRegInfo::UNKNOWN:
  574. error(Twine("Cannot determine class/bank of virtual register ") +
  575. Name + " in function '" + MF.getName() + "'");
  576. Error = true;
  577. break;
  578. case VRegInfo::NORMAL:
  579. MRI.setRegClass(Reg, Info.D.RC);
  580. if (Info.PreferredReg != 0)
  581. MRI.setSimpleHint(Reg, Info.PreferredReg);
  582. break;
  583. case VRegInfo::GENERIC:
  584. break;
  585. case VRegInfo::REGBANK:
  586. MRI.setRegBank(Reg, *Info.D.RegBank);
  587. break;
  588. }
  589. };
  590. for (const auto &P : PFS.VRegInfosNamed) {
  591. const VRegInfo &Info = *P.second;
  592. populateVRegInfo(Info, Twine(P.first()));
  593. }
  594. for (auto P : PFS.VRegInfos) {
  595. const VRegInfo &Info = *P.second;
  596. populateVRegInfo(Info, Twine(P.first));
  597. }
  598. // Compute MachineRegisterInfo::UsedPhysRegMask
  599. for (const MachineBasicBlock &MBB : MF) {
  600. // Make sure MRI knows about registers clobbered by unwinder.
  601. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  602. if (MBB.isEHPad())
  603. if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
  604. MRI.addPhysRegsUsedFromRegMask(RegMask);
  605. for (const MachineInstr &MI : MBB) {
  606. for (const MachineOperand &MO : MI.operands()) {
  607. if (!MO.isRegMask())
  608. continue;
  609. MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
  610. }
  611. }
  612. }
  613. return Error;
  614. }
  615. bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
  616. const yaml::MachineFunction &YamlMF) {
  617. MachineFunction &MF = PFS.MF;
  618. MachineFrameInfo &MFI = MF.getFrameInfo();
  619. const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
  620. const Function &F = MF.getFunction();
  621. const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
  622. MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
  623. MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
  624. MFI.setHasStackMap(YamlMFI.HasStackMap);
  625. MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
  626. MFI.setStackSize(YamlMFI.StackSize);
  627. MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
  628. if (YamlMFI.MaxAlignment)
  629. MFI.ensureMaxAlignment(Align(YamlMFI.MaxAlignment));
  630. MFI.setAdjustsStack(YamlMFI.AdjustsStack);
  631. MFI.setHasCalls(YamlMFI.HasCalls);
  632. if (YamlMFI.MaxCallFrameSize != ~0u)
  633. MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
  634. MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters);
  635. MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
  636. MFI.setHasVAStart(YamlMFI.HasVAStart);
  637. MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
  638. MFI.setHasTailCall(YamlMFI.HasTailCall);
  639. MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
  640. if (!YamlMFI.SavePoint.Value.empty()) {
  641. MachineBasicBlock *MBB = nullptr;
  642. if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
  643. return true;
  644. MFI.setSavePoint(MBB);
  645. }
  646. if (!YamlMFI.RestorePoint.Value.empty()) {
  647. MachineBasicBlock *MBB = nullptr;
  648. if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
  649. return true;
  650. MFI.setRestorePoint(MBB);
  651. }
  652. std::vector<CalleeSavedInfo> CSIInfo;
  653. // Initialize the fixed frame objects.
  654. for (const auto &Object : YamlMF.FixedStackObjects) {
  655. int ObjectIdx;
  656. if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
  657. ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
  658. Object.IsImmutable, Object.IsAliased);
  659. else
  660. ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
  661. if (!TFI->isSupportedStackID(Object.StackID))
  662. return error(Object.ID.SourceRange.Start,
  663. Twine("StackID is not supported by target"));
  664. MFI.setStackID(ObjectIdx, Object.StackID);
  665. MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
  666. if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
  667. ObjectIdx))
  668. .second)
  669. return error(Object.ID.SourceRange.Start,
  670. Twine("redefinition of fixed stack object '%fixed-stack.") +
  671. Twine(Object.ID.Value) + "'");
  672. if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
  673. Object.CalleeSavedRestored, ObjectIdx))
  674. return true;
  675. if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
  676. return true;
  677. }
  678. // Initialize the ordinary frame objects.
  679. for (const auto &Object : YamlMF.StackObjects) {
  680. int ObjectIdx;
  681. const AllocaInst *Alloca = nullptr;
  682. const yaml::StringValue &Name = Object.Name;
  683. if (!Name.Value.empty()) {
  684. Alloca = dyn_cast_or_null<AllocaInst>(
  685. F.getValueSymbolTable()->lookup(Name.Value));
  686. if (!Alloca)
  687. return error(Name.SourceRange.Start,
  688. "alloca instruction named '" + Name.Value +
  689. "' isn't defined in the function '" + F.getName() +
  690. "'");
  691. }
  692. if (!TFI->isSupportedStackID(Object.StackID))
  693. return error(Object.ID.SourceRange.Start,
  694. Twine("StackID is not supported by target"));
  695. if (Object.Type == yaml::MachineStackObject::VariableSized)
  696. ObjectIdx =
  697. MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
  698. else
  699. ObjectIdx = MFI.CreateStackObject(
  700. Object.Size, Object.Alignment.valueOrOne(),
  701. Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
  702. Object.StackID);
  703. MFI.setObjectOffset(ObjectIdx, Object.Offset);
  704. if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
  705. .second)
  706. return error(Object.ID.SourceRange.Start,
  707. Twine("redefinition of stack object '%stack.") +
  708. Twine(Object.ID.Value) + "'");
  709. if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
  710. Object.CalleeSavedRestored, ObjectIdx))
  711. return true;
  712. if (Object.LocalOffset)
  713. MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue());
  714. if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
  715. return true;
  716. }
  717. MFI.setCalleeSavedInfo(CSIInfo);
  718. if (!CSIInfo.empty())
  719. MFI.setCalleeSavedInfoValid(true);
  720. // Initialize the various stack object references after initializing the
  721. // stack objects.
  722. if (!YamlMFI.StackProtector.Value.empty()) {
  723. SMDiagnostic Error;
  724. int FI;
  725. if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
  726. return error(Error, YamlMFI.StackProtector.SourceRange);
  727. MFI.setStackProtectorIndex(FI);
  728. }
  729. return false;
  730. }
  731. bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
  732. std::vector<CalleeSavedInfo> &CSIInfo,
  733. const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
  734. if (RegisterSource.Value.empty())
  735. return false;
  736. Register Reg;
  737. SMDiagnostic Error;
  738. if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
  739. return error(Error, RegisterSource.SourceRange);
  740. CalleeSavedInfo CSI(Reg, FrameIdx);
  741. CSI.setRestored(IsRestored);
  742. CSIInfo.push_back(CSI);
  743. return false;
  744. }
  745. /// Verify that given node is of a certain type. Return true on error.
  746. template <typename T>
  747. static bool typecheckMDNode(T *&Result, MDNode *Node,
  748. const yaml::StringValue &Source,
  749. StringRef TypeString, MIRParserImpl &Parser) {
  750. if (!Node)
  751. return false;
  752. Result = dyn_cast<T>(Node);
  753. if (!Result)
  754. return Parser.error(Source.SourceRange.Start,
  755. "expected a reference to a '" + TypeString +
  756. "' metadata node");
  757. return false;
  758. }
  759. template <typename T>
  760. bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
  761. const T &Object, int FrameIdx) {
  762. // Debug information can only be attached to stack objects; Fixed stack
  763. // objects aren't supported.
  764. MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
  765. if (parseMDNode(PFS, Var, Object.DebugVar) ||
  766. parseMDNode(PFS, Expr, Object.DebugExpr) ||
  767. parseMDNode(PFS, Loc, Object.DebugLoc))
  768. return true;
  769. if (!Var && !Expr && !Loc)
  770. return false;
  771. DILocalVariable *DIVar = nullptr;
  772. DIExpression *DIExpr = nullptr;
  773. DILocation *DILoc = nullptr;
  774. if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
  775. typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
  776. typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
  777. return true;
  778. PFS.MF.setVariableDbgInfo(DIVar, DIExpr, FrameIdx, DILoc);
  779. return false;
  780. }
  781. bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
  782. MDNode *&Node, const yaml::StringValue &Source) {
  783. if (Source.Value.empty())
  784. return false;
  785. SMDiagnostic Error;
  786. if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
  787. return error(Error, Source.SourceRange);
  788. return false;
  789. }
  790. bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
  791. MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
  792. DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
  793. const MachineFunction &MF = PFS.MF;
  794. const auto &M = *MF.getFunction().getParent();
  795. SMDiagnostic Error;
  796. for (const auto &YamlConstant : YamlMF.Constants) {
  797. if (YamlConstant.IsTargetSpecific)
  798. // FIXME: Support target-specific constant pools
  799. return error(YamlConstant.Value.SourceRange.Start,
  800. "Can't parse target-specific constant pool entries yet");
  801. const Constant *Value = dyn_cast_or_null<Constant>(
  802. parseConstantValue(YamlConstant.Value.Value, Error, M));
  803. if (!Value)
  804. return error(Error, YamlConstant.Value.SourceRange);
  805. const Align PrefTypeAlign =
  806. M.getDataLayout().getPrefTypeAlign(Value->getType());
  807. const Align Alignment = YamlConstant.Alignment.getValueOr(PrefTypeAlign);
  808. unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
  809. if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
  810. .second)
  811. return error(YamlConstant.ID.SourceRange.Start,
  812. Twine("redefinition of constant pool item '%const.") +
  813. Twine(YamlConstant.ID.Value) + "'");
  814. }
  815. return false;
  816. }
  817. bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
  818. const yaml::MachineJumpTable &YamlJTI) {
  819. MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
  820. for (const auto &Entry : YamlJTI.Entries) {
  821. std::vector<MachineBasicBlock *> Blocks;
  822. for (const auto &MBBSource : Entry.Blocks) {
  823. MachineBasicBlock *MBB = nullptr;
  824. if (parseMBBReference(PFS, MBB, MBBSource.Value))
  825. return true;
  826. Blocks.push_back(MBB);
  827. }
  828. unsigned Index = JTI->createJumpTableIndex(Blocks);
  829. if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
  830. .second)
  831. return error(Entry.ID.SourceRange.Start,
  832. Twine("redefinition of jump table entry '%jump-table.") +
  833. Twine(Entry.ID.Value) + "'");
  834. }
  835. return false;
  836. }
  837. bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
  838. MachineBasicBlock *&MBB,
  839. const yaml::StringValue &Source) {
  840. SMDiagnostic Error;
  841. if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
  842. return error(Error, Source.SourceRange);
  843. return false;
  844. }
  845. bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState &PFS,
  846. const yaml::StringValue &Source) {
  847. SMDiagnostic Error;
  848. if (llvm::parseMachineMetadata(PFS, Source.Value, Source.SourceRange, Error))
  849. return error(Error, Source.SourceRange);
  850. return false;
  851. }
  852. bool MIRParserImpl::parseMachineMetadataNodes(
  853. PerFunctionMIParsingState &PFS, MachineFunction &MF,
  854. const yaml::MachineFunction &YMF) {
  855. for (auto &MDS : YMF.MachineMetadataNodes) {
  856. if (parseMachineMetadata(PFS, MDS))
  857. return true;
  858. }
  859. // Report missing definitions from forward referenced nodes.
  860. if (!PFS.MachineForwardRefMDNodes.empty())
  861. return error(PFS.MachineForwardRefMDNodes.begin()->second.second,
  862. "use of undefined metadata '!" +
  863. Twine(PFS.MachineForwardRefMDNodes.begin()->first) + "'");
  864. return false;
  865. }
  866. SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
  867. SMRange SourceRange) {
  868. assert(SourceRange.isValid() && "Invalid source range");
  869. SMLoc Loc = SourceRange.Start;
  870. bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
  871. *Loc.getPointer() == '\'';
  872. // Translate the location of the error from the location in the MI string to
  873. // the corresponding location in the MIR file.
  874. Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
  875. (HasQuote ? 1 : 0));
  876. // TODO: Translate any source ranges as well.
  877. return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
  878. Error.getFixIts());
  879. }
  880. SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
  881. SMRange SourceRange) {
  882. assert(SourceRange.isValid());
  883. // Translate the location of the error from the location in the llvm IR string
  884. // to the corresponding location in the MIR file.
  885. auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
  886. unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
  887. unsigned Column = Error.getColumnNo();
  888. StringRef LineStr = Error.getLineContents();
  889. SMLoc Loc = Error.getLoc();
  890. // Get the full line and adjust the column number by taking the indentation of
  891. // LLVM IR into account.
  892. for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
  893. L != E; ++L) {
  894. if (L.line_number() == Line) {
  895. LineStr = *L;
  896. Loc = SMLoc::getFromPointer(LineStr.data());
  897. auto Indent = LineStr.find(Error.getLineContents());
  898. if (Indent != StringRef::npos)
  899. Column += Indent;
  900. break;
  901. }
  902. }
  903. return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
  904. Error.getMessage(), LineStr, Error.getRanges(),
  905. Error.getFixIts());
  906. }
  907. MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
  908. : Impl(std::move(Impl)) {}
  909. MIRParser::~MIRParser() {}
  910. std::unique_ptr<Module>
  911. MIRParser::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
  912. return Impl->parseIRModule(DataLayoutCallback);
  913. }
  914. bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
  915. return Impl->parseMachineFunctions(M, MMI);
  916. }
  917. std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
  918. StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
  919. std::function<void(Function &)> ProcessIRFunction) {
  920. auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
  921. if (std::error_code EC = FileOrErr.getError()) {
  922. Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
  923. "Could not open input file: " + EC.message());
  924. return nullptr;
  925. }
  926. return createMIRParser(std::move(FileOrErr.get()), Context,
  927. ProcessIRFunction);
  928. }
  929. std::unique_ptr<MIRParser>
  930. llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
  931. LLVMContext &Context,
  932. std::function<void(Function &)> ProcessIRFunction) {
  933. auto Filename = Contents->getBufferIdentifier();
  934. if (Context.shouldDiscardValueNames()) {
  935. Context.diagnose(DiagnosticInfoMIRParser(
  936. DS_Error,
  937. SMDiagnostic(
  938. Filename, SourceMgr::DK_Error,
  939. "Can't read MIR with a Context that discards named Values")));
  940. return nullptr;
  941. }
  942. return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
  943. std::move(Contents), Filename, Context, ProcessIRFunction));
  944. }