MIRParser.cpp 34 KB

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