MIRParser.cpp 39 KB

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