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