1 //===- CodeGenInstruction.cpp - CodeGen Instruction Class Wrapper ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenInstruction class.
12 //===----------------------------------------------------------------------===//
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"
24 //===----------------------------------------------------------------------===//
25 // CGIOperandList Implementation
26 //===----------------------------------------------------------------------===//
28 CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
30 hasOptionalDef = false;
33 DagInit *OutDI = R->getValueAsDag("OutOperandList");
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'");
39 PrintFatalError(R->getName() + ": invalid output list: use 'outs'");
41 NumDefs = OutDI->getNumArgs();
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'");
48 PrintFatalError(R->getName() + ": invalid input list: use 'ins'");
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){
58 ArgInit = OutDI->getArg(i);
59 ArgName = OutDI->getArgNameStr(i);
61 ArgInit = InDI->getArg(i-NumDefs);
62 ArgName = InDI->getArgNameStr(i-NumDefs);
65 DefInit *Arg = dyn_cast<DefInit>(ArgInit);
67 PrintFatalError("Illegal operand for the '" + R->getName() + "' instruction!");
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";
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");
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() +
95 // If we have MIOpInfo, then we have #operands equal to number of entries
97 if (unsigned NumArgs = MIOpInfo->getNumArgs())
100 if (Rec->isSubClassOf("PredicateOp"))
102 else if (Rec->isSubClassOf("OptionalDefOperand"))
103 hasOptionalDef = true;
104 } else if (Rec->getName() == "variable_ops") {
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!");
114 // Check that the operand has a name and that it's unique.
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!");
122 OperandList.emplace_back(Rec, ArgName, PrintMethod, EncoderMethod,
123 OperandNamespace + "::" + OperandType, MIOperandNo,
125 MIOperandNo += NumOps;
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);
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.
140 unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
142 if (hasOperandNamed(Name, OpIdx)) return OpIdx;
143 PrintFatalError("'" + TheDef->getName() +
144 "' does not have an operand named '$" + Name + "'!");
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) {
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 + "'");
165 std::string OpName = Op.substr(1);
166 std::string SubOpName;
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);
177 unsigned OpIdx = getOperandNamed(OpName);
179 if (SubOpName.empty()) { // If no suboperand name was specified:
180 // If one was needed, throw.
181 if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
183 PrintFatalError(TheDef->getName() + ": Illegal to refer to"
184 " whole operand part of complex operand '" + Op + "'");
186 // Otherwise, return the operand.
187 return std::make_pair(OpIdx, 0U);
190 // Find the suboperand number involved.
191 DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
193 PrintFatalError(TheDef->getName() + ": unknown suboperand name in '" + Op + "'");
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);
200 // Otherwise, didn't find it!
201 PrintFatalError(TheDef->getName() + ": unknown suboperand name in '" + Op + "'");
202 return std::make_pair(0U, 0U);
205 static void ParseConstraint(const std::string &CStr, CGIOperandList &Ops,
207 // EARLY_CLOBBER: @early $reg
208 std::string::size_type wpos = CStr.find_first_of(" \t");
209 std::string::size_type start = CStr.find_first_not_of(" \t");
210 std::string Tok = CStr.substr(start, wpos - start);
211 if (Tok == "@earlyclobber") {
212 std::string Name = CStr.substr(wpos+1);
213 wpos = Name.find_first_not_of(" \t");
214 if (wpos == std::string::npos)
216 Rec->getLoc(), "Illegal format for @earlyclobber constraint in '" +
217 Rec->getName() + "': '" + CStr + "'");
218 Name = Name.substr(wpos);
219 std::pair<unsigned,unsigned> Op = Ops.ParseOperandName(Name, false);
221 // Build the string for the operand
222 if (!Ops[Op.first].Constraints[Op.second].isNone())
224 Rec->getLoc(), "Operand '" + Name + "' of '" + Rec->getName() +
225 "' cannot have multiple constraints!");
226 Ops[Op.first].Constraints[Op.second] =
227 CGIOperandList::ConstraintInfo::getEarlyClobber();
231 // Only other constraint is "TIED_TO" for now.
232 std::string::size_type pos = CStr.find_first_of('=');
233 if (pos == std::string::npos)
235 Rec->getLoc(), "Unrecognized constraint '" + CStr +
236 "' in '" + Rec->getName() + "'");
237 start = CStr.find_first_not_of(" \t");
239 // TIED_TO: $src1 = $dst
240 wpos = CStr.find_first_of(" \t", start);
241 if (wpos == std::string::npos || wpos > pos)
243 Rec->getLoc(), "Illegal format for tied-to constraint in '" +
244 Rec->getName() + "': '" + CStr + "'");
245 std::string LHSOpName = StringRef(CStr).substr(start, wpos - start);
246 std::pair<unsigned,unsigned> LHSOp = Ops.ParseOperandName(LHSOpName, false);
248 wpos = CStr.find_first_not_of(" \t", pos + 1);
249 if (wpos == std::string::npos)
251 Rec->getLoc(), "Illegal format for tied-to constraint: '" + CStr + "'");
253 std::string RHSOpName = StringRef(CStr).substr(wpos);
254 std::pair<unsigned,unsigned> RHSOp = Ops.ParseOperandName(RHSOpName, false);
256 // Sort the operands into order, which should put the output one
257 // first. But keep the original order, for use in diagnostics.
258 bool FirstIsDest = (LHSOp < RHSOp);
259 std::pair<unsigned,unsigned> DestOp = (FirstIsDest ? LHSOp : RHSOp);
260 StringRef DestOpName = (FirstIsDest ? LHSOpName : RHSOpName);
261 std::pair<unsigned,unsigned> SrcOp = (FirstIsDest ? RHSOp : LHSOp);
262 StringRef SrcOpName = (FirstIsDest ? RHSOpName : LHSOpName);
264 // Ensure one operand is a def and the other is a use.
265 if (DestOp.first >= Ops.NumDefs)
267 Rec->getLoc(), "Input operands '" + LHSOpName + "' and '" + RHSOpName +
268 "' of '" + Rec->getName() + "' cannot be tied!");
269 if (SrcOp.first < Ops.NumDefs)
271 Rec->getLoc(), "Output operands '" + LHSOpName + "' and '" + RHSOpName +
272 "' of '" + Rec->getName() + "' cannot be tied!");
274 // The constraint has to go on the operand with higher index, i.e.
275 // the source one. Check there isn't another constraint there
277 if (!Ops[SrcOp.first].Constraints[SrcOp.second].isNone())
279 Rec->getLoc(), "Operand '" + SrcOpName + "' of '" + Rec->getName() +
280 "' cannot have multiple constraints!");
282 unsigned DestFlatOpNo = Ops.getFlattenedOperandNumber(DestOp);
283 auto NewConstraint = CGIOperandList::ConstraintInfo::getTied(DestFlatOpNo);
285 // Check that the earlier operand is not the target of another tie
286 // before making it the target of this one.
287 for (const CGIOperandList::OperandInfo &Op : Ops) {
288 for (unsigned i = 0; i < Op.MINumOperands; i++)
289 if (Op.Constraints[i] == NewConstraint)
291 Rec->getLoc(), "Operand '" + DestOpName + "' of '" + Rec->getName() +
292 "' cannot have multiple operands tied to it!");
295 Ops[SrcOp.first].Constraints[SrcOp.second] = NewConstraint;
298 static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops,
300 if (CStr.empty()) return;
302 const std::string delims(",");
303 std::string::size_type bidx, eidx;
305 bidx = CStr.find_first_not_of(delims);
306 while (bidx != std::string::npos) {
307 eidx = CStr.find_first_of(delims, bidx);
308 if (eidx == std::string::npos)
309 eidx = CStr.length();
311 ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops, Rec);
312 bidx = CStr.find_first_not_of(delims, eidx);
316 void CGIOperandList::ProcessDisableEncoding(std::string DisableEncoding) {
318 std::pair<StringRef, StringRef> P = getToken(DisableEncoding, " ,\t");
319 std::string OpName = P.first;
320 DisableEncoding = P.second;
321 if (OpName.empty()) break;
323 // Figure out which operand this is.
324 std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
326 // Mark the operand as not-to-be encoded.
327 if (Op.second >= OperandList[Op.first].DoNotEncode.size())
328 OperandList[Op.first].DoNotEncode.resize(Op.second+1);
329 OperandList[Op.first].DoNotEncode[Op.second] = true;
334 //===----------------------------------------------------------------------===//
335 // CodeGenInstruction Implementation
336 //===----------------------------------------------------------------------===//
338 CodeGenInstruction::CodeGenInstruction(Record *R)
339 : TheDef(R), Operands(R), InferredFrom(nullptr) {
340 Namespace = R->getValueAsString("Namespace");
341 AsmString = R->getValueAsString("AsmString");
343 isReturn = R->getValueAsBit("isReturn");
344 isEHScopeReturn = R->getValueAsBit("isEHScopeReturn");
345 isBranch = R->getValueAsBit("isBranch");
346 isIndirectBranch = R->getValueAsBit("isIndirectBranch");
347 isCompare = R->getValueAsBit("isCompare");
348 isMoveImm = R->getValueAsBit("isMoveImm");
349 isMoveReg = R->getValueAsBit("isMoveReg");
350 isBitcast = R->getValueAsBit("isBitcast");
351 isSelect = R->getValueAsBit("isSelect");
352 isBarrier = R->getValueAsBit("isBarrier");
353 isCall = R->getValueAsBit("isCall");
354 isAdd = R->getValueAsBit("isAdd");
355 isTrap = R->getValueAsBit("isTrap");
356 canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
357 isPredicable = Operands.isPredicable || R->getValueAsBit("isPredicable");
358 isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
359 isCommutable = R->getValueAsBit("isCommutable");
360 isTerminator = R->getValueAsBit("isTerminator");
361 isReMaterializable = R->getValueAsBit("isReMaterializable");
362 hasDelaySlot = R->getValueAsBit("hasDelaySlot");
363 usesCustomInserter = R->getValueAsBit("usesCustomInserter");
364 hasPostISelHook = R->getValueAsBit("hasPostISelHook");
365 hasCtrlDep = R->getValueAsBit("hasCtrlDep");
366 isNotDuplicable = R->getValueAsBit("isNotDuplicable");
367 isRegSequence = R->getValueAsBit("isRegSequence");
368 isExtractSubreg = R->getValueAsBit("isExtractSubreg");
369 isInsertSubreg = R->getValueAsBit("isInsertSubreg");
370 isConvergent = R->getValueAsBit("isConvergent");
371 hasNoSchedulingInfo = R->getValueAsBit("hasNoSchedulingInfo");
372 FastISelShouldIgnore = R->getValueAsBit("FastISelShouldIgnore");
373 variadicOpsAreDefs = R->getValueAsBit("variadicOpsAreDefs");
376 mayLoad = R->getValueAsBitOrUnset("mayLoad", Unset);
377 mayLoad_Unset = Unset;
378 mayStore = R->getValueAsBitOrUnset("mayStore", Unset);
379 mayStore_Unset = Unset;
380 hasSideEffects = R->getValueAsBitOrUnset("hasSideEffects", Unset);
381 hasSideEffects_Unset = Unset;
383 isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
384 hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
385 hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
386 isCodeGenOnly = R->getValueAsBit("isCodeGenOnly");
387 isPseudo = R->getValueAsBit("isPseudo");
388 ImplicitDefs = R->getValueAsListOfDefs("Defs");
389 ImplicitUses = R->getValueAsListOfDefs("Uses");
391 // This flag is only inferred from the pattern.
393 hasChain_Inferred = false;
395 // Parse Constraints.
396 ParseConstraints(R->getValueAsString("Constraints"), Operands, R);
398 // Parse the DisableEncoding field.
399 Operands.ProcessDisableEncoding(R->getValueAsString("DisableEncoding"));
401 // First check for a ComplexDeprecationPredicate.
402 if (R->getValue("ComplexDeprecationPredicate")) {
403 HasComplexDeprecationPredicate = true;
404 DeprecatedReason = R->getValueAsString("ComplexDeprecationPredicate");
405 } else if (RecordVal *Dep = R->getValue("DeprecatedFeatureMask")) {
406 // Check if we have a Subtarget feature mask.
407 HasComplexDeprecationPredicate = false;
408 DeprecatedReason = Dep->getValue()->getAsString();
410 // This instruction isn't deprecated.
411 HasComplexDeprecationPredicate = false;
412 DeprecatedReason = "";
416 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
417 /// implicit def and it has a known VT, return the VT, otherwise return
419 MVT::SimpleValueType CodeGenInstruction::
420 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
421 if (ImplicitDefs.empty()) return MVT::Other;
423 // Check to see if the first implicit def has a resolvable type.
424 Record *FirstImplicitDef = ImplicitDefs[0];
425 assert(FirstImplicitDef->isSubClassOf("Register"));
426 const std::vector<ValueTypeByHwMode> &RegVTs =
427 TargetInfo.getRegisterVTs(FirstImplicitDef);
428 if (RegVTs.size() == 1 && RegVTs[0].isSimple())
429 return RegVTs[0].getSimple().SimpleTy;
434 /// FlattenAsmStringVariants - Flatten the specified AsmString to only
435 /// include text from the specified variant, returning the new string.
436 std::string CodeGenInstruction::
437 FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
438 std::string Res = "";
441 // Find the start of the next variant string.
442 size_t VariantsStart = 0;
443 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
444 if (Cur[VariantsStart] == '{' &&
445 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
446 Cur[VariantsStart-1] != '\\')))
449 // Add the prefix to the result.
450 Res += Cur.slice(0, VariantsStart);
451 if (VariantsStart == Cur.size())
454 ++VariantsStart; // Skip the '{'.
456 // Scan to the end of the variants string.
457 size_t VariantsEnd = VariantsStart;
458 unsigned NestedBraces = 1;
459 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
460 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
461 if (--NestedBraces == 0)
463 } else if (Cur[VariantsEnd] == '{')
467 // Select the Nth variant (or empty).
468 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
469 for (unsigned i = 0; i != Variant; ++i)
470 Selection = Selection.split('|').second;
471 Res += Selection.split('|').first;
473 assert(VariantsEnd != Cur.size() &&
474 "Unterminated variants in assembly string!");
475 Cur = Cur.substr(VariantsEnd + 1);
481 bool CodeGenInstruction::isOperandAPointer(unsigned i) const {
482 if (DagInit *ConstraintList = TheDef->getValueAsDag("InOperandList")) {
483 if (i < ConstraintList->getNumArgs()) {
484 if (DefInit *Constraint = dyn_cast<DefInit>(ConstraintList->getArg(i))) {
485 return Constraint->getDef()->isSubClassOf("TypedOperand") &&
486 Constraint->getDef()->getValueAsBit("IsPointer");
493 //===----------------------------------------------------------------------===//
494 /// CodeGenInstAlias Implementation
495 //===----------------------------------------------------------------------===//
497 /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
498 /// constructor. It checks if an argument in an InstAlias pattern matches
499 /// the corresponding operand of the instruction. It returns true on a
500 /// successful match, with ResOp set to the result operand to be used.
501 bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
502 Record *InstOpRec, bool hasSubOps,
503 ArrayRef<SMLoc> Loc, CodeGenTarget &T,
504 ResultOperand &ResOp) {
505 Init *Arg = Result->getArg(AliasOpNo);
506 DefInit *ADI = dyn_cast<DefInit>(Arg);
507 Record *ResultRecord = ADI ? ADI->getDef() : nullptr;
509 if (ADI && ADI->getDef() == InstOpRec) {
510 // If the operand is a record, it must have a name, and the record type
511 // must match up with the instruction's argument type.
512 if (!Result->getArgName(AliasOpNo))
513 PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
514 " must have a name!");
515 ResOp = ResultOperand(Result->getArgNameStr(AliasOpNo), ResultRecord);
519 // For register operands, the source register class can be a subclass
520 // of the instruction register class, not just an exact match.
521 if (InstOpRec->isSubClassOf("RegisterOperand"))
522 InstOpRec = InstOpRec->getValueAsDef("RegClass");
524 if (ADI && ADI->getDef()->isSubClassOf("RegisterOperand"))
525 ADI = ADI->getDef()->getValueAsDef("RegClass")->getDefInit();
527 if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
528 if (!InstOpRec->isSubClassOf("RegisterClass"))
530 if (!T.getRegisterClass(InstOpRec)
531 .hasSubClass(&T.getRegisterClass(ADI->getDef())))
533 ResOp = ResultOperand(Result->getArgNameStr(AliasOpNo), ResultRecord);
537 // Handle explicit registers.
538 if (ADI && ADI->getDef()->isSubClassOf("Register")) {
539 if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
540 DagInit *DI = InstOpRec->getValueAsDag("MIOperandInfo");
541 // The operand info should only have a single (register) entry. We
542 // want the register class of it.
543 InstOpRec = cast<DefInit>(DI->getArg(0))->getDef();
546 if (!InstOpRec->isSubClassOf("RegisterClass"))
549 if (!T.getRegisterClass(InstOpRec)
550 .contains(T.getRegBank().getReg(ADI->getDef())))
551 PrintFatalError(Loc, "fixed register " + ADI->getDef()->getName() +
552 " is not a member of the " + InstOpRec->getName() +
555 if (Result->getArgName(AliasOpNo))
556 PrintFatalError(Loc, "result fixed register argument must "
559 ResOp = ResultOperand(ResultRecord);
563 // Handle "zero_reg" for optional def operands.
564 if (ADI && ADI->getDef()->getName() == "zero_reg") {
566 // Check if this is an optional def.
567 // Tied operands where the source is a sub-operand of a complex operand
568 // need to represent both operands in the alias destination instruction.
569 // Allow zero_reg for the tied portion. This can and should go away once
570 // the MC representation of things doesn't use tied operands at all.
571 //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
572 // throw TGError(Loc, "reg0 used for result that is not an "
573 // "OptionalDefOperand!");
575 ResOp = ResultOperand(static_cast<Record*>(nullptr));
580 if (IntInit *II = dyn_cast<IntInit>(Arg)) {
581 if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
583 // Integer arguments can't have names.
584 if (Result->getArgName(AliasOpNo))
585 PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
586 " must not have a name!");
587 ResOp = ResultOperand(II->getValue());
591 // Bits<n> (also used for 0bxx literals)
592 if (BitsInit *BI = dyn_cast<BitsInit>(Arg)) {
593 if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
595 if (!BI->isComplete())
597 // Convert the bits init to an integer and use that for the result.
599 dyn_cast_or_null<IntInit>(BI->convertInitializerTo(IntRecTy::get()));
602 ResOp = ResultOperand(II->getValue());
606 // If both are Operands with the same MVT, allow the conversion. It's
607 // up to the user to make sure the values are appropriate, just like
609 if (InstOpRec->isSubClassOf("Operand") && ADI &&
610 ADI->getDef()->isSubClassOf("Operand")) {
611 // FIXME: What other attributes should we check here? Identical
612 // MIOperandInfo perhaps?
613 if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type"))
615 ResOp = ResultOperand(Result->getArgNameStr(AliasOpNo), ADI->getDef());
622 unsigned CodeGenInstAlias::ResultOperand::getMINumOperands() const {
626 Record *Rec = getRecord();
627 if (!Rec->isSubClassOf("Operand"))
630 DagInit *MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
631 if (MIOpInfo->getNumArgs() == 0) {
632 // Unspecified, so it defaults to 1
636 return MIOpInfo->getNumArgs();
639 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T)
641 Result = R->getValueAsDag("ResultInst");
642 AsmString = R->getValueAsString("AsmString");
645 // Verify that the root of the result is an instruction.
646 DefInit *DI = dyn_cast<DefInit>(Result->getOperator());
647 if (!DI || !DI->getDef()->isSubClassOf("Instruction"))
648 PrintFatalError(R->getLoc(),
649 "result of inst alias should be an instruction");
651 ResultInst = &T.getInstruction(DI->getDef());
653 // NameClass - If argument names are repeated, we need to verify they have
655 StringMap<Record*> NameClass;
656 for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
657 DefInit *ADI = dyn_cast<DefInit>(Result->getArg(i));
658 if (!ADI || !Result->getArgName(i))
660 // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
661 // $foo can exist multiple times in the result list, but it must have the
663 Record *&Entry = NameClass[Result->getArgNameStr(i)];
664 if (Entry && Entry != ADI->getDef())
665 PrintFatalError(R->getLoc(), "result value $" + Result->getArgNameStr(i) +
666 " is both " + Entry->getName() + " and " +
667 ADI->getDef()->getName() + "!");
668 Entry = ADI->getDef();
671 // Decode and validate the arguments of the result.
672 unsigned AliasOpNo = 0;
673 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
675 // Tied registers don't have an entry in the result dag unless they're part
676 // of a complex operand, in which case we include them anyways, as we
677 // don't have any other way to specify the whole operand.
678 if (ResultInst->Operands[i].MINumOperands == 1 &&
679 ResultInst->Operands[i].getTiedRegister() != -1) {
680 // Tied operands of different RegisterClass should be explicit within an
681 // instruction's syntax and so cannot be skipped.
682 int TiedOpNum = ResultInst->Operands[i].getTiedRegister();
683 if (ResultInst->Operands[i].Rec->getName() ==
684 ResultInst->Operands[TiedOpNum].Rec->getName())
688 if (AliasOpNo >= Result->getNumArgs())
689 PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
691 Record *InstOpRec = ResultInst->Operands[i].Rec;
692 unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
693 ResultOperand ResOp(static_cast<int64_t>(0));
694 if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
695 R->getLoc(), T, ResOp)) {
696 // If this is a simple operand, or a complex operand with a custom match
697 // class, then we can match is verbatim.
698 if (NumSubOps == 1 ||
699 (InstOpRec->getValue("ParserMatchClass") &&
700 InstOpRec->getValueAsDef("ParserMatchClass")
701 ->getValueAsString("Name") != "Imm")) {
702 ResultOperands.push_back(ResOp);
703 ResultInstOperandIndex.push_back(std::make_pair(i, -1));
706 // Otherwise, we need to match each of the suboperands individually.
708 DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
709 for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
710 Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
712 // Take care to instantiate each of the suboperands with the correct
713 // nomenclature: $foo.bar
714 ResultOperands.emplace_back(
715 Result->getArgName(AliasOpNo)->getAsUnquotedString() + "." +
716 MIOI->getArgName(SubOp)->getAsUnquotedString(), SubRec);
717 ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
724 // If the argument did not match the instruction operand, and the operand
725 // is composed of multiple suboperands, try matching the suboperands.
727 DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
728 for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
729 if (AliasOpNo >= Result->getNumArgs())
730 PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
731 Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
732 if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
733 R->getLoc(), T, ResOp)) {
734 ResultOperands.push_back(ResOp);
735 ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
738 PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
739 " does not match instruction operand class " +
740 (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
745 PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
746 " does not match instruction operand class " +
747 InstOpRec->getName());
750 if (AliasOpNo != Result->getNumArgs())
751 PrintFatalError(R->getLoc(), "too many operands for instruction!");