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