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"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/STLExtras.h"
23 //===----------------------------------------------------------------------===//
24 // CGIOperandList Implementation
25 //===----------------------------------------------------------------------===//
27 CGIOperandList::CGIOperandList(Record *R) : TheDef(R) {
29 hasOptionalDef = false;
32 DagInit *OutDI = R->getValueAsDag("OutOperandList");
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'";
38 throw R->getName() + ": invalid output list: use 'outs'";
40 NumDefs = OutDI->getNumArgs();
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'";
47 throw R->getName() + ": invalid input list: use 'ins'";
49 unsigned MIOperandNo = 0;
50 std::set<std::string> OperandNames;
51 for (unsigned i = 0, e = InDI->getNumArgs()+OutDI->getNumArgs(); i != e; ++i){
55 ArgInit = OutDI->getArg(i);
56 ArgName = OutDI->getArgName(i);
58 ArgInit = InDI->getArg(i-NumDefs);
59 ArgName = InDI->getArgName(i-NumDefs);
62 DefInit *Arg = dynamic_cast<DefInit*>(ArgInit);
64 throw "Illegal operand for the '" + R->getName() + "' instruction!";
66 Record *Rec = Arg->getDef();
67 std::string PrintMethod = "printOperand";
68 std::string EncoderMethod;
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");
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() +
84 // If we have MIOpInfo, then we have #operands equal to number of entries
86 if (unsigned NumArgs = MIOpInfo->getNumArgs())
89 if (Rec->isSubClassOf("PredicateOperand"))
91 else if (Rec->isSubClassOf("OptionalDefOperand"))
92 hasOptionalDef = true;
93 } else if (Rec->getName() == "variable_ops") {
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!";
102 // Check that the operand has a name and that it's unique.
104 throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
106 if (!OperandNames.insert(ArgName).second)
107 throw "In instruction '" + R->getName() + "', operand #" + utostr(i) +
108 " has the same name as a previous operand!";
110 OperandList.push_back(OperandInfo(Rec, ArgName, PrintMethod, EncoderMethod,
111 MIOperandNo, NumOps, MIOpInfo));
112 MIOperandNo += NumOps;
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);
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.
127 unsigned CGIOperandList::getOperandNamed(StringRef Name) const {
129 if (hasOperandNamed(Name, OpIdx)) return OpIdx;
130 throw "'" + TheDef->getName() + "' does not have an operand named '$" +
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) {
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 + "'";
152 std::string OpName = Op.substr(1);
153 std::string SubOpName;
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);
164 unsigned OpIdx = getOperandNamed(OpName);
166 if (SubOpName.empty()) { // If no suboperand name was specified:
167 // If one was needed, throw.
168 if (OperandList[OpIdx].MINumOperands > 1 && !AllowWholeOp &&
170 throw TheDef->getName() + ": Illegal to refer to"
171 " whole operand part of complex operand '" + Op + "'";
173 // Otherwise, return the operand.
174 return std::make_pair(OpIdx, 0U);
177 // Find the suboperand number involved.
178 DagInit *MIOpInfo = OperandList[OpIdx].MIOperandInfo;
180 throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
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);
187 // Otherwise, didn't find it!
188 throw TheDef->getName() + ": unknown suboperand name in '" + Op + "'";
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);
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();
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);
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);
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 + "'";
230 std::pair<unsigned,unsigned> SrcOp =
231 Ops.ParseOperandName(Name.substr(wpos), false);
233 throw "Illegal tied-to operand constraint '" + CStr + "'";
236 unsigned FlatOpNo = Ops.getFlattenedOperandNumber(SrcOp);
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);
244 static void ParseConstraints(const std::string &CStr, CGIOperandList &Ops) {
245 if (CStr.empty()) return;
247 const std::string delims(",");
248 std::string::size_type bidx, eidx;
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();
256 ParseConstraint(CStr.substr(bidx, eidx - bidx), Ops);
257 bidx = CStr.find_first_not_of(delims, eidx);
261 void CGIOperandList::ProcessDisableEncoding(std::string DisableEncoding) {
264 tie(OpName, DisableEncoding) = getToken(DisableEncoding, " ,\t");
265 if (OpName.empty()) break;
267 // Figure out which operand this is.
268 std::pair<unsigned,unsigned> Op = ParseOperandName(OpName, false);
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;
278 //===----------------------------------------------------------------------===//
279 // CodeGenInstruction Implementation
280 //===----------------------------------------------------------------------===//
282 CodeGenInstruction::CodeGenInstruction(Record *R) : TheDef(R), Operands(R) {
283 Namespace = R->getValueAsString("Namespace");
284 AsmString = R->getValueAsString("AsmString");
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 isBitcast = R->getValueAsBit("isBitcast");
292 isBarrier = R->getValueAsBit("isBarrier");
293 isCall = R->getValueAsBit("isCall");
294 canFoldAsLoad = R->getValueAsBit("canFoldAsLoad");
295 mayLoad = R->getValueAsBit("mayLoad");
296 mayStore = R->getValueAsBit("mayStore");
297 isPredicable = Operands.isPredicable || R->getValueAsBit("isPredicable");
298 isConvertibleToThreeAddress = R->getValueAsBit("isConvertibleToThreeAddress");
299 isCommutable = R->getValueAsBit("isCommutable");
300 isTerminator = R->getValueAsBit("isTerminator");
301 isReMaterializable = R->getValueAsBit("isReMaterializable");
302 hasDelaySlot = R->getValueAsBit("hasDelaySlot");
303 usesCustomInserter = R->getValueAsBit("usesCustomInserter");
304 hasCtrlDep = R->getValueAsBit("hasCtrlDep");
305 isNotDuplicable = R->getValueAsBit("isNotDuplicable");
306 hasSideEffects = R->getValueAsBit("hasSideEffects");
307 neverHasSideEffects = R->getValueAsBit("neverHasSideEffects");
308 isAsCheapAsAMove = R->getValueAsBit("isAsCheapAsAMove");
309 hasExtraSrcRegAllocReq = R->getValueAsBit("hasExtraSrcRegAllocReq");
310 hasExtraDefRegAllocReq = R->getValueAsBit("hasExtraDefRegAllocReq");
311 ImplicitDefs = R->getValueAsListOfDefs("Defs");
312 ImplicitUses = R->getValueAsListOfDefs("Uses");
314 if (neverHasSideEffects + hasSideEffects > 1)
315 throw R->getName() + ": multiple conflicting side-effect flags set!";
317 // Parse Constraints.
318 ParseConstraints(R->getValueAsString("Constraints"), Operands);
320 // Parse the DisableEncoding field.
321 Operands.ProcessDisableEncoding(R->getValueAsString("DisableEncoding"));
324 /// HasOneImplicitDefWithKnownVT - If the instruction has at least one
325 /// implicit def and it has a known VT, return the VT, otherwise return
327 MVT::SimpleValueType CodeGenInstruction::
328 HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const {
329 if (ImplicitDefs.empty()) return MVT::Other;
331 // Check to see if the first implicit def has a resolvable type.
332 Record *FirstImplicitDef = ImplicitDefs[0];
333 assert(FirstImplicitDef->isSubClassOf("Register"));
334 const std::vector<MVT::SimpleValueType> &RegVTs =
335 TargetInfo.getRegisterVTs(FirstImplicitDef);
336 if (RegVTs.size() == 1)
342 /// FlattenAsmStringVariants - Flatten the specified AsmString to only
343 /// include text from the specified variant, returning the new string.
344 std::string CodeGenInstruction::
345 FlattenAsmStringVariants(StringRef Cur, unsigned Variant) {
346 std::string Res = "";
349 // Find the start of the next variant string.
350 size_t VariantsStart = 0;
351 for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart)
352 if (Cur[VariantsStart] == '{' &&
353 (VariantsStart == 0 || (Cur[VariantsStart-1] != '$' &&
354 Cur[VariantsStart-1] != '\\')))
357 // Add the prefix to the result.
358 Res += Cur.slice(0, VariantsStart);
359 if (VariantsStart == Cur.size())
362 ++VariantsStart; // Skip the '{'.
364 // Scan to the end of the variants string.
365 size_t VariantsEnd = VariantsStart;
366 unsigned NestedBraces = 1;
367 for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) {
368 if (Cur[VariantsEnd] == '}' && Cur[VariantsEnd-1] != '\\') {
369 if (--NestedBraces == 0)
371 } else if (Cur[VariantsEnd] == '{')
375 // Select the Nth variant (or empty).
376 StringRef Selection = Cur.slice(VariantsStart, VariantsEnd);
377 for (unsigned i = 0; i != Variant; ++i)
378 Selection = Selection.split('|').second;
379 Res += Selection.split('|').first;
381 assert(VariantsEnd != Cur.size() &&
382 "Unterminated variants in assembly string!");
383 Cur = Cur.substr(VariantsEnd + 1);
390 //===----------------------------------------------------------------------===//
391 /// CodeGenInstAlias Implementation
392 //===----------------------------------------------------------------------===//
394 /// tryAliasOpMatch - This is a helper function for the CodeGenInstAlias
395 /// constructor. It checks if an argument in an InstAlias pattern matches
396 /// the corresponding operand of the instruction. It returns true on a
397 /// successful match, with ResOp set to the result operand to be used.
398 bool CodeGenInstAlias::tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo,
399 Record *InstOpRec, bool hasSubOps,
400 SMLoc Loc, CodeGenTarget &T,
401 ResultOperand &ResOp) {
402 Init *Arg = Result->getArg(AliasOpNo);
403 DefInit *ADI = dynamic_cast<DefInit*>(Arg);
405 if (ADI && ADI->getDef() == InstOpRec) {
406 // If the operand is a record, it must have a name, and the record type
407 // must match up with the instruction's argument type.
408 if (Result->getArgName(AliasOpNo).empty())
409 throw TGError(Loc, "result argument #" + utostr(AliasOpNo) +
410 " must have a name!");
411 ResOp = ResultOperand(Result->getArgName(AliasOpNo), ADI->getDef());
415 // Handle explicit registers.
416 if (ADI && ADI->getDef()->isSubClassOf("Register")) {
417 if (!InstOpRec->isSubClassOf("RegisterClass"))
420 if (!T.getRegisterClass(InstOpRec).containsRegister(ADI->getDef()))
421 throw TGError(Loc, "fixed register " +ADI->getDef()->getName()
422 + " is not a member of the " + InstOpRec->getName() +
425 if (!Result->getArgName(AliasOpNo).empty())
426 throw TGError(Loc, "result fixed register argument must "
429 ResOp = ResultOperand(ADI->getDef());
433 // Handle "zero_reg" for optional def operands.
434 if (ADI && ADI->getDef()->getName() == "zero_reg") {
436 // Check if this is an optional def.
437 if (!InstOpRec->isSubClassOf("OptionalDefOperand"))
438 throw TGError(Loc, "reg0 used for result that is not an "
439 "OptionalDefOperand!");
441 ResOp = ResultOperand(static_cast<Record*>(0));
445 if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
446 if (hasSubOps || !InstOpRec->isSubClassOf("Operand"))
448 // Integer arguments can't have names.
449 if (!Result->getArgName(AliasOpNo).empty())
450 throw TGError(Loc, "result argument #" + utostr(AliasOpNo) +
451 " must not have a name!");
452 ResOp = ResultOperand(II->getValue());
459 CodeGenInstAlias::CodeGenInstAlias(Record *R, CodeGenTarget &T) : TheDef(R) {
460 AsmString = R->getValueAsString("AsmString");
461 Result = R->getValueAsDag("ResultInst");
463 // Verify that the root of the result is an instruction.
464 DefInit *DI = dynamic_cast<DefInit*>(Result->getOperator());
465 if (DI == 0 || !DI->getDef()->isSubClassOf("Instruction"))
466 throw TGError(R->getLoc(), "result of inst alias should be an instruction");
468 ResultInst = &T.getInstruction(DI->getDef());
470 // NameClass - If argument names are repeated, we need to verify they have
472 StringMap<Record*> NameClass;
473 for (unsigned i = 0, e = Result->getNumArgs(); i != e; ++i) {
474 DefInit *ADI = dynamic_cast<DefInit*>(Result->getArg(i));
475 if (!ADI || Result->getArgName(i).empty())
477 // Verify we don't have something like: (someinst GR16:$foo, GR32:$foo)
478 // $foo can exist multiple times in the result list, but it must have the
480 Record *&Entry = NameClass[Result->getArgName(i)];
481 if (Entry && Entry != ADI->getDef())
482 throw TGError(R->getLoc(), "result value $" + Result->getArgName(i) +
483 " is both " + Entry->getName() + " and " +
484 ADI->getDef()->getName() + "!");
485 Entry = ADI->getDef();
488 // Decode and validate the arguments of the result.
489 unsigned AliasOpNo = 0;
490 for (unsigned i = 0, e = ResultInst->Operands.size(); i != e; ++i) {
492 // Tied registers don't have an entry in the result dag.
493 if (ResultInst->Operands[i].getTiedRegister() != -1)
496 if (AliasOpNo >= Result->getNumArgs())
497 throw TGError(R->getLoc(), "not enough arguments for instruction!");
499 Record *InstOpRec = ResultInst->Operands[i].Rec;
500 unsigned NumSubOps = ResultInst->Operands[i].MINumOperands;
501 ResultOperand ResOp(static_cast<int64_t>(0));
502 if (tryAliasOpMatch(Result, AliasOpNo, InstOpRec, (NumSubOps > 1),
503 R->getLoc(), T, ResOp)) {
504 ResultOperands.push_back(ResOp);
505 ResultInstOperandIndex.push_back(std::make_pair(i, -1));
510 // If the argument did not match the instruction operand, and the operand
511 // is composed of multiple suboperands, try matching the suboperands.
513 DagInit *MIOI = ResultInst->Operands[i].MIOperandInfo;
514 for (unsigned SubOp = 0; SubOp != NumSubOps; ++SubOp) {
515 if (AliasOpNo >= Result->getNumArgs())
516 throw TGError(R->getLoc(), "not enough arguments for instruction!");
517 Record *SubRec = dynamic_cast<DefInit*>(MIOI->getArg(SubOp))->getDef();
518 if (tryAliasOpMatch(Result, AliasOpNo, SubRec, false,
519 R->getLoc(), T, ResOp)) {
520 ResultOperands.push_back(ResOp);
521 ResultInstOperandIndex.push_back(std::make_pair(i, SubOp));
524 throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
525 " does not match instruction operand class " +
526 (SubOp == 0 ? InstOpRec->getName() :SubRec->getName()));
531 throw TGError(R->getLoc(), "result argument #" + utostr(AliasOpNo) +
532 " does not match instruction operand class " +
533 InstOpRec->getName());
536 if (AliasOpNo != Result->getNumArgs())
537 throw TGError(R->getLoc(), "too many operands for instruction!");