TableGen: PointerLikeRegClass can be accepted to operand.
[oota-llvm.git] / utils / TableGen / CodeGenInstruction.cpp
1 //===- CodeGenInstruction.cpp - CodeGen Instruction Class Wrapper ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the CodeGenInstruction class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "CodeGenInstruction.h"
15 #include "CodeGenTarget.h"
16 #include "Record.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include <set>
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // CGIOperandList Implementation
25 //===----------------------------------------------------------------------===//
26
27 CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
28   isPredicable = false;
29   hasOptionalDef = false;
30   isVariadic = false;
31
32   DagInit *OutDI = R->getValueAsDag("OutOperandList");
33
34   if (DefInit *Init = dynamic_cast<DefInit*>(OutDI->getOperator())) {
35     if (Init->getDef()->getName() != "outs")
36       throw R->getName() + ": invalid def name for output list: use 'outs'";
37   } else
38     throw R->getName() + ": invalid output list: use 'outs'";
39
40   NumDefs = OutDI->getNumArgs();
41
42   DagInit *InDI = R->getValueAsDag("InOperandList");
43   if (DefInit *Init = dynamic_cast<DefInit*>(InDI->getOperator())) {
44     if (Init->getDef()->getName() != "ins")
45       throw R->getName() + ": invalid def name for input list: use 'ins'";
46   } else
47     throw R->getName() + ": invalid input list: use 'ins'";
48
49   unsigned MIOperandNo = 0;
50   std::set<std::string> OperandNames;
51   for (unsigned i = 0, e = InDI->getNumArgs()+OutDI->getNumArgs(); i != e; ++i){
52     Init *ArgInit;
53     std::string ArgName;
54     if (i < NumDefs) {
55       ArgInit = OutDI->getArg(i);
56       ArgName = OutDI->getArgName(i);
57     } else {
58       ArgInit = InDI->getArg(i-NumDefs);
59       ArgName = InDI->getArgName(i-NumDefs);
60     }
61
62     DefInit *Arg = dynamic_cast<DefInit*>(ArgInit);
63     if (!Arg)
64       throw "Illegal operand for the '" + R->getName() + "' instruction!";
65
66     Record *Rec = Arg->getDef();
67     std::string PrintMethod = "printOperand";
68     std::string EncoderMethod;
69     unsigned NumOps = 1;
70     DagInit *MIOpInfo = 0;
71     if (Rec->isSubClassOf("Operand")) {
72       PrintMethod = Rec->getValueAsString("PrintMethod");
73       // If there is an explicit encoder method, use it.
74       EncoderMethod = Rec->getValueAsString("EncoderMethod");
75       MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
76
77       // Verify that MIOpInfo has an 'ops' root value.
78       if (!dynamic_cast<DefInit*>(MIOpInfo->getOperator()) ||
79           dynamic_cast<DefInit*>(MIOpInfo->getOperator())
80           ->getDef()->getName() != "ops")
81         throw "Bad value for MIOperandInfo in operand '" + Rec->getName() +
82         "'\n";
83
84       // If we have MIOpInfo, then we have #operands equal to number of entries
85       // in MIOperandInfo.
86       if (unsigned NumArgs = MIOpInfo->getNumArgs())
87         NumOps = NumArgs;
88
89       if (Rec->isSubClassOf("PredicateOperand"))
90         isPredicable = true;
91       else if (Rec->isSubClassOf("OptionalDefOperand"))
92         hasOptionalDef = true;
93     } else if (Rec->getName() == "variable_ops") {
94       isVariadic = true;
95       continue;
96     } else if (!Rec->isSubClassOf("RegisterClass") &&
97                !Rec->isSubClassOf("PointerLikeRegClass") &&
98                Rec->getName() != "unknown")
99       throw "Unknown operand class '" + Rec->getName() +
100       "' in '" + R->getName() + "' instruction!";
101
102     // Check that the operand has a name and that it's unique.
103     if (ArgName.empty())
104       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
105       " has no name!";
106     if (!OperandNames.insert(ArgName).second)
107       throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
108       " has the same name as a previous operand!";
109
110     OperandList.push_back(OperandInfo(Rec, ArgName, PrintMethod, EncoderMethod,
111                                       MIOperandNo, NumOps, MIOpInfo));
112     MIOperandNo += NumOps;
113   }
114
115
116   // Make sure the constraints list for each operand is large enough to hold
117   // constraint info, even if none is present.
118   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
119     OperandList[i].Constraints.resize(OperandList[i].MINumOperands);
120 }
121
122
123 /// getOperandNamed - Return the index of the operand with the specified
124 /// non-empty name.  If the instruction does not have an operand with the
125 /// specified name, throw an exception.
126 ///
127 unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
128   unsigned OpIdx;
129   if (hasOperandNamed(Name, OpIdx)) return OpIdx;
130   throw "'" + TheDef->getName() + "' does not have an operand named '$" +
131     Name.str() + "'!";
132 }
133
134 /// hasOperandNamed - Query whether the instruction has an operand of the
135 /// given name. If so, return true and set OpIdx to the index of the
136 /// operand. Otherwise, return false.
137 bool CGIOperandList::hasOperandNamed(StringRef Name, unsigned &OpIdx) const {
138   assert(!Name.empty() && "Cannot search for operand with no name!");
139   for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
140     if (OperandList[i].Name == Name) {
141       OpIdx = i;
142       return true;
143     }
144   return false;
145 }
146
147 std::pair<unsigned,unsigned>
148 CGIOperandList::ParseOperandName(const std::string &Op, bool AllowWholeOp) {
149   if (Op.empty() || Op[0] != '$')
150     throw TheDef->getName() + ": Illegal operand name: '" + Op + "'";
151
152   std::string OpName = Op.substr(1);
153   std::string SubOpName;
154
155   // Check to see if this is $foo.bar.
156   std::string::size_type DotIdx = OpName.find_first_of(".");
157   if (DotIdx != std::string::npos) {
158     SubOpName = OpName.substr(DotIdx+1);
159     if (SubOpName.empty())
160       throw TheDef->getName() + ": illegal empty suboperand name in '" +Op +"'";
161     OpName = OpName.substr(0, DotIdx);
162   }
163
164   unsigned OpIdx = getOperandNamed(OpName);
165
166   if (SubOpName.empty()) {  // If no suboperand name was specified:
167     // If one was needed, throw.
168     if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
169         SubOpName.empty())
170       throw TheDef->getName() + ": Illegal to refer to"
171       " whole operand part of complex operand '" + Op + "'";
172
173     // Otherwise, return the operand.
174     return std::make_pair(OpIdx, 0U);
175   }
176
177   // Find the suboperand number involved.
178   DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
179   if (MIOpInfo == 0)
180     throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
181
182   // Find the operand with the right name.
183   for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
184     if (MIOpInfo->getArgName(i) == SubOpName)
185       return std::make_pair(OpIdx, i);
186
187   // Otherwise, didn't find it!
188   throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
189 }
190
191 static void ParseConstraint(const std::string &CStr, CGIOperandList &Ops) {
192   // EARLY_CLOBBER: @early $reg
193   std::string::size_type wpos = CStr.find_first_of(" \t");
194   std::string::size_type start = CStr.find_first_not_of(" \t");
195   std::string Tok = CStr.substr(start, wpos - start);
196   if (Tok == "@earlyclobber") {
197     std::string Name = CStr.substr(wpos+1);
198     wpos = Name.find_first_not_of(" \t");
199     if (wpos == std::string::npos)
200       throw "Illegal format for @earlyclobber constraint: '" + CStr + "'";
201     Name = Name.substr(wpos);
202     std::pair<unsigned,unsigned> Op = Ops.ParseOperandName(Name, false);
203
204     // Build the string for the operand
205     if (!Ops[Op.first].Constraints[Op.second].isNone())
206       throw "Operand '" + Name + "' cannot have multiple constraints!";
207     Ops[Op.first].Constraints[Op.second] =
208     CGIOperandList::ConstraintInfo::getEarlyClobber();
209     return;
210   }
211
212   // Only other constraint is "TIED_TO" for now.
213   std::string::size_type pos = CStr.find_first_of('=');
214   assert(pos != std::string::npos && "Unrecognized constraint");
215   start = CStr.find_first_not_of(" \t");
216   std::string Name = CStr.substr(start, pos - start);
217
218   // TIED_TO: $src1 = $dst
219   wpos = Name.find_first_of(" \t");
220   if (wpos == std::string::npos)
221     throw "Illegal format for tied-to constraint: '" + CStr + "'";
222   std::string DestOpName = Name.substr(0, wpos);
223   std::pair<unsigned,unsigned> DestOp = Ops.ParseOperandName(DestOpName, false);
224
225   Name = CStr.substr(pos+1);
226   wpos = Name.find_first_not_of(" \t");
227   if (wpos == std::string::npos)
228     throw "Illegal format for tied-to constraint: '" + CStr + "'";
229
230   std::pair<unsigned,unsigned> SrcOp =
231   Ops.ParseOperandName(Name.substr(wpos), false);
232   if (SrcOp > DestOp)
233     throw "Illegal tied-to operand constraint '" + CStr + "'";
234
235
236   unsigned FlatOpNo = Ops.getFlattenedOperandNumber(SrcOp);
237
238   if (!Ops[DestOp.first].Constraints[DestOp.second].isNone())
239     throw "Operand '" + DestOpName + "' cannot have multiple constraints!";
240   Ops[DestOp.first].Constraints[DestOp.second] =
241   CGIOperandList::ConstraintInfo::getTied(FlatOpNo);
242 }
243
244 static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops) {
245   if (CStr.empty()) return;
246
247   const std::string delims(",");
248   std::string::size_type bidx, eidx;
249
250   bidx = CStr.find_first_not_of(delims);
251   while (bidx != std::string::npos) {
252     eidx = CStr.find_first_of(delims, bidx);
253     if (eidx == std::string::npos)
254       eidx = CStr.length();
255
256     ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops);
257     bidx = CStr.find_first_not_of(delims, eidx);
258   }
259 }
260
261 void CGIOperandList::ProcessDisableEncoding(std::string DisableEncoding) {
262   while (1) {
263     std::string OpName;
264     tie(OpName, DisableEncoding) = getToken(DisableEncoding, " ,\t");
265     if (OpName.empty()) break;
266
267     // Figure out which operand this is.
268     std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
269
270     // Mark the operand as not-to-be encoded.
271     if (Op.second >= OperandList[Op.first].DoNotEncode.size())
272       OperandList[Op.first].DoNotEncode.resize(Op.second+1);
273     OperandList[Op.first].DoNotEncode[Op.second] = true;
274   }
275
276 }
277
278 //===----------------------------------------------------------------------===//
279 // CodeGenInstruction Implementation
280 //===----------------------------------------------------------------------===//
281
282 CodeGenInstruction::CodeGenInstruction(Record *R) : TheDef(R), Operands(R) {
283   Namespace = R->getValueAsString("Namespace");
284   AsmString = R->getValueAsString("AsmString");
285
286   isReturn     = R->getValueAsBit("isReturn");
287   isBranch     = R->getValueAsBit("isBranch");
288   isIndirectBranch = R->getValueAsBit("isIndirectBranch");
289   isCompare    = R->getValueAsBit("isCompare");
290   isMoveImm    = R->getValueAsBit("isMoveImm");
291   isBarrier    = R->getValueAsBit("isBarrier");
292   isCall       = R->getValueAsBit("isCall");
293   canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
294   mayLoad      = R->getValueAsBit("mayLoad");
295   mayStore     = R->getValueAsBit("mayStore");
296   isPredicable = Operands.isPredicable || R->getValueAsBit("isPredicable");
297   isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
298   isCommutable = R->getValueAsBit("isCommutable");
299   isTerminator = R->getValueAsBit("isTerminator");
300   isReMaterializable = R->getValueAsBit("isReMaterializable");
301   hasDelaySlot = R->getValueAsBit("hasDelaySlot");
302   usesCustomInserter = R->getValueAsBit("usesCustomInserter");
303   hasCtrlDep   = R->getValueAsBit("hasCtrlDep");
304   isNotDuplicable = R->getValueAsBit("isNotDuplicable");
305   hasSideEffects = R->getValueAsBit("hasSideEffects");
306   neverHasSideEffects = R->getValueAsBit("neverHasSideEffects");
307   isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
308   hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
309   hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
310   ImplicitDefs = R->getValueAsListOfDefs("Defs");
311   ImplicitUses = R->getValueAsListOfDefs("Uses");
312
313   if (neverHasSideEffects + hasSideEffects > 1)
314     throw R->getName() + ": multiple conflicting side-effect flags set!";
315
316   // Parse Constraints.
317   ParseConstraints(R->getValueAsString("Constraints"), Operands);
318
319   // Parse the DisableEncoding field.
320   Operands.ProcessDisableEncoding(R->getValueAsString("DisableEncoding"));
321 }
322
323 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
324 /// implicit def and it has a known VT, return the VT, otherwise return
325 /// MVT::Other.
326 MVT::SimpleValueType CodeGenInstruction::
327 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
328   if (ImplicitDefs.empty()) return MVT::Other;
329
330   // Check to see if the first implicit def has a resolvable type.
331   Record *FirstImplicitDef = ImplicitDefs[0];
332   assert(FirstImplicitDef->isSubClassOf("Register"));
333   const std::vector<MVT::SimpleValueType> &RegVTs =
334     TargetInfo.getRegisterVTs(FirstImplicitDef);
335   if (RegVTs.size() == 1)
336     return RegVTs[0];
337   return MVT::Other;
338 }
339
340
341 /// FlattenAsmStringVariants - Flatten the specified AsmString to only
342 /// include text from the specified variant, returning the new string.
343 std::string CodeGenInstruction::
344 FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
345   std::string Res = "";
346
347   for (;;) {
348     // Find the start of the next variant string.
349     size_t VariantsStart = 0;
350     for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
351       if (Cur[VariantsStart] == '{' &&
352           (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
353                                   Cur[VariantsStart-1] != '\\')))
354         break;
355
356     // Add the prefix to the result.
357     Res += Cur.slice(0, VariantsStart);
358     if (VariantsStart == Cur.size())
359       break;
360
361     ++VariantsStart; // Skip the '{'.
362
363     // Scan to the end of the variants string.
364     size_t VariantsEnd = VariantsStart;
365     unsigned NestedBraces = 1;
366     for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
367       if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
368         if (--NestedBraces == 0)
369           break;
370       } else if (Cur[VariantsEnd] == '{')
371         ++NestedBraces;
372     }
373
374     // Select the Nth variant (or empty).
375     StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
376     for (unsigned i = 0; i != Variant; ++i)
377       Selection = Selection.split('|').second;
378     Res += Selection.split('|').first;
379
380     assert(VariantsEnd != Cur.size() &&
381            "Unterminated variants in assembly string!");
382     Cur = Cur.substr(VariantsEnd + 1);
383   }
384
385   return Res;
386 }
387
388
389 //===----------------------------------------------------------------------===//
390 /// CodeGenInstAlias Implementation
391 //===----------------------------------------------------------------------===//
392
393 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T) : TheDef(R) {
394   AsmString = R->getValueAsString("AsmString");
395   Result = R->getValueAsDag("ResultInst");
396
397   // Verify that the root of the result is an instruction.
398   DefInit *DI = dynamic_cast<DefInit*>(Result->getOperator());
399   if (DI == 0 || !DI->getDef()->isSubClassOf("Instruction"))
400     throw TGError(R->getLoc(), "result of inst alias should be an instruction");
401
402   ResultInst = &T.getInstruction(DI->getDef());
403
404   // NameClass - If argument names are repeated, we need to verify they have
405   // the same class.
406   StringMap<Record*> NameClass;
407   for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
408     DefInit *ADI = dynamic_cast<DefInit*>(Result->getArg(i));
409     if (!ADI || Result->getArgName(i).empty())
410       continue;
411     // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
412     // $foo can exist multiple times in the result list, but it must have the
413     // same type.
414     Record *&Entry = NameClass[Result->getArgName(i)];
415     if (Entry && Entry != ADI->getDef())
416       throw TGError(R->getLoc(), "result value $" + Result->getArgName(i) +
417                     " is both " + Entry->getName() + " and " +
418                     ADI->getDef()->getName() + "!");
419     Entry = ADI->getDef();
420   }
421
422   // Decode and validate the arguments of the result.
423   unsigned AliasOpNo = 0;
424   for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
425     // Tied registers don't have an entry in the result dag.
426     if (ResultInst->Operands[i].getTiedRegister() != -1)
427       continue;
428
429     if (AliasOpNo >= Result->getNumArgs())
430       throw TGError(R->getLoc(), "result has " + utostr(Result->getNumArgs()) +
431                     " arguments, but " + ResultInst->TheDef->getName() +
432                     " instruction expects " +
433                     utostr(ResultInst->Operands.size()) + " operands!");
434
435
436     Init *Arg = Result->getArg(AliasOpNo);
437     Record *ResultOpRec = ResultInst->Operands[i].Rec;
438
439     // Handle explicit registers.
440     if (DefInit *ADI = dynamic_cast<DefInit*>(Arg)) {
441       if (ADI->getDef()->isSubClassOf("Register")) {
442         if (!Result->getArgName(AliasOpNo).empty())
443           throw TGError(R->getLoc(), "result fixed register argument must "
444                         "not have a name!");
445
446         if (!ResultOpRec->isSubClassOf("RegisterClass"))
447           throw TGError(R->getLoc(), "result fixed register argument is not "
448                         "passed to a RegisterClass operand!");
449
450         if (!T.getRegisterClass(ResultOpRec).containsRegister(ADI->getDef()))
451           throw TGError(R->getLoc(), "fixed register " +ADI->getDef()->getName()
452                         + " is not a member of the " + ResultOpRec->getName() +
453                         " register class!");
454
455         // Now that it is validated, add it.
456         ResultOperands.push_back(ResultOperand(ADI->getDef()));
457         ResultInstOperandIndex.push_back(i);
458         ++AliasOpNo;
459         continue;
460       }
461       if (ADI->getDef()->getName() == "zero_reg") {
462         if (!Result->getArgName(AliasOpNo).empty())
463           throw TGError(R->getLoc(), "result fixed register argument must "
464                         "not have a name!");
465
466         // Check if this is an optional def.
467         if (!ResultOpRec->isSubClassOf("OptionalDefOperand"))
468           throw TGError(R->getLoc(), "reg0 used for result that is not an "
469                         "OptionalDefOperand!");
470
471         // Now that it is validated, add it.
472         ResultOperands.push_back(ResultOperand(static_cast<Record*>(0)));
473         ResultInstOperandIndex.push_back(i);
474         ++AliasOpNo;
475         continue;
476       }
477     }
478
479     // If the operand is a record, it must have a name, and the record type must
480     // match up with the instruction's argument type.
481     if (DefInit *ADI = dynamic_cast<DefInit*>(Arg)) {
482       if (Result->getArgName(AliasOpNo).empty())
483         throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
484                       " must have a name!");
485
486       if (ADI->getDef() != ResultOpRec)
487         throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
488                       " declared with class " + ADI->getDef()->getName() +
489                       ", instruction operand is class " +
490                       ResultOpRec->getName());
491
492       // Now that it is validated, add it.
493       ResultOperands.push_back(ResultOperand(Result->getArgName(AliasOpNo),
494                                              ADI->getDef()));
495       ResultInstOperandIndex.push_back(i);
496       ++AliasOpNo;
497       continue;
498     }
499
500     if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
501       // Integer arguments can't have names.
502       if (!Result->getArgName(AliasOpNo).empty())
503         throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
504                       " must not have a name!");
505       if (ResultInst->Operands[i].MINumOperands != 1 ||
506           !ResultOpRec->isSubClassOf("Operand"))
507         throw TGError(R->getLoc(), "invalid argument class " +
508                       ResultOpRec->getName() +
509                       " for integer result operand!");
510       ResultOperands.push_back(ResultOperand(II->getValue()));
511       ResultInstOperandIndex.push_back(i);
512       ++AliasOpNo;
513       continue;
514     }
515
516     throw TGError(R->getLoc(), "result of inst alias has unknown operand type");
517   }
518
519   if (AliasOpNo != Result->getNumArgs())
520     throw TGError(R->getLoc(), "result has " + utostr(Result->getNumArgs()) +
521                   " arguments, but " + ResultInst->TheDef->getName() +
522                   " instruction expects " + utostr(ResultInst->Operands.size())+
523                   " operands!");
524 }