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