CodeGenInstruction.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  1. //===- CodeGenInstruction.cpp - CodeGen Instruction Class Wrapper ---------===//
  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 CodeGenInstruction class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CodeGenInstruction.h"
  13. #include "CodeGenTarget.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/ADT/StringMap.h"
  17. #include "llvm/TableGen/Error.h"
  18. #include "llvm/TableGen/Record.h"
  19. #include <set>
  20. using namespace llvm;
  21. //===----------------------------------------------------------------------===//
  22. // CGIOperandList Implementation
  23. //===----------------------------------------------------------------------===//
  24. CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
  25. isPredicable = false;
  26. hasOptionalDef = false;
  27. isVariadic = false;
  28. DagInit *OutDI = R->getValueAsDag("OutOperandList");
  29. if (DefInit *Init = dyn_cast<DefInit>(OutDI->getOperator())) {
  30. if (Init->getDef()->getName() != "outs")
  31. PrintFatalError(R->getLoc(),
  32. R->getName() +
  33. ": invalid def name for output list: use 'outs'");
  34. } else
  35. PrintFatalError(R->getLoc(),
  36. R->getName() + ": invalid output list: use 'outs'");
  37. NumDefs = OutDI->getNumArgs();
  38. DagInit *InDI = R->getValueAsDag("InOperandList");
  39. if (DefInit *Init = dyn_cast<DefInit>(InDI->getOperator())) {
  40. if (Init->getDef()->getName() != "ins")
  41. PrintFatalError(R->getLoc(),
  42. R->getName() +
  43. ": invalid def name for input list: use 'ins'");
  44. } else
  45. PrintFatalError(R->getLoc(),
  46. R->getName() + ": invalid input list: use 'ins'");
  47. unsigned MIOperandNo = 0;
  48. std::set<std::string> OperandNames;
  49. unsigned e = InDI->getNumArgs() + OutDI->getNumArgs();
  50. OperandList.reserve(e);
  51. bool VariadicOuts = false;
  52. for (unsigned i = 0; i != e; ++i){
  53. Init *ArgInit;
  54. StringRef ArgName;
  55. if (i < NumDefs) {
  56. ArgInit = OutDI->getArg(i);
  57. ArgName = OutDI->getArgNameStr(i);
  58. } else {
  59. ArgInit = InDI->getArg(i-NumDefs);
  60. ArgName = InDI->getArgNameStr(i-NumDefs);
  61. }
  62. DefInit *Arg = dyn_cast<DefInit>(ArgInit);
  63. if (!Arg)
  64. PrintFatalError(R->getLoc(), "Illegal operand for the '" + R->getName() +
  65. "' instruction!");
  66. Record *Rec = Arg->getDef();
  67. std::string PrintMethod = "printOperand";
  68. std::string EncoderMethod;
  69. std::string OperandType = "OPERAND_UNKNOWN";
  70. std::string OperandNamespace = "MCOI";
  71. unsigned NumOps = 1;
  72. DagInit *MIOpInfo = nullptr;
  73. if (Rec->isSubClassOf("RegisterOperand")) {
  74. PrintMethod = std::string(Rec->getValueAsString("PrintMethod"));
  75. OperandType = std::string(Rec->getValueAsString("OperandType"));
  76. OperandNamespace = std::string(Rec->getValueAsString("OperandNamespace"));
  77. EncoderMethod = std::string(Rec->getValueAsString("EncoderMethod"));
  78. } else if (Rec->isSubClassOf("Operand")) {
  79. PrintMethod = std::string(Rec->getValueAsString("PrintMethod"));
  80. OperandType = std::string(Rec->getValueAsString("OperandType"));
  81. OperandNamespace = std::string(Rec->getValueAsString("OperandNamespace"));
  82. // If there is an explicit encoder method, use it.
  83. EncoderMethod = std::string(Rec->getValueAsString("EncoderMethod"));
  84. MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
  85. // Verify that MIOpInfo has an 'ops' root value.
  86. if (!isa<DefInit>(MIOpInfo->getOperator()) ||
  87. cast<DefInit>(MIOpInfo->getOperator())->getDef()->getName() != "ops")
  88. PrintFatalError(R->getLoc(),
  89. "Bad value for MIOperandInfo in operand '" +
  90. Rec->getName() + "'\n");
  91. // If we have MIOpInfo, then we have #operands equal to number of entries
  92. // in MIOperandInfo.
  93. if (unsigned NumArgs = MIOpInfo->getNumArgs())
  94. NumOps = NumArgs;
  95. if (Rec->isSubClassOf("PredicateOp"))
  96. isPredicable = true;
  97. else if (Rec->isSubClassOf("OptionalDefOperand"))
  98. hasOptionalDef = true;
  99. } else if (Rec->getName() == "variable_ops") {
  100. if (i < NumDefs)
  101. VariadicOuts = true;
  102. isVariadic = true;
  103. continue;
  104. } else if (Rec->isSubClassOf("RegisterClass")) {
  105. OperandType = "OPERAND_REGISTER";
  106. } else if (!Rec->isSubClassOf("PointerLikeRegClass") &&
  107. !Rec->isSubClassOf("unknown_class"))
  108. PrintFatalError(R->getLoc(), "Unknown operand class '" + Rec->getName() +
  109. "' in '" + R->getName() +
  110. "' instruction!");
  111. // Check that the operand has a name and that it's unique.
  112. if (ArgName.empty())
  113. PrintFatalError(R->getLoc(), "In instruction '" + R->getName() +
  114. "', operand #" + Twine(i) +
  115. " has no name!");
  116. if (!OperandNames.insert(std::string(ArgName)).second)
  117. PrintFatalError(R->getLoc(),
  118. "In instruction '" + R->getName() + "', operand #" +
  119. Twine(i) +
  120. " has the same name as a previous operand!");
  121. OperandList.emplace_back(
  122. Rec, std::string(ArgName), std::string(PrintMethod),
  123. std::string(EncoderMethod), OperandNamespace + "::" + OperandType,
  124. MIOperandNo, NumOps, MIOpInfo);
  125. MIOperandNo += NumOps;
  126. }
  127. if (VariadicOuts)
  128. --NumDefs;
  129. // Make sure the constraints list for each operand is large enough to hold
  130. // constraint info, even if none is present.
  131. for (OperandInfo &OpInfo : OperandList)
  132. OpInfo.Constraints.resize(OpInfo.MINumOperands);
  133. }
  134. /// getOperandNamed - Return the index of the operand with the specified
  135. /// non-empty name. If the instruction does not have an operand with the
  136. /// specified name, abort.
  137. ///
  138. unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
  139. unsigned OpIdx;
  140. if (hasOperandNamed(Name, OpIdx))
  141. return OpIdx;
  142. PrintFatalError(TheDef->getLoc(), "'" + TheDef->getName() +
  143. "' does not have an operand named '$" +
  144. Name + "'!");
  145. }
  146. /// hasOperandNamed - Query whether the instruction has an operand of the
  147. /// given name. If so, return true and set OpIdx to the index of the
  148. /// operand. Otherwise, return false.
  149. bool CGIOperandList::hasOperandNamed(StringRef Name, unsigned &OpIdx) const {
  150. assert(!Name.empty() && "Cannot search for operand with no name!");
  151. for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
  152. if (OperandList[i].Name == Name) {
  153. OpIdx = i;
  154. return true;
  155. }
  156. return false;
  157. }
  158. std::pair<unsigned,unsigned>
  159. CGIOperandList::ParseOperandName(StringRef Op, bool AllowWholeOp) {
  160. if (Op.empty() || Op[0] != '$')
  161. PrintFatalError(TheDef->getLoc(),
  162. TheDef->getName() + ": Illegal operand name: '" + Op + "'");
  163. StringRef OpName = Op.substr(1);
  164. StringRef SubOpName;
  165. // Check to see if this is $foo.bar.
  166. StringRef::size_type DotIdx = OpName.find_first_of('.');
  167. if (DotIdx != StringRef::npos) {
  168. SubOpName = OpName.substr(DotIdx+1);
  169. if (SubOpName.empty())
  170. PrintFatalError(TheDef->getLoc(),
  171. TheDef->getName() +
  172. ": illegal empty suboperand name in '" + Op + "'");
  173. OpName = OpName.substr(0, DotIdx);
  174. }
  175. unsigned OpIdx = getOperandNamed(OpName);
  176. if (SubOpName.empty()) { // If no suboperand name was specified:
  177. // If one was needed, throw.
  178. if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
  179. SubOpName.empty())
  180. PrintFatalError(TheDef->getLoc(),
  181. TheDef->getName() +
  182. ": Illegal to refer to"
  183. " whole operand part of complex operand '" +
  184. Op + "'");
  185. // Otherwise, return the operand.
  186. return std::make_pair(OpIdx, 0U);
  187. }
  188. // Find the suboperand number involved.
  189. DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
  190. if (!MIOpInfo)
  191. PrintFatalError(TheDef->getLoc(), TheDef->getName() +
  192. ": unknown suboperand name in '" +
  193. Op + "'");
  194. // Find the operand with the right name.
  195. for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
  196. if (MIOpInfo->getArgNameStr(i) == SubOpName)
  197. return std::make_pair(OpIdx, i);
  198. // Otherwise, didn't find it!
  199. PrintFatalError(TheDef->getLoc(), TheDef->getName() +
  200. ": unknown suboperand name in '" + Op +
  201. "'");
  202. return std::make_pair(0U, 0U);
  203. }
  204. static void ParseConstraint(StringRef CStr, CGIOperandList &Ops,
  205. Record *Rec) {
  206. // EARLY_CLOBBER: @early $reg
  207. StringRef::size_type wpos = CStr.find_first_of(" \t");
  208. StringRef::size_type start = CStr.find_first_not_of(" \t");
  209. StringRef Tok = CStr.substr(start, wpos - start);
  210. if (Tok == "@earlyclobber") {
  211. StringRef Name = CStr.substr(wpos+1);
  212. wpos = Name.find_first_not_of(" \t");
  213. if (wpos == StringRef::npos)
  214. PrintFatalError(
  215. Rec->getLoc(), "Illegal format for @earlyclobber constraint in '" +
  216. Rec->getName() + "': '" + CStr + "'");
  217. Name = Name.substr(wpos);
  218. std::pair<unsigned,unsigned> Op = Ops.ParseOperandName(Name, false);
  219. // Build the string for the operand
  220. if (!Ops[Op.first].Constraints[Op.second].isNone())
  221. PrintFatalError(
  222. Rec->getLoc(), "Operand '" + Name + "' of '" + Rec->getName() +
  223. "' cannot have multiple constraints!");
  224. Ops[Op.first].Constraints[Op.second] =
  225. CGIOperandList::ConstraintInfo::getEarlyClobber();
  226. return;
  227. }
  228. // Only other constraint is "TIED_TO" for now.
  229. StringRef::size_type pos = CStr.find_first_of('=');
  230. if (pos == StringRef::npos)
  231. PrintFatalError(
  232. Rec->getLoc(), "Unrecognized constraint '" + CStr +
  233. "' in '" + Rec->getName() + "'");
  234. start = CStr.find_first_not_of(" \t");
  235. // TIED_TO: $src1 = $dst
  236. wpos = CStr.find_first_of(" \t", start);
  237. if (wpos == StringRef::npos || wpos > pos)
  238. PrintFatalError(
  239. Rec->getLoc(), "Illegal format for tied-to constraint in '" +
  240. Rec->getName() + "': '" + CStr + "'");
  241. StringRef LHSOpName = CStr.substr(start, wpos - start);
  242. std::pair<unsigned,unsigned> LHSOp = Ops.ParseOperandName(LHSOpName, false);
  243. wpos = CStr.find_first_not_of(" \t", pos + 1);
  244. if (wpos == StringRef::npos)
  245. PrintFatalError(
  246. Rec->getLoc(), "Illegal format for tied-to constraint: '" + CStr + "'");
  247. StringRef RHSOpName = CStr.substr(wpos);
  248. std::pair<unsigned,unsigned> RHSOp = Ops.ParseOperandName(RHSOpName, false);
  249. // Sort the operands into order, which should put the output one
  250. // first. But keep the original order, for use in diagnostics.
  251. bool FirstIsDest = (LHSOp < RHSOp);
  252. std::pair<unsigned,unsigned> DestOp = (FirstIsDest ? LHSOp : RHSOp);
  253. StringRef DestOpName = (FirstIsDest ? LHSOpName : RHSOpName);
  254. std::pair<unsigned,unsigned> SrcOp = (FirstIsDest ? RHSOp : LHSOp);
  255. StringRef SrcOpName = (FirstIsDest ? RHSOpName : LHSOpName);
  256. // Ensure one operand is a def and the other is a use.
  257. if (DestOp.first >= Ops.NumDefs)
  258. PrintFatalError(
  259. Rec->getLoc(), "Input operands '" + LHSOpName + "' and '" + RHSOpName +
  260. "' of '" + Rec->getName() + "' cannot be tied!");
  261. if (SrcOp.first < Ops.NumDefs)
  262. PrintFatalError(
  263. Rec->getLoc(), "Output operands '" + LHSOpName + "' and '" + RHSOpName +
  264. "' of '" + Rec->getName() + "' cannot be tied!");
  265. // The constraint has to go on the operand with higher index, i.e.
  266. // the source one. Check there isn't another constraint there
  267. // already.
  268. if (!Ops[SrcOp.first].Constraints[SrcOp.second].isNone())
  269. PrintFatalError(
  270. Rec->getLoc(), "Operand '" + SrcOpName + "' of '" + Rec->getName() +
  271. "' cannot have multiple constraints!");
  272. unsigned DestFlatOpNo = Ops.getFlattenedOperandNumber(DestOp);
  273. auto NewConstraint = CGIOperandList::ConstraintInfo::getTied(DestFlatOpNo);
  274. // Check that the earlier operand is not the target of another tie
  275. // before making it the target of this one.
  276. for (const CGIOperandList::OperandInfo &Op : Ops) {
  277. for (unsigned i = 0; i < Op.MINumOperands; i++)
  278. if (Op.Constraints[i] == NewConstraint)
  279. PrintFatalError(
  280. Rec->getLoc(), "Operand '" + DestOpName + "' of '" + Rec->getName() +
  281. "' cannot have multiple operands tied to it!");
  282. }
  283. Ops[SrcOp.first].Constraints[SrcOp.second] = NewConstraint;
  284. }
  285. static void ParseConstraints(StringRef CStr, CGIOperandList &Ops, Record *Rec) {
  286. if (CStr.empty()) return;
  287. StringRef delims(",");
  288. StringRef::size_type bidx, eidx;
  289. bidx = CStr.find_first_not_of(delims);
  290. while (bidx != StringRef::npos) {
  291. eidx = CStr.find_first_of(delims, bidx);
  292. if (eidx == StringRef::npos)
  293. eidx = CStr.size();
  294. ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops, Rec);
  295. bidx = CStr.find_first_not_of(delims, eidx);
  296. }
  297. }
  298. void CGIOperandList::ProcessDisableEncoding(StringRef DisableEncoding) {
  299. while (true) {
  300. StringRef OpName;
  301. std::tie(OpName, DisableEncoding) = getToken(DisableEncoding, " ,\t");
  302. if (OpName.empty()) break;
  303. // Figure out which operand this is.
  304. std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
  305. // Mark the operand as not-to-be encoded.
  306. if (Op.second >= OperandList[Op.first].DoNotEncode.size())
  307. OperandList[Op.first].DoNotEncode.resize(Op.second+1);
  308. OperandList[Op.first].DoNotEncode[Op.second] = true;
  309. }
  310. }
  311. //===----------------------------------------------------------------------===//
  312. // CodeGenInstruction Implementation
  313. //===----------------------------------------------------------------------===//
  314. CodeGenInstruction::CodeGenInstruction(Record *R)
  315. : TheDef(R), Operands(R), InferredFrom(nullptr) {
  316. Namespace = R->getValueAsString("Namespace");
  317. AsmString = std::string(R->getValueAsString("AsmString"));
  318. isPreISelOpcode = R->getValueAsBit("isPreISelOpcode");
  319. isReturn = R->getValueAsBit("isReturn");
  320. isEHScopeReturn = R->getValueAsBit("isEHScopeReturn");
  321. isBranch = R->getValueAsBit("isBranch");
  322. isIndirectBranch = R->getValueAsBit("isIndirectBranch");
  323. isCompare = R->getValueAsBit("isCompare");
  324. isMoveImm = R->getValueAsBit("isMoveImm");
  325. isMoveReg = R->getValueAsBit("isMoveReg");
  326. isBitcast = R->getValueAsBit("isBitcast");
  327. isSelect = R->getValueAsBit("isSelect");
  328. isBarrier = R->getValueAsBit("isBarrier");
  329. isCall = R->getValueAsBit("isCall");
  330. isAdd = R->getValueAsBit("isAdd");
  331. isTrap = R->getValueAsBit("isTrap");
  332. canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
  333. isPredicable = !R->getValueAsBit("isUnpredicable") && (
  334. Operands.isPredicable || R->getValueAsBit("isPredicable"));
  335. isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
  336. isCommutable = R->getValueAsBit("isCommutable");
  337. isTerminator = R->getValueAsBit("isTerminator");
  338. isReMaterializable = R->getValueAsBit("isReMaterializable");
  339. hasDelaySlot = R->getValueAsBit("hasDelaySlot");
  340. usesCustomInserter = R->getValueAsBit("usesCustomInserter");
  341. hasPostISelHook = R->getValueAsBit("hasPostISelHook");
  342. hasCtrlDep = R->getValueAsBit("hasCtrlDep");
  343. isNotDuplicable = R->getValueAsBit("isNotDuplicable");
  344. isRegSequence = R->getValueAsBit("isRegSequence");
  345. isExtractSubreg = R->getValueAsBit("isExtractSubreg");
  346. isInsertSubreg = R->getValueAsBit("isInsertSubreg");
  347. isConvergent = R->getValueAsBit("isConvergent");
  348. hasNoSchedulingInfo = R->getValueAsBit("hasNoSchedulingInfo");
  349. FastISelShouldIgnore = R->getValueAsBit("FastISelShouldIgnore");
  350. variadicOpsAreDefs = R->getValueAsBit("variadicOpsAreDefs");
  351. isAuthenticated = R->getValueAsBit("isAuthenticated");
  352. bool Unset;
  353. mayLoad = R->getValueAsBitOrUnset("mayLoad", Unset);
  354. mayLoad_Unset = Unset;
  355. mayStore = R->getValueAsBitOrUnset("mayStore", Unset);
  356. mayStore_Unset = Unset;
  357. mayRaiseFPException = R->getValueAsBit("mayRaiseFPException");
  358. hasSideEffects = R->getValueAsBitOrUnset("hasSideEffects", Unset);
  359. hasSideEffects_Unset = Unset;
  360. isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
  361. hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
  362. hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
  363. isCodeGenOnly = R->getValueAsBit("isCodeGenOnly");
  364. isPseudo = R->getValueAsBit("isPseudo");
  365. ImplicitDefs = R->getValueAsListOfDefs("Defs");
  366. ImplicitUses = R->getValueAsListOfDefs("Uses");
  367. // This flag is only inferred from the pattern.
  368. hasChain = false;
  369. hasChain_Inferred = false;
  370. // Parse Constraints.
  371. ParseConstraints(R->getValueAsString("Constraints"), Operands, R);
  372. // Parse the DisableEncoding field.
  373. Operands.ProcessDisableEncoding(
  374. R->getValueAsString("DisableEncoding"));
  375. // First check for a ComplexDeprecationPredicate.
  376. if (R->getValue("ComplexDeprecationPredicate")) {
  377. HasComplexDeprecationPredicate = true;
  378. DeprecatedReason =
  379. std::string(R->getValueAsString("ComplexDeprecationPredicate"));
  380. } else if (RecordVal *Dep = R->getValue("DeprecatedFeatureMask")) {
  381. // Check if we have a Subtarget feature mask.
  382. HasComplexDeprecationPredicate = false;
  383. DeprecatedReason = Dep->getValue()->getAsString();
  384. } else {
  385. // This instruction isn't deprecated.
  386. HasComplexDeprecationPredicate = false;
  387. DeprecatedReason = "";
  388. }
  389. }
  390. /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
  391. /// implicit def and it has a known VT, return the VT, otherwise return
  392. /// MVT::Other.
  393. MVT::SimpleValueType CodeGenInstruction::
  394. HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
  395. if (ImplicitDefs.empty()) return MVT::Other;
  396. // Check to see if the first implicit def has a resolvable type.
  397. Record *FirstImplicitDef = ImplicitDefs[0];
  398. assert(FirstImplicitDef->isSubClassOf("Register"));
  399. const std::vector<ValueTypeByHwMode> &RegVTs =
  400. TargetInfo.getRegisterVTs(FirstImplicitDef);
  401. if (RegVTs.size() == 1 && RegVTs[0].isSimple())
  402. return RegVTs[0].getSimple().SimpleTy;
  403. return MVT::Other;
  404. }
  405. /// FlattenAsmStringVariants - Flatten the specified AsmString to only
  406. /// include text from the specified variant, returning the new string.
  407. std::string CodeGenInstruction::
  408. FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
  409. std::string Res;
  410. for (;;) {
  411. // Find the start of the next variant string.
  412. size_t VariantsStart = 0;
  413. for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
  414. if (Cur[VariantsStart] == '{' &&
  415. (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
  416. Cur[VariantsStart-1] != '\\')))
  417. break;
  418. // Add the prefix to the result.
  419. Res += Cur.slice(0, VariantsStart);
  420. if (VariantsStart == Cur.size())
  421. break;
  422. ++VariantsStart; // Skip the '{'.
  423. // Scan to the end of the variants string.
  424. size_t VariantsEnd = VariantsStart;
  425. unsigned NestedBraces = 1;
  426. for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
  427. if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
  428. if (--NestedBraces == 0)
  429. break;
  430. } else if (Cur[VariantsEnd] == '{')
  431. ++NestedBraces;
  432. }
  433. // Select the Nth variant (or empty).
  434. StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
  435. for (unsigned i = 0; i != Variant; ++i)
  436. Selection = Selection.split('|').second;
  437. Res += Selection.split('|').first;
  438. assert(VariantsEnd != Cur.size() &&
  439. "Unterminated variants in assembly string!");
  440. Cur = Cur.substr(VariantsEnd + 1);
  441. }
  442. return Res;
  443. }
  444. bool CodeGenInstruction::isOperandImpl(unsigned i,
  445. StringRef PropertyName) const {
  446. DagInit *ConstraintList = TheDef->getValueAsDag("InOperandList");
  447. if (!ConstraintList || i >= ConstraintList->getNumArgs())
  448. return false;
  449. DefInit *Constraint = dyn_cast<DefInit>(ConstraintList->getArg(i));
  450. if (!Constraint)
  451. return false;
  452. return Constraint->getDef()->isSubClassOf("TypedOperand") &&
  453. Constraint->getDef()->getValueAsBit(PropertyName);
  454. }
  455. //===----------------------------------------------------------------------===//
  456. /// CodeGenInstAlias Implementation
  457. //===----------------------------------------------------------------------===//
  458. /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
  459. /// constructor. It checks if an argument in an InstAlias pattern matches
  460. /// the corresponding operand of the instruction. It returns true on a
  461. /// successful match, with ResOp set to the result operand to be used.
  462. bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
  463. Record *InstOpRec, bool hasSubOps,
  464. ArrayRef<SMLoc> Loc, CodeGenTarget &T,
  465. ResultOperand &ResOp) {
  466. Init *Arg = Result->getArg(AliasOpNo);
  467. DefInit *ADI = dyn_cast<DefInit>(Arg);
  468. Record *ResultRecord = ADI ? ADI->getDef() : nullptr;
  469. if (ADI && ADI->getDef() == InstOpRec) {
  470. // If the operand is a record, it must have a name, and the record type
  471. // must match up with the instruction's argument type.
  472. if (!Result->getArgName(AliasOpNo))
  473. PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
  474. " must have a name!");
  475. ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
  476. ResultRecord);
  477. return true;
  478. }
  479. // For register operands, the source register class can be a subclass
  480. // of the instruction register class, not just an exact match.
  481. if (InstOpRec->isSubClassOf("RegisterOperand"))
  482. InstOpRec = InstOpRec->getValueAsDef("RegClass");
  483. if (ADI && ADI->getDef()->isSubClassOf("RegisterOperand"))
  484. ADI = ADI->getDef()->getValueAsDef("RegClass")->getDefInit();
  485. if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
  486. if (!InstOpRec->isSubClassOf("RegisterClass"))
  487. return false;
  488. if (!T.getRegisterClass(InstOpRec)
  489. .hasSubClass(&T.getRegisterClass(ADI->getDef())))
  490. return false;
  491. ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
  492. ResultRecord);
  493. return true;
  494. }
  495. // Handle explicit registers.
  496. if (ADI && ADI->getDef()->isSubClassOf("Register")) {
  497. if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
  498. DagInit *DI = InstOpRec->getValueAsDag("MIOperandInfo");
  499. // The operand info should only have a single (register) entry. We
  500. // want the register class of it.
  501. InstOpRec = cast<DefInit>(DI->getArg(0))->getDef();
  502. }
  503. if (!InstOpRec->isSubClassOf("RegisterClass"))
  504. return false;
  505. if (!T.getRegisterClass(InstOpRec)
  506. .contains(T.getRegBank().getReg(ADI->getDef())))
  507. PrintFatalError(Loc, "fixed register " + ADI->getDef()->getName() +
  508. " is not a member of the " + InstOpRec->getName() +
  509. " register class!");
  510. if (Result->getArgName(AliasOpNo))
  511. PrintFatalError(Loc, "result fixed register argument must "
  512. "not have a name!");
  513. ResOp = ResultOperand(ResultRecord);
  514. return true;
  515. }
  516. // Handle "zero_reg" for optional def operands.
  517. if (ADI && ADI->getDef()->getName() == "zero_reg") {
  518. // Check if this is an optional def.
  519. // Tied operands where the source is a sub-operand of a complex operand
  520. // need to represent both operands in the alias destination instruction.
  521. // Allow zero_reg for the tied portion. This can and should go away once
  522. // the MC representation of things doesn't use tied operands at all.
  523. //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
  524. // throw TGError(Loc, "reg0 used for result that is not an "
  525. // "OptionalDefOperand!");
  526. ResOp = ResultOperand(static_cast<Record*>(nullptr));
  527. return true;
  528. }
  529. // Literal integers.
  530. if (IntInit *II = dyn_cast<IntInit>(Arg)) {
  531. if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
  532. return false;
  533. // Integer arguments can't have names.
  534. if (Result->getArgName(AliasOpNo))
  535. PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
  536. " must not have a name!");
  537. ResOp = ResultOperand(II->getValue());
  538. return true;
  539. }
  540. // Bits<n> (also used for 0bxx literals)
  541. if (BitsInit *BI = dyn_cast<BitsInit>(Arg)) {
  542. if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
  543. return false;
  544. if (!BI->isComplete())
  545. return false;
  546. // Convert the bits init to an integer and use that for the result.
  547. IntInit *II =
  548. dyn_cast_or_null<IntInit>(BI->convertInitializerTo(IntRecTy::get()));
  549. if (!II)
  550. return false;
  551. ResOp = ResultOperand(II->getValue());
  552. return true;
  553. }
  554. // If both are Operands with the same MVT, allow the conversion. It's
  555. // up to the user to make sure the values are appropriate, just like
  556. // for isel Pat's.
  557. if (InstOpRec->isSubClassOf("Operand") && ADI &&
  558. ADI->getDef()->isSubClassOf("Operand")) {
  559. // FIXME: What other attributes should we check here? Identical
  560. // MIOperandInfo perhaps?
  561. if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type"))
  562. return false;
  563. ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
  564. ADI->getDef());
  565. return true;
  566. }
  567. return false;
  568. }
  569. unsigned CodeGenInstAlias::ResultOperand::getMINumOperands() const {
  570. if (!isRecord())
  571. return 1;
  572. Record *Rec = getRecord();
  573. if (!Rec->isSubClassOf("Operand"))
  574. return 1;
  575. DagInit *MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
  576. if (MIOpInfo->getNumArgs() == 0) {
  577. // Unspecified, so it defaults to 1
  578. return 1;
  579. }
  580. return MIOpInfo->getNumArgs();
  581. }
  582. CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T)
  583. : TheDef(R) {
  584. Result = R->getValueAsDag("ResultInst");
  585. AsmString = std::string(R->getValueAsString("AsmString"));
  586. // Verify that the root of the result is an instruction.
  587. DefInit *DI = dyn_cast<DefInit>(Result->getOperator());
  588. if (!DI || !DI->getDef()->isSubClassOf("Instruction"))
  589. PrintFatalError(R->getLoc(),
  590. "result of inst alias should be an instruction");
  591. ResultInst = &T.getInstruction(DI->getDef());
  592. // NameClass - If argument names are repeated, we need to verify they have
  593. // the same class.
  594. StringMap<Record*> NameClass;
  595. for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
  596. DefInit *ADI = dyn_cast<DefInit>(Result->getArg(i));
  597. if (!ADI || !Result->getArgName(i))
  598. continue;
  599. // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
  600. // $foo can exist multiple times in the result list, but it must have the
  601. // same type.
  602. Record *&Entry = NameClass[Result->getArgNameStr(i)];
  603. if (Entry && Entry != ADI->getDef())
  604. PrintFatalError(R->getLoc(), "result value $" + Result->getArgNameStr(i) +
  605. " is both " + Entry->getName() + " and " +
  606. ADI->getDef()->getName() + "!");
  607. Entry = ADI->getDef();
  608. }
  609. // Decode and validate the arguments of the result.
  610. unsigned AliasOpNo = 0;
  611. for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
  612. // Tied registers don't have an entry in the result dag unless they're part
  613. // of a complex operand, in which case we include them anyways, as we
  614. // don't have any other way to specify the whole operand.
  615. if (ResultInst->Operands[i].MINumOperands == 1 &&
  616. ResultInst->Operands[i].getTiedRegister() != -1) {
  617. // Tied operands of different RegisterClass should be explicit within an
  618. // instruction's syntax and so cannot be skipped.
  619. int TiedOpNum = ResultInst->Operands[i].getTiedRegister();
  620. if (ResultInst->Operands[i].Rec->getName() ==
  621. ResultInst->Operands[TiedOpNum].Rec->getName())
  622. continue;
  623. }
  624. if (AliasOpNo >= Result->getNumArgs())
  625. PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
  626. Record *InstOpRec = ResultInst->Operands[i].Rec;
  627. unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
  628. ResultOperand ResOp(static_cast<int64_t>(0));
  629. if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
  630. R->getLoc(), T, ResOp)) {
  631. // If this is a simple operand, or a complex operand with a custom match
  632. // class, then we can match is verbatim.
  633. if (NumSubOps == 1 ||
  634. (InstOpRec->getValue("ParserMatchClass") &&
  635. InstOpRec->getValueAsDef("ParserMatchClass")
  636. ->getValueAsString("Name") != "Imm")) {
  637. ResultOperands.push_back(ResOp);
  638. ResultInstOperandIndex.push_back(std::make_pair(i, -1));
  639. ++AliasOpNo;
  640. // Otherwise, we need to match each of the suboperands individually.
  641. } else {
  642. DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
  643. for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
  644. Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
  645. // Take care to instantiate each of the suboperands with the correct
  646. // nomenclature: $foo.bar
  647. ResultOperands.emplace_back(
  648. Result->getArgName(AliasOpNo)->getAsUnquotedString() + "." +
  649. MIOI->getArgName(SubOp)->getAsUnquotedString(), SubRec);
  650. ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
  651. }
  652. ++AliasOpNo;
  653. }
  654. continue;
  655. }
  656. // If the argument did not match the instruction operand, and the operand
  657. // is composed of multiple suboperands, try matching the suboperands.
  658. if (NumSubOps > 1) {
  659. DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
  660. for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
  661. if (AliasOpNo >= Result->getNumArgs())
  662. PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
  663. Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
  664. if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
  665. R->getLoc(), T, ResOp)) {
  666. ResultOperands.push_back(ResOp);
  667. ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
  668. ++AliasOpNo;
  669. } else {
  670. PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
  671. " does not match instruction operand class " +
  672. (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
  673. }
  674. }
  675. continue;
  676. }
  677. PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
  678. " does not match instruction operand class " +
  679. InstOpRec->getName());
  680. }
  681. if (AliasOpNo != Result->getNumArgs())
  682. PrintFatalError(R->getLoc(), "too many operands for instruction!");
  683. }