1 //===- CodeGenInstruction.cpp - CodeGen Instruction Class Wrapper ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeGenInstruction class.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenInstruction.h"
15 #include "CodeGenTarget.h"
16 #include "llvm/TableGen/Error.h"
17 #include "llvm/TableGen/Record.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/STLExtras.h"
24 //===----------------------------------------------------------------------===//
25 // CGIOperandList Implementation
26 //===----------------------------------------------------------------------===//
28 CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
30 hasOptionalDef = false;
33 DagInit *OutDI = R->getValueAsDag("OutOperandList");
35 if (DefInit *Init = dynamic_cast<DefInit*>(OutDI->getOperator())) {
36 if (Init->getDef()->getName() != "outs")
37 throw R->getName() + ": invalid def name for output list: use 'outs'";
39 throw R->getName() + ": invalid output list: use 'outs'";
41 NumDefs = OutDI->getNumArgs();
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'";
48 throw R->getName() + ": invalid input list: use 'ins'";
50 unsigned MIOperandNo = 0;
51 std::set<std::string> OperandNames;
52 for (unsigned i = 0, e = InDI->getNumArgs()+OutDI->getNumArgs(); i != e; ++i){
56 ArgInit = OutDI->getArg(i);
57 ArgName = OutDI->getArgName(i);
59 ArgInit = InDI->getArg(i-NumDefs);
60 ArgName = InDI->getArgName(i-NumDefs);
63 DefInit *Arg = dynamic_cast<DefInit*>(ArgInit);
65 throw "Illegal operand for the '" + R->getName() + "' instruction!";
67 Record *Rec = Arg->getDef();
68 std::string PrintMethod = "printOperand";
69 std::string EncoderMethod;
70 std::string OperandType = "OPERAND_UNKNOWN";
72 DagInit *MIOpInfo = 0;
73 if (Rec->isSubClassOf("RegisterOperand")) {
74 PrintMethod = Rec->getValueAsString("PrintMethod");
75 } else if (Rec->isSubClassOf("Operand")) {
76 PrintMethod = Rec->getValueAsString("PrintMethod");
77 OperandType = Rec->getValueAsString("OperandType");
78 // If there is an explicit encoder method, use it.
79 EncoderMethod = Rec->getValueAsString("EncoderMethod");
80 MIOpInfo = Rec->getValueAsDag("MIOperandInfo");
82 // Verify that MIOpInfo has an 'ops' root value.
83 if (!dynamic_cast<DefInit*>(MIOpInfo->getOperator()) ||
84 dynamic_cast<DefInit*>(MIOpInfo->getOperator())
85 ->getDef()->getName() != "ops")
86 throw "Bad value for MIOperandInfo in operand '" + Rec->getName() +
89 // If we have MIOpInfo, then we have #operands equal to number of entries
91 if (unsigned NumArgs = MIOpInfo->getNumArgs())
94 if (Rec->isSubClassOf("PredicateOperand"))
96 else if (Rec->isSubClassOf("OptionalDefOperand"))
97 hasOptionalDef = true;
98 } else if (Rec->getName() == "variable_ops") {
101 } else if (Rec->isSubClassOf("RegisterClass")) {
102 OperandType = "OPERAND_REGISTER";
103 } else if (!Rec->isSubClassOf("PointerLikeRegClass") &&
104 Rec->getName() != "unknown")
105 throw "Unknown operand class '" + Rec->getName() +
106 "' in '" + R->getName() + "' instruction!";
108 // Check that the operand has a name and that it's unique.
110 throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
112 if (!OperandNames.insert(ArgName).second)
113 throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
114 " has the same name as a previous operand!";
116 OperandList.push_back(OperandInfo(Rec, ArgName, PrintMethod, EncoderMethod,
117 OperandType, MIOperandNo, NumOps,
119 MIOperandNo += NumOps;
123 // Make sure the constraints list for each operand is large enough to hold
124 // constraint info, even if none is present.
125 for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
126 OperandList[i].Constraints.resize(OperandList[i].MINumOperands);
130 /// getOperandNamed - Return the index of the operand with the specified
131 /// non-empty name. If the instruction does not have an operand with the
132 /// specified name, throw an exception.
134 unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
136 if (hasOperandNamed(Name, OpIdx)) return OpIdx;
137 throw "'" + TheDef->getName() + "' does not have an operand named '$" +
141 /// hasOperandNamed - Query whether the instruction has an operand of the
142 /// given name. If so, return true and set OpIdx to the index of the
143 /// operand. Otherwise, return false.
144 bool CGIOperandList::hasOperandNamed(StringRef Name, unsigned &OpIdx) const {
145 assert(!Name.empty() && "Cannot search for operand with no name!");
146 for (unsigned i = 0, e = OperandList.size(); i != e; ++i)
147 if (OperandList[i].Name == Name) {
154 std::pair<unsigned,unsigned>
155 CGIOperandList::ParseOperandName(const std::string &Op, bool AllowWholeOp) {
156 if (Op.empty() || Op[0] != '$')
157 throw TheDef->getName() + ": Illegal operand name: '" + Op + "'";
159 std::string OpName = Op.substr(1);
160 std::string SubOpName;
162 // Check to see if this is $foo.bar.
163 std::string::size_type DotIdx = OpName.find_first_of(".");
164 if (DotIdx != std::string::npos) {
165 SubOpName = OpName.substr(DotIdx+1);
166 if (SubOpName.empty())
167 throw TheDef->getName() + ": illegal empty suboperand name in '" +Op +"'";
168 OpName = OpName.substr(0, DotIdx);
171 unsigned OpIdx = getOperandNamed(OpName);
173 if (SubOpName.empty()) { // If no suboperand name was specified:
174 // If one was needed, throw.
175 if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
177 throw TheDef->getName() + ": Illegal to refer to"
178 " whole operand part of complex operand '" + Op + "'";
180 // Otherwise, return the operand.
181 return std::make_pair(OpIdx, 0U);
184 // Find the suboperand number involved.
185 DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
187 throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
189 // Find the operand with the right name.
190 for (unsigned i = 0, e = MIOpInfo->getNumArgs(); i != e; ++i)
191 if (MIOpInfo->getArgName(i) == SubOpName)
192 return std::make_pair(OpIdx, i);
194 // Otherwise, didn't find it!
195 throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
198 static void ParseConstraint(const std::string &CStr, CGIOperandList &Ops) {
199 // EARLY_CLOBBER: @early $reg
200 std::string::size_type wpos = CStr.find_first_of(" \t");
201 std::string::size_type start = CStr.find_first_not_of(" \t");
202 std::string Tok = CStr.substr(start, wpos - start);
203 if (Tok == "@earlyclobber") {
204 std::string Name = CStr.substr(wpos+1);
205 wpos = Name.find_first_not_of(" \t");
206 if (wpos == std::string::npos)
207 throw "Illegal format for @earlyclobber constraint: '" + CStr + "'";
208 Name = Name.substr(wpos);
209 std::pair<unsigned,unsigned> Op = Ops.ParseOperandName(Name, false);
211 // Build the string for the operand
212 if (!Ops[Op.first].Constraints[Op.second].isNone())
213 throw "Operand '" + Name + "' cannot have multiple constraints!";
214 Ops[Op.first].Constraints[Op.second] =
215 CGIOperandList::ConstraintInfo::getEarlyClobber();
219 // Only other constraint is "TIED_TO" for now.
220 std::string::size_type pos = CStr.find_first_of('=');
221 assert(pos != std::string::npos && "Unrecognized constraint");
222 start = CStr.find_first_not_of(" \t");
223 std::string Name = CStr.substr(start, pos - start);
225 // TIED_TO: $src1 = $dst
226 wpos = Name.find_first_of(" \t");
227 if (wpos == std::string::npos)
228 throw "Illegal format for tied-to constraint: '" + CStr + "'";
229 std::string DestOpName = Name.substr(0, wpos);
230 std::pair<unsigned,unsigned> DestOp = Ops.ParseOperandName(DestOpName, false);
232 Name = CStr.substr(pos+1);
233 wpos = Name.find_first_not_of(" \t");
234 if (wpos == std::string::npos)
235 throw "Illegal format for tied-to constraint: '" + CStr + "'";
237 std::pair<unsigned,unsigned> SrcOp =
238 Ops.ParseOperandName(Name.substr(wpos), false);
240 throw "Illegal tied-to operand constraint '" + CStr + "'";
243 unsigned FlatOpNo = Ops.getFlattenedOperandNumber(SrcOp);
245 if (!Ops[DestOp.first].Constraints[DestOp.second].isNone())
246 throw "Operand '" + DestOpName + "' cannot have multiple constraints!";
247 Ops[DestOp.first].Constraints[DestOp.second] =
248 CGIOperandList::ConstraintInfo::getTied(FlatOpNo);
251 static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops) {
252 if (CStr.empty()) return;
254 const std::string delims(",");
255 std::string::size_type bidx, eidx;
257 bidx = CStr.find_first_not_of(delims);
258 while (bidx != std::string::npos) {
259 eidx = CStr.find_first_of(delims, bidx);
260 if (eidx == std::string::npos)
261 eidx = CStr.length();
263 ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops);
264 bidx = CStr.find_first_not_of(delims, eidx);
268 void CGIOperandList::ProcessDisableEncoding(std::string DisableEncoding) {
270 std::pair<StringRef, StringRef> P = getToken(DisableEncoding, " ,\t");
271 std::string OpName = P.first;
272 DisableEncoding = P.second;
273 if (OpName.empty()) break;
275 // Figure out which operand this is.
276 std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
278 // Mark the operand as not-to-be encoded.
279 if (Op.second >= OperandList[Op.first].DoNotEncode.size())
280 OperandList[Op.first].DoNotEncode.resize(Op.second+1);
281 OperandList[Op.first].DoNotEncode[Op.second] = true;
286 //===----------------------------------------------------------------------===//
287 // CodeGenInstruction Implementation
288 //===----------------------------------------------------------------------===//
290 CodeGenInstruction::CodeGenInstruction(Record *R) : TheDef(R), Operands(R) {
291 Namespace = R->getValueAsString("Namespace");
292 AsmString = R->getValueAsString("AsmString");
294 isReturn = R->getValueAsBit("isReturn");
295 isBranch = R->getValueAsBit("isBranch");
296 isIndirectBranch = R->getValueAsBit("isIndirectBranch");
297 isCompare = R->getValueAsBit("isCompare");
298 isMoveImm = R->getValueAsBit("isMoveImm");
299 isBitcast = R->getValueAsBit("isBitcast");
300 isBarrier = R->getValueAsBit("isBarrier");
301 isCall = R->getValueAsBit("isCall");
302 canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
303 mayLoad = R->getValueAsBit("mayLoad");
304 mayStore = R->getValueAsBit("mayStore");
305 isPredicable = Operands.isPredicable || R->getValueAsBit("isPredicable");
306 isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
307 isCommutable = R->getValueAsBit("isCommutable");
308 isTerminator = R->getValueAsBit("isTerminator");
309 isReMaterializable = R->getValueAsBit("isReMaterializable");
310 hasDelaySlot = R->getValueAsBit("hasDelaySlot");
311 usesCustomInserter = R->getValueAsBit("usesCustomInserter");
312 hasPostISelHook = R->getValueAsBit("hasPostISelHook");
313 hasCtrlDep = R->getValueAsBit("hasCtrlDep");
314 isNotDuplicable = R->getValueAsBit("isNotDuplicable");
315 hasSideEffects = R->getValueAsBit("hasSideEffects");
316 neverHasSideEffects = R->getValueAsBit("neverHasSideEffects");
317 isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
318 hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
319 hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
320 isCodeGenOnly = R->getValueAsBit("isCodeGenOnly");
321 isPseudo = R->getValueAsBit("isPseudo");
322 ImplicitDefs = R->getValueAsListOfDefs("Defs");
323 ImplicitUses = R->getValueAsListOfDefs("Uses");
325 if (neverHasSideEffects + hasSideEffects > 1)
326 throw R->getName() + ": multiple conflicting side-effect flags set!";
328 // Parse Constraints.
329 ParseConstraints(R->getValueAsString("Constraints"), Operands);
331 // Parse the DisableEncoding field.
332 Operands.ProcessDisableEncoding(R->getValueAsString("DisableEncoding"));
335 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
336 /// implicit def and it has a known VT, return the VT, otherwise return
338 MVT::SimpleValueType CodeGenInstruction::
339 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
340 if (ImplicitDefs.empty()) return MVT::Other;
342 // Check to see if the first implicit def has a resolvable type.
343 Record *FirstImplicitDef = ImplicitDefs[0];
344 assert(FirstImplicitDef->isSubClassOf("Register"));
345 const std::vector<MVT::SimpleValueType> &RegVTs =
346 TargetInfo.getRegisterVTs(FirstImplicitDef);
347 if (RegVTs.size() == 1)
353 /// FlattenAsmStringVariants - Flatten the specified AsmString to only
354 /// include text from the specified variant, returning the new string.
355 std::string CodeGenInstruction::
356 FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
357 std::string Res = "";
360 // Find the start of the next variant string.
361 size_t VariantsStart = 0;
362 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
363 if (Cur[VariantsStart] == '{' &&
364 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
365 Cur[VariantsStart-1] != '\\')))
368 // Add the prefix to the result.
369 Res += Cur.slice(0, VariantsStart);
370 if (VariantsStart == Cur.size())
373 ++VariantsStart; // Skip the '{'.
375 // Scan to the end of the variants string.
376 size_t VariantsEnd = VariantsStart;
377 unsigned NestedBraces = 1;
378 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
379 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
380 if (--NestedBraces == 0)
382 } else if (Cur[VariantsEnd] == '{')
386 // Select the Nth variant (or empty).
387 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
388 for (unsigned i = 0; i != Variant; ++i)
389 Selection = Selection.split('|').second;
390 Res += Selection.split('|').first;
392 assert(VariantsEnd != Cur.size() &&
393 "Unterminated variants in assembly string!");
394 Cur = Cur.substr(VariantsEnd + 1);
401 //===----------------------------------------------------------------------===//
402 /// CodeGenInstAlias Implementation
403 //===----------------------------------------------------------------------===//
405 /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
406 /// constructor. It checks if an argument in an InstAlias pattern matches
407 /// the corresponding operand of the instruction. It returns true on a
408 /// successful match, with ResOp set to the result operand to be used.
409 bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
410 Record *InstOpRec, bool hasSubOps,
411 SMLoc Loc, CodeGenTarget &T,
412 ResultOperand &ResOp) {
413 Init *Arg = Result->getArg(AliasOpNo);
414 DefInit *ADI = dynamic_cast<DefInit*>(Arg);
416 if (ADI && ADI->getDef() == InstOpRec) {
417 // If the operand is a record, it must have a name, and the record type
418 // must match up with the instruction's argument type.
419 if (Result->getArgName(AliasOpNo).empty())
420 throw TGError(Loc, "result argument #" + utostr(AliasOpNo) +
421 " must have a name!");
422 ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
426 // For register operands, the source register class can be a subclass
427 // of the instruction register class, not just an exact match.
428 if (ADI && ADI->getDef()->isSubClassOf("RegisterClass")) {
429 if (!InstOpRec->isSubClassOf("RegisterClass"))
431 if (!T.getRegisterClass(InstOpRec)
432 .hasSubClass(&T.getRegisterClass(ADI->getDef())))
434 ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
438 // Handle explicit registers.
439 if (ADI && ADI->getDef()->isSubClassOf("Register")) {
440 if (InstOpRec->isSubClassOf("OptionalDefOperand")) {
441 DagInit *DI = InstOpRec->getValueAsDag("MIOperandInfo");
442 // The operand info should only have a single (register) entry. We
443 // want the register class of it.
444 InstOpRec = dynamic_cast<DefInit*>(DI->getArg(0))->getDef();
447 if (InstOpRec->isSubClassOf("RegisterOperand"))
448 InstOpRec = InstOpRec->getValueAsDef("RegClass");
450 if (!InstOpRec->isSubClassOf("RegisterClass"))
453 if (!T.getRegisterClass(InstOpRec)
454 .contains(T.getRegBank().getReg(ADI->getDef())))
455 throw TGError(Loc, "fixed register " + ADI->getDef()->getName() +
456 " is not a member of the " + InstOpRec->getName() +
459 if (!Result->getArgName(AliasOpNo).empty())
460 throw TGError(Loc, "result fixed register argument must "
463 ResOp = ResultOperand(ADI->getDef());
467 // Handle "zero_reg" for optional def operands.
468 if (ADI && ADI->getDef()->getName() == "zero_reg") {
470 // Check if this is an optional def.
471 // Tied operands where the source is a sub-operand of a complex operand
472 // need to represent both operands in the alias destination instruction.
473 // Allow zero_reg for the tied portion. This can and should go away once
474 // the MC representation of things doesn't use tied operands at all.
475 //if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
476 // throw TGError(Loc, "reg0 used for result that is not an "
477 // "OptionalDefOperand!");
479 ResOp = ResultOperand(static_cast<Record*>(0));
484 if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
485 if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
487 // Integer arguments can't have names.
488 if (!Result->getArgName(AliasOpNo).empty())
489 throw TGError(Loc, "result argument #" + utostr(AliasOpNo) +
490 " must not have a name!");
491 ResOp = ResultOperand(II->getValue());
495 // If both are Operands with the same MVT, allow the conversion. It's
496 // up to the user to make sure the values are appropriate, just like
498 if (InstOpRec->isSubClassOf("Operand") &&
499 ADI->getDef()->isSubClassOf("Operand")) {
500 // FIXME: What other attributes should we check here? Identical
501 // MIOperandInfo perhaps?
502 if (InstOpRec->getValueInit("Type") != ADI->getDef()->getValueInit("Type"))
504 ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
511 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T) : TheDef(R) {
512 AsmString = R->getValueAsString("AsmString");
513 Result = R->getValueAsDag("ResultInst");
515 // Verify that the root of the result is an instruction.
516 DefInit *DI = dynamic_cast<DefInit*>(Result->getOperator());
517 if (DI == 0 || !DI->getDef()->isSubClassOf("Instruction"))
518 throw TGError(R->getLoc(), "result of inst alias should be an instruction");
520 ResultInst = &T.getInstruction(DI->getDef());
522 // NameClass - If argument names are repeated, we need to verify they have
524 StringMap<Record*> NameClass;
525 for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
526 DefInit *ADI = dynamic_cast<DefInit*>(Result->getArg(i));
527 if (!ADI || Result->getArgName(i).empty())
529 // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
530 // $foo can exist multiple times in the result list, but it must have the
532 Record *&Entry = NameClass[Result->getArgName(i)];
533 if (Entry && Entry != ADI->getDef())
534 throw TGError(R->getLoc(), "result value $" + Result->getArgName(i) +
535 " is both " + Entry->getName() + " and " +
536 ADI->getDef()->getName() + "!");
537 Entry = ADI->getDef();
540 // Decode and validate the arguments of the result.
541 unsigned AliasOpNo = 0;
542 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
544 // Tied registers don't have an entry in the result dag unless they're part
545 // of a complex operand, in which case we include them anyways, as we
546 // don't have any other way to specify the whole operand.
547 if (ResultInst->Operands[i].MINumOperands == 1 &&
548 ResultInst->Operands[i].getTiedRegister() != -1)
551 if (AliasOpNo >= Result->getNumArgs())
552 throw TGError(R->getLoc(), "not enough arguments for instruction!");
554 Record *InstOpRec = ResultInst->Operands[i].Rec;
555 unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
556 ResultOperand ResOp(static_cast<int64_t>(0));
557 if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
558 R->getLoc(), T, ResOp)) {
559 ResultOperands.push_back(ResOp);
560 ResultInstOperandIndex.push_back(std::make_pair(i, -1));
565 // If the argument did not match the instruction operand, and the operand
566 // is composed of multiple suboperands, try matching the suboperands.
568 DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
569 for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
570 if (AliasOpNo >= Result->getNumArgs())
571 throw TGError(R->getLoc(), "not enough arguments for instruction!");
572 Record *SubRec = dynamic_cast<DefInit*>(MIOI->getArg(SubOp))->getDef();
573 if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
574 R->getLoc(), T, ResOp)) {
575 ResultOperands.push_back(ResOp);
576 ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
579 throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
580 " does not match instruction operand class " +
581 (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
586 throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
587 " does not match instruction operand class " +
588 InstOpRec->getName());
591 if (AliasOpNo != Result->getNumArgs())
592 throw TGError(R->getLoc(), "too many operands for instruction!");