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