DAGISelMatcherGen.cpp revision ae321ed287009072e94a41d9c912243c558c43cc
1//===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===// 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#include "DAGISelMatcher.h" 11#include "CodeGenDAGPatterns.h" 12#include "Record.h" 13#include "llvm/ADT/SmallVector.h" 14#include "llvm/ADT/StringMap.h" 15#include <utility> 16using namespace llvm; 17 18 19/// getRegisterValueType - Look up and return the ValueType of the specified 20/// register. If the register is a member of multiple register classes which 21/// have different associated types, return MVT::Other. 22static MVT::SimpleValueType getRegisterValueType(Record *R, 23 const CodeGenTarget &T) { 24 bool FoundRC = false; 25 MVT::SimpleValueType VT = MVT::Other; 26 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses(); 27 std::vector<Record*>::const_iterator Element; 28 29 for (unsigned rc = 0, e = RCs.size(); rc != e; ++rc) { 30 const CodeGenRegisterClass &RC = RCs[rc]; 31 if (!std::count(RC.Elements.begin(), RC.Elements.end(), R)) 32 continue; 33 34 if (!FoundRC) { 35 FoundRC = true; 36 VT = RC.getValueTypeNum(0); 37 continue; 38 } 39 40 // If this occurs in multiple register classes, they all have to agree. 41 assert(VT == RC.getValueTypeNum(0)); 42 } 43 return VT; 44} 45 46 47namespace { 48 class MatcherGen { 49 const PatternToMatch &Pattern; 50 const CodeGenDAGPatterns &CGP; 51 52 /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts 53 /// out with all of the types removed. This allows us to insert type checks 54 /// as we scan the tree. 55 TreePatternNode *PatWithNoTypes; 56 57 /// VariableMap - A map from variable names ('$dst') to the recorded operand 58 /// number that they were captured as. These are biased by 1 to make 59 /// insertion easier. 60 StringMap<unsigned> VariableMap; 61 62 /// NextRecordedOperandNo - As we emit opcodes to record matched values in 63 /// the RecordedNodes array, this keeps track of which slot will be next to 64 /// record into. 65 unsigned NextRecordedOperandNo; 66 67 /// MatchedChainNodes - This maintains the position in the recorded nodes 68 /// array of all of the recorded input nodes that have chains. 69 SmallVector<unsigned, 2> MatchedChainNodes; 70 71 /// MatchedFlagResultNodes - This maintains the position in the recorded 72 /// nodes array of all of the recorded input nodes that have flag results. 73 SmallVector<unsigned, 2> MatchedFlagResultNodes; 74 75 /// MatchedComplexPatterns - This maintains a list of all of the 76 /// ComplexPatterns that we need to check. The patterns are known to have 77 /// names which were recorded. The second element of each pair is the first 78 /// slot number that the OPC_CheckComplexPat opcode drops the matched 79 /// results into. 80 SmallVector<std::pair<const TreePatternNode*, 81 unsigned>, 2> MatchedComplexPatterns; 82 83 /// PhysRegInputs - List list has an entry for each explicitly specified 84 /// physreg input to the pattern. The first elt is the Register node, the 85 /// second is the recorded slot number the input pattern match saved it in. 86 SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs; 87 88 /// Matcher - This is the top level of the generated matcher, the result. 89 Matcher *TheMatcher; 90 91 /// CurPredicate - As we emit matcher nodes, this points to the latest check 92 /// which should have future checks stuck into its Next position. 93 Matcher *CurPredicate; 94 public: 95 MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp); 96 97 ~MatcherGen() { 98 delete PatWithNoTypes; 99 } 100 101 bool EmitMatcherCode(unsigned Variant); 102 void EmitResultCode(); 103 104 Matcher *GetMatcher() const { return TheMatcher; } 105 Matcher *GetCurPredicate() const { return CurPredicate; } 106 private: 107 void AddMatcher(Matcher *NewNode); 108 void InferPossibleTypes(); 109 110 // Matcher Generation. 111 void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes); 112 void EmitLeafMatchCode(const TreePatternNode *N); 113 void EmitOperatorMatchCode(const TreePatternNode *N, 114 TreePatternNode *NodeNoTypes); 115 116 // Result Code Generation. 117 unsigned getNamedArgumentSlot(StringRef Name) { 118 unsigned VarMapEntry = VariableMap[Name]; 119 assert(VarMapEntry != 0 && 120 "Variable referenced but not defined and not caught earlier!"); 121 return VarMapEntry-1; 122 } 123 124 /// GetInstPatternNode - Get the pattern for an instruction. 125 const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins, 126 const TreePatternNode *N); 127 128 void EmitResultOperand(const TreePatternNode *N, 129 SmallVectorImpl<unsigned> &ResultOps); 130 void EmitResultOfNamedOperand(const TreePatternNode *N, 131 SmallVectorImpl<unsigned> &ResultOps); 132 void EmitResultLeafAsOperand(const TreePatternNode *N, 133 SmallVectorImpl<unsigned> &ResultOps); 134 void EmitResultInstructionAsOperand(const TreePatternNode *N, 135 SmallVectorImpl<unsigned> &ResultOps); 136 void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N, 137 SmallVectorImpl<unsigned> &ResultOps); 138 }; 139 140} // end anon namespace. 141 142MatcherGen::MatcherGen(const PatternToMatch &pattern, 143 const CodeGenDAGPatterns &cgp) 144: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0), 145 TheMatcher(0), CurPredicate(0) { 146 // We need to produce the matcher tree for the patterns source pattern. To do 147 // this we need to match the structure as well as the types. To do the type 148 // matching, we want to figure out the fewest number of type checks we need to 149 // emit. For example, if there is only one integer type supported by a 150 // target, there should be no type comparisons at all for integer patterns! 151 // 152 // To figure out the fewest number of type checks needed, clone the pattern, 153 // remove the types, then perform type inference on the pattern as a whole. 154 // If there are unresolved types, emit an explicit check for those types, 155 // apply the type to the tree, then rerun type inference. Iterate until all 156 // types are resolved. 157 // 158 PatWithNoTypes = Pattern.getSrcPattern()->clone(); 159 PatWithNoTypes->RemoveAllTypes(); 160 161 // If there are types that are manifestly known, infer them. 162 InferPossibleTypes(); 163} 164 165/// InferPossibleTypes - As we emit the pattern, we end up generating type 166/// checks and applying them to the 'PatWithNoTypes' tree. As we do this, we 167/// want to propagate implied types as far throughout the tree as possible so 168/// that we avoid doing redundant type checks. This does the type propagation. 169void MatcherGen::InferPossibleTypes() { 170 // TP - Get *SOME* tree pattern, we don't care which. It is only used for 171 // diagnostics, which we know are impossible at this point. 172 TreePattern &TP = *CGP.pf_begin()->second; 173 174 try { 175 bool MadeChange = true; 176 while (MadeChange) 177 MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP, 178 true/*Ignore reg constraints*/); 179 } catch (...) { 180 errs() << "Type constraint application shouldn't fail!"; 181 abort(); 182 } 183} 184 185 186/// AddMatcher - Add a matcher node to the current graph we're building. 187void MatcherGen::AddMatcher(Matcher *NewNode) { 188 if (CurPredicate != 0) 189 CurPredicate->setNext(NewNode); 190 else 191 TheMatcher = NewNode; 192 CurPredicate = NewNode; 193} 194 195 196//===----------------------------------------------------------------------===// 197// Pattern Match Generation 198//===----------------------------------------------------------------------===// 199 200/// EmitLeafMatchCode - Generate matching code for leaf nodes. 201void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) { 202 assert(N->isLeaf() && "Not a leaf?"); 203 204 // Direct match against an integer constant. 205 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) { 206 // If this is the root of the dag we're matching, we emit a redundant opcode 207 // check to ensure that this gets folded into the normal top-level 208 // OpcodeSwitch. 209 if (N == Pattern.getSrcPattern()) { 210 const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm")); 211 AddMatcher(new CheckOpcodeMatcher(NI)); 212 } 213 214 return AddMatcher(new CheckIntegerMatcher(II->getValue())); 215 } 216 217 DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue()); 218 if (DI == 0) { 219 errs() << "Unknown leaf kind: " << *DI << "\n"; 220 abort(); 221 } 222 223 Record *LeafRec = DI->getDef(); 224 if (// Handle register references. Nothing to do here, they always match. 225 LeafRec->isSubClassOf("RegisterClass") || 226 LeafRec->isSubClassOf("PointerLikeRegClass") || 227 LeafRec->isSubClassOf("SubRegIndex") || 228 // Place holder for SRCVALUE nodes. Nothing to do here. 229 LeafRec->getName() == "srcvalue") 230 return; 231 232 // If we have a physreg reference like (mul gpr:$src, EAX) then we need to 233 // record the register 234 if (LeafRec->isSubClassOf("Register")) { 235 AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(), 236 NextRecordedOperandNo)); 237 PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++)); 238 return; 239 } 240 241 if (LeafRec->isSubClassOf("ValueType")) 242 return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName())); 243 244 if (LeafRec->isSubClassOf("CondCode")) 245 return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName())); 246 247 if (LeafRec->isSubClassOf("ComplexPattern")) { 248 // We can't model ComplexPattern uses that don't have their name taken yet. 249 // The OPC_CheckComplexPattern operation implicitly records the results. 250 if (N->getName().empty()) { 251 errs() << "We expect complex pattern uses to have names: " << *N << "\n"; 252 exit(1); 253 } 254 255 // Remember this ComplexPattern so that we can emit it after all the other 256 // structural matches are done. 257 MatchedComplexPatterns.push_back(std::make_pair(N, 0)); 258 return; 259 } 260 261 errs() << "Unknown leaf kind: " << *N << "\n"; 262 abort(); 263} 264 265void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N, 266 TreePatternNode *NodeNoTypes) { 267 assert(!N->isLeaf() && "Not an operator?"); 268 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator()); 269 270 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is 271 // a constant without a predicate fn that has more that one bit set, handle 272 // this as a special case. This is usually for targets that have special 273 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit 274 // handling stuff). Using these instructions is often far more efficient 275 // than materializing the constant. Unfortunately, both the instcombiner 276 // and the dag combiner can often infer that bits are dead, and thus drop 277 // them from the mask in the dag. For example, it might turn 'AND X, 255' 278 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks 279 // to handle this. 280 if ((N->getOperator()->getName() == "and" || 281 N->getOperator()->getName() == "or") && 282 N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() && 283 N->getPredicateFns().empty()) { 284 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) { 285 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits. 286 // If this is at the root of the pattern, we emit a redundant 287 // CheckOpcode so that the following checks get factored properly under 288 // a single opcode check. 289 if (N == Pattern.getSrcPattern()) 290 AddMatcher(new CheckOpcodeMatcher(CInfo)); 291 292 // Emit the CheckAndImm/CheckOrImm node. 293 if (N->getOperator()->getName() == "and") 294 AddMatcher(new CheckAndImmMatcher(II->getValue())); 295 else 296 AddMatcher(new CheckOrImmMatcher(II->getValue())); 297 298 // Match the LHS of the AND as appropriate. 299 AddMatcher(new MoveChildMatcher(0)); 300 EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0)); 301 AddMatcher(new MoveParentMatcher()); 302 return; 303 } 304 } 305 } 306 307 // Check that the current opcode lines up. 308 AddMatcher(new CheckOpcodeMatcher(CInfo)); 309 310 // If this node has memory references (i.e. is a load or store), tell the 311 // interpreter to capture them in the memref array. 312 if (N->NodeHasProperty(SDNPMemOperand, CGP)) 313 AddMatcher(new RecordMemRefMatcher()); 314 315 // If this node has a chain, then the chain is operand #0 is the SDNode, and 316 // the child numbers of the node are all offset by one. 317 unsigned OpNo = 0; 318 if (N->NodeHasProperty(SDNPHasChain, CGP)) { 319 // Record the node and remember it in our chained nodes list. 320 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() + 321 "' chained node", 322 NextRecordedOperandNo)); 323 // Remember all of the input chains our pattern will match. 324 MatchedChainNodes.push_back(NextRecordedOperandNo++); 325 326 // Don't look at the input chain when matching the tree pattern to the 327 // SDNode. 328 OpNo = 1; 329 330 // If this node is not the root and the subtree underneath it produces a 331 // chain, then the result of matching the node is also produce a chain. 332 // Beyond that, this means that we're also folding (at least) the root node 333 // into the node that produce the chain (for example, matching 334 // "(add reg, (load ptr))" as a add_with_memory on X86). This is 335 // problematic, if the 'reg' node also uses the load (say, its chain). 336 // Graphically: 337 // 338 // [LD] 339 // ^ ^ 340 // | \ DAG's like cheese. 341 // / | 342 // / [YY] 343 // | ^ 344 // [XX]--/ 345 // 346 // It would be invalid to fold XX and LD. In this case, folding the two 347 // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG' 348 // To prevent this, we emit a dynamic check for legality before allowing 349 // this to be folded. 350 // 351 const TreePatternNode *Root = Pattern.getSrcPattern(); 352 if (N != Root) { // Not the root of the pattern. 353 // If there is a node between the root and this node, then we definitely 354 // need to emit the check. 355 bool NeedCheck = !Root->hasChild(N); 356 357 // If it *is* an immediate child of the root, we can still need a check if 358 // the root SDNode has multiple inputs. For us, this means that it is an 359 // intrinsic, has multiple operands, or has other inputs like chain or 360 // flag). 361 if (!NeedCheck) { 362 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator()); 363 NeedCheck = 364 Root->getOperator() == CGP.get_intrinsic_void_sdnode() || 365 Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() || 366 Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() || 367 PInfo.getNumOperands() > 1 || 368 PInfo.hasProperty(SDNPHasChain) || 369 PInfo.hasProperty(SDNPInFlag) || 370 PInfo.hasProperty(SDNPOptInFlag); 371 } 372 373 if (NeedCheck) 374 AddMatcher(new CheckFoldableChainNodeMatcher()); 375 } 376 } 377 378 // If this node has an output flag and isn't the root, remember it. 379 if (N->NodeHasProperty(SDNPOutFlag, CGP) && 380 N != Pattern.getSrcPattern()) { 381 // TODO: This redundantly records nodes with both flags and chains. 382 383 // Record the node and remember it in our chained nodes list. 384 AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() + 385 "' flag output node", 386 NextRecordedOperandNo)); 387 // Remember all of the nodes with output flags our pattern will match. 388 MatchedFlagResultNodes.push_back(NextRecordedOperandNo++); 389 } 390 391 // If this node is known to have an input flag or if it *might* have an input 392 // flag, capture it as the flag input of the pattern. 393 if (N->NodeHasProperty(SDNPOptInFlag, CGP) || 394 N->NodeHasProperty(SDNPInFlag, CGP)) 395 AddMatcher(new CaptureFlagInputMatcher()); 396 397 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) { 398 // Get the code suitable for matching this child. Move to the child, check 399 // it then move back to the parent. 400 AddMatcher(new MoveChildMatcher(OpNo)); 401 EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i)); 402 AddMatcher(new MoveParentMatcher()); 403 } 404} 405 406 407void MatcherGen::EmitMatchCode(const TreePatternNode *N, 408 TreePatternNode *NodeNoTypes) { 409 // If N and NodeNoTypes don't agree on a type, then this is a case where we 410 // need to do a type check. Emit the check, apply the tyep to NodeNoTypes and 411 // reinfer any correlated types. 412 SmallVector<unsigned, 2> ResultsToTypeCheck; 413 414 for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) { 415 if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue; 416 NodeNoTypes->setType(i, N->getExtType(i)); 417 InferPossibleTypes(); 418 ResultsToTypeCheck.push_back(i); 419 } 420 421 // If this node has a name associated with it, capture it in VariableMap. If 422 // we already saw this in the pattern, emit code to verify dagness. 423 if (!N->getName().empty()) { 424 unsigned &VarMapEntry = VariableMap[N->getName()]; 425 if (VarMapEntry == 0) { 426 // If it is a named node, we must emit a 'Record' opcode. 427 AddMatcher(new RecordMatcher("$" + N->getName(), NextRecordedOperandNo)); 428 VarMapEntry = ++NextRecordedOperandNo; 429 } else { 430 // If we get here, this is a second reference to a specific name. Since 431 // we already have checked that the first reference is valid, we don't 432 // have to recursively match it, just check that it's the same as the 433 // previously named thing. 434 AddMatcher(new CheckSameMatcher(VarMapEntry-1)); 435 return; 436 } 437 } 438 439 if (N->isLeaf()) 440 EmitLeafMatchCode(N); 441 else 442 EmitOperatorMatchCode(N, NodeNoTypes); 443 444 // If there are node predicates for this node, generate their checks. 445 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i) 446 AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i])); 447 448 for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i) 449 AddMatcher(new CheckTypeMatcher(N->getType(ResultsToTypeCheck[i]), 450 ResultsToTypeCheck[i])); 451} 452 453/// EmitMatcherCode - Generate the code that matches the predicate of this 454/// pattern for the specified Variant. If the variant is invalid this returns 455/// true and does not generate code, if it is valid, it returns false. 456bool MatcherGen::EmitMatcherCode(unsigned Variant) { 457 // If the root of the pattern is a ComplexPattern and if it is specified to 458 // match some number of root opcodes, these are considered to be our variants. 459 // Depending on which variant we're generating code for, emit the root opcode 460 // check. 461 if (const ComplexPattern *CP = 462 Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) { 463 const std::vector<Record*> &OpNodes = CP->getRootNodes(); 464 assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match"); 465 if (Variant >= OpNodes.size()) return true; 466 467 AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant]))); 468 } else { 469 if (Variant != 0) return true; 470 } 471 472 // Emit the matcher for the pattern structure and types. 473 EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes); 474 475 // If the pattern has a predicate on it (e.g. only enabled when a subtarget 476 // feature is around, do the check). 477 if (!Pattern.getPredicateCheck().empty()) 478 AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck())); 479 480 // Now that we've completed the structural type match, emit any ComplexPattern 481 // checks (e.g. addrmode matches). We emit this after the structural match 482 // because they are generally more expensive to evaluate and more difficult to 483 // factor. 484 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) { 485 const TreePatternNode *N = MatchedComplexPatterns[i].first; 486 487 // Remember where the results of this match get stuck. 488 MatchedComplexPatterns[i].second = NextRecordedOperandNo; 489 490 // Get the slot we recorded the value in from the name on the node. 491 unsigned RecNodeEntry = VariableMap[N->getName()]; 492 assert(!N->getName().empty() && RecNodeEntry && 493 "Complex pattern should have a name and slot"); 494 --RecNodeEntry; // Entries in VariableMap are biased. 495 496 const ComplexPattern &CP = 497 CGP.getComplexPattern(((DefInit*)N->getLeafValue())->getDef()); 498 499 // Emit a CheckComplexPat operation, which does the match (aborting if it 500 // fails) and pushes the matched operands onto the recorded nodes list. 501 AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry, 502 N->getName(), NextRecordedOperandNo)); 503 504 // Record the right number of operands. 505 NextRecordedOperandNo += CP.getNumOperands(); 506 if (CP.hasProperty(SDNPHasChain)) { 507 // If the complex pattern has a chain, then we need to keep track of the 508 // fact that we just recorded a chain input. The chain input will be 509 // matched as the last operand of the predicate if it was successful. 510 ++NextRecordedOperandNo; // Chained node operand. 511 512 // It is the last operand recorded. 513 assert(NextRecordedOperandNo > 1 && 514 "Should have recorded input/result chains at least!"); 515 MatchedChainNodes.push_back(NextRecordedOperandNo-1); 516 } 517 518 // TODO: Complex patterns can't have output flags, if they did, we'd want 519 // to record them. 520 } 521 522 return false; 523} 524 525 526//===----------------------------------------------------------------------===// 527// Node Result Generation 528//===----------------------------------------------------------------------===// 529 530void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N, 531 SmallVectorImpl<unsigned> &ResultOps){ 532 assert(!N->getName().empty() && "Operand not named!"); 533 534 // A reference to a complex pattern gets all of the results of the complex 535 // pattern's match. 536 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) { 537 unsigned SlotNo = 0; 538 for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) 539 if (MatchedComplexPatterns[i].first->getName() == N->getName()) { 540 SlotNo = MatchedComplexPatterns[i].second; 541 break; 542 } 543 assert(SlotNo != 0 && "Didn't get a slot number assigned?"); 544 545 // The first slot entry is the node itself, the subsequent entries are the 546 // matched values. 547 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) 548 ResultOps.push_back(SlotNo+i); 549 return; 550 } 551 552 unsigned SlotNo = getNamedArgumentSlot(N->getName()); 553 554 // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target 555 // version of the immediate so that it doesn't get selected due to some other 556 // node use. 557 if (!N->isLeaf()) { 558 StringRef OperatorName = N->getOperator()->getName(); 559 if (OperatorName == "imm" || OperatorName == "fpimm") { 560 AddMatcher(new EmitConvertToTargetMatcher(SlotNo)); 561 ResultOps.push_back(NextRecordedOperandNo++); 562 return; 563 } 564 } 565 566 ResultOps.push_back(SlotNo); 567} 568 569void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N, 570 SmallVectorImpl<unsigned> &ResultOps) { 571 assert(N->isLeaf() && "Must be a leaf"); 572 573 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) { 574 AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getType(0))); 575 ResultOps.push_back(NextRecordedOperandNo++); 576 return; 577 } 578 579 // If this is an explicit register reference, handle it. 580 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) { 581 if (DI->getDef()->isSubClassOf("Register")) { 582 AddMatcher(new EmitRegisterMatcher(DI->getDef(), N->getType(0))); 583 ResultOps.push_back(NextRecordedOperandNo++); 584 return; 585 } 586 587 if (DI->getDef()->getName() == "zero_reg") { 588 AddMatcher(new EmitRegisterMatcher(0, N->getType(0))); 589 ResultOps.push_back(NextRecordedOperandNo++); 590 return; 591 } 592 593 // Handle a reference to a register class. This is used 594 // in COPY_TO_SUBREG instructions. 595 if (DI->getDef()->isSubClassOf("RegisterClass")) { 596 std::string Value = getQualifiedName(DI->getDef()) + "RegClassID"; 597 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32)); 598 ResultOps.push_back(NextRecordedOperandNo++); 599 return; 600 } 601 602 // Handle a subregister index. This is used for INSERT_SUBREG etc. 603 if (DI->getDef()->isSubClassOf("SubRegIndex")) { 604 std::string Value = getQualifiedName(DI->getDef()); 605 AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32)); 606 ResultOps.push_back(NextRecordedOperandNo++); 607 return; 608 } 609 } 610 611 errs() << "unhandled leaf node: \n"; 612 N->dump(); 613} 614 615/// GetInstPatternNode - Get the pattern for an instruction. 616/// 617const TreePatternNode *MatcherGen:: 618GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) { 619 const TreePattern *InstPat = Inst.getPattern(); 620 621 // FIXME2?: Assume actual pattern comes before "implicit". 622 TreePatternNode *InstPatNode; 623 if (InstPat) 624 InstPatNode = InstPat->getTree(0); 625 else if (/*isRoot*/ N == Pattern.getDstPattern()) 626 InstPatNode = Pattern.getSrcPattern(); 627 else 628 return 0; 629 630 if (InstPatNode && !InstPatNode->isLeaf() && 631 InstPatNode->getOperator()->getName() == "set") 632 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1); 633 634 return InstPatNode; 635} 636 637void MatcherGen:: 638EmitResultInstructionAsOperand(const TreePatternNode *N, 639 SmallVectorImpl<unsigned> &OutputOps) { 640 Record *Op = N->getOperator(); 641 const CodeGenTarget &CGT = CGP.getTargetInfo(); 642 CodeGenInstruction &II = CGT.getInstruction(Op); 643 const DAGInstruction &Inst = CGP.getInstruction(Op); 644 645 // If we can, get the pattern for the instruction we're generating. We derive 646 // a variety of information from this pattern, such as whether it has a chain. 647 // 648 // FIXME2: This is extremely dubious for several reasons, not the least of 649 // which it gives special status to instructions with patterns that Pat<> 650 // nodes can't duplicate. 651 const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N); 652 653 // NodeHasChain - Whether the instruction node we're creating takes chains. 654 bool NodeHasChain = InstPatNode && 655 InstPatNode->TreeHasProperty(SDNPHasChain, CGP); 656 657 bool isRoot = N == Pattern.getDstPattern(); 658 659 // TreeHasOutFlag - True if this tree has a flag. 660 bool TreeHasInFlag = false, TreeHasOutFlag = false; 661 if (isRoot) { 662 const TreePatternNode *SrcPat = Pattern.getSrcPattern(); 663 TreeHasInFlag = SrcPat->TreeHasProperty(SDNPOptInFlag, CGP) || 664 SrcPat->TreeHasProperty(SDNPInFlag, CGP); 665 666 // FIXME2: this is checking the entire pattern, not just the node in 667 // question, doing this just for the root seems like a total hack. 668 TreeHasOutFlag = SrcPat->TreeHasProperty(SDNPOutFlag, CGP); 669 } 670 671 // NumResults - This is the number of results produced by the instruction in 672 // the "outs" list. 673 unsigned NumResults = Inst.getNumResults(); 674 675 // Loop over all of the operands of the instruction pattern, emitting code 676 // to fill them all in. The node 'N' usually has number children equal to 677 // the number of input operands of the instruction. However, in cases 678 // where there are predicate operands for an instruction, we need to fill 679 // in the 'execute always' values. Match up the node operands to the 680 // instruction operands to do this. 681 SmallVector<unsigned, 8> InstOps; 682 for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.OperandList.size(); 683 InstOpNo != e; ++InstOpNo) { 684 685 // Determine what to emit for this operand. 686 Record *OperandNode = II.OperandList[InstOpNo].Rec; 687 if ((OperandNode->isSubClassOf("PredicateOperand") || 688 OperandNode->isSubClassOf("OptionalDefOperand")) && 689 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) { 690 // This is a predicate or optional def operand; emit the 691 // 'default ops' operands. 692 const DAGDefaultOperand &DefaultOp 693 = CGP.getDefaultOperand(OperandNode); 694 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) 695 EmitResultOperand(DefaultOp.DefaultOps[i], InstOps); 696 continue; 697 } 698 699 const TreePatternNode *Child = N->getChild(ChildNo); 700 701 // Otherwise this is a normal operand or a predicate operand without 702 // 'execute always'; emit it. 703 unsigned BeforeAddingNumOps = InstOps.size(); 704 EmitResultOperand(Child, InstOps); 705 assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands"); 706 707 // If the operand is an instruction and it produced multiple results, just 708 // take the first one. 709 if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction")) 710 InstOps.resize(BeforeAddingNumOps+1); 711 712 ++ChildNo; 713 } 714 715 // If this node has an input flag or explicitly specified input physregs, we 716 // need to add chained and flagged copyfromreg nodes and materialize the flag 717 // input. 718 if (isRoot && !PhysRegInputs.empty()) { 719 // Emit all of the CopyToReg nodes for the input physical registers. These 720 // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src). 721 for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i) 722 AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second, 723 PhysRegInputs[i].first)); 724 // Even if the node has no other flag inputs, the resultant node must be 725 // flagged to the CopyFromReg nodes we just generated. 726 TreeHasInFlag = true; 727 } 728 729 // Result order: node results, chain, flags 730 731 // Determine the result types. 732 SmallVector<MVT::SimpleValueType, 4> ResultVTs; 733 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) 734 ResultVTs.push_back(N->getType(i)); 735 736 // If this is the root instruction of a pattern that has physical registers in 737 // its result pattern, add output VTs for them. For example, X86 has: 738 // (set AL, (mul ...)) 739 // This also handles implicit results like: 740 // (implicit EFLAGS) 741 if (isRoot && !Pattern.getDstRegs().empty()) { 742 // If the root came from an implicit def in the instruction handling stuff, 743 // don't re-add it. 744 Record *HandledReg = 0; 745 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other) 746 HandledReg = II.ImplicitDefs[0]; 747 748 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) { 749 Record *Reg = Pattern.getDstRegs()[i]; 750 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue; 751 ResultVTs.push_back(getRegisterValueType(Reg, CGT)); 752 } 753 } 754 755 // If this is the root of the pattern and the pattern we're matching includes 756 // a node that is variadic, mark the generated node as variadic so that it 757 // gets the excess operands from the input DAG. 758 int NumFixedArityOperands = -1; 759 if (isRoot && 760 (Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP))) 761 NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren(); 762 763 // If this is the root node and any of the nodes matched nodes in the input 764 // pattern have MemRefs in them, have the interpreter collect them and plop 765 // them onto this node. 766 // 767 // FIXME3: This is actively incorrect for result patterns where the root of 768 // the pattern is not the memory reference and is also incorrect when the 769 // result pattern has multiple memory-referencing instructions. For example, 770 // in the X86 backend, this pattern causes the memrefs to get attached to the 771 // CVTSS2SDrr instead of the MOVSSrm: 772 // 773 // def : Pat<(extloadf32 addr:$src), 774 // (CVTSS2SDrr (MOVSSrm addr:$src))>; 775 // 776 bool NodeHasMemRefs = 777 isRoot && Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP); 778 779 assert((!ResultVTs.empty() || TreeHasOutFlag || NodeHasChain) && 780 "Node has no result"); 781 782 AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(), 783 ResultVTs.data(), ResultVTs.size(), 784 InstOps.data(), InstOps.size(), 785 NodeHasChain, TreeHasInFlag, TreeHasOutFlag, 786 NodeHasMemRefs, NumFixedArityOperands, 787 NextRecordedOperandNo)); 788 789 // The non-chain and non-flag results of the newly emitted node get recorded. 790 for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) { 791 if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Flag) break; 792 OutputOps.push_back(NextRecordedOperandNo++); 793 } 794} 795 796void MatcherGen:: 797EmitResultSDNodeXFormAsOperand(const TreePatternNode *N, 798 SmallVectorImpl<unsigned> &ResultOps) { 799 assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?"); 800 801 // Emit the operand. 802 SmallVector<unsigned, 8> InputOps; 803 804 // FIXME2: Could easily generalize this to support multiple inputs and outputs 805 // to the SDNodeXForm. For now we just support one input and one output like 806 // the old instruction selector. 807 assert(N->getNumChildren() == 1); 808 EmitResultOperand(N->getChild(0), InputOps); 809 810 // The input currently must have produced exactly one result. 811 assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm"); 812 813 AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator())); 814 ResultOps.push_back(NextRecordedOperandNo++); 815} 816 817void MatcherGen::EmitResultOperand(const TreePatternNode *N, 818 SmallVectorImpl<unsigned> &ResultOps) { 819 // This is something selected from the pattern we matched. 820 if (!N->getName().empty()) 821 return EmitResultOfNamedOperand(N, ResultOps); 822 823 if (N->isLeaf()) 824 return EmitResultLeafAsOperand(N, ResultOps); 825 826 Record *OpRec = N->getOperator(); 827 if (OpRec->isSubClassOf("Instruction")) 828 return EmitResultInstructionAsOperand(N, ResultOps); 829 if (OpRec->isSubClassOf("SDNodeXForm")) 830 return EmitResultSDNodeXFormAsOperand(N, ResultOps); 831 errs() << "Unknown result node to emit code for: " << *N << '\n'; 832 throw std::string("Unknown node in result pattern!"); 833} 834 835void MatcherGen::EmitResultCode() { 836 // Patterns that match nodes with (potentially multiple) chain inputs have to 837 // merge them together into a token factor. This informs the generated code 838 // what all the chained nodes are. 839 if (!MatchedChainNodes.empty()) 840 AddMatcher(new EmitMergeInputChainsMatcher 841 (MatchedChainNodes.data(), MatchedChainNodes.size())); 842 843 // Codegen the root of the result pattern, capturing the resulting values. 844 SmallVector<unsigned, 8> Ops; 845 EmitResultOperand(Pattern.getDstPattern(), Ops); 846 847 // At this point, we have however many values the result pattern produces. 848 // However, the input pattern might not need all of these. If there are 849 // excess values at the end (such as implicit defs of condition codes etc) 850 // just lop them off. This doesn't need to worry about flags or chains, just 851 // explicit results. 852 // 853 unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes(); 854 855 // If the pattern also has (implicit) results, count them as well. 856 if (!Pattern.getDstRegs().empty()) { 857 // If the root came from an implicit def in the instruction handling stuff, 858 // don't re-add it. 859 Record *HandledReg = 0; 860 const TreePatternNode *DstPat = Pattern.getDstPattern(); 861 if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){ 862 const CodeGenTarget &CGT = CGP.getTargetInfo(); 863 CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator()); 864 865 if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other) 866 HandledReg = II.ImplicitDefs[0]; 867 } 868 869 for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) { 870 Record *Reg = Pattern.getDstRegs()[i]; 871 if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue; 872 ++NumSrcResults; 873 } 874 } 875 876 assert(Ops.size() >= NumSrcResults && "Didn't provide enough results"); 877 Ops.resize(NumSrcResults); 878 879 // If the matched pattern covers nodes which define a flag result, emit a node 880 // that tells the matcher about them so that it can update their results. 881 if (!MatchedFlagResultNodes.empty()) 882 AddMatcher(new MarkFlagResultsMatcher(MatchedFlagResultNodes.data(), 883 MatchedFlagResultNodes.size())); 884 885 AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern)); 886} 887 888 889/// ConvertPatternToMatcher - Create the matcher for the specified pattern with 890/// the specified variant. If the variant number is invalid, this returns null. 891Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern, 892 unsigned Variant, 893 const CodeGenDAGPatterns &CGP) { 894 MatcherGen Gen(Pattern, CGP); 895 896 // Generate the code for the matcher. 897 if (Gen.EmitMatcherCode(Variant)) 898 return 0; 899 900 // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence. 901 // FIXME2: Split result code out to another table, and make the matcher end 902 // with an "Emit <index>" command. This allows result generation stuff to be 903 // shared and factored? 904 905 // If the match succeeds, then we generate Pattern. 906 Gen.EmitResultCode(); 907 908 // Unconditional match. 909 return Gen.GetMatcher(); 910} 911