1 //===- CodeGenInstruction.cpp - CodeGen Instruction Class Wrapper ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the CodeGenInstruction class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeGenInstruction.h"
14 #include "CodeGenTarget.h"
15 #include "llvm/ADT/StringExtras.h"
16 #include "llvm/ADT/StringMap.h"
17 #include "llvm/TableGen/Error.h"
18 #include "llvm/TableGen/Record.h"
19 #include <set>
20 using namespace llvm;
21 
22 //===----------------------------------------------------------------------===//
23 // CGIOperandList Implementation
24 //===----------------------------------------------------------------------===//
25 
CGIOperandList(Record * R)26 CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
27   isPredicable = false;
28   hasOptionalDef = false;
29   isVariadic = false;
30 
31   DagInit *OutDI = R->getValueAsDag("OutOperandList");
32 
33   if (DefInit *Init = dyn_cast<DefInit>(OutDI->getOperator())) {
34     if (Init->getDef()->getName() != "outs")
35       PrintFatalError(R->getLoc(),
36                       R->getName() +
37                           ": invalid def name for output list: use 'outs'");
38   } else
39     PrintFatalError(R->getLoc(),
40                     R->getName() + ": invalid output list: use 'outs'");
41 
42   NumDefs = OutDI->getNumArgs();
43 
44   DagInit *InDI = R->getValueAsDag("InOperandList");
45   if (DefInit *Init = dyn_cast<DefInit>(InDI->getOperator())) {
46     if (Init->getDef()->getName() != "ins")
47       PrintFatalError(R->getLoc(),
48                       R->getName() +
49                           ": invalid def name for input list: use 'ins'");
50   } else
51     PrintFatalError(R->getLoc(),
52                     R->getName() + ": invalid input list: use 'ins'");
53 
54   unsigned MIOperandNo = 0;
55   std::set<std::string> OperandNames;
56   unsigned e = InDI->getNumArgs() + OutDI->getNumArgs();
57   OperandList.reserve(e);
58   bool VariadicOuts = false;
59   for (unsigned i = 0; i != e; ++i){
60     Init *ArgInit;
61     StringRef ArgName;
62     if (i < NumDefs) {
63       ArgInit = OutDI->getArg(i);
64       ArgName = OutDI->getArgNameStr(i);
65     } else {
66       ArgInit = InDI->getArg(i-NumDefs);
67       ArgName = InDI->getArgNameStr(i-NumDefs);
68     }
69 
70     DagInit *SubArgDag = dyn_cast<DagInit>(ArgInit);
71     if (SubArgDag)
72       ArgInit = SubArgDag->getOperator();
73 
74     DefInit *Arg = dyn_cast<DefInit>(ArgInit);
75     if (!Arg)
76       PrintFatalError(R->getLoc(), "Illegal operand for the '" + R->getName() +
77                                        "' instruction!");
78 
79     Record *Rec = Arg->getDef();
80     std::string PrintMethod = "printOperand";
81     std::string EncoderMethod;
82     std::string OperandType = "OPERAND_UNKNOWN";
83     std::string OperandNamespace = "MCOI";
84     unsigned NumOps = 1;
85     DagInit *MIOpInfo = nullptr;
86     if (Rec->isSubClassOf("RegisterOperand")) {
87       PrintMethod = std::string(Rec->getValueAsString("PrintMethod"));
88       OperandType = std::string(Rec->getValueAsString("OperandType"));
89       OperandNamespace = std::string(Rec->getValueAsString("OperandNamespace"));
90       EncoderMethod = std::string(Rec->getValueAsString("EncoderMethod"));
91     } else if (Rec->isSubClassOf("Operand")) {
92       PrintMethod = std::string(Rec->getValueAsString("PrintMethod"));
93       OperandType = std::string(Rec->getValueAsString("OperandType"));
94       OperandNamespace = std::string(Rec->getValueAsString("OperandNamespace"));
95       // If there is an explicit encoder method, use it.
96       EncoderMethod = std::string(Rec->getValueAsString("EncoderMethod"));
97       MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
98 
99       // Verify that MIOpInfo has an 'ops' root value.
100       if (!isa<DefInit>(MIOpInfo->getOperator()) ||
101           cast<DefInit>(MIOpInfo->getOperator())->getDef()->getName() != "ops")
102         PrintFatalError(R->getLoc(),
103                         "Bad value for MIOperandInfo in operand '" +
104                             Rec->getName() + "'\n");
105 
106       // If we have MIOpInfo, then we have #operands equal to number of entries
107       // in MIOperandInfo.
108       if (unsigned NumArgs = MIOpInfo->getNumArgs())
109         NumOps = NumArgs;
110 
111       if (Rec->isSubClassOf("PredicateOp"))
112         isPredicable = true;
113       else if (Rec->isSubClassOf("OptionalDefOperand"))
114         hasOptionalDef = true;
115     } else if (Rec->getName() == "variable_ops") {
116       if (i < NumDefs)
117         VariadicOuts = true;
118       isVariadic = true;
119       continue;
120     } else if (Rec->isSubClassOf("RegisterClass")) {
121       OperandType = "OPERAND_REGISTER";
122     } else if (!Rec->isSubClassOf("PointerLikeRegClass") &&
123                !Rec->isSubClassOf("unknown_class")) {
124       PrintFatalError(R->getLoc(), "Unknown operand class '" + Rec->getName() +
125                                        "' in '" + R->getName() +
126                                        "' instruction!");
127     }
128 
129     // Check that the operand has a name and that it's unique.
130     if (ArgName.empty())
131       PrintFatalError(R->getLoc(), "In instruction '" + R->getName() +
132                                        "', operand #" + Twine(i) +
133                                        " has no name!");
134     if (!OperandNames.insert(std::string(ArgName)).second)
135       PrintFatalError(R->getLoc(),
136                       "In instruction '" + R->getName() + "', operand #" +
137                           Twine(i) +
138                           " has the same name as a previous operand!");
139 
140     OperandInfo &OpInfo = OperandList.emplace_back(
141         Rec, std::string(ArgName), std::string(PrintMethod),
142         OperandNamespace + "::" + OperandType, MIOperandNo, NumOps, MIOpInfo);
143 
144     if (SubArgDag) {
145       if (SubArgDag->getNumArgs() != NumOps) {
146         PrintFatalError(R->getLoc(), "In instruction '" + R->getName() +
147                                          "', operand #" + Twine(i) + " has " +
148                                          Twine(SubArgDag->getNumArgs()) +
149                                          " sub-arg names, expected " +
150                                          Twine(NumOps) + ".");
151       }
152 
153       for (unsigned j = 0; j < NumOps; ++j) {
154         if (!isa<UnsetInit>(SubArgDag->getArg(j)))
155           PrintFatalError(R->getLoc(),
156                           "In instruction '" + R->getName() + "', operand #" +
157                               Twine(i) + " sub-arg #" + Twine(j) +
158                               " has unexpected operand (expected only $name).");
159 
160         StringRef SubArgName = SubArgDag->getArgNameStr(j);
161         if (SubArgName.empty())
162           PrintFatalError(R->getLoc(), "In instruction '" + R->getName() +
163                                            "', operand #" + Twine(i) +
164                                            " has no name!");
165         if (!OperandNames.insert(std::string(SubArgName)).second)
166           PrintFatalError(R->getLoc(),
167                           "In instruction '" + R->getName() + "', operand #" +
168                               Twine(i) + " sub-arg #" + Twine(j) +
169                               " has the same name as a previous operand!");
170 
171         if (auto MaybeEncoderMethod =
172                 cast<DefInit>(MIOpInfo->getArg(j))
173                     ->getDef()
174                     ->getValueAsOptionalString("EncoderMethod")) {
175           OpInfo.EncoderMethodNames[j] = *MaybeEncoderMethod;
176         }
177 
178         OpInfo.SubOpNames[j] = SubArgName;
179         SubOpAliases[SubArgName] = std::make_pair(MIOperandNo, j);
180       }
181     } else if (!EncoderMethod.empty()) {
182       // If we have no explicit sub-op dag, but have an top-level encoder
183       // method, the single encoder will multiple sub-ops, itself.
184       OpInfo.EncoderMethodNames[0] = EncoderMethod;
185       for (unsigned j = 1; j < NumOps; ++j)
186         OpInfo.DoNotEncode[j] = true;
187     }
188 
189     MIOperandNo += NumOps;
190   }
191 
192   if (VariadicOuts)
193     --NumDefs;
194 }
195 
196 
197 /// getOperandNamed - Return the index of the operand with the specified
198 /// non-empty name.  If the instruction does not have an operand with the
199 /// specified name, abort.
200 ///
getOperandNamed(StringRef Name) const201 unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
202   unsigned OpIdx;
203   if (hasOperandNamed(Name, OpIdx))
204     return OpIdx;
205   PrintFatalError(TheDef->getLoc(), "'" + TheDef->getName() +
206                                         "' does not have an operand named '$" +
207                                         Name + "'!");
208 }
209 
210 /// hasOperandNamed - Query whether the instruction has an operand of the
211 /// given name. If so, return true and set OpIdx to the index of the
212 /// operand. Otherwise, return false.
hasOperandNamed(StringRef Name,unsigned & OpIdx) const213 bool CGIOperandList::hasOperandNamed(StringRef Name, unsigned &OpIdx) const {
214   assert(!Name.empty() && "Cannot search for operand with no name!");
215   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
216     if (OperandList[i].Name == Name) {
217       OpIdx = i;
218       return true;
219     }
220   return false;
221 }
222 
hasSubOperandAlias(StringRef Name,std::pair<unsigned,unsigned> & SubOp) const223 bool CGIOperandList::hasSubOperandAlias(
224     StringRef Name, std::pair<unsigned, unsigned> &SubOp) const {
225   assert(!Name.empty() && "Cannot search for operand with no name!");
226   auto SubOpIter = SubOpAliases.find(Name);
227   if (SubOpIter != SubOpAliases.end()) {
228     SubOp = SubOpIter->second;
229     return true;
230   }
231   return false;
232 }
233 
234 std::pair<unsigned,unsigned>
ParseOperandName(StringRef Op,bool AllowWholeOp)235 CGIOperandList::ParseOperandName(StringRef Op, bool AllowWholeOp) {
236   if (Op.empty() || Op[0] != '$')
237     PrintFatalError(TheDef->getLoc(),
238                     TheDef->getName() + ": Illegal operand name: '" + Op + "'");
239 
240   StringRef OpName = Op.substr(1);
241   StringRef SubOpName;
242 
243   // Check to see if this is $foo.bar.
244   StringRef::size_type DotIdx = OpName.find_first_of('.');
245   if (DotIdx != StringRef::npos) {
246     SubOpName = OpName.substr(DotIdx+1);
247     if (SubOpName.empty())
248       PrintFatalError(TheDef->getLoc(),
249                       TheDef->getName() +
250                           ": illegal empty suboperand name in '" + Op + "'");
251     OpName = OpName.substr(0, DotIdx);
252   }
253 
254   unsigned OpIdx;
255 
256   if (std::pair<unsigned, unsigned> SubOp; hasSubOperandAlias(OpName, SubOp)) {
257     // Found a name for a piece of an operand, just return it directly.
258     if (!SubOpName.empty()) {
259       PrintFatalError(
260           TheDef->getLoc(),
261           TheDef->getName() +
262               ": Cannot use dotted suboperand name within suboperand '" +
263               OpName + "'");
264     }
265     return SubOp;
266   }
267 
268   OpIdx = getOperandNamed(OpName);
269 
270   if (SubOpName.empty()) {  // If no suboperand name was specified:
271     // If one was needed, throw.
272     if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
273         SubOpName.empty())
274       PrintFatalError(TheDef->getLoc(),
275                       TheDef->getName() +
276                           ": Illegal to refer to"
277                           " whole operand part of complex operand '" +
278                           Op + "'");
279 
280     // Otherwise, return the operand.
281     return std::make_pair(OpIdx, 0U);
282   }
283 
284   // Find the suboperand number involved.
285   DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
286   if (!MIOpInfo)
287     PrintFatalError(TheDef->getLoc(), TheDef->getName() +
288                                           ": unknown suboperand name in '" +
289                                           Op + "'");
290 
291   // Find the operand with the right name.
292   for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
293     if (MIOpInfo->getArgNameStr(i) == SubOpName)
294       return std::make_pair(OpIdx, i);
295 
296   // Otherwise, didn't find it!
297   PrintFatalError(TheDef->getLoc(), TheDef->getName() +
298                                         ": unknown suboperand name in '" + Op +
299                                         "'");
300   return std::make_pair(0U, 0U);
301 }
302 
ParseConstraint(StringRef CStr,CGIOperandList & Ops,Record * Rec)303 static void ParseConstraint(StringRef CStr, CGIOperandList &Ops,
304                             Record *Rec) {
305   // EARLY_CLOBBER: @early $reg
306   StringRef::size_type wpos = CStr.find_first_of(" \t");
307   StringRef::size_type start = CStr.find_first_not_of(" \t");
308   StringRef Tok = CStr.substr(start, wpos - start);
309   if (Tok == "@earlyclobber") {
310     StringRef Name = CStr.substr(wpos+1);
311     wpos = Name.find_first_not_of(" \t");
312     if (wpos == StringRef::npos)
313       PrintFatalError(
314         Rec->getLoc(), "Illegal format for @earlyclobber constraint in '" +
315         Rec->getName() + "': '" + CStr + "'");
316     Name = Name.substr(wpos);
317     std::pair<unsigned,unsigned> Op = Ops.ParseOperandName(Name, false);
318 
319     // Build the string for the operand
320     if (!Ops[Op.first].Constraints[Op.second].isNone())
321       PrintFatalError(
322         Rec->getLoc(), "Operand '" + Name + "' of '" + Rec->getName() +
323         "' cannot have multiple constraints!");
324     Ops[Op.first].Constraints[Op.second] =
325     CGIOperandList::ConstraintInfo::getEarlyClobber();
326     return;
327   }
328 
329   // Only other constraint is "TIED_TO" for now.
330   StringRef::size_type pos = CStr.find_first_of('=');
331   if (pos == StringRef::npos)
332     PrintFatalError(
333       Rec->getLoc(), "Unrecognized constraint '" + CStr +
334       "' in '" + Rec->getName() + "'");
335   start = CStr.find_first_not_of(" \t");
336 
337   // TIED_TO: $src1 = $dst
338   wpos = CStr.find_first_of(" \t", start);
339   if (wpos == StringRef::npos || wpos > pos)
340     PrintFatalError(
341       Rec->getLoc(), "Illegal format for tied-to constraint in '" +
342       Rec->getName() + "': '" + CStr + "'");
343   StringRef LHSOpName = CStr.substr(start, wpos - start);
344   std::pair<unsigned,unsigned> LHSOp = Ops.ParseOperandName(LHSOpName, false);
345 
346   wpos = CStr.find_first_not_of(" \t", pos + 1);
347   if (wpos == StringRef::npos)
348     PrintFatalError(
349       Rec->getLoc(), "Illegal format for tied-to constraint: '" + CStr + "'");
350 
351   StringRef RHSOpName = CStr.substr(wpos);
352   std::pair<unsigned,unsigned> RHSOp = Ops.ParseOperandName(RHSOpName, false);
353 
354   // Sort the operands into order, which should put the output one
355   // first. But keep the original order, for use in diagnostics.
356   bool FirstIsDest = (LHSOp < RHSOp);
357   std::pair<unsigned,unsigned> DestOp = (FirstIsDest ? LHSOp : RHSOp);
358   StringRef DestOpName = (FirstIsDest ? LHSOpName : RHSOpName);
359   std::pair<unsigned,unsigned> SrcOp = (FirstIsDest ? RHSOp : LHSOp);
360   StringRef SrcOpName = (FirstIsDest ? RHSOpName : LHSOpName);
361 
362   // Ensure one operand is a def and the other is a use.
363   if (DestOp.first >= Ops.NumDefs)
364     PrintFatalError(
365       Rec->getLoc(), "Input operands '" + LHSOpName + "' and '" + RHSOpName +
366       "' of '" + Rec->getName() + "' cannot be tied!");
367   if (SrcOp.first < Ops.NumDefs)
368     PrintFatalError(
369       Rec->getLoc(), "Output operands '" + LHSOpName + "' and '" + RHSOpName +
370       "' of '" + Rec->getName() + "' cannot be tied!");
371 
372   // The constraint has to go on the operand with higher index, i.e.
373   // the source one. Check there isn't another constraint there
374   // already.
375   if (!Ops[SrcOp.first].Constraints[SrcOp.second].isNone())
376     PrintFatalError(
377       Rec->getLoc(), "Operand '" + SrcOpName + "' of '" + Rec->getName() +
378       "' cannot have multiple constraints!");
379 
380   unsigned DestFlatOpNo = Ops.getFlattenedOperandNumber(DestOp);
381   auto NewConstraint = CGIOperandList::ConstraintInfo::getTied(DestFlatOpNo);
382 
383   // Check that the earlier operand is not the target of another tie
384   // before making it the target of this one.
385   for (const CGIOperandList::OperandInfo &Op : Ops) {
386     for (unsigned i = 0; i < Op.MINumOperands; i++)
387       if (Op.Constraints[i] == NewConstraint)
388         PrintFatalError(
389           Rec->getLoc(), "Operand '" + DestOpName + "' of '" + Rec->getName() +
390           "' cannot have multiple operands tied to it!");
391   }
392 
393   Ops[SrcOp.first].Constraints[SrcOp.second] = NewConstraint;
394 }
395 
ParseConstraints(StringRef CStr,CGIOperandList & Ops,Record * Rec)396 static void ParseConstraints(StringRef CStr, CGIOperandList &Ops, Record *Rec) {
397   if (CStr.empty()) return;
398 
399   StringRef delims(",");
400   StringRef::size_type bidx, eidx;
401 
402   bidx = CStr.find_first_not_of(delims);
403   while (bidx != StringRef::npos) {
404     eidx = CStr.find_first_of(delims, bidx);
405     if (eidx == StringRef::npos)
406       eidx = CStr.size();
407 
408     ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops, Rec);
409     bidx = CStr.find_first_not_of(delims, eidx);
410   }
411 }
412 
ProcessDisableEncoding(StringRef DisableEncoding)413 void CGIOperandList::ProcessDisableEncoding(StringRef DisableEncoding) {
414   while (true) {
415     StringRef OpName;
416     std::tie(OpName, DisableEncoding) = getToken(DisableEncoding, " ,\t");
417     if (OpName.empty()) break;
418 
419     // Figure out which operand this is.
420     std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
421 
422     // Mark the operand as not-to-be encoded.
423     OperandList[Op.first].DoNotEncode[Op.second] = true;
424   }
425 
426 }
427 
428 //===----------------------------------------------------------------------===//
429 // CodeGenInstruction Implementation
430 //===----------------------------------------------------------------------===//
431 
CodeGenInstruction(Record * R)432 CodeGenInstruction::CodeGenInstruction(Record *R)
433   : TheDef(R), Operands(R), InferredFrom(nullptr) {
434   Namespace = R->getValueAsString("Namespace");
435   AsmString = std::string(R->getValueAsString("AsmString"));
436 
437   isPreISelOpcode = R->getValueAsBit("isPreISelOpcode");
438   isReturn     = R->getValueAsBit("isReturn");
439   isEHScopeReturn = R->getValueAsBit("isEHScopeReturn");
440   isBranch     = R->getValueAsBit("isBranch");
441   isIndirectBranch = R->getValueAsBit("isIndirectBranch");
442   isCompare    = R->getValueAsBit("isCompare");
443   isMoveImm    = R->getValueAsBit("isMoveImm");
444   isMoveReg    = R->getValueAsBit("isMoveReg");
445   isBitcast    = R->getValueAsBit("isBitcast");
446   isSelect     = R->getValueAsBit("isSelect");
447   isBarrier    = R->getValueAsBit("isBarrier");
448   isCall       = R->getValueAsBit("isCall");
449   isAdd        = R->getValueAsBit("isAdd");
450   isTrap       = R->getValueAsBit("isTrap");
451   canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
452   isPredicable = !R->getValueAsBit("isUnpredicable") && (
453       Operands.isPredicable || R->getValueAsBit("isPredicable"));
454   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
455   isCommutable = R->getValueAsBit("isCommutable");
456   isTerminator = R->getValueAsBit("isTerminator");
457   isReMaterializable = R->getValueAsBit("isReMaterializable");
458   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
459   usesCustomInserter = R->getValueAsBit("usesCustomInserter");
460   hasPostISelHook = R->getValueAsBit("hasPostISelHook");
461   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
462   isNotDuplicable = R->getValueAsBit("isNotDuplicable");
463   isRegSequence = R->getValueAsBit("isRegSequence");
464   isExtractSubreg = R->getValueAsBit("isExtractSubreg");
465   isInsertSubreg = R->getValueAsBit("isInsertSubreg");
466   isConvergent = R->getValueAsBit("isConvergent");
467   hasNoSchedulingInfo = R->getValueAsBit("hasNoSchedulingInfo");
468   FastISelShouldIgnore = R->getValueAsBit("FastISelShouldIgnore");
469   variadicOpsAreDefs = R->getValueAsBit("variadicOpsAreDefs");
470   isAuthenticated = R->getValueAsBit("isAuthenticated");
471 
472   bool Unset;
473   mayLoad      = R->getValueAsBitOrUnset("mayLoad", Unset);
474   mayLoad_Unset = Unset;
475   mayStore     = R->getValueAsBitOrUnset("mayStore", Unset);
476   mayStore_Unset = Unset;
477   mayRaiseFPException = R->getValueAsBit("mayRaiseFPException");
478   hasSideEffects = R->getValueAsBitOrUnset("hasSideEffects", Unset);
479   hasSideEffects_Unset = Unset;
480 
481   isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
482   hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
483   hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
484   isCodeGenOnly = R->getValueAsBit("isCodeGenOnly");
485   isPseudo = R->getValueAsBit("isPseudo");
486   isMeta = R->getValueAsBit("isMeta");
487   ImplicitDefs = R->getValueAsListOfDefs("Defs");
488   ImplicitUses = R->getValueAsListOfDefs("Uses");
489 
490   // This flag is only inferred from the pattern.
491   hasChain = false;
492   hasChain_Inferred = false;
493 
494   // Parse Constraints.
495   ParseConstraints(R->getValueAsString("Constraints"), Operands, R);
496 
497   // Parse the DisableEncoding field.
498   Operands.ProcessDisableEncoding(
499       R->getValueAsString("DisableEncoding"));
500 
501   // First check for a ComplexDeprecationPredicate.
502   if (R->getValue("ComplexDeprecationPredicate")) {
503     HasComplexDeprecationPredicate = true;
504     DeprecatedReason =
505         std::string(R->getValueAsString("ComplexDeprecationPredicate"));
506   } else if (RecordVal *Dep = R->getValue("DeprecatedFeatureMask")) {
507     // Check if we have a Subtarget feature mask.
508     HasComplexDeprecationPredicate = false;
509     DeprecatedReason = Dep->getValue()->getAsString();
510   } else {
511     // This instruction isn't deprecated.
512     HasComplexDeprecationPredicate = false;
513     DeprecatedReason = "";
514   }
515 }
516 
517 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
518 /// implicit def and it has a known VT, return the VT, otherwise return
519 /// MVT::Other.
520 MVT::SimpleValueType CodeGenInstruction::
HasOneImplicitDefWithKnownVT(const CodeGenTarget & TargetInfo) const521 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
522   if (ImplicitDefs.empty()) return MVT::Other;
523 
524   // Check to see if the first implicit def has a resolvable type.
525   Record *FirstImplicitDef = ImplicitDefs[0];
526   assert(FirstImplicitDef->isSubClassOf("Register"));
527   const std::vector<ValueTypeByHwMode> &RegVTs =
528     TargetInfo.getRegisterVTs(FirstImplicitDef);
529   if (RegVTs.size() == 1 && RegVTs[0].isSimple())
530     return RegVTs[0].getSimple().SimpleTy;
531   return MVT::Other;
532 }
533 
534 
535 /// FlattenAsmStringVariants - Flatten the specified AsmString to only
536 /// include text from the specified variant, returning the new string.
537 std::string CodeGenInstruction::
FlattenAsmStringVariants(StringRef Cur,unsigned Variant)538 FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
539   std::string Res;
540 
541   for (;;) {
542     // Find the start of the next variant string.
543     size_t VariantsStart = 0;
544     for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
545       if (Cur[VariantsStart] == '{' &&
546           (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
547                                   Cur[VariantsStart-1] != '\\')))
548         break;
549 
550     // Add the prefix to the result.
551     Res += Cur.slice(0, VariantsStart);
552     if (VariantsStart == Cur.size())
553       break;
554 
555     ++VariantsStart; // Skip the '{'.
556 
557     // Scan to the end of the variants string.
558     size_t VariantsEnd = VariantsStart;
559     unsigned NestedBraces = 1;
560     for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
561       if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
562         if (--NestedBraces == 0)
563           break;
564       } else if (Cur[VariantsEnd] == '{')
565         ++NestedBraces;
566     }
567 
568     // Select the Nth variant (or empty).
569     StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
570     for (unsigned i = 0; i != Variant; ++i)
571       Selection = Selection.split('|').second;
572     Res += Selection.split('|').first;
573 
574     assert(VariantsEnd != Cur.size() &&
575            "Unterminated variants in assembly string!");
576     Cur = Cur.substr(VariantsEnd + 1);
577   }
578 
579   return Res;
580 }
581 
isOperandImpl(StringRef OpListName,unsigned i,StringRef PropertyName) const582 bool CodeGenInstruction::isOperandImpl(StringRef OpListName, unsigned i,
583                                        StringRef PropertyName) const {
584   DagInit *ConstraintList = TheDef->getValueAsDag(OpListName);
585   if (!ConstraintList || i >= ConstraintList->getNumArgs())
586     return false;
587 
588   DefInit *Constraint = dyn_cast<DefInit>(ConstraintList->getArg(i));
589   if (!Constraint)
590     return false;
591 
592   return Constraint->getDef()->isSubClassOf("TypedOperand") &&
593          Constraint->getDef()->getValueAsBit(PropertyName);
594 }
595 
596 //===----------------------------------------------------------------------===//
597 /// CodeGenInstAlias Implementation
598 //===----------------------------------------------------------------------===//
599 
600 /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
601 /// constructor.  It checks if an argument in an InstAlias pattern matches
602 /// the corresponding operand of the instruction.  It returns true on a
603 /// successful match, with ResOp set to the result operand to be used.
tryAliasOpMatch(DagInit * Result,unsigned AliasOpNo,Record * InstOpRec,bool hasSubOps,ArrayRef<SMLoc> Loc,CodeGenTarget & T,ResultOperand & ResOp)604 bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
605                                        Record *InstOpRec, bool hasSubOps,
606                                        ArrayRef<SMLoc> Loc, CodeGenTarget &T,
607                                        ResultOperand &ResOp) {
608   Init *Arg = Result->getArg(AliasOpNo);
609   DefInit *ADI = dyn_cast<DefInit>(Arg);
610   Record *ResultRecord = ADI ? ADI->getDef() : nullptr;
611 
612   if (ADI && ADI->getDef() == InstOpRec) {
613     // If the operand is a record, it must have a name, and the record type
614     // must match up with the instruction's argument type.
615     if (!Result->getArgName(AliasOpNo))
616       PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
617                            " must have a name!");
618     ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
619                           ResultRecord);
620     return true;
621   }
622 
623   // For register operands, the source register class can be a subclass
624   // of the instruction register class, not just an exact match.
625   if (InstOpRec->isSubClassOf("RegisterOperand"))
626     InstOpRec = InstOpRec->getValueAsDef("RegClass");
627 
628   if (ADI && ADI->getDef()->isSubClassOf("RegisterOperand"))
629     ADI = ADI->getDef()->getValueAsDef("RegClass")->getDefInit();
630 
631   if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
632     if (!InstOpRec->isSubClassOf("RegisterClass"))
633       return false;
634     if (!T.getRegisterClass(InstOpRec)
635               .hasSubClass(&T.getRegisterClass(ADI->getDef())))
636       return false;
637     ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
638                           ResultRecord);
639     return true;
640   }
641 
642   // Handle explicit registers.
643   if (ADI && ADI->getDef()->isSubClassOf("Register")) {
644     if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
645       DagInit *DI = InstOpRec->getValueAsDag("MIOperandInfo");
646       // The operand info should only have a single (register) entry. We
647       // want the register class of it.
648       InstOpRec = cast<DefInit>(DI->getArg(0))->getDef();
649     }
650 
651     if (!InstOpRec->isSubClassOf("RegisterClass"))
652       return false;
653 
654     if (!T.getRegisterClass(InstOpRec)
655         .contains(T.getRegBank().getReg(ADI->getDef())))
656       PrintFatalError(Loc, "fixed register " + ADI->getDef()->getName() +
657                       " is not a member of the " + InstOpRec->getName() +
658                       " register class!");
659 
660     if (Result->getArgName(AliasOpNo))
661       PrintFatalError(Loc, "result fixed register argument must "
662                       "not have a name!");
663 
664     ResOp = ResultOperand(ResultRecord);
665     return true;
666   }
667 
668   // Handle "zero_reg" for optional def operands.
669   if (ADI && ADI->getDef()->getName() == "zero_reg") {
670 
671     // Check if this is an optional def.
672     // Tied operands where the source is a sub-operand of a complex operand
673     // need to represent both operands in the alias destination instruction.
674     // Allow zero_reg for the tied portion. This can and should go away once
675     // the MC representation of things doesn't use tied operands at all.
676     //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
677     //  throw TGError(Loc, "reg0 used for result that is not an "
678     //                "OptionalDefOperand!");
679 
680     ResOp = ResultOperand(static_cast<Record*>(nullptr));
681     return true;
682   }
683 
684   // Literal integers.
685   if (IntInit *II = dyn_cast<IntInit>(Arg)) {
686     if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
687       return false;
688     // Integer arguments can't have names.
689     if (Result->getArgName(AliasOpNo))
690       PrintFatalError(Loc, "result argument #" + Twine(AliasOpNo) +
691                       " must not have a name!");
692     ResOp = ResultOperand(II->getValue());
693     return true;
694   }
695 
696   // Bits<n> (also used for 0bxx literals)
697   if (BitsInit *BI = dyn_cast<BitsInit>(Arg)) {
698     if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
699       return false;
700     if (!BI->isComplete())
701       return false;
702     // Convert the bits init to an integer and use that for the result.
703     IntInit *II = dyn_cast_or_null<IntInit>(
704         BI->convertInitializerTo(IntRecTy::get(BI->getRecordKeeper())));
705     if (!II)
706       return false;
707     ResOp = ResultOperand(II->getValue());
708     return true;
709   }
710 
711   // If both are Operands with the same MVT, allow the conversion. It's
712   // up to the user to make sure the values are appropriate, just like
713   // for isel Pat's.
714   if (InstOpRec->isSubClassOf("Operand") && ADI &&
715       ADI->getDef()->isSubClassOf("Operand")) {
716     // FIXME: What other attributes should we check here? Identical
717     // MIOperandInfo perhaps?
718     if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type"))
719       return false;
720     ResOp = ResultOperand(std::string(Result->getArgNameStr(AliasOpNo)),
721                           ADI->getDef());
722     return true;
723   }
724 
725   return false;
726 }
727 
getMINumOperands() const728 unsigned CodeGenInstAlias::ResultOperand::getMINumOperands() const {
729   if (!isRecord())
730     return 1;
731 
732   Record *Rec = getRecord();
733   if (!Rec->isSubClassOf("Operand"))
734     return 1;
735 
736   DagInit *MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
737   if (MIOpInfo->getNumArgs() == 0) {
738     // Unspecified, so it defaults to 1
739     return 1;
740   }
741 
742   return MIOpInfo->getNumArgs();
743 }
744 
CodeGenInstAlias(Record * R,CodeGenTarget & T)745 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T)
746     : TheDef(R) {
747   Result = R->getValueAsDag("ResultInst");
748   AsmString = std::string(R->getValueAsString("AsmString"));
749 
750   // Verify that the root of the result is an instruction.
751   DefInit *DI = dyn_cast<DefInit>(Result->getOperator());
752   if (!DI || !DI->getDef()->isSubClassOf("Instruction"))
753     PrintFatalError(R->getLoc(),
754                     "result of inst alias should be an instruction");
755 
756   ResultInst = &T.getInstruction(DI->getDef());
757 
758   // NameClass - If argument names are repeated, we need to verify they have
759   // the same class.
760   StringMap<Record*> NameClass;
761   for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
762     DefInit *ADI = dyn_cast<DefInit>(Result->getArg(i));
763     if (!ADI || !Result->getArgName(i))
764       continue;
765     // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
766     // $foo can exist multiple times in the result list, but it must have the
767     // same type.
768     Record *&Entry = NameClass[Result->getArgNameStr(i)];
769     if (Entry && Entry != ADI->getDef())
770       PrintFatalError(R->getLoc(), "result value $" + Result->getArgNameStr(i) +
771                       " is both " + Entry->getName() + " and " +
772                       ADI->getDef()->getName() + "!");
773     Entry = ADI->getDef();
774   }
775 
776   // Decode and validate the arguments of the result.
777   unsigned AliasOpNo = 0;
778   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
779 
780     // Tied registers don't have an entry in the result dag unless they're part
781     // of a complex operand, in which case we include them anyways, as we
782     // don't have any other way to specify the whole operand.
783     if (ResultInst->Operands[i].MINumOperands == 1 &&
784         ResultInst->Operands[i].getTiedRegister() != -1) {
785       // Tied operands of different RegisterClass should be explicit within an
786       // instruction's syntax and so cannot be skipped.
787       int TiedOpNum = ResultInst->Operands[i].getTiedRegister();
788       if (ResultInst->Operands[i].Rec->getName() ==
789           ResultInst->Operands[TiedOpNum].Rec->getName())
790         continue;
791     }
792 
793     if (AliasOpNo >= Result->getNumArgs())
794       PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
795 
796     Record *InstOpRec = ResultInst->Operands[i].Rec;
797     unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
798     ResultOperand ResOp(static_cast<int64_t>(0));
799     if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
800                         R->getLoc(), T, ResOp)) {
801       // If this is a simple operand, or a complex operand with a custom match
802       // class, then we can match is verbatim.
803       if (NumSubOps == 1 ||
804           (InstOpRec->getValue("ParserMatchClass") &&
805            InstOpRec->getValueAsDef("ParserMatchClass")
806              ->getValueAsString("Name") != "Imm")) {
807         ResultOperands.push_back(ResOp);
808         ResultInstOperandIndex.push_back(std::make_pair(i, -1));
809         ++AliasOpNo;
810 
811       // Otherwise, we need to match each of the suboperands individually.
812       } else {
813          DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
814          for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
815           Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
816 
817           // Take care to instantiate each of the suboperands with the correct
818           // nomenclature: $foo.bar
819           ResultOperands.emplace_back(
820             Result->getArgName(AliasOpNo)->getAsUnquotedString() + "." +
821             MIOI->getArgName(SubOp)->getAsUnquotedString(), SubRec);
822           ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
823          }
824          ++AliasOpNo;
825       }
826       continue;
827     }
828 
829     // If the argument did not match the instruction operand, and the operand
830     // is composed of multiple suboperands, try matching the suboperands.
831     if (NumSubOps > 1) {
832       DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
833       for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
834         if (AliasOpNo >= Result->getNumArgs())
835           PrintFatalError(R->getLoc(), "not enough arguments for instruction!");
836         Record *SubRec = cast<DefInit>(MIOI->getArg(SubOp))->getDef();
837         if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
838                             R->getLoc(), T, ResOp)) {
839           ResultOperands.push_back(ResOp);
840           ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
841           ++AliasOpNo;
842         } else {
843           PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
844                         " does not match instruction operand class " +
845                         (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
846         }
847       }
848       continue;
849     }
850     PrintFatalError(R->getLoc(), "result argument #" + Twine(AliasOpNo) +
851                     " does not match instruction operand class " +
852                     InstOpRec->getName());
853   }
854 
855   if (AliasOpNo != Result->getNumArgs())
856     PrintFatalError(R->getLoc(), "too many operands for instruction!");
857 }
858