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