OSDN Git Service

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