Home | History | Annotate | Download | only in TableGen
      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 = 0;
     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("PredicateOperand"))
     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 #" + utostr(i) +
    110         " has no name!");
    111     if (!OperandNames.insert(ArgName).second)
    112       PrintFatalError("In instruction '" + R->getName() + "', operand #" + utostr(i) +
    113         " 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() + "' does not have an operand named '$" +
    137     Name.str() + "'!");
    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 == 0)
    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 }
    196 
    197 static void ParseConstraint(const std::string &CStr, CGIOperandList &Ops) {
    198   // EARLY_CLOBBER: @early $reg
    199   std::string::size_type wpos = CStr.find_first_of(" \t");
    200   std::string::size_type start = CStr.find_first_not_of(" \t");
    201   std::string Tok = CStr.substr(start, wpos - start);
    202   if (Tok == "@earlyclobber") {
    203     std::string Name = CStr.substr(wpos+1);
    204     wpos = Name.find_first_not_of(" \t");
    205     if (wpos == std::string::npos)
    206       PrintFatalError("Illegal format for @earlyclobber constraint: '" + CStr + "'");
    207     Name = Name.substr(wpos);
    208     std::pair<unsigned,unsigned> Op = Ops.ParseOperandName(Name, false);
    209 
    210     // Build the string for the operand
    211     if (!Ops[Op.first].Constraints[Op.second].isNone())
    212       PrintFatalError("Operand '" + Name + "' cannot have multiple constraints!");
    213     Ops[Op.first].Constraints[Op.second] =
    214     CGIOperandList::ConstraintInfo::getEarlyClobber();
    215     return;
    216   }
    217 
    218   // Only other constraint is "TIED_TO" for now.
    219   std::string::size_type pos = CStr.find_first_of('=');
    220   assert(pos != std::string::npos && "Unrecognized constraint");
    221   start = CStr.find_first_not_of(" \t");
    222   std::string Name = CStr.substr(start, pos - start);
    223 
    224   // TIED_TO: $src1 = $dst
    225   wpos = Name.find_first_of(" \t");
    226   if (wpos == std::string::npos)
    227     PrintFatalError("Illegal format for tied-to constraint: '" + CStr + "'");
    228   std::string DestOpName = Name.substr(0, wpos);
    229   std::pair<unsigned,unsigned> DestOp = Ops.ParseOperandName(DestOpName, false);
    230 
    231   Name = CStr.substr(pos+1);
    232   wpos = Name.find_first_not_of(" \t");
    233   if (wpos == std::string::npos)
    234     PrintFatalError("Illegal format for tied-to constraint: '" + CStr + "'");
    235 
    236   std::string SrcOpName = Name.substr(wpos);
    237   std::pair<unsigned,unsigned> SrcOp = Ops.ParseOperandName(SrcOpName, false);
    238   if (SrcOp > DestOp) {
    239     std::swap(SrcOp, DestOp);
    240     std::swap(SrcOpName, DestOpName);
    241   }
    242 
    243   unsigned FlatOpNo = Ops.getFlattenedOperandNumber(SrcOp);
    244 
    245   if (!Ops[DestOp.first].Constraints[DestOp.second].isNone())
    246     PrintFatalError("Operand '" + DestOpName +
    247       "' cannot have multiple constraints!");
    248   Ops[DestOp.first].Constraints[DestOp.second] =
    249     CGIOperandList::ConstraintInfo::getTied(FlatOpNo);
    250 }
    251 
    252 static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops) {
    253   if (CStr.empty()) return;
    254 
    255   const std::string delims(",");
    256   std::string::size_type bidx, eidx;
    257 
    258   bidx = CStr.find_first_not_of(delims);
    259   while (bidx != std::string::npos) {
    260     eidx = CStr.find_first_of(delims, bidx);
    261     if (eidx == std::string::npos)
    262       eidx = CStr.length();
    263 
    264     ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops);
    265     bidx = CStr.find_first_not_of(delims, eidx);
    266   }
    267 }
    268 
    269 void CGIOperandList::ProcessDisableEncoding(std::string DisableEncoding) {
    270   while (1) {
    271     std::pair<StringRef, StringRef> P = getToken(DisableEncoding, " ,\t");
    272     std::string OpName = P.first;
    273     DisableEncoding = P.second;
    274     if (OpName.empty()) break;
    275 
    276     // Figure out which operand this is.
    277     std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
    278 
    279     // Mark the operand as not-to-be encoded.
    280     if (Op.second >= OperandList[Op.first].DoNotEncode.size())
    281       OperandList[Op.first].DoNotEncode.resize(Op.second+1);
    282     OperandList[Op.first].DoNotEncode[Op.second] = true;
    283   }
    284 
    285 }
    286 
    287 //===----------------------------------------------------------------------===//
    288 // CodeGenInstruction Implementation
    289 //===----------------------------------------------------------------------===//
    290 
    291 CodeGenInstruction::CodeGenInstruction(Record *R)
    292   : TheDef(R), Operands(R), InferredFrom(0) {
    293   Namespace = R->getValueAsString("Namespace");
    294   AsmString = R->getValueAsString("AsmString");
    295 
    296   isReturn     = R->getValueAsBit("isReturn");
    297   isBranch     = R->getValueAsBit("isBranch");
    298   isIndirectBranch = R->getValueAsBit("isIndirectBranch");
    299   isCompare    = R->getValueAsBit("isCompare");
    300   isMoveImm    = R->getValueAsBit("isMoveImm");
    301   isBitcast    = R->getValueAsBit("isBitcast");
    302   isSelect     = R->getValueAsBit("isSelect");
    303   isBarrier    = R->getValueAsBit("isBarrier");
    304   isCall       = R->getValueAsBit("isCall");
    305   canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
    306   isPredicable = Operands.isPredicable || R->getValueAsBit("isPredicable");
    307   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
    308   isCommutable = R->getValueAsBit("isCommutable");
    309   isTerminator = R->getValueAsBit("isTerminator");
    310   isReMaterializable = R->getValueAsBit("isReMaterializable");
    311   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
    312   usesCustomInserter = R->getValueAsBit("usesCustomInserter");
    313   hasPostISelHook = R->getValueAsBit("hasPostISelHook");
    314   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
    315   isNotDuplicable = R->getValueAsBit("isNotDuplicable");
    316 
    317   mayLoad      = R->getValueAsBitOrUnset("mayLoad", mayLoad_Unset);
    318   mayStore     = R->getValueAsBitOrUnset("mayStore", mayStore_Unset);
    319   hasSideEffects = R->getValueAsBitOrUnset("hasSideEffects",
    320                                            hasSideEffects_Unset);
    321   neverHasSideEffects = R->getValueAsBit("neverHasSideEffects");
    322 
    323   isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
    324   hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
    325   hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
    326   isCodeGenOnly = R->getValueAsBit("isCodeGenOnly");
    327   isPseudo = R->getValueAsBit("isPseudo");
    328   ImplicitDefs = R->getValueAsListOfDefs("Defs");
    329   ImplicitUses = R->getValueAsListOfDefs("Uses");
    330 
    331   if (neverHasSideEffects + hasSideEffects > 1)
    332     PrintFatalError(R->getName() + ": multiple conflicting side-effect flags set!");
    333 
    334   // Parse Constraints.
    335   ParseConstraints(R->getValueAsString("Constraints"), Operands);
    336 
    337   // Parse the DisableEncoding field.
    338   Operands.ProcessDisableEncoding(R->getValueAsString("DisableEncoding"));
    339 }
    340 
    341 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
    342 /// implicit def and it has a known VT, return the VT, otherwise return
    343 /// MVT::Other.
    344 MVT::SimpleValueType CodeGenInstruction::
    345 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
    346   if (ImplicitDefs.empty()) return MVT::Other;
    347 
    348   // Check to see if the first implicit def has a resolvable type.
    349   Record *FirstImplicitDef = ImplicitDefs[0];
    350   assert(FirstImplicitDef->isSubClassOf("Register"));
    351   const std::vector<MVT::SimpleValueType> &RegVTs =
    352     TargetInfo.getRegisterVTs(FirstImplicitDef);
    353   if (RegVTs.size() == 1)
    354     return RegVTs[0];
    355   return MVT::Other;
    356 }
    357 
    358 
    359 /// FlattenAsmStringVariants - Flatten the specified AsmString to only
    360 /// include text from the specified variant, returning the new string.
    361 std::string CodeGenInstruction::
    362 FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
    363   std::string Res = "";
    364 
    365   for (;;) {
    366     // Find the start of the next variant string.
    367     size_t VariantsStart = 0;
    368     for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
    369       if (Cur[VariantsStart] == '{' &&
    370           (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
    371                                   Cur[VariantsStart-1] != '\\')))
    372         break;
    373 
    374     // Add the prefix to the result.
    375     Res += Cur.slice(0, VariantsStart);
    376     if (VariantsStart == Cur.size())
    377       break;
    378 
    379     ++VariantsStart; // Skip the '{'.
    380 
    381     // Scan to the end of the variants string.
    382     size_t VariantsEnd = VariantsStart;
    383     unsigned NestedBraces = 1;
    384     for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
    385       if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
    386         if (--NestedBraces == 0)
    387           break;
    388       } else if (Cur[VariantsEnd] == '{')
    389         ++NestedBraces;
    390     }
    391 
    392     // Select the Nth variant (or empty).
    393     StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
    394     for (unsigned i = 0; i != Variant; ++i)
    395       Selection = Selection.split('|').second;
    396     Res += Selection.split('|').first;
    397 
    398     assert(VariantsEnd != Cur.size() &&
    399            "Unterminated variants in assembly string!");
    400     Cur = Cur.substr(VariantsEnd + 1);
    401   }
    402 
    403   return Res;
    404 }
    405 
    406 
    407 //===----------------------------------------------------------------------===//
    408 /// CodeGenInstAlias Implementation
    409 //===----------------------------------------------------------------------===//
    410 
    411 /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
    412 /// constructor.  It checks if an argument in an InstAlias pattern matches
    413 /// the corresponding operand of the instruction.  It returns true on a
    414 /// successful match, with ResOp set to the result operand to be used.
    415 bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
    416                                        Record *InstOpRec, bool hasSubOps,
    417                                        ArrayRef<SMLoc> Loc, CodeGenTarget &T,
    418                                        ResultOperand &ResOp) {
    419   Init *Arg = Result->getArg(AliasOpNo);
    420   DefInit *ADI = dyn_cast<DefInit>(Arg);
    421 
    422   if (ADI && ADI->getDef() == InstOpRec) {
    423     // If the operand is a record, it must have a name, and the record type
    424     // must match up with the instruction's argument type.
    425     if (Result->getArgName(AliasOpNo).empty())
    426       PrintFatalError(Loc, "result argument #" + utostr(AliasOpNo) +
    427                     " must have a name!");
    428     ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
    429     return true;
    430   }
    431 
    432   // For register operands, the source register class can be a subclass
    433   // of the instruction register class, not just an exact match.
    434   if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
    435     if (!InstOpRec->isSubClassOf("RegisterClass"))
    436       return false;
    437     if (!T.getRegisterClass(InstOpRec)
    438               .hasSubClass(&T.getRegisterClass(ADI->getDef())))
    439       return false;
    440     ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
    441     return true;
    442   }
    443 
    444   // Handle explicit registers.
    445   if (ADI && ADI->getDef()->isSubClassOf("Register")) {
    446     if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
    447       DagInit *DI = InstOpRec->getValueAsDag("MIOperandInfo");
    448       // The operand info should only have a single (register) entry. We
    449       // want the register class of it.
    450       InstOpRec = cast<DefInit>(DI->getArg(0))->getDef();
    451     }
    452 
    453     if (InstOpRec->isSubClassOf("RegisterOperand"))
    454       InstOpRec = InstOpRec->getValueAsDef("RegClass");
    455 
    456     if (!InstOpRec->isSubClassOf("RegisterClass"))
    457       return false;
    458 
    459     if (!T.getRegisterClass(InstOpRec)
    460         .contains(T.getRegBank().getReg(ADI->getDef())))
    461       PrintFatalError(Loc, "fixed register " + ADI->getDef()->getName() +
    462                       " is not a member of the " + InstOpRec->getName() +
    463                       " register class!");
    464 
    465     if (!Result->getArgName(AliasOpNo).empty())
    466       PrintFatalError(Loc, "result fixed register argument must "
    467                       "not have a name!");
    468 
    469     ResOp = ResultOperand(ADI->getDef());
    470     return true;
    471   }
    472 
    473   // Handle "zero_reg" for optional def operands.
    474   if (ADI && ADI->getDef()->getName() == "zero_reg") {
    475 
    476     // Check if this is an optional def.
    477     // Tied operands where the source is a sub-operand of a complex operand
    478     // need to represent both operands in the alias destination instruction.
    479     // Allow zero_reg for the tied portion. This can and should go away once
    480     // the MC representation of things doesn't use tied operands at all.
    481     //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
    482     //  throw TGError(Loc, "reg0 used for result that is not an "
    483     //                "OptionalDefOperand!");
    484 
    485     ResOp = ResultOperand(static_cast<Record*>(0));
    486     return true;
    487   }
    488 
    489   // Literal integers.
    490   if (IntInit *II = dyn_cast<IntInit>(Arg)) {
    491     if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
    492       return false;
    493     // Integer arguments can't have names.
    494     if (!Result->getArgName(AliasOpNo).empty())
    495       PrintFatalError(Loc, "result argument #" + utostr(AliasOpNo) +
    496                       " must not have a name!");
    497     ResOp = ResultOperand(II->getValue());
    498     return true;
    499   }
    500 
    501   // If both are Operands with the same MVT, allow the conversion. It's
    502   // up to the user to make sure the values are appropriate, just like
    503   // for isel Pat's.
    504   if (InstOpRec->isSubClassOf("Operand") &&
    505       ADI->getDef()->isSubClassOf("Operand")) {
    506     // FIXME: What other attributes should we check here? Identical
    507     // MIOperandInfo perhaps?
    508     if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type"))
    509       return false;
    510     ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
    511     return true;
    512   }
    513 
    514   return false;
    515 }
    516 
    517 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T) : TheDef(R) {
    518   AsmString = R->getValueAsString("AsmString");
    519   Result = R->getValueAsDag("ResultInst");
    520 
    521   // Verify that the root of the result is an instruction.
    522   DefInit *DI = dyn_cast<DefInit>(Result->getOperator());
    523   if (DI == 0 || !DI->getDef()->isSubClassOf("Instruction"))
    524     PrintFatalError(R->getLoc(),
    525                     "result of inst alias should be an instruction");
    526 
    527   ResultInst = &T.getInstruction(DI->getDef());
    528 
    529   // NameClass - If argument names are repeated, we need to verify they have
    530   // the same class.
    531   StringMap<Record*> NameClass;
    532   for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
    533     DefInit *ADI = dyn_cast<DefInit>(Result->getArg(i));
    534     if (!ADI || Result->getArgName(i).empty())
    535       continue;
    536     // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
    537     // $foo can exist multiple times in the result list, but it must have the
    538     // same type.
    539     Record *&Entry = NameClass[Result->getArgName(i)];
    540     if (Entry && Entry != ADI->getDef())
    541       PrintFatalError(R->getLoc(), "result value $" + Result->getArgName(i) +
    542                       " is both " + Entry->getName() + " and " +
    543                       ADI->getDef()->getName() + "!");
    544     Entry = ADI->getDef();
    545   }
    546 
    547   // Decode and validate the arguments of the result.
    548   unsigned AliasOpNo = 0;
    549   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
    550 
    551     // Tied registers don't have an entry in the result dag unless they're part
    552     // of a complex operand, in which case we include them anyways, as we
    553     // don't have any other way to specify the whole operand.
    554     if (ResultInst->Operands[i].MINumOperands == 1 &&
    555         ResultInst->Operands[i].getTiedRegister() != -1)
    556       continue;
    557 
    558     if (AliasOpNo >= Result->getNumArgs())
    559       PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
    560 
    561     Record *InstOpRec = ResultInst->Operands[i].Rec;
    562     unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
    563     ResultOperand ResOp(static_cast<int64_t>(0));
    564     if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
    565                         R->getLoc(), T, ResOp)) {
    566       // If this is a simple operand, or a complex operand with a custom match
    567       // class, then we can match is verbatim.
    568       if (NumSubOps == 1 ||
    569           (InstOpRec->getValue("ParserMatchClass") &&
    570            InstOpRec->getValueAsDef("ParserMatchClass")
    571              ->getValueAsString("Name") != "Imm")) {
    572         ResultOperands.push_back(ResOp);
    573         ResultInstOperandIndex.push_back(std::make_pair(i, -1));
    574         ++AliasOpNo;
    575 
    576       // Otherwise, we need to match each of the suboperands individually.
    577       } else {
    578          DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
    579          for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
    580           Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
    581 
    582           // Take care to instantiate each of the suboperands with the correct
    583           // nomenclature: $foo.bar
    584           ResultOperands.push_back(
    585               ResultOperand(Result->getArgName(AliasOpNo) + "." +
    586                             MIOI->getArgName(SubOp), SubRec));
    587           ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
    588          }
    589          ++AliasOpNo;
    590       }
    591       continue;
    592     }
    593 
    594     // If the argument did not match the instruction operand, and the operand
    595     // is composed of multiple suboperands, try matching the suboperands.
    596     if (NumSubOps > 1) {
    597       DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
    598       for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
    599         if (AliasOpNo >= Result->getNumArgs())
    600           PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
    601         Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
    602         if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
    603                             R->getLoc(), T, ResOp)) {
    604           ResultOperands.push_back(ResOp);
    605           ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
    606           ++AliasOpNo;
    607         } else {
    608           PrintFatalError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
    609                         " does not match instruction operand class " +
    610                         (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
    611         }
    612       }
    613       continue;
    614     }
    615     PrintFatalError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
    616                     " does not match instruction operand class " +
    617                     InstOpRec->getName());
    618   }
    619 
    620   if (AliasOpNo != Result->getNumArgs())
    621     PrintFatalError(R->getLoc(), "too many operands for instruction!");
    622 }
    623