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