1 //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===// 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 CodeGenDAGPatterns class, which is used to read and 11 // represent the patterns present in a .td file for instructions. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CodeGenDAGPatterns.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallString.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/ADT/Twine.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/ErrorHandling.h" 22 #include "llvm/TableGen/Error.h" 23 #include "llvm/TableGen/Record.h" 24 #include <algorithm> 25 #include <cstdio> 26 #include <set> 27 using namespace llvm; 28 29 #define DEBUG_TYPE "dag-patterns" 30 31 //===----------------------------------------------------------------------===// 32 // EEVT::TypeSet Implementation 33 //===----------------------------------------------------------------------===// 34 35 static inline bool isInteger(MVT::SimpleValueType VT) { 36 return MVT(VT).isInteger(); 37 } 38 static inline bool isFloatingPoint(MVT::SimpleValueType VT) { 39 return MVT(VT).isFloatingPoint(); 40 } 41 static inline bool isVector(MVT::SimpleValueType VT) { 42 return MVT(VT).isVector(); 43 } 44 static inline bool isScalar(MVT::SimpleValueType VT) { 45 return !MVT(VT).isVector(); 46 } 47 48 EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) { 49 if (VT == MVT::iAny) 50 EnforceInteger(TP); 51 else if (VT == MVT::fAny) 52 EnforceFloatingPoint(TP); 53 else if (VT == MVT::vAny) 54 EnforceVector(TP); 55 else { 56 assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR || 57 VT == MVT::iPTRAny || VT == MVT::Any) && "Not a concrete type!"); 58 TypeVec.push_back(VT); 59 } 60 } 61 62 63 EEVT::TypeSet::TypeSet(ArrayRef<MVT::SimpleValueType> VTList) { 64 assert(!VTList.empty() && "empty list?"); 65 TypeVec.append(VTList.begin(), VTList.end()); 66 67 if (!VTList.empty()) 68 assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny && 69 VTList[0] != MVT::fAny); 70 71 // Verify no duplicates. 72 array_pod_sort(TypeVec.begin(), TypeVec.end()); 73 assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end()); 74 } 75 76 /// FillWithPossibleTypes - Set to all legal types and return true, only valid 77 /// on completely unknown type sets. 78 bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP, 79 bool (*Pred)(MVT::SimpleValueType), 80 const char *PredicateName) { 81 assert(isCompletelyUnknown()); 82 ArrayRef<MVT::SimpleValueType> LegalTypes = 83 TP.getDAGPatterns().getTargetInfo().getLegalValueTypes(); 84 85 if (TP.hasError()) 86 return false; 87 88 for (MVT::SimpleValueType VT : LegalTypes) 89 if (!Pred || Pred(VT)) 90 TypeVec.push_back(VT); 91 92 // If we have nothing that matches the predicate, bail out. 93 if (TypeVec.empty()) { 94 TP.error("Type inference contradiction found, no " + 95 std::string(PredicateName) + " types found"); 96 return false; 97 } 98 // No need to sort with one element. 99 if (TypeVec.size() == 1) return true; 100 101 // Remove duplicates. 102 array_pod_sort(TypeVec.begin(), TypeVec.end()); 103 TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end()); 104 105 return true; 106 } 107 108 /// hasIntegerTypes - Return true if this TypeSet contains iAny or an 109 /// integer value type. 110 bool EEVT::TypeSet::hasIntegerTypes() const { 111 return any_of(TypeVec, isInteger); 112 } 113 114 /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or 115 /// a floating point value type. 116 bool EEVT::TypeSet::hasFloatingPointTypes() const { 117 return any_of(TypeVec, isFloatingPoint); 118 } 119 120 /// hasScalarTypes - Return true if this TypeSet contains a scalar value type. 121 bool EEVT::TypeSet::hasScalarTypes() const { 122 return any_of(TypeVec, isScalar); 123 } 124 125 /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector 126 /// value type. 127 bool EEVT::TypeSet::hasVectorTypes() const { 128 return any_of(TypeVec, isVector); 129 } 130 131 132 std::string EEVT::TypeSet::getName() const { 133 if (TypeVec.empty()) return "<empty>"; 134 135 std::string Result; 136 137 for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) { 138 std::string VTName = llvm::getEnumName(TypeVec[i]); 139 // Strip off MVT:: prefix if present. 140 if (VTName.substr(0,5) == "MVT::") 141 VTName = VTName.substr(5); 142 if (i) Result += ':'; 143 Result += VTName; 144 } 145 146 if (TypeVec.size() == 1) 147 return Result; 148 return "{" + Result + "}"; 149 } 150 151 /// MergeInTypeInfo - This merges in type information from the specified 152 /// argument. If 'this' changes, it returns true. If the two types are 153 /// contradictory (e.g. merge f32 into i32) then this flags an error. 154 bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){ 155 if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError()) 156 return false; 157 158 if (isCompletelyUnknown()) { 159 *this = InVT; 160 return true; 161 } 162 163 assert(!TypeVec.empty() && !InVT.TypeVec.empty() && "No unknowns"); 164 165 // Handle the abstract cases, seeing if we can resolve them better. 166 switch (TypeVec[0]) { 167 default: break; 168 case MVT::iPTR: 169 case MVT::iPTRAny: 170 if (InVT.hasIntegerTypes()) { 171 EEVT::TypeSet InCopy(InVT); 172 InCopy.EnforceInteger(TP); 173 InCopy.EnforceScalar(TP); 174 175 if (InCopy.isConcrete()) { 176 // If the RHS has one integer type, upgrade iPTR to i32. 177 TypeVec[0] = InVT.TypeVec[0]; 178 return true; 179 } 180 181 // If the input has multiple scalar integers, this doesn't add any info. 182 if (!InCopy.isCompletelyUnknown()) 183 return false; 184 } 185 break; 186 } 187 188 // If the input constraint is iAny/iPTR and this is an integer type list, 189 // remove non-integer types from the list. 190 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) && 191 hasIntegerTypes()) { 192 bool MadeChange = EnforceInteger(TP); 193 194 // If we're merging in iPTR/iPTRAny and the node currently has a list of 195 // multiple different integer types, replace them with a single iPTR. 196 if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) && 197 TypeVec.size() != 1) { 198 TypeVec.assign(1, InVT.TypeVec[0]); 199 MadeChange = true; 200 } 201 202 return MadeChange; 203 } 204 205 // If this is a type list and the RHS is a typelist as well, eliminate entries 206 // from this list that aren't in the other one. 207 TypeSet InputSet(*this); 208 209 TypeVec.clear(); 210 std::set_intersection(InputSet.TypeVec.begin(), InputSet.TypeVec.end(), 211 InVT.TypeVec.begin(), InVT.TypeVec.end(), 212 std::back_inserter(TypeVec)); 213 214 // If the intersection is the same size as the original set then we're done. 215 if (TypeVec.size() == InputSet.TypeVec.size()) 216 return false; 217 218 // If we removed all of our types, we have a type contradiction. 219 if (!TypeVec.empty()) 220 return true; 221 222 // FIXME: Really want an SMLoc here! 223 TP.error("Type inference contradiction found, merging '" + 224 InVT.getName() + "' into '" + InputSet.getName() + "'"); 225 return false; 226 } 227 228 /// EnforceInteger - Remove all non-integer types from this set. 229 bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) { 230 if (TP.hasError()) 231 return false; 232 // If we know nothing, then get the full set. 233 if (TypeVec.empty()) 234 return FillWithPossibleTypes(TP, isInteger, "integer"); 235 236 if (!hasFloatingPointTypes()) 237 return false; 238 239 TypeSet InputSet(*this); 240 241 // Filter out all the fp types. 242 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isInteger))), 243 TypeVec.end()); 244 245 if (TypeVec.empty()) { 246 TP.error("Type inference contradiction found, '" + 247 InputSet.getName() + "' needs to be integer"); 248 return false; 249 } 250 return true; 251 } 252 253 /// EnforceFloatingPoint - Remove all integer types from this set. 254 bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) { 255 if (TP.hasError()) 256 return false; 257 // If we know nothing, then get the full set. 258 if (TypeVec.empty()) 259 return FillWithPossibleTypes(TP, isFloatingPoint, "floating point"); 260 261 if (!hasIntegerTypes()) 262 return false; 263 264 TypeSet InputSet(*this); 265 266 // Filter out all the integer types. 267 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isFloatingPoint))), 268 TypeVec.end()); 269 270 if (TypeVec.empty()) { 271 TP.error("Type inference contradiction found, '" + 272 InputSet.getName() + "' needs to be floating point"); 273 return false; 274 } 275 return true; 276 } 277 278 /// EnforceScalar - Remove all vector types from this. 279 bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) { 280 if (TP.hasError()) 281 return false; 282 283 // If we know nothing, then get the full set. 284 if (TypeVec.empty()) 285 return FillWithPossibleTypes(TP, isScalar, "scalar"); 286 287 if (!hasVectorTypes()) 288 return false; 289 290 TypeSet InputSet(*this); 291 292 // Filter out all the vector types. 293 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isScalar))), 294 TypeVec.end()); 295 296 if (TypeVec.empty()) { 297 TP.error("Type inference contradiction found, '" + 298 InputSet.getName() + "' needs to be scalar"); 299 return false; 300 } 301 return true; 302 } 303 304 /// EnforceVector - Remove all vector types from this. 305 bool EEVT::TypeSet::EnforceVector(TreePattern &TP) { 306 if (TP.hasError()) 307 return false; 308 309 // If we know nothing, then get the full set. 310 if (TypeVec.empty()) 311 return FillWithPossibleTypes(TP, isVector, "vector"); 312 313 TypeSet InputSet(*this); 314 bool MadeChange = false; 315 316 // Filter out all the scalar types. 317 TypeVec.erase(remove_if(TypeVec, std::not1(std::ptr_fun(isVector))), 318 TypeVec.end()); 319 320 if (TypeVec.empty()) { 321 TP.error("Type inference contradiction found, '" + 322 InputSet.getName() + "' needs to be a vector"); 323 return false; 324 } 325 return MadeChange; 326 } 327 328 329 330 /// EnforceSmallerThan - 'this' must be a smaller VT than Other. For vectors 331 /// this should be based on the element type. Update this and other based on 332 /// this information. 333 bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) { 334 if (TP.hasError()) 335 return false; 336 337 // Both operands must be integer or FP, but we don't care which. 338 bool MadeChange = false; 339 340 if (isCompletelyUnknown()) 341 MadeChange = FillWithPossibleTypes(TP); 342 343 if (Other.isCompletelyUnknown()) 344 MadeChange = Other.FillWithPossibleTypes(TP); 345 346 // If one side is known to be integer or known to be FP but the other side has 347 // no information, get at least the type integrality info in there. 348 if (!hasFloatingPointTypes()) 349 MadeChange |= Other.EnforceInteger(TP); 350 else if (!hasIntegerTypes()) 351 MadeChange |= Other.EnforceFloatingPoint(TP); 352 if (!Other.hasFloatingPointTypes()) 353 MadeChange |= EnforceInteger(TP); 354 else if (!Other.hasIntegerTypes()) 355 MadeChange |= EnforceFloatingPoint(TP); 356 357 assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() && 358 "Should have a type list now"); 359 360 // If one contains vectors but the other doesn't pull vectors out. 361 if (!hasVectorTypes()) 362 MadeChange |= Other.EnforceScalar(TP); 363 else if (!hasScalarTypes()) 364 MadeChange |= Other.EnforceVector(TP); 365 if (!Other.hasVectorTypes()) 366 MadeChange |= EnforceScalar(TP); 367 else if (!Other.hasScalarTypes()) 368 MadeChange |= EnforceVector(TP); 369 370 // This code does not currently handle nodes which have multiple types, 371 // where some types are integer, and some are fp. Assert that this is not 372 // the case. 373 assert(!(hasIntegerTypes() && hasFloatingPointTypes()) && 374 !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) && 375 "SDTCisOpSmallerThanOp does not handle mixed int/fp types!"); 376 377 if (TP.hasError()) 378 return false; 379 380 // Okay, find the smallest type from current set and remove anything the 381 // same or smaller from the other set. We need to ensure that the scalar 382 // type size is smaller than the scalar size of the smallest type. For 383 // vectors, we also need to make sure that the total size is no larger than 384 // the size of the smallest type. 385 { 386 TypeSet InputSet(Other); 387 MVT Smallest = *std::min_element(TypeVec.begin(), TypeVec.end(), 388 [](MVT A, MVT B) { 389 return A.getScalarSizeInBits() < B.getScalarSizeInBits() || 390 (A.getScalarSizeInBits() == B.getScalarSizeInBits() && 391 A.getSizeInBits() < B.getSizeInBits()); 392 }); 393 394 auto I = remove_if(Other.TypeVec, [Smallest](MVT OtherVT) { 395 // Don't compare vector and non-vector types. 396 if (OtherVT.isVector() != Smallest.isVector()) 397 return false; 398 // The getSizeInBits() check here is only needed for vectors, but is 399 // a subset of the scalar check for scalars so no need to qualify. 400 return OtherVT.getScalarSizeInBits() <= Smallest.getScalarSizeInBits() || 401 OtherVT.getSizeInBits() < Smallest.getSizeInBits(); 402 }); 403 MadeChange |= I != Other.TypeVec.end(); // If we're about to remove types. 404 Other.TypeVec.erase(I, Other.TypeVec.end()); 405 406 if (Other.TypeVec.empty()) { 407 TP.error("Type inference contradiction found, '" + InputSet.getName() + 408 "' has nothing larger than '" + getName() +"'!"); 409 return false; 410 } 411 } 412 413 // Okay, find the largest type from the other set and remove anything the 414 // same or smaller from the current set. We need to ensure that the scalar 415 // type size is larger than the scalar size of the largest type. For 416 // vectors, we also need to make sure that the total size is no smaller than 417 // the size of the largest type. 418 { 419 TypeSet InputSet(*this); 420 MVT Largest = *std::max_element(Other.TypeVec.begin(), Other.TypeVec.end(), 421 [](MVT A, MVT B) { 422 return A.getScalarSizeInBits() < B.getScalarSizeInBits() || 423 (A.getScalarSizeInBits() == B.getScalarSizeInBits() && 424 A.getSizeInBits() < B.getSizeInBits()); 425 }); 426 auto I = remove_if(TypeVec, [Largest](MVT OtherVT) { 427 // Don't compare vector and non-vector types. 428 if (OtherVT.isVector() != Largest.isVector()) 429 return false; 430 return OtherVT.getScalarSizeInBits() >= Largest.getScalarSizeInBits() || 431 OtherVT.getSizeInBits() > Largest.getSizeInBits(); 432 }); 433 MadeChange |= I != TypeVec.end(); // If we're about to remove types. 434 TypeVec.erase(I, TypeVec.end()); 435 436 if (TypeVec.empty()) { 437 TP.error("Type inference contradiction found, '" + InputSet.getName() + 438 "' has nothing smaller than '" + Other.getName() +"'!"); 439 return false; 440 } 441 } 442 443 return MadeChange; 444 } 445 446 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type 447 /// whose element is specified by VTOperand. 448 bool EEVT::TypeSet::EnforceVectorEltTypeIs(MVT::SimpleValueType VT, 449 TreePattern &TP) { 450 bool MadeChange = false; 451 452 MadeChange |= EnforceVector(TP); 453 454 TypeSet InputSet(*this); 455 456 // Filter out all the types which don't have the right element type. 457 auto I = remove_if(TypeVec, [VT](MVT VVT) { 458 return VVT.getVectorElementType().SimpleTy != VT; 459 }); 460 MadeChange |= I != TypeVec.end(); 461 TypeVec.erase(I, TypeVec.end()); 462 463 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here! 464 TP.error("Type inference contradiction found, forcing '" + 465 InputSet.getName() + "' to have a vector element of type " + 466 getEnumName(VT)); 467 return false; 468 } 469 470 return MadeChange; 471 } 472 473 /// EnforceVectorEltTypeIs - 'this' is now constrained to be a vector type 474 /// whose element is specified by VTOperand. 475 bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand, 476 TreePattern &TP) { 477 if (TP.hasError()) 478 return false; 479 480 // "This" must be a vector and "VTOperand" must be a scalar. 481 bool MadeChange = false; 482 MadeChange |= EnforceVector(TP); 483 MadeChange |= VTOperand.EnforceScalar(TP); 484 485 // If we know the vector type, it forces the scalar to agree. 486 if (isConcrete()) { 487 MVT IVT = getConcrete(); 488 IVT = IVT.getVectorElementType(); 489 return MadeChange || VTOperand.MergeInTypeInfo(IVT.SimpleTy, TP); 490 } 491 492 // If the scalar type is known, filter out vector types whose element types 493 // disagree. 494 if (!VTOperand.isConcrete()) 495 return MadeChange; 496 497 MVT::SimpleValueType VT = VTOperand.getConcrete(); 498 499 MadeChange |= EnforceVectorEltTypeIs(VT, TP); 500 501 return MadeChange; 502 } 503 504 /// EnforceVectorSubVectorTypeIs - 'this' is now constrained to be a 505 /// vector type specified by VTOperand. 506 bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand, 507 TreePattern &TP) { 508 if (TP.hasError()) 509 return false; 510 511 // "This" must be a vector and "VTOperand" must be a vector. 512 bool MadeChange = false; 513 MadeChange |= EnforceVector(TP); 514 MadeChange |= VTOperand.EnforceVector(TP); 515 516 // If one side is known to be integer or known to be FP but the other side has 517 // no information, get at least the type integrality info in there. 518 if (!hasFloatingPointTypes()) 519 MadeChange |= VTOperand.EnforceInteger(TP); 520 else if (!hasIntegerTypes()) 521 MadeChange |= VTOperand.EnforceFloatingPoint(TP); 522 if (!VTOperand.hasFloatingPointTypes()) 523 MadeChange |= EnforceInteger(TP); 524 else if (!VTOperand.hasIntegerTypes()) 525 MadeChange |= EnforceFloatingPoint(TP); 526 527 assert(!isCompletelyUnknown() && !VTOperand.isCompletelyUnknown() && 528 "Should have a type list now"); 529 530 // If we know the vector type, it forces the scalar types to agree. 531 // Also force one vector to have more elements than the other. 532 if (isConcrete()) { 533 MVT IVT = getConcrete(); 534 unsigned NumElems = IVT.getVectorNumElements(); 535 IVT = IVT.getVectorElementType(); 536 537 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP); 538 MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP); 539 540 // Only keep types that have less elements than VTOperand. 541 TypeSet InputSet(VTOperand); 542 543 auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) { 544 return VVT.getVectorNumElements() >= NumElems; 545 }); 546 MadeChange |= I != VTOperand.TypeVec.end(); 547 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end()); 548 549 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here! 550 TP.error("Type inference contradiction found, forcing '" + 551 InputSet.getName() + "' to have less vector elements than '" + 552 getName() + "'"); 553 return false; 554 } 555 } else if (VTOperand.isConcrete()) { 556 MVT IVT = VTOperand.getConcrete(); 557 unsigned NumElems = IVT.getVectorNumElements(); 558 IVT = IVT.getVectorElementType(); 559 560 EEVT::TypeSet EltTypeSet(IVT.SimpleTy, TP); 561 MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP); 562 563 // Only keep types that have more elements than 'this'. 564 TypeSet InputSet(*this); 565 566 auto I = remove_if(TypeVec, [NumElems](MVT VVT) { 567 return VVT.getVectorNumElements() <= NumElems; 568 }); 569 MadeChange |= I != TypeVec.end(); 570 TypeVec.erase(I, TypeVec.end()); 571 572 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here! 573 TP.error("Type inference contradiction found, forcing '" + 574 InputSet.getName() + "' to have more vector elements than '" + 575 VTOperand.getName() + "'"); 576 return false; 577 } 578 } 579 580 return MadeChange; 581 } 582 583 /// EnforceameNumElts - If VTOperand is a scalar, then 'this' is a scalar. If 584 /// VTOperand is a vector, then 'this' must have the same number of elements. 585 bool EEVT::TypeSet::EnforceSameNumElts(EEVT::TypeSet &VTOperand, 586 TreePattern &TP) { 587 if (TP.hasError()) 588 return false; 589 590 bool MadeChange = false; 591 592 if (isCompletelyUnknown()) 593 MadeChange = FillWithPossibleTypes(TP); 594 595 if (VTOperand.isCompletelyUnknown()) 596 MadeChange = VTOperand.FillWithPossibleTypes(TP); 597 598 // If one contains vectors but the other doesn't pull vectors out. 599 if (!hasVectorTypes()) 600 MadeChange |= VTOperand.EnforceScalar(TP); 601 else if (!hasScalarTypes()) 602 MadeChange |= VTOperand.EnforceVector(TP); 603 if (!VTOperand.hasVectorTypes()) 604 MadeChange |= EnforceScalar(TP); 605 else if (!VTOperand.hasScalarTypes()) 606 MadeChange |= EnforceVector(TP); 607 608 // If one type is a vector, make sure the other has the same element count. 609 // If this a scalar, then we are already done with the above. 610 if (isConcrete()) { 611 MVT IVT = getConcrete(); 612 if (IVT.isVector()) { 613 unsigned NumElems = IVT.getVectorNumElements(); 614 615 // Only keep types that have same elements as 'this'. 616 TypeSet InputSet(VTOperand); 617 618 auto I = remove_if(VTOperand.TypeVec, [NumElems](MVT VVT) { 619 return VVT.getVectorNumElements() != NumElems; 620 }); 621 MadeChange |= I != VTOperand.TypeVec.end(); 622 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end()); 623 624 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here! 625 TP.error("Type inference contradiction found, forcing '" + 626 InputSet.getName() + "' to have same number elements as '" + 627 getName() + "'"); 628 return false; 629 } 630 } 631 } else if (VTOperand.isConcrete()) { 632 MVT IVT = VTOperand.getConcrete(); 633 if (IVT.isVector()) { 634 unsigned NumElems = IVT.getVectorNumElements(); 635 636 // Only keep types that have same elements as VTOperand. 637 TypeSet InputSet(*this); 638 639 auto I = remove_if(TypeVec, [NumElems](MVT VVT) { 640 return VVT.getVectorNumElements() != NumElems; 641 }); 642 MadeChange |= I != TypeVec.end(); 643 TypeVec.erase(I, TypeVec.end()); 644 645 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here! 646 TP.error("Type inference contradiction found, forcing '" + 647 InputSet.getName() + "' to have same number elements than '" + 648 VTOperand.getName() + "'"); 649 return false; 650 } 651 } 652 } 653 654 return MadeChange; 655 } 656 657 /// EnforceSameSize - 'this' is now constrained to be same size as VTOperand. 658 bool EEVT::TypeSet::EnforceSameSize(EEVT::TypeSet &VTOperand, 659 TreePattern &TP) { 660 if (TP.hasError()) 661 return false; 662 663 bool MadeChange = false; 664 665 if (isCompletelyUnknown()) 666 MadeChange = FillWithPossibleTypes(TP); 667 668 if (VTOperand.isCompletelyUnknown()) 669 MadeChange = VTOperand.FillWithPossibleTypes(TP); 670 671 // If we know one of the types, it forces the other type agree. 672 if (isConcrete()) { 673 MVT IVT = getConcrete(); 674 unsigned Size = IVT.getSizeInBits(); 675 676 // Only keep types that have the same size as 'this'. 677 TypeSet InputSet(VTOperand); 678 679 auto I = remove_if(VTOperand.TypeVec, 680 [&](MVT VT) { return VT.getSizeInBits() != Size; }); 681 MadeChange |= I != VTOperand.TypeVec.end(); 682 VTOperand.TypeVec.erase(I, VTOperand.TypeVec.end()); 683 684 if (VTOperand.TypeVec.empty()) { // FIXME: Really want an SMLoc here! 685 TP.error("Type inference contradiction found, forcing '" + 686 InputSet.getName() + "' to have same size as '" + 687 getName() + "'"); 688 return false; 689 } 690 } else if (VTOperand.isConcrete()) { 691 MVT IVT = VTOperand.getConcrete(); 692 unsigned Size = IVT.getSizeInBits(); 693 694 // Only keep types that have the same size as VTOperand. 695 TypeSet InputSet(*this); 696 697 auto I = 698 remove_if(TypeVec, [&](MVT VT) { return VT.getSizeInBits() != Size; }); 699 MadeChange |= I != TypeVec.end(); 700 TypeVec.erase(I, TypeVec.end()); 701 702 if (TypeVec.empty()) { // FIXME: Really want an SMLoc here! 703 TP.error("Type inference contradiction found, forcing '" + 704 InputSet.getName() + "' to have same size as '" + 705 VTOperand.getName() + "'"); 706 return false; 707 } 708 } 709 710 return MadeChange; 711 } 712 713 //===----------------------------------------------------------------------===// 714 // Helpers for working with extended types. 715 716 /// Dependent variable map for CodeGenDAGPattern variant generation 717 typedef std::map<std::string, int> DepVarMap; 718 719 static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) { 720 if (N->isLeaf()) { 721 if (isa<DefInit>(N->getLeafValue())) 722 DepMap[N->getName()]++; 723 } else { 724 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i) 725 FindDepVarsOf(N->getChild(i), DepMap); 726 } 727 } 728 729 /// Find dependent variables within child patterns 730 static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) { 731 DepVarMap depcounts; 732 FindDepVarsOf(N, depcounts); 733 for (const std::pair<std::string, int> &Pair : depcounts) { 734 if (Pair.second > 1) 735 DepVars.insert(Pair.first); 736 } 737 } 738 739 #ifndef NDEBUG 740 /// Dump the dependent variable set: 741 static void DumpDepVars(MultipleUseVarSet &DepVars) { 742 if (DepVars.empty()) { 743 DEBUG(errs() << "<empty set>"); 744 } else { 745 DEBUG(errs() << "[ "); 746 for (const std::string &DepVar : DepVars) { 747 DEBUG(errs() << DepVar << " "); 748 } 749 DEBUG(errs() << "]"); 750 } 751 } 752 #endif 753 754 755 //===----------------------------------------------------------------------===// 756 // TreePredicateFn Implementation 757 //===----------------------------------------------------------------------===// 758 759 /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag. 760 TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) { 761 assert((getPredCode().empty() || getImmCode().empty()) && 762 ".td file corrupt: can't have a node predicate *and* an imm predicate"); 763 } 764 765 std::string TreePredicateFn::getPredCode() const { 766 return PatFragRec->getRecord()->getValueAsString("PredicateCode"); 767 } 768 769 std::string TreePredicateFn::getImmCode() const { 770 return PatFragRec->getRecord()->getValueAsString("ImmediateCode"); 771 } 772 773 774 /// isAlwaysTrue - Return true if this is a noop predicate. 775 bool TreePredicateFn::isAlwaysTrue() const { 776 return getPredCode().empty() && getImmCode().empty(); 777 } 778 779 /// Return the name to use in the generated code to reference this, this is 780 /// "Predicate_foo" if from a pattern fragment "foo". 781 std::string TreePredicateFn::getFnName() const { 782 return "Predicate_" + PatFragRec->getRecord()->getName().str(); 783 } 784 785 /// getCodeToRunOnSDNode - Return the code for the function body that 786 /// evaluates this predicate. The argument is expected to be in "Node", 787 /// not N. This handles casting and conversion to a concrete node type as 788 /// appropriate. 789 std::string TreePredicateFn::getCodeToRunOnSDNode() const { 790 // Handle immediate predicates first. 791 std::string ImmCode = getImmCode(); 792 if (!ImmCode.empty()) { 793 std::string Result = 794 " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n"; 795 return Result + ImmCode; 796 } 797 798 // Handle arbitrary node predicates. 799 assert(!getPredCode().empty() && "Don't have any predicate code!"); 800 std::string ClassName; 801 if (PatFragRec->getOnlyTree()->isLeaf()) 802 ClassName = "SDNode"; 803 else { 804 Record *Op = PatFragRec->getOnlyTree()->getOperator(); 805 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName(); 806 } 807 std::string Result; 808 if (ClassName == "SDNode") 809 Result = " SDNode *N = Node;\n"; 810 else 811 Result = " auto *N = cast<" + ClassName + ">(Node);\n"; 812 813 return Result + getPredCode(); 814 } 815 816 //===----------------------------------------------------------------------===// 817 // PatternToMatch implementation 818 // 819 820 821 /// getPatternSize - Return the 'size' of this pattern. We want to match large 822 /// patterns before small ones. This is used to determine the size of a 823 /// pattern. 824 static unsigned getPatternSize(const TreePatternNode *P, 825 const CodeGenDAGPatterns &CGP) { 826 unsigned Size = 3; // The node itself. 827 // If the root node is a ConstantSDNode, increases its size. 828 // e.g. (set R32:$dst, 0). 829 if (P->isLeaf() && isa<IntInit>(P->getLeafValue())) 830 Size += 2; 831 832 const ComplexPattern *AM = P->getComplexPatternInfo(CGP); 833 if (AM) { 834 Size += AM->getComplexity(); 835 836 // We don't want to count any children twice, so return early. 837 return Size; 838 } 839 840 // If this node has some predicate function that must match, it adds to the 841 // complexity of this node. 842 if (!P->getPredicateFns().empty()) 843 ++Size; 844 845 // Count children in the count if they are also nodes. 846 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) { 847 TreePatternNode *Child = P->getChild(i); 848 if (!Child->isLeaf() && Child->getNumTypes() && 849 Child->getType(0) != MVT::Other) 850 Size += getPatternSize(Child, CGP); 851 else if (Child->isLeaf()) { 852 if (isa<IntInit>(Child->getLeafValue())) 853 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2). 854 else if (Child->getComplexPatternInfo(CGP)) 855 Size += getPatternSize(Child, CGP); 856 else if (!Child->getPredicateFns().empty()) 857 ++Size; 858 } 859 } 860 861 return Size; 862 } 863 864 /// Compute the complexity metric for the input pattern. This roughly 865 /// corresponds to the number of nodes that are covered. 866 int PatternToMatch:: 867 getPatternComplexity(const CodeGenDAGPatterns &CGP) const { 868 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity(); 869 } 870 871 872 /// getPredicateCheck - Return a single string containing all of this 873 /// pattern's predicates concatenated with "&&" operators. 874 /// 875 std::string PatternToMatch::getPredicateCheck() const { 876 SmallVector<Record *, 4> PredicateRecs; 877 for (Init *I : Predicates->getValues()) { 878 if (DefInit *Pred = dyn_cast<DefInit>(I)) { 879 Record *Def = Pred->getDef(); 880 if (!Def->isSubClassOf("Predicate")) { 881 #ifndef NDEBUG 882 Def->dump(); 883 #endif 884 llvm_unreachable("Unknown predicate type!"); 885 } 886 PredicateRecs.push_back(Def); 887 } 888 } 889 // Sort so that different orders get canonicalized to the same string. 890 std::sort(PredicateRecs.begin(), PredicateRecs.end(), LessRecord()); 891 892 SmallString<128> PredicateCheck; 893 for (Record *Pred : PredicateRecs) { 894 if (!PredicateCheck.empty()) 895 PredicateCheck += " && "; 896 PredicateCheck += "(" + Pred->getValueAsString("CondString") + ")"; 897 } 898 899 return PredicateCheck.str(); 900 } 901 902 //===----------------------------------------------------------------------===// 903 // SDTypeConstraint implementation 904 // 905 906 SDTypeConstraint::SDTypeConstraint(Record *R) { 907 OperandNo = R->getValueAsInt("OperandNum"); 908 909 if (R->isSubClassOf("SDTCisVT")) { 910 ConstraintType = SDTCisVT; 911 x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT")); 912 if (x.SDTCisVT_Info.VT == MVT::isVoid) 913 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT"); 914 915 } else if (R->isSubClassOf("SDTCisPtrTy")) { 916 ConstraintType = SDTCisPtrTy; 917 } else if (R->isSubClassOf("SDTCisInt")) { 918 ConstraintType = SDTCisInt; 919 } else if (R->isSubClassOf("SDTCisFP")) { 920 ConstraintType = SDTCisFP; 921 } else if (R->isSubClassOf("SDTCisVec")) { 922 ConstraintType = SDTCisVec; 923 } else if (R->isSubClassOf("SDTCisSameAs")) { 924 ConstraintType = SDTCisSameAs; 925 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum"); 926 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) { 927 ConstraintType = SDTCisVTSmallerThanOp; 928 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum = 929 R->getValueAsInt("OtherOperandNum"); 930 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) { 931 ConstraintType = SDTCisOpSmallerThanOp; 932 x.SDTCisOpSmallerThanOp_Info.BigOperandNum = 933 R->getValueAsInt("BigOperandNum"); 934 } else if (R->isSubClassOf("SDTCisEltOfVec")) { 935 ConstraintType = SDTCisEltOfVec; 936 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum"); 937 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) { 938 ConstraintType = SDTCisSubVecOfVec; 939 x.SDTCisSubVecOfVec_Info.OtherOperandNum = 940 R->getValueAsInt("OtherOpNum"); 941 } else if (R->isSubClassOf("SDTCVecEltisVT")) { 942 ConstraintType = SDTCVecEltisVT; 943 x.SDTCVecEltisVT_Info.VT = getValueType(R->getValueAsDef("VT")); 944 if (MVT(x.SDTCVecEltisVT_Info.VT).isVector()) 945 PrintFatalError(R->getLoc(), "Cannot use vector type as SDTCVecEltisVT"); 946 if (!MVT(x.SDTCVecEltisVT_Info.VT).isInteger() && 947 !MVT(x.SDTCVecEltisVT_Info.VT).isFloatingPoint()) 948 PrintFatalError(R->getLoc(), "Must use integer or floating point type " 949 "as SDTCVecEltisVT"); 950 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) { 951 ConstraintType = SDTCisSameNumEltsAs; 952 x.SDTCisSameNumEltsAs_Info.OtherOperandNum = 953 R->getValueAsInt("OtherOperandNum"); 954 } else if (R->isSubClassOf("SDTCisSameSizeAs")) { 955 ConstraintType = SDTCisSameSizeAs; 956 x.SDTCisSameSizeAs_Info.OtherOperandNum = 957 R->getValueAsInt("OtherOperandNum"); 958 } else { 959 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n"); 960 } 961 } 962 963 /// getOperandNum - Return the node corresponding to operand #OpNo in tree 964 /// N, and the result number in ResNo. 965 static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N, 966 const SDNodeInfo &NodeInfo, 967 unsigned &ResNo) { 968 unsigned NumResults = NodeInfo.getNumResults(); 969 if (OpNo < NumResults) { 970 ResNo = OpNo; 971 return N; 972 } 973 974 OpNo -= NumResults; 975 976 if (OpNo >= N->getNumChildren()) { 977 std::string S; 978 raw_string_ostream OS(S); 979 OS << "Invalid operand number in type constraint " 980 << (OpNo+NumResults) << " "; 981 N->print(OS); 982 PrintFatalError(OS.str()); 983 } 984 985 return N->getChild(OpNo); 986 } 987 988 /// ApplyTypeConstraint - Given a node in a pattern, apply this type 989 /// constraint to the nodes operands. This returns true if it makes a 990 /// change, false otherwise. If a type contradiction is found, flag an error. 991 bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N, 992 const SDNodeInfo &NodeInfo, 993 TreePattern &TP) const { 994 if (TP.hasError()) 995 return false; 996 997 unsigned ResNo = 0; // The result number being referenced. 998 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo); 999 1000 switch (ConstraintType) { 1001 case SDTCisVT: 1002 // Operand must be a particular type. 1003 return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP); 1004 case SDTCisPtrTy: 1005 // Operand must be same as target pointer type. 1006 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP); 1007 case SDTCisInt: 1008 // Require it to be one of the legal integer VTs. 1009 return NodeToApply->getExtType(ResNo).EnforceInteger(TP); 1010 case SDTCisFP: 1011 // Require it to be one of the legal fp VTs. 1012 return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP); 1013 case SDTCisVec: 1014 // Require it to be one of the legal vector VTs. 1015 return NodeToApply->getExtType(ResNo).EnforceVector(TP); 1016 case SDTCisSameAs: { 1017 unsigned OResNo = 0; 1018 TreePatternNode *OtherNode = 1019 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo); 1020 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)| 1021 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP); 1022 } 1023 case SDTCisVTSmallerThanOp: { 1024 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must 1025 // have an integer type that is smaller than the VT. 1026 if (!NodeToApply->isLeaf() || 1027 !isa<DefInit>(NodeToApply->getLeafValue()) || 1028 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef() 1029 ->isSubClassOf("ValueType")) { 1030 TP.error(N->getOperator()->getName() + " expects a VT operand!"); 1031 return false; 1032 } 1033 MVT::SimpleValueType VT = 1034 getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()); 1035 1036 EEVT::TypeSet TypeListTmp(VT, TP); 1037 1038 unsigned OResNo = 0; 1039 TreePatternNode *OtherNode = 1040 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo, 1041 OResNo); 1042 1043 return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP); 1044 } 1045 case SDTCisOpSmallerThanOp: { 1046 unsigned BResNo = 0; 1047 TreePatternNode *BigOperand = 1048 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo, 1049 BResNo); 1050 return NodeToApply->getExtType(ResNo). 1051 EnforceSmallerThan(BigOperand->getExtType(BResNo), TP); 1052 } 1053 case SDTCisEltOfVec: { 1054 unsigned VResNo = 0; 1055 TreePatternNode *VecOperand = 1056 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo, 1057 VResNo); 1058 1059 // Filter vector types out of VecOperand that don't have the right element 1060 // type. 1061 return VecOperand->getExtType(VResNo). 1062 EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP); 1063 } 1064 case SDTCisSubVecOfVec: { 1065 unsigned VResNo = 0; 1066 TreePatternNode *BigVecOperand = 1067 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo, 1068 VResNo); 1069 1070 // Filter vector types out of BigVecOperand that don't have the 1071 // right subvector type. 1072 return BigVecOperand->getExtType(VResNo). 1073 EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP); 1074 } 1075 case SDTCVecEltisVT: { 1076 return NodeToApply->getExtType(ResNo). 1077 EnforceVectorEltTypeIs(x.SDTCVecEltisVT_Info.VT, TP); 1078 } 1079 case SDTCisSameNumEltsAs: { 1080 unsigned OResNo = 0; 1081 TreePatternNode *OtherNode = 1082 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum, 1083 N, NodeInfo, OResNo); 1084 return OtherNode->getExtType(OResNo). 1085 EnforceSameNumElts(NodeToApply->getExtType(ResNo), TP); 1086 } 1087 case SDTCisSameSizeAs: { 1088 unsigned OResNo = 0; 1089 TreePatternNode *OtherNode = 1090 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum, 1091 N, NodeInfo, OResNo); 1092 return OtherNode->getExtType(OResNo). 1093 EnforceSameSize(NodeToApply->getExtType(ResNo), TP); 1094 } 1095 } 1096 llvm_unreachable("Invalid ConstraintType!"); 1097 } 1098 1099 // Update the node type to match an instruction operand or result as specified 1100 // in the ins or outs lists on the instruction definition. Return true if the 1101 // type was actually changed. 1102 bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo, 1103 Record *Operand, 1104 TreePattern &TP) { 1105 // The 'unknown' operand indicates that types should be inferred from the 1106 // context. 1107 if (Operand->isSubClassOf("unknown_class")) 1108 return false; 1109 1110 // The Operand class specifies a type directly. 1111 if (Operand->isSubClassOf("Operand")) 1112 return UpdateNodeType(ResNo, getValueType(Operand->getValueAsDef("Type")), 1113 TP); 1114 1115 // PointerLikeRegClass has a type that is determined at runtime. 1116 if (Operand->isSubClassOf("PointerLikeRegClass")) 1117 return UpdateNodeType(ResNo, MVT::iPTR, TP); 1118 1119 // Both RegisterClass and RegisterOperand operands derive their types from a 1120 // register class def. 1121 Record *RC = nullptr; 1122 if (Operand->isSubClassOf("RegisterClass")) 1123 RC = Operand; 1124 else if (Operand->isSubClassOf("RegisterOperand")) 1125 RC = Operand->getValueAsDef("RegClass"); 1126 1127 assert(RC && "Unknown operand type"); 1128 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo(); 1129 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP); 1130 } 1131 1132 1133 //===----------------------------------------------------------------------===// 1134 // SDNodeInfo implementation 1135 // 1136 SDNodeInfo::SDNodeInfo(Record *R) : Def(R) { 1137 EnumName = R->getValueAsString("Opcode"); 1138 SDClassName = R->getValueAsString("SDClass"); 1139 Record *TypeProfile = R->getValueAsDef("TypeProfile"); 1140 NumResults = TypeProfile->getValueAsInt("NumResults"); 1141 NumOperands = TypeProfile->getValueAsInt("NumOperands"); 1142 1143 // Parse the properties. 1144 Properties = 0; 1145 for (Record *Property : R->getValueAsListOfDefs("Properties")) { 1146 if (Property->getName() == "SDNPCommutative") { 1147 Properties |= 1 << SDNPCommutative; 1148 } else if (Property->getName() == "SDNPAssociative") { 1149 Properties |= 1 << SDNPAssociative; 1150 } else if (Property->getName() == "SDNPHasChain") { 1151 Properties |= 1 << SDNPHasChain; 1152 } else if (Property->getName() == "SDNPOutGlue") { 1153 Properties |= 1 << SDNPOutGlue; 1154 } else if (Property->getName() == "SDNPInGlue") { 1155 Properties |= 1 << SDNPInGlue; 1156 } else if (Property->getName() == "SDNPOptInGlue") { 1157 Properties |= 1 << SDNPOptInGlue; 1158 } else if (Property->getName() == "SDNPMayStore") { 1159 Properties |= 1 << SDNPMayStore; 1160 } else if (Property->getName() == "SDNPMayLoad") { 1161 Properties |= 1 << SDNPMayLoad; 1162 } else if (Property->getName() == "SDNPSideEffect") { 1163 Properties |= 1 << SDNPSideEffect; 1164 } else if (Property->getName() == "SDNPMemOperand") { 1165 Properties |= 1 << SDNPMemOperand; 1166 } else if (Property->getName() == "SDNPVariadic") { 1167 Properties |= 1 << SDNPVariadic; 1168 } else { 1169 PrintFatalError("Unknown SD Node property '" + 1170 Property->getName() + "' on node '" + 1171 R->getName() + "'!"); 1172 } 1173 } 1174 1175 1176 // Parse the type constraints. 1177 std::vector<Record*> ConstraintList = 1178 TypeProfile->getValueAsListOfDefs("Constraints"); 1179 TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end()); 1180 } 1181 1182 /// getKnownType - If the type constraints on this node imply a fixed type 1183 /// (e.g. all stores return void, etc), then return it as an 1184 /// MVT::SimpleValueType. Otherwise, return EEVT::Other. 1185 MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const { 1186 unsigned NumResults = getNumResults(); 1187 assert(NumResults <= 1 && 1188 "We only work with nodes with zero or one result so far!"); 1189 assert(ResNo == 0 && "Only handles single result nodes so far"); 1190 1191 for (const SDTypeConstraint &Constraint : TypeConstraints) { 1192 // Make sure that this applies to the correct node result. 1193 if (Constraint.OperandNo >= NumResults) // FIXME: need value # 1194 continue; 1195 1196 switch (Constraint.ConstraintType) { 1197 default: break; 1198 case SDTypeConstraint::SDTCisVT: 1199 return Constraint.x.SDTCisVT_Info.VT; 1200 case SDTypeConstraint::SDTCisPtrTy: 1201 return MVT::iPTR; 1202 } 1203 } 1204 return MVT::Other; 1205 } 1206 1207 //===----------------------------------------------------------------------===// 1208 // TreePatternNode implementation 1209 // 1210 1211 TreePatternNode::~TreePatternNode() { 1212 #if 0 // FIXME: implement refcounted tree nodes! 1213 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) 1214 delete getChild(i); 1215 #endif 1216 } 1217 1218 static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) { 1219 if (Operator->getName() == "set" || 1220 Operator->getName() == "implicit") 1221 return 0; // All return nothing. 1222 1223 if (Operator->isSubClassOf("Intrinsic")) 1224 return CDP.getIntrinsic(Operator).IS.RetVTs.size(); 1225 1226 if (Operator->isSubClassOf("SDNode")) 1227 return CDP.getSDNodeInfo(Operator).getNumResults(); 1228 1229 if (Operator->isSubClassOf("PatFrag")) { 1230 // If we've already parsed this pattern fragment, get it. Otherwise, handle 1231 // the forward reference case where one pattern fragment references another 1232 // before it is processed. 1233 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) 1234 return PFRec->getOnlyTree()->getNumTypes(); 1235 1236 // Get the result tree. 1237 DagInit *Tree = Operator->getValueAsDag("Fragment"); 1238 Record *Op = nullptr; 1239 if (Tree) 1240 if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator())) 1241 Op = DI->getDef(); 1242 assert(Op && "Invalid Fragment"); 1243 return GetNumNodeResults(Op, CDP); 1244 } 1245 1246 if (Operator->isSubClassOf("Instruction")) { 1247 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator); 1248 1249 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs; 1250 1251 // Subtract any defaulted outputs. 1252 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) { 1253 Record *OperandNode = InstInfo.Operands[i].Rec; 1254 1255 if (OperandNode->isSubClassOf("OperandWithDefaultOps") && 1256 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty()) 1257 --NumDefsToAdd; 1258 } 1259 1260 // Add on one implicit def if it has a resolvable type. 1261 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other) 1262 ++NumDefsToAdd; 1263 return NumDefsToAdd; 1264 } 1265 1266 if (Operator->isSubClassOf("SDNodeXForm")) 1267 return 1; // FIXME: Generalize SDNodeXForm 1268 1269 if (Operator->isSubClassOf("ValueType")) 1270 return 1; // A type-cast of one result. 1271 1272 if (Operator->isSubClassOf("ComplexPattern")) 1273 return 1; 1274 1275 errs() << *Operator; 1276 PrintFatalError("Unhandled node in GetNumNodeResults"); 1277 } 1278 1279 void TreePatternNode::print(raw_ostream &OS) const { 1280 if (isLeaf()) 1281 OS << *getLeafValue(); 1282 else 1283 OS << '(' << getOperator()->getName(); 1284 1285 for (unsigned i = 0, e = Types.size(); i != e; ++i) 1286 OS << ':' << getExtType(i).getName(); 1287 1288 if (!isLeaf()) { 1289 if (getNumChildren() != 0) { 1290 OS << " "; 1291 getChild(0)->print(OS); 1292 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) { 1293 OS << ", "; 1294 getChild(i)->print(OS); 1295 } 1296 } 1297 OS << ")"; 1298 } 1299 1300 for (const TreePredicateFn &Pred : PredicateFns) 1301 OS << "<<P:" << Pred.getFnName() << ">>"; 1302 if (TransformFn) 1303 OS << "<<X:" << TransformFn->getName() << ">>"; 1304 if (!getName().empty()) 1305 OS << ":$" << getName(); 1306 1307 } 1308 void TreePatternNode::dump() const { 1309 print(errs()); 1310 } 1311 1312 /// isIsomorphicTo - Return true if this node is recursively 1313 /// isomorphic to the specified node. For this comparison, the node's 1314 /// entire state is considered. The assigned name is ignored, since 1315 /// nodes with differing names are considered isomorphic. However, if 1316 /// the assigned name is present in the dependent variable set, then 1317 /// the assigned name is considered significant and the node is 1318 /// isomorphic if the names match. 1319 bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N, 1320 const MultipleUseVarSet &DepVars) const { 1321 if (N == this) return true; 1322 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() || 1323 getPredicateFns() != N->getPredicateFns() || 1324 getTransformFn() != N->getTransformFn()) 1325 return false; 1326 1327 if (isLeaf()) { 1328 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) { 1329 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) { 1330 return ((DI->getDef() == NDI->getDef()) 1331 && (DepVars.find(getName()) == DepVars.end() 1332 || getName() == N->getName())); 1333 } 1334 } 1335 return getLeafValue() == N->getLeafValue(); 1336 } 1337 1338 if (N->getOperator() != getOperator() || 1339 N->getNumChildren() != getNumChildren()) return false; 1340 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) 1341 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars)) 1342 return false; 1343 return true; 1344 } 1345 1346 /// clone - Make a copy of this tree and all of its children. 1347 /// 1348 TreePatternNode *TreePatternNode::clone() const { 1349 TreePatternNode *New; 1350 if (isLeaf()) { 1351 New = new TreePatternNode(getLeafValue(), getNumTypes()); 1352 } else { 1353 std::vector<TreePatternNode*> CChildren; 1354 CChildren.reserve(Children.size()); 1355 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) 1356 CChildren.push_back(getChild(i)->clone()); 1357 New = new TreePatternNode(getOperator(), CChildren, getNumTypes()); 1358 } 1359 New->setName(getName()); 1360 New->Types = Types; 1361 New->setPredicateFns(getPredicateFns()); 1362 New->setTransformFn(getTransformFn()); 1363 return New; 1364 } 1365 1366 /// RemoveAllTypes - Recursively strip all the types of this tree. 1367 void TreePatternNode::RemoveAllTypes() { 1368 // Reset to unknown type. 1369 std::fill(Types.begin(), Types.end(), EEVT::TypeSet()); 1370 if (isLeaf()) return; 1371 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) 1372 getChild(i)->RemoveAllTypes(); 1373 } 1374 1375 1376 /// SubstituteFormalArguments - Replace the formal arguments in this tree 1377 /// with actual values specified by ArgMap. 1378 void TreePatternNode:: 1379 SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) { 1380 if (isLeaf()) return; 1381 1382 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) { 1383 TreePatternNode *Child = getChild(i); 1384 if (Child->isLeaf()) { 1385 Init *Val = Child->getLeafValue(); 1386 // Note that, when substituting into an output pattern, Val might be an 1387 // UnsetInit. 1388 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) && 1389 cast<DefInit>(Val)->getDef()->getName() == "node")) { 1390 // We found a use of a formal argument, replace it with its value. 1391 TreePatternNode *NewChild = ArgMap[Child->getName()]; 1392 assert(NewChild && "Couldn't find formal argument!"); 1393 assert((Child->getPredicateFns().empty() || 1394 NewChild->getPredicateFns() == Child->getPredicateFns()) && 1395 "Non-empty child predicate clobbered!"); 1396 setChild(i, NewChild); 1397 } 1398 } else { 1399 getChild(i)->SubstituteFormalArguments(ArgMap); 1400 } 1401 } 1402 } 1403 1404 1405 /// InlinePatternFragments - If this pattern refers to any pattern 1406 /// fragments, inline them into place, giving us a pattern without any 1407 /// PatFrag references. 1408 TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) { 1409 if (TP.hasError()) 1410 return nullptr; 1411 1412 if (isLeaf()) 1413 return this; // nothing to do. 1414 Record *Op = getOperator(); 1415 1416 if (!Op->isSubClassOf("PatFrag")) { 1417 // Just recursively inline children nodes. 1418 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) { 1419 TreePatternNode *Child = getChild(i); 1420 TreePatternNode *NewChild = Child->InlinePatternFragments(TP); 1421 1422 assert((Child->getPredicateFns().empty() || 1423 NewChild->getPredicateFns() == Child->getPredicateFns()) && 1424 "Non-empty child predicate clobbered!"); 1425 1426 setChild(i, NewChild); 1427 } 1428 return this; 1429 } 1430 1431 // Otherwise, we found a reference to a fragment. First, look up its 1432 // TreePattern record. 1433 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op); 1434 1435 // Verify that we are passing the right number of operands. 1436 if (Frag->getNumArgs() != Children.size()) { 1437 TP.error("'" + Op->getName() + "' fragment requires " + 1438 utostr(Frag->getNumArgs()) + " operands!"); 1439 return nullptr; 1440 } 1441 1442 TreePatternNode *FragTree = Frag->getOnlyTree()->clone(); 1443 1444 TreePredicateFn PredFn(Frag); 1445 if (!PredFn.isAlwaysTrue()) 1446 FragTree->addPredicateFn(PredFn); 1447 1448 // Resolve formal arguments to their actual value. 1449 if (Frag->getNumArgs()) { 1450 // Compute the map of formal to actual arguments. 1451 std::map<std::string, TreePatternNode*> ArgMap; 1452 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) 1453 ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP); 1454 1455 FragTree->SubstituteFormalArguments(ArgMap); 1456 } 1457 1458 FragTree->setName(getName()); 1459 for (unsigned i = 0, e = Types.size(); i != e; ++i) 1460 FragTree->UpdateNodeType(i, getExtType(i), TP); 1461 1462 // Transfer in the old predicates. 1463 for (const TreePredicateFn &Pred : getPredicateFns()) 1464 FragTree->addPredicateFn(Pred); 1465 1466 // Get a new copy of this fragment to stitch into here. 1467 //delete this; // FIXME: implement refcounting! 1468 1469 // The fragment we inlined could have recursive inlining that is needed. See 1470 // if there are any pattern fragments in it and inline them as needed. 1471 return FragTree->InlinePatternFragments(TP); 1472 } 1473 1474 /// getImplicitType - Check to see if the specified record has an implicit 1475 /// type which should be applied to it. This will infer the type of register 1476 /// references from the register file information, for example. 1477 /// 1478 /// When Unnamed is set, return the type of a DAG operand with no name, such as 1479 /// the F8RC register class argument in: 1480 /// 1481 /// (COPY_TO_REGCLASS GPR:$src, F8RC) 1482 /// 1483 /// When Unnamed is false, return the type of a named DAG operand such as the 1484 /// GPR:$src operand above. 1485 /// 1486 static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo, 1487 bool NotRegisters, 1488 bool Unnamed, 1489 TreePattern &TP) { 1490 // Check to see if this is a register operand. 1491 if (R->isSubClassOf("RegisterOperand")) { 1492 assert(ResNo == 0 && "Regoperand ref only has one result!"); 1493 if (NotRegisters) 1494 return EEVT::TypeSet(); // Unknown. 1495 Record *RegClass = R->getValueAsDef("RegClass"); 1496 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo(); 1497 return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes()); 1498 } 1499 1500 // Check to see if this is a register or a register class. 1501 if (R->isSubClassOf("RegisterClass")) { 1502 assert(ResNo == 0 && "Regclass ref only has one result!"); 1503 // An unnamed register class represents itself as an i32 immediate, for 1504 // example on a COPY_TO_REGCLASS instruction. 1505 if (Unnamed) 1506 return EEVT::TypeSet(MVT::i32, TP); 1507 1508 // In a named operand, the register class provides the possible set of 1509 // types. 1510 if (NotRegisters) 1511 return EEVT::TypeSet(); // Unknown. 1512 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo(); 1513 return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes()); 1514 } 1515 1516 if (R->isSubClassOf("PatFrag")) { 1517 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?"); 1518 // Pattern fragment types will be resolved when they are inlined. 1519 return EEVT::TypeSet(); // Unknown. 1520 } 1521 1522 if (R->isSubClassOf("Register")) { 1523 assert(ResNo == 0 && "Registers only produce one result!"); 1524 if (NotRegisters) 1525 return EEVT::TypeSet(); // Unknown. 1526 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo(); 1527 return EEVT::TypeSet(T.getRegisterVTs(R)); 1528 } 1529 1530 if (R->isSubClassOf("SubRegIndex")) { 1531 assert(ResNo == 0 && "SubRegisterIndices only produce one result!"); 1532 return EEVT::TypeSet(MVT::i32, TP); 1533 } 1534 1535 if (R->isSubClassOf("ValueType")) { 1536 assert(ResNo == 0 && "This node only has one result!"); 1537 // An unnamed VTSDNode represents itself as an MVT::Other immediate. 1538 // 1539 // (sext_inreg GPR:$src, i16) 1540 // ~~~ 1541 if (Unnamed) 1542 return EEVT::TypeSet(MVT::Other, TP); 1543 // With a name, the ValueType simply provides the type of the named 1544 // variable. 1545 // 1546 // (sext_inreg i32:$src, i16) 1547 // ~~~~~~~~ 1548 if (NotRegisters) 1549 return EEVT::TypeSet(); // Unknown. 1550 return EEVT::TypeSet(getValueType(R), TP); 1551 } 1552 1553 if (R->isSubClassOf("CondCode")) { 1554 assert(ResNo == 0 && "This node only has one result!"); 1555 // Using a CondCodeSDNode. 1556 return EEVT::TypeSet(MVT::Other, TP); 1557 } 1558 1559 if (R->isSubClassOf("ComplexPattern")) { 1560 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?"); 1561 if (NotRegisters) 1562 return EEVT::TypeSet(); // Unknown. 1563 return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(), 1564 TP); 1565 } 1566 if (R->isSubClassOf("PointerLikeRegClass")) { 1567 assert(ResNo == 0 && "Regclass can only have one result!"); 1568 return EEVT::TypeSet(MVT::iPTR, TP); 1569 } 1570 1571 if (R->getName() == "node" || R->getName() == "srcvalue" || 1572 R->getName() == "zero_reg") { 1573 // Placeholder. 1574 return EEVT::TypeSet(); // Unknown. 1575 } 1576 1577 if (R->isSubClassOf("Operand")) 1578 return EEVT::TypeSet(getValueType(R->getValueAsDef("Type"))); 1579 1580 TP.error("Unknown node flavor used in pattern: " + R->getName()); 1581 return EEVT::TypeSet(MVT::Other, TP); 1582 } 1583 1584 1585 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the 1586 /// CodeGenIntrinsic information for it, otherwise return a null pointer. 1587 const CodeGenIntrinsic *TreePatternNode:: 1588 getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const { 1589 if (getOperator() != CDP.get_intrinsic_void_sdnode() && 1590 getOperator() != CDP.get_intrinsic_w_chain_sdnode() && 1591 getOperator() != CDP.get_intrinsic_wo_chain_sdnode()) 1592 return nullptr; 1593 1594 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue(); 1595 return &CDP.getIntrinsicInfo(IID); 1596 } 1597 1598 /// getComplexPatternInfo - If this node corresponds to a ComplexPattern, 1599 /// return the ComplexPattern information, otherwise return null. 1600 const ComplexPattern * 1601 TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const { 1602 Record *Rec; 1603 if (isLeaf()) { 1604 DefInit *DI = dyn_cast<DefInit>(getLeafValue()); 1605 if (!DI) 1606 return nullptr; 1607 Rec = DI->getDef(); 1608 } else 1609 Rec = getOperator(); 1610 1611 if (!Rec->isSubClassOf("ComplexPattern")) 1612 return nullptr; 1613 return &CGP.getComplexPattern(Rec); 1614 } 1615 1616 unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const { 1617 // A ComplexPattern specifically declares how many results it fills in. 1618 if (const ComplexPattern *CP = getComplexPatternInfo(CGP)) 1619 return CP->getNumOperands(); 1620 1621 // If MIOperandInfo is specified, that gives the count. 1622 if (isLeaf()) { 1623 DefInit *DI = dyn_cast<DefInit>(getLeafValue()); 1624 if (DI && DI->getDef()->isSubClassOf("Operand")) { 1625 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo"); 1626 if (MIOps->getNumArgs()) 1627 return MIOps->getNumArgs(); 1628 } 1629 } 1630 1631 // Otherwise there is just one result. 1632 return 1; 1633 } 1634 1635 /// NodeHasProperty - Return true if this node has the specified property. 1636 bool TreePatternNode::NodeHasProperty(SDNP Property, 1637 const CodeGenDAGPatterns &CGP) const { 1638 if (isLeaf()) { 1639 if (const ComplexPattern *CP = getComplexPatternInfo(CGP)) 1640 return CP->hasProperty(Property); 1641 return false; 1642 } 1643 1644 Record *Operator = getOperator(); 1645 if (!Operator->isSubClassOf("SDNode")) return false; 1646 1647 return CGP.getSDNodeInfo(Operator).hasProperty(Property); 1648 } 1649 1650 1651 1652 1653 /// TreeHasProperty - Return true if any node in this tree has the specified 1654 /// property. 1655 bool TreePatternNode::TreeHasProperty(SDNP Property, 1656 const CodeGenDAGPatterns &CGP) const { 1657 if (NodeHasProperty(Property, CGP)) 1658 return true; 1659 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) 1660 if (getChild(i)->TreeHasProperty(Property, CGP)) 1661 return true; 1662 return false; 1663 } 1664 1665 /// isCommutativeIntrinsic - Return true if the node corresponds to a 1666 /// commutative intrinsic. 1667 bool 1668 TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const { 1669 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) 1670 return Int->isCommutative; 1671 return false; 1672 } 1673 1674 static bool isOperandClass(const TreePatternNode *N, StringRef Class) { 1675 if (!N->isLeaf()) 1676 return N->getOperator()->isSubClassOf(Class); 1677 1678 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue()); 1679 if (DI && DI->getDef()->isSubClassOf(Class)) 1680 return true; 1681 1682 return false; 1683 } 1684 1685 static void emitTooManyOperandsError(TreePattern &TP, 1686 StringRef InstName, 1687 unsigned Expected, 1688 unsigned Actual) { 1689 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) + 1690 " operands but expected only " + Twine(Expected) + "!"); 1691 } 1692 1693 static void emitTooFewOperandsError(TreePattern &TP, 1694 StringRef InstName, 1695 unsigned Actual) { 1696 TP.error("Instruction '" + InstName + 1697 "' expects more than the provided " + Twine(Actual) + " operands!"); 1698 } 1699 1700 /// ApplyTypeConstraints - Apply all of the type constraints relevant to 1701 /// this node and its children in the tree. This returns true if it makes a 1702 /// change, false otherwise. If a type contradiction is found, flag an error. 1703 bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) { 1704 if (TP.hasError()) 1705 return false; 1706 1707 CodeGenDAGPatterns &CDP = TP.getDAGPatterns(); 1708 if (isLeaf()) { 1709 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) { 1710 // If it's a regclass or something else known, include the type. 1711 bool MadeChange = false; 1712 for (unsigned i = 0, e = Types.size(); i != e; ++i) 1713 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i, 1714 NotRegisters, 1715 !hasName(), TP), TP); 1716 return MadeChange; 1717 } 1718 1719 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) { 1720 assert(Types.size() == 1 && "Invalid IntInit"); 1721 1722 // Int inits are always integers. :) 1723 bool MadeChange = Types[0].EnforceInteger(TP); 1724 1725 if (!Types[0].isConcrete()) 1726 return MadeChange; 1727 1728 MVT::SimpleValueType VT = getType(0); 1729 if (VT == MVT::iPTR || VT == MVT::iPTRAny) 1730 return MadeChange; 1731 1732 unsigned Size = MVT(VT).getSizeInBits(); 1733 // Make sure that the value is representable for this type. 1734 if (Size >= 32) return MadeChange; 1735 1736 // Check that the value doesn't use more bits than we have. It must either 1737 // be a sign- or zero-extended equivalent of the original. 1738 int64_t SignBitAndAbove = II->getValue() >> (Size - 1); 1739 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1) 1740 return MadeChange; 1741 1742 TP.error("Integer value '" + itostr(II->getValue()) + 1743 "' is out of range for type '" + getEnumName(getType(0)) + "'!"); 1744 return false; 1745 } 1746 return false; 1747 } 1748 1749 // special handling for set, which isn't really an SDNode. 1750 if (getOperator()->getName() == "set") { 1751 assert(getNumTypes() == 0 && "Set doesn't produce a value"); 1752 assert(getNumChildren() >= 2 && "Missing RHS of a set?"); 1753 unsigned NC = getNumChildren(); 1754 1755 TreePatternNode *SetVal = getChild(NC-1); 1756 bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters); 1757 1758 for (unsigned i = 0; i < NC-1; ++i) { 1759 TreePatternNode *Child = getChild(i); 1760 MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters); 1761 1762 // Types of operands must match. 1763 MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP); 1764 MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP); 1765 } 1766 return MadeChange; 1767 } 1768 1769 if (getOperator()->getName() == "implicit") { 1770 assert(getNumTypes() == 0 && "Node doesn't produce a value"); 1771 1772 bool MadeChange = false; 1773 for (unsigned i = 0; i < getNumChildren(); ++i) 1774 MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters); 1775 return MadeChange; 1776 } 1777 1778 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) { 1779 bool MadeChange = false; 1780 1781 // Apply the result type to the node. 1782 unsigned NumRetVTs = Int->IS.RetVTs.size(); 1783 unsigned NumParamVTs = Int->IS.ParamVTs.size(); 1784 1785 for (unsigned i = 0, e = NumRetVTs; i != e; ++i) 1786 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP); 1787 1788 if (getNumChildren() != NumParamVTs + 1) { 1789 TP.error("Intrinsic '" + Int->Name + "' expects " + 1790 utostr(NumParamVTs) + " operands, not " + 1791 utostr(getNumChildren() - 1) + " operands!"); 1792 return false; 1793 } 1794 1795 // Apply type info to the intrinsic ID. 1796 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP); 1797 1798 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) { 1799 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters); 1800 1801 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i]; 1802 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case"); 1803 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP); 1804 } 1805 return MadeChange; 1806 } 1807 1808 if (getOperator()->isSubClassOf("SDNode")) { 1809 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator()); 1810 1811 // Check that the number of operands is sane. Negative operands -> varargs. 1812 if (NI.getNumOperands() >= 0 && 1813 getNumChildren() != (unsigned)NI.getNumOperands()) { 1814 TP.error(getOperator()->getName() + " node requires exactly " + 1815 itostr(NI.getNumOperands()) + " operands!"); 1816 return false; 1817 } 1818 1819 bool MadeChange = NI.ApplyTypeConstraints(this, TP); 1820 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) 1821 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters); 1822 return MadeChange; 1823 } 1824 1825 if (getOperator()->isSubClassOf("Instruction")) { 1826 const DAGInstruction &Inst = CDP.getInstruction(getOperator()); 1827 CodeGenInstruction &InstInfo = 1828 CDP.getTargetInfo().getInstruction(getOperator()); 1829 1830 bool MadeChange = false; 1831 1832 // Apply the result types to the node, these come from the things in the 1833 // (outs) list of the instruction. 1834 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs, 1835 Inst.getNumResults()); 1836 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) 1837 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP); 1838 1839 // If the instruction has implicit defs, we apply the first one as a result. 1840 // FIXME: This sucks, it should apply all implicit defs. 1841 if (!InstInfo.ImplicitDefs.empty()) { 1842 unsigned ResNo = NumResultsToAdd; 1843 1844 // FIXME: Generalize to multiple possible types and multiple possible 1845 // ImplicitDefs. 1846 MVT::SimpleValueType VT = 1847 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()); 1848 1849 if (VT != MVT::Other) 1850 MadeChange |= UpdateNodeType(ResNo, VT, TP); 1851 } 1852 1853 // If this is an INSERT_SUBREG, constrain the source and destination VTs to 1854 // be the same. 1855 if (getOperator()->getName() == "INSERT_SUBREG") { 1856 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled"); 1857 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP); 1858 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP); 1859 } else if (getOperator()->getName() == "REG_SEQUENCE") { 1860 // We need to do extra, custom typechecking for REG_SEQUENCE since it is 1861 // variadic. 1862 1863 unsigned NChild = getNumChildren(); 1864 if (NChild < 3) { 1865 TP.error("REG_SEQUENCE requires at least 3 operands!"); 1866 return false; 1867 } 1868 1869 if (NChild % 2 == 0) { 1870 TP.error("REG_SEQUENCE requires an odd number of operands!"); 1871 return false; 1872 } 1873 1874 if (!isOperandClass(getChild(0), "RegisterClass")) { 1875 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!"); 1876 return false; 1877 } 1878 1879 for (unsigned I = 1; I < NChild; I += 2) { 1880 TreePatternNode *SubIdxChild = getChild(I + 1); 1881 if (!isOperandClass(SubIdxChild, "SubRegIndex")) { 1882 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " + 1883 itostr(I + 1) + "!"); 1884 return false; 1885 } 1886 } 1887 } 1888 1889 unsigned ChildNo = 0; 1890 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) { 1891 Record *OperandNode = Inst.getOperand(i); 1892 1893 // If the instruction expects a predicate or optional def operand, we 1894 // codegen this by setting the operand to it's default value if it has a 1895 // non-empty DefaultOps field. 1896 if (OperandNode->isSubClassOf("OperandWithDefaultOps") && 1897 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty()) 1898 continue; 1899 1900 // Verify that we didn't run out of provided operands. 1901 if (ChildNo >= getNumChildren()) { 1902 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren()); 1903 return false; 1904 } 1905 1906 TreePatternNode *Child = getChild(ChildNo++); 1907 unsigned ChildResNo = 0; // Instructions always use res #0 of their op. 1908 1909 // If the operand has sub-operands, they may be provided by distinct 1910 // child patterns, so attempt to match each sub-operand separately. 1911 if (OperandNode->isSubClassOf("Operand")) { 1912 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo"); 1913 if (unsigned NumArgs = MIOpInfo->getNumArgs()) { 1914 // But don't do that if the whole operand is being provided by 1915 // a single ComplexPattern-related Operand. 1916 1917 if (Child->getNumMIResults(CDP) < NumArgs) { 1918 // Match first sub-operand against the child we already have. 1919 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef(); 1920 MadeChange |= 1921 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP); 1922 1923 // And the remaining sub-operands against subsequent children. 1924 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) { 1925 if (ChildNo >= getNumChildren()) { 1926 emitTooFewOperandsError(TP, getOperator()->getName(), 1927 getNumChildren()); 1928 return false; 1929 } 1930 Child = getChild(ChildNo++); 1931 1932 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef(); 1933 MadeChange |= 1934 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP); 1935 } 1936 continue; 1937 } 1938 } 1939 } 1940 1941 // If we didn't match by pieces above, attempt to match the whole 1942 // operand now. 1943 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP); 1944 } 1945 1946 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) { 1947 emitTooManyOperandsError(TP, getOperator()->getName(), 1948 ChildNo, getNumChildren()); 1949 return false; 1950 } 1951 1952 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) 1953 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters); 1954 return MadeChange; 1955 } 1956 1957 if (getOperator()->isSubClassOf("ComplexPattern")) { 1958 bool MadeChange = false; 1959 1960 for (unsigned i = 0; i < getNumChildren(); ++i) 1961 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters); 1962 1963 return MadeChange; 1964 } 1965 1966 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!"); 1967 1968 // Node transforms always take one operand. 1969 if (getNumChildren() != 1) { 1970 TP.error("Node transform '" + getOperator()->getName() + 1971 "' requires one operand!"); 1972 return false; 1973 } 1974 1975 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters); 1976 1977 1978 // If either the output or input of the xform does not have exact 1979 // type info. We assume they must be the same. Otherwise, it is perfectly 1980 // legal to transform from one type to a completely different type. 1981 #if 0 1982 if (!hasTypeSet() || !getChild(0)->hasTypeSet()) { 1983 bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP); 1984 MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP); 1985 return MadeChange; 1986 } 1987 #endif 1988 return MadeChange; 1989 } 1990 1991 /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the 1992 /// RHS of a commutative operation, not the on LHS. 1993 static bool OnlyOnRHSOfCommutative(TreePatternNode *N) { 1994 if (!N->isLeaf() && N->getOperator()->getName() == "imm") 1995 return true; 1996 if (N->isLeaf() && isa<IntInit>(N->getLeafValue())) 1997 return true; 1998 return false; 1999 } 2000 2001 2002 /// canPatternMatch - If it is impossible for this pattern to match on this 2003 /// target, fill in Reason and return false. Otherwise, return true. This is 2004 /// used as a sanity check for .td files (to prevent people from writing stuff 2005 /// that can never possibly work), and to prevent the pattern permuter from 2006 /// generating stuff that is useless. 2007 bool TreePatternNode::canPatternMatch(std::string &Reason, 2008 const CodeGenDAGPatterns &CDP) { 2009 if (isLeaf()) return true; 2010 2011 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) 2012 if (!getChild(i)->canPatternMatch(Reason, CDP)) 2013 return false; 2014 2015 // If this is an intrinsic, handle cases that would make it not match. For 2016 // example, if an operand is required to be an immediate. 2017 if (getOperator()->isSubClassOf("Intrinsic")) { 2018 // TODO: 2019 return true; 2020 } 2021 2022 if (getOperator()->isSubClassOf("ComplexPattern")) 2023 return true; 2024 2025 // If this node is a commutative operator, check that the LHS isn't an 2026 // immediate. 2027 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator()); 2028 bool isCommIntrinsic = isCommutativeIntrinsic(CDP); 2029 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) { 2030 // Scan all of the operands of the node and make sure that only the last one 2031 // is a constant node, unless the RHS also is. 2032 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) { 2033 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id. 2034 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i) 2035 if (OnlyOnRHSOfCommutative(getChild(i))) { 2036 Reason="Immediate value must be on the RHS of commutative operators!"; 2037 return false; 2038 } 2039 } 2040 } 2041 2042 return true; 2043 } 2044 2045 //===----------------------------------------------------------------------===// 2046 // TreePattern implementation 2047 // 2048 2049 TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput, 2050 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp), 2051 isInputPattern(isInput), HasError(false) { 2052 for (Init *I : RawPat->getValues()) 2053 Trees.push_back(ParseTreePattern(I, "")); 2054 } 2055 2056 TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput, 2057 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp), 2058 isInputPattern(isInput), HasError(false) { 2059 Trees.push_back(ParseTreePattern(Pat, "")); 2060 } 2061 2062 TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput, 2063 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp), 2064 isInputPattern(isInput), HasError(false) { 2065 Trees.push_back(Pat); 2066 } 2067 2068 void TreePattern::error(const Twine &Msg) { 2069 if (HasError) 2070 return; 2071 dump(); 2072 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg); 2073 HasError = true; 2074 } 2075 2076 void TreePattern::ComputeNamedNodes() { 2077 for (TreePatternNode *Tree : Trees) 2078 ComputeNamedNodes(Tree); 2079 } 2080 2081 void TreePattern::ComputeNamedNodes(TreePatternNode *N) { 2082 if (!N->getName().empty()) 2083 NamedNodes[N->getName()].push_back(N); 2084 2085 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) 2086 ComputeNamedNodes(N->getChild(i)); 2087 } 2088 2089 2090 TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){ 2091 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) { 2092 Record *R = DI->getDef(); 2093 2094 // Direct reference to a leaf DagNode or PatFrag? Turn it into a 2095 // TreePatternNode of its own. For example: 2096 /// (foo GPR, imm) -> (foo GPR, (imm)) 2097 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag")) 2098 return ParseTreePattern( 2099 DagInit::get(DI, nullptr, 2100 std::vector<std::pair<Init*, StringInit*> >()), 2101 OpName); 2102 2103 // Input argument? 2104 TreePatternNode *Res = new TreePatternNode(DI, 1); 2105 if (R->getName() == "node" && !OpName.empty()) { 2106 if (OpName.empty()) 2107 error("'node' argument requires a name to match with operand list"); 2108 Args.push_back(OpName); 2109 } 2110 2111 Res->setName(OpName); 2112 return Res; 2113 } 2114 2115 // ?:$name or just $name. 2116 if (isa<UnsetInit>(TheInit)) { 2117 if (OpName.empty()) 2118 error("'?' argument requires a name to match with operand list"); 2119 TreePatternNode *Res = new TreePatternNode(TheInit, 1); 2120 Args.push_back(OpName); 2121 Res->setName(OpName); 2122 return Res; 2123 } 2124 2125 if (IntInit *II = dyn_cast<IntInit>(TheInit)) { 2126 if (!OpName.empty()) 2127 error("Constant int argument should not have a name!"); 2128 return new TreePatternNode(II, 1); 2129 } 2130 2131 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) { 2132 // Turn this into an IntInit. 2133 Init *II = BI->convertInitializerTo(IntRecTy::get()); 2134 if (!II || !isa<IntInit>(II)) 2135 error("Bits value must be constants!"); 2136 return ParseTreePattern(II, OpName); 2137 } 2138 2139 DagInit *Dag = dyn_cast<DagInit>(TheInit); 2140 if (!Dag) { 2141 TheInit->print(errs()); 2142 error("Pattern has unexpected init kind!"); 2143 } 2144 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator()); 2145 if (!OpDef) error("Pattern has unexpected operator type!"); 2146 Record *Operator = OpDef->getDef(); 2147 2148 if (Operator->isSubClassOf("ValueType")) { 2149 // If the operator is a ValueType, then this must be "type cast" of a leaf 2150 // node. 2151 if (Dag->getNumArgs() != 1) 2152 error("Type cast only takes one operand!"); 2153 2154 TreePatternNode *New = ParseTreePattern(Dag->getArg(0), 2155 Dag->getArgNameStr(0)); 2156 2157 // Apply the type cast. 2158 assert(New->getNumTypes() == 1 && "FIXME: Unhandled"); 2159 New->UpdateNodeType(0, getValueType(Operator), *this); 2160 2161 if (!OpName.empty()) 2162 error("ValueType cast should not have a name!"); 2163 return New; 2164 } 2165 2166 // Verify that this is something that makes sense for an operator. 2167 if (!Operator->isSubClassOf("PatFrag") && 2168 !Operator->isSubClassOf("SDNode") && 2169 !Operator->isSubClassOf("Instruction") && 2170 !Operator->isSubClassOf("SDNodeXForm") && 2171 !Operator->isSubClassOf("Intrinsic") && 2172 !Operator->isSubClassOf("ComplexPattern") && 2173 Operator->getName() != "set" && 2174 Operator->getName() != "implicit") 2175 error("Unrecognized node '" + Operator->getName() + "'!"); 2176 2177 // Check to see if this is something that is illegal in an input pattern. 2178 if (isInputPattern) { 2179 if (Operator->isSubClassOf("Instruction") || 2180 Operator->isSubClassOf("SDNodeXForm")) 2181 error("Cannot use '" + Operator->getName() + "' in an input pattern!"); 2182 } else { 2183 if (Operator->isSubClassOf("Intrinsic")) 2184 error("Cannot use '" + Operator->getName() + "' in an output pattern!"); 2185 2186 if (Operator->isSubClassOf("SDNode") && 2187 Operator->getName() != "imm" && 2188 Operator->getName() != "fpimm" && 2189 Operator->getName() != "tglobaltlsaddr" && 2190 Operator->getName() != "tconstpool" && 2191 Operator->getName() != "tjumptable" && 2192 Operator->getName() != "tframeindex" && 2193 Operator->getName() != "texternalsym" && 2194 Operator->getName() != "tblockaddress" && 2195 Operator->getName() != "tglobaladdr" && 2196 Operator->getName() != "bb" && 2197 Operator->getName() != "vt" && 2198 Operator->getName() != "mcsym") 2199 error("Cannot use '" + Operator->getName() + "' in an output pattern!"); 2200 } 2201 2202 std::vector<TreePatternNode*> Children; 2203 2204 // Parse all the operands. 2205 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) 2206 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i))); 2207 2208 // If the operator is an intrinsic, then this is just syntactic sugar for for 2209 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and 2210 // convert the intrinsic name to a number. 2211 if (Operator->isSubClassOf("Intrinsic")) { 2212 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator); 2213 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1; 2214 2215 // If this intrinsic returns void, it must have side-effects and thus a 2216 // chain. 2217 if (Int.IS.RetVTs.empty()) 2218 Operator = getDAGPatterns().get_intrinsic_void_sdnode(); 2219 else if (Int.ModRef != CodeGenIntrinsic::NoMem) 2220 // Has side-effects, requires chain. 2221 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode(); 2222 else // Otherwise, no chain. 2223 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode(); 2224 2225 TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1); 2226 Children.insert(Children.begin(), IIDNode); 2227 } 2228 2229 if (Operator->isSubClassOf("ComplexPattern")) { 2230 for (unsigned i = 0; i < Children.size(); ++i) { 2231 TreePatternNode *Child = Children[i]; 2232 2233 if (Child->getName().empty()) 2234 error("All arguments to a ComplexPattern must be named"); 2235 2236 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)" 2237 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern; 2238 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)". 2239 auto OperandId = std::make_pair(Operator, i); 2240 auto PrevOp = ComplexPatternOperands.find(Child->getName()); 2241 if (PrevOp != ComplexPatternOperands.end()) { 2242 if (PrevOp->getValue() != OperandId) 2243 error("All ComplexPattern operands must appear consistently: " 2244 "in the same order in just one ComplexPattern instance."); 2245 } else 2246 ComplexPatternOperands[Child->getName()] = OperandId; 2247 } 2248 } 2249 2250 unsigned NumResults = GetNumNodeResults(Operator, CDP); 2251 TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults); 2252 Result->setName(OpName); 2253 2254 if (Dag->getName()) { 2255 assert(Result->getName().empty()); 2256 Result->setName(Dag->getNameStr()); 2257 } 2258 return Result; 2259 } 2260 2261 /// SimplifyTree - See if we can simplify this tree to eliminate something that 2262 /// will never match in favor of something obvious that will. This is here 2263 /// strictly as a convenience to target authors because it allows them to write 2264 /// more type generic things and have useless type casts fold away. 2265 /// 2266 /// This returns true if any change is made. 2267 static bool SimplifyTree(TreePatternNode *&N) { 2268 if (N->isLeaf()) 2269 return false; 2270 2271 // If we have a bitconvert with a resolved type and if the source and 2272 // destination types are the same, then the bitconvert is useless, remove it. 2273 if (N->getOperator()->getName() == "bitconvert" && 2274 N->getExtType(0).isConcrete() && 2275 N->getExtType(0) == N->getChild(0)->getExtType(0) && 2276 N->getName().empty()) { 2277 N = N->getChild(0); 2278 SimplifyTree(N); 2279 return true; 2280 } 2281 2282 // Walk all children. 2283 bool MadeChange = false; 2284 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) { 2285 TreePatternNode *Child = N->getChild(i); 2286 MadeChange |= SimplifyTree(Child); 2287 N->setChild(i, Child); 2288 } 2289 return MadeChange; 2290 } 2291 2292 2293 2294 /// InferAllTypes - Infer/propagate as many types throughout the expression 2295 /// patterns as possible. Return true if all types are inferred, false 2296 /// otherwise. Flags an error if a type contradiction is found. 2297 bool TreePattern:: 2298 InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) { 2299 if (NamedNodes.empty()) 2300 ComputeNamedNodes(); 2301 2302 bool MadeChange = true; 2303 while (MadeChange) { 2304 MadeChange = false; 2305 for (TreePatternNode *Tree : Trees) { 2306 MadeChange |= Tree->ApplyTypeConstraints(*this, false); 2307 MadeChange |= SimplifyTree(Tree); 2308 } 2309 2310 // If there are constraints on our named nodes, apply them. 2311 for (auto &Entry : NamedNodes) { 2312 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second; 2313 2314 // If we have input named node types, propagate their types to the named 2315 // values here. 2316 if (InNamedTypes) { 2317 if (!InNamedTypes->count(Entry.getKey())) { 2318 error("Node '" + std::string(Entry.getKey()) + 2319 "' in output pattern but not input pattern"); 2320 return true; 2321 } 2322 2323 const SmallVectorImpl<TreePatternNode*> &InNodes = 2324 InNamedTypes->find(Entry.getKey())->second; 2325 2326 // The input types should be fully resolved by now. 2327 for (TreePatternNode *Node : Nodes) { 2328 // If this node is a register class, and it is the root of the pattern 2329 // then we're mapping something onto an input register. We allow 2330 // changing the type of the input register in this case. This allows 2331 // us to match things like: 2332 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>; 2333 if (Node == Trees[0] && Node->isLeaf()) { 2334 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue()); 2335 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") || 2336 DI->getDef()->isSubClassOf("RegisterOperand"))) 2337 continue; 2338 } 2339 2340 assert(Node->getNumTypes() == 1 && 2341 InNodes[0]->getNumTypes() == 1 && 2342 "FIXME: cannot name multiple result nodes yet"); 2343 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0), 2344 *this); 2345 } 2346 } 2347 2348 // If there are multiple nodes with the same name, they must all have the 2349 // same type. 2350 if (Entry.second.size() > 1) { 2351 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) { 2352 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1]; 2353 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 && 2354 "FIXME: cannot name multiple result nodes yet"); 2355 2356 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this); 2357 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this); 2358 } 2359 } 2360 } 2361 } 2362 2363 bool HasUnresolvedTypes = false; 2364 for (const TreePatternNode *Tree : Trees) 2365 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(); 2366 return !HasUnresolvedTypes; 2367 } 2368 2369 void TreePattern::print(raw_ostream &OS) const { 2370 OS << getRecord()->getName(); 2371 if (!Args.empty()) { 2372 OS << "(" << Args[0]; 2373 for (unsigned i = 1, e = Args.size(); i != e; ++i) 2374 OS << ", " << Args[i]; 2375 OS << ")"; 2376 } 2377 OS << ": "; 2378 2379 if (Trees.size() > 1) 2380 OS << "[\n"; 2381 for (const TreePatternNode *Tree : Trees) { 2382 OS << "\t"; 2383 Tree->print(OS); 2384 OS << "\n"; 2385 } 2386 2387 if (Trees.size() > 1) 2388 OS << "]\n"; 2389 } 2390 2391 void TreePattern::dump() const { print(errs()); } 2392 2393 //===----------------------------------------------------------------------===// 2394 // CodeGenDAGPatterns implementation 2395 // 2396 2397 CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) : 2398 Records(R), Target(R) { 2399 2400 Intrinsics = CodeGenIntrinsicTable(Records, false); 2401 TgtIntrinsics = CodeGenIntrinsicTable(Records, true); 2402 ParseNodeInfo(); 2403 ParseNodeTransforms(); 2404 ParseComplexPatterns(); 2405 ParsePatternFragments(); 2406 ParseDefaultOperands(); 2407 ParseInstructions(); 2408 ParsePatternFragments(/*OutFrags*/true); 2409 ParsePatterns(); 2410 2411 // Generate variants. For example, commutative patterns can match 2412 // multiple ways. Add them to PatternsToMatch as well. 2413 GenerateVariants(); 2414 2415 // Infer instruction flags. For example, we can detect loads, 2416 // stores, and side effects in many cases by examining an 2417 // instruction's pattern. 2418 InferInstructionFlags(); 2419 2420 // Verify that instruction flags match the patterns. 2421 VerifyInstructionFlags(); 2422 } 2423 2424 Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const { 2425 Record *N = Records.getDef(Name); 2426 if (!N || !N->isSubClassOf("SDNode")) 2427 PrintFatalError("Error getting SDNode '" + Name + "'!"); 2428 2429 return N; 2430 } 2431 2432 // Parse all of the SDNode definitions for the target, populating SDNodes. 2433 void CodeGenDAGPatterns::ParseNodeInfo() { 2434 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode"); 2435 while (!Nodes.empty()) { 2436 SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back())); 2437 Nodes.pop_back(); 2438 } 2439 2440 // Get the builtin intrinsic nodes. 2441 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void"); 2442 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain"); 2443 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain"); 2444 } 2445 2446 /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms 2447 /// map, and emit them to the file as functions. 2448 void CodeGenDAGPatterns::ParseNodeTransforms() { 2449 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm"); 2450 while (!Xforms.empty()) { 2451 Record *XFormNode = Xforms.back(); 2452 Record *SDNode = XFormNode->getValueAsDef("Opcode"); 2453 std::string Code = XFormNode->getValueAsString("XFormFunction"); 2454 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code))); 2455 2456 Xforms.pop_back(); 2457 } 2458 } 2459 2460 void CodeGenDAGPatterns::ParseComplexPatterns() { 2461 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern"); 2462 while (!AMs.empty()) { 2463 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back())); 2464 AMs.pop_back(); 2465 } 2466 } 2467 2468 2469 /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td 2470 /// file, building up the PatternFragments map. After we've collected them all, 2471 /// inline fragments together as necessary, so that there are no references left 2472 /// inside a pattern fragment to a pattern fragment. 2473 /// 2474 void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) { 2475 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag"); 2476 2477 // First step, parse all of the fragments. 2478 for (Record *Frag : Fragments) { 2479 if (OutFrags != Frag->isSubClassOf("OutPatFrag")) 2480 continue; 2481 2482 DagInit *Tree = Frag->getValueAsDag("Fragment"); 2483 TreePattern *P = 2484 (PatternFragments[Frag] = llvm::make_unique<TreePattern>( 2485 Frag, Tree, !Frag->isSubClassOf("OutPatFrag"), 2486 *this)).get(); 2487 2488 // Validate the argument list, converting it to set, to discard duplicates. 2489 std::vector<std::string> &Args = P->getArgList(); 2490 std::set<std::string> OperandsSet(Args.begin(), Args.end()); 2491 2492 if (OperandsSet.count("")) 2493 P->error("Cannot have unnamed 'node' values in pattern fragment!"); 2494 2495 // Parse the operands list. 2496 DagInit *OpsList = Frag->getValueAsDag("Operands"); 2497 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator()); 2498 // Special cases: ops == outs == ins. Different names are used to 2499 // improve readability. 2500 if (!OpsOp || 2501 (OpsOp->getDef()->getName() != "ops" && 2502 OpsOp->getDef()->getName() != "outs" && 2503 OpsOp->getDef()->getName() != "ins")) 2504 P->error("Operands list should start with '(ops ... '!"); 2505 2506 // Copy over the arguments. 2507 Args.clear(); 2508 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) { 2509 if (!isa<DefInit>(OpsList->getArg(j)) || 2510 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node") 2511 P->error("Operands list should all be 'node' values."); 2512 if (!OpsList->getArgName(j)) 2513 P->error("Operands list should have names for each operand!"); 2514 StringRef ArgNameStr = OpsList->getArgNameStr(j); 2515 if (!OperandsSet.count(ArgNameStr)) 2516 P->error("'" + ArgNameStr + 2517 "' does not occur in pattern or was multiply specified!"); 2518 OperandsSet.erase(ArgNameStr); 2519 Args.push_back(ArgNameStr); 2520 } 2521 2522 if (!OperandsSet.empty()) 2523 P->error("Operands list does not contain an entry for operand '" + 2524 *OperandsSet.begin() + "'!"); 2525 2526 // If there is a code init for this fragment, keep track of the fact that 2527 // this fragment uses it. 2528 TreePredicateFn PredFn(P); 2529 if (!PredFn.isAlwaysTrue()) 2530 P->getOnlyTree()->addPredicateFn(PredFn); 2531 2532 // If there is a node transformation corresponding to this, keep track of 2533 // it. 2534 Record *Transform = Frag->getValueAsDef("OperandTransform"); 2535 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform? 2536 P->getOnlyTree()->setTransformFn(Transform); 2537 } 2538 2539 // Now that we've parsed all of the tree fragments, do a closure on them so 2540 // that there are not references to PatFrags left inside of them. 2541 for (Record *Frag : Fragments) { 2542 if (OutFrags != Frag->isSubClassOf("OutPatFrag")) 2543 continue; 2544 2545 TreePattern &ThePat = *PatternFragments[Frag]; 2546 ThePat.InlinePatternFragments(); 2547 2548 // Infer as many types as possible. Don't worry about it if we don't infer 2549 // all of them, some may depend on the inputs of the pattern. 2550 ThePat.InferAllTypes(); 2551 ThePat.resetError(); 2552 2553 // If debugging, print out the pattern fragment result. 2554 DEBUG(ThePat.dump()); 2555 } 2556 } 2557 2558 void CodeGenDAGPatterns::ParseDefaultOperands() { 2559 std::vector<Record*> DefaultOps; 2560 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps"); 2561 2562 // Find some SDNode. 2563 assert(!SDNodes.empty() && "No SDNodes parsed?"); 2564 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first); 2565 2566 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) { 2567 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps"); 2568 2569 // Clone the DefaultInfo dag node, changing the operator from 'ops' to 2570 // SomeSDnode so that we can parse this. 2571 std::vector<std::pair<Init*, StringInit*> > Ops; 2572 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op) 2573 Ops.push_back(std::make_pair(DefaultInfo->getArg(op), 2574 DefaultInfo->getArgName(op))); 2575 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops); 2576 2577 // Create a TreePattern to parse this. 2578 TreePattern P(DefaultOps[i], DI, false, *this); 2579 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!"); 2580 2581 // Copy the operands over into a DAGDefaultOperand. 2582 DAGDefaultOperand DefaultOpInfo; 2583 2584 TreePatternNode *T = P.getTree(0); 2585 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) { 2586 TreePatternNode *TPN = T->getChild(op); 2587 while (TPN->ApplyTypeConstraints(P, false)) 2588 /* Resolve all types */; 2589 2590 if (TPN->ContainsUnresolvedType()) { 2591 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" + 2592 DefaultOps[i]->getName() + 2593 "' doesn't have a concrete type!"); 2594 } 2595 DefaultOpInfo.DefaultOps.push_back(TPN); 2596 } 2597 2598 // Insert it into the DefaultOperands map so we can find it later. 2599 DefaultOperands[DefaultOps[i]] = DefaultOpInfo; 2600 } 2601 } 2602 2603 /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an 2604 /// instruction input. Return true if this is a real use. 2605 static bool HandleUse(TreePattern *I, TreePatternNode *Pat, 2606 std::map<std::string, TreePatternNode*> &InstInputs) { 2607 // No name -> not interesting. 2608 if (Pat->getName().empty()) { 2609 if (Pat->isLeaf()) { 2610 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue()); 2611 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") || 2612 DI->getDef()->isSubClassOf("RegisterOperand"))) 2613 I->error("Input " + DI->getDef()->getName() + " must be named!"); 2614 } 2615 return false; 2616 } 2617 2618 Record *Rec; 2619 if (Pat->isLeaf()) { 2620 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue()); 2621 if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!"); 2622 Rec = DI->getDef(); 2623 } else { 2624 Rec = Pat->getOperator(); 2625 } 2626 2627 // SRCVALUE nodes are ignored. 2628 if (Rec->getName() == "srcvalue") 2629 return false; 2630 2631 TreePatternNode *&Slot = InstInputs[Pat->getName()]; 2632 if (!Slot) { 2633 Slot = Pat; 2634 return true; 2635 } 2636 Record *SlotRec; 2637 if (Slot->isLeaf()) { 2638 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef(); 2639 } else { 2640 assert(Slot->getNumChildren() == 0 && "can't be a use with children!"); 2641 SlotRec = Slot->getOperator(); 2642 } 2643 2644 // Ensure that the inputs agree if we've already seen this input. 2645 if (Rec != SlotRec) 2646 I->error("All $" + Pat->getName() + " inputs must agree with each other"); 2647 if (Slot->getExtTypes() != Pat->getExtTypes()) 2648 I->error("All $" + Pat->getName() + " inputs must agree with each other"); 2649 return true; 2650 } 2651 2652 /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is 2653 /// part of "I", the instruction), computing the set of inputs and outputs of 2654 /// the pattern. Report errors if we see anything naughty. 2655 void CodeGenDAGPatterns:: 2656 FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat, 2657 std::map<std::string, TreePatternNode*> &InstInputs, 2658 std::map<std::string, TreePatternNode*>&InstResults, 2659 std::vector<Record*> &InstImpResults) { 2660 if (Pat->isLeaf()) { 2661 bool isUse = HandleUse(I, Pat, InstInputs); 2662 if (!isUse && Pat->getTransformFn()) 2663 I->error("Cannot specify a transform function for a non-input value!"); 2664 return; 2665 } 2666 2667 if (Pat->getOperator()->getName() == "implicit") { 2668 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) { 2669 TreePatternNode *Dest = Pat->getChild(i); 2670 if (!Dest->isLeaf()) 2671 I->error("implicitly defined value should be a register!"); 2672 2673 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue()); 2674 if (!Val || !Val->getDef()->isSubClassOf("Register")) 2675 I->error("implicitly defined value should be a register!"); 2676 InstImpResults.push_back(Val->getDef()); 2677 } 2678 return; 2679 } 2680 2681 if (Pat->getOperator()->getName() != "set") { 2682 // If this is not a set, verify that the children nodes are not void typed, 2683 // and recurse. 2684 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) { 2685 if (Pat->getChild(i)->getNumTypes() == 0) 2686 I->error("Cannot have void nodes inside of patterns!"); 2687 FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults, 2688 InstImpResults); 2689 } 2690 2691 // If this is a non-leaf node with no children, treat it basically as if 2692 // it were a leaf. This handles nodes like (imm). 2693 bool isUse = HandleUse(I, Pat, InstInputs); 2694 2695 if (!isUse && Pat->getTransformFn()) 2696 I->error("Cannot specify a transform function for a non-input value!"); 2697 return; 2698 } 2699 2700 // Otherwise, this is a set, validate and collect instruction results. 2701 if (Pat->getNumChildren() == 0) 2702 I->error("set requires operands!"); 2703 2704 if (Pat->getTransformFn()) 2705 I->error("Cannot specify a transform function on a set node!"); 2706 2707 // Check the set destinations. 2708 unsigned NumDests = Pat->getNumChildren()-1; 2709 for (unsigned i = 0; i != NumDests; ++i) { 2710 TreePatternNode *Dest = Pat->getChild(i); 2711 if (!Dest->isLeaf()) 2712 I->error("set destination should be a register!"); 2713 2714 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue()); 2715 if (!Val) { 2716 I->error("set destination should be a register!"); 2717 continue; 2718 } 2719 2720 if (Val->getDef()->isSubClassOf("RegisterClass") || 2721 Val->getDef()->isSubClassOf("ValueType") || 2722 Val->getDef()->isSubClassOf("RegisterOperand") || 2723 Val->getDef()->isSubClassOf("PointerLikeRegClass")) { 2724 if (Dest->getName().empty()) 2725 I->error("set destination must have a name!"); 2726 if (InstResults.count(Dest->getName())) 2727 I->error("cannot set '" + Dest->getName() +"' multiple times"); 2728 InstResults[Dest->getName()] = Dest; 2729 } else if (Val->getDef()->isSubClassOf("Register")) { 2730 InstImpResults.push_back(Val->getDef()); 2731 } else { 2732 I->error("set destination should be a register!"); 2733 } 2734 } 2735 2736 // Verify and collect info from the computation. 2737 FindPatternInputsAndOutputs(I, Pat->getChild(NumDests), 2738 InstInputs, InstResults, InstImpResults); 2739 } 2740 2741 //===----------------------------------------------------------------------===// 2742 // Instruction Analysis 2743 //===----------------------------------------------------------------------===// 2744 2745 class InstAnalyzer { 2746 const CodeGenDAGPatterns &CDP; 2747 public: 2748 bool hasSideEffects; 2749 bool mayStore; 2750 bool mayLoad; 2751 bool isBitcast; 2752 bool isVariadic; 2753 2754 InstAnalyzer(const CodeGenDAGPatterns &cdp) 2755 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false), 2756 isBitcast(false), isVariadic(false) {} 2757 2758 void Analyze(const TreePattern *Pat) { 2759 // Assume only the first tree is the pattern. The others are clobber nodes. 2760 AnalyzeNode(Pat->getTree(0)); 2761 } 2762 2763 void Analyze(const PatternToMatch *Pat) { 2764 AnalyzeNode(Pat->getSrcPattern()); 2765 } 2766 2767 private: 2768 bool IsNodeBitcast(const TreePatternNode *N) const { 2769 if (hasSideEffects || mayLoad || mayStore || isVariadic) 2770 return false; 2771 2772 if (N->getNumChildren() != 2) 2773 return false; 2774 2775 const TreePatternNode *N0 = N->getChild(0); 2776 if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue())) 2777 return false; 2778 2779 const TreePatternNode *N1 = N->getChild(1); 2780 if (N1->isLeaf()) 2781 return false; 2782 if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf()) 2783 return false; 2784 2785 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator()); 2786 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1) 2787 return false; 2788 return OpInfo.getEnumName() == "ISD::BITCAST"; 2789 } 2790 2791 public: 2792 void AnalyzeNode(const TreePatternNode *N) { 2793 if (N->isLeaf()) { 2794 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) { 2795 Record *LeafRec = DI->getDef(); 2796 // Handle ComplexPattern leaves. 2797 if (LeafRec->isSubClassOf("ComplexPattern")) { 2798 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec); 2799 if (CP.hasProperty(SDNPMayStore)) mayStore = true; 2800 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true; 2801 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true; 2802 } 2803 } 2804 return; 2805 } 2806 2807 // Analyze children. 2808 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) 2809 AnalyzeNode(N->getChild(i)); 2810 2811 // Ignore set nodes, which are not SDNodes. 2812 if (N->getOperator()->getName() == "set") { 2813 isBitcast = IsNodeBitcast(N); 2814 return; 2815 } 2816 2817 // Notice properties of the node. 2818 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true; 2819 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true; 2820 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true; 2821 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true; 2822 2823 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) { 2824 // If this is an intrinsic, analyze it. 2825 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref) 2826 mayLoad = true;// These may load memory. 2827 2828 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod) 2829 mayStore = true;// Intrinsics that can write to memory are 'mayStore'. 2830 2831 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem) 2832 // ReadWriteMem intrinsics can have other strange effects. 2833 hasSideEffects = true; 2834 } 2835 } 2836 2837 }; 2838 2839 static bool InferFromPattern(CodeGenInstruction &InstInfo, 2840 const InstAnalyzer &PatInfo, 2841 Record *PatDef) { 2842 bool Error = false; 2843 2844 // Remember where InstInfo got its flags. 2845 if (InstInfo.hasUndefFlags()) 2846 InstInfo.InferredFrom = PatDef; 2847 2848 // Check explicitly set flags for consistency. 2849 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects && 2850 !InstInfo.hasSideEffects_Unset) { 2851 // Allow explicitly setting hasSideEffects = 1 on instructions, even when 2852 // the pattern has no side effects. That could be useful for div/rem 2853 // instructions that may trap. 2854 if (!InstInfo.hasSideEffects) { 2855 Error = true; 2856 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " + 2857 Twine(InstInfo.hasSideEffects)); 2858 } 2859 } 2860 2861 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) { 2862 Error = true; 2863 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " + 2864 Twine(InstInfo.mayStore)); 2865 } 2866 2867 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) { 2868 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads. 2869 // Some targets translate immediates to loads. 2870 if (!InstInfo.mayLoad) { 2871 Error = true; 2872 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " + 2873 Twine(InstInfo.mayLoad)); 2874 } 2875 } 2876 2877 // Transfer inferred flags. 2878 InstInfo.hasSideEffects |= PatInfo.hasSideEffects; 2879 InstInfo.mayStore |= PatInfo.mayStore; 2880 InstInfo.mayLoad |= PatInfo.mayLoad; 2881 2882 // These flags are silently added without any verification. 2883 InstInfo.isBitcast |= PatInfo.isBitcast; 2884 2885 // Don't infer isVariadic. This flag means something different on SDNodes and 2886 // instructions. For example, a CALL SDNode is variadic because it has the 2887 // call arguments as operands, but a CALL instruction is not variadic - it 2888 // has argument registers as implicit, not explicit uses. 2889 2890 return Error; 2891 } 2892 2893 /// hasNullFragReference - Return true if the DAG has any reference to the 2894 /// null_frag operator. 2895 static bool hasNullFragReference(DagInit *DI) { 2896 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator()); 2897 if (!OpDef) return false; 2898 Record *Operator = OpDef->getDef(); 2899 2900 // If this is the null fragment, return true. 2901 if (Operator->getName() == "null_frag") return true; 2902 // If any of the arguments reference the null fragment, return true. 2903 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) { 2904 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i)); 2905 if (Arg && hasNullFragReference(Arg)) 2906 return true; 2907 } 2908 2909 return false; 2910 } 2911 2912 /// hasNullFragReference - Return true if any DAG in the list references 2913 /// the null_frag operator. 2914 static bool hasNullFragReference(ListInit *LI) { 2915 for (Init *I : LI->getValues()) { 2916 DagInit *DI = dyn_cast<DagInit>(I); 2917 assert(DI && "non-dag in an instruction Pattern list?!"); 2918 if (hasNullFragReference(DI)) 2919 return true; 2920 } 2921 return false; 2922 } 2923 2924 /// Get all the instructions in a tree. 2925 static void 2926 getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) { 2927 if (Tree->isLeaf()) 2928 return; 2929 if (Tree->getOperator()->isSubClassOf("Instruction")) 2930 Instrs.push_back(Tree->getOperator()); 2931 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i) 2932 getInstructionsInTree(Tree->getChild(i), Instrs); 2933 } 2934 2935 /// Check the class of a pattern leaf node against the instruction operand it 2936 /// represents. 2937 static bool checkOperandClass(CGIOperandList::OperandInfo &OI, 2938 Record *Leaf) { 2939 if (OI.Rec == Leaf) 2940 return true; 2941 2942 // Allow direct value types to be used in instruction set patterns. 2943 // The type will be checked later. 2944 if (Leaf->isSubClassOf("ValueType")) 2945 return true; 2946 2947 // Patterns can also be ComplexPattern instances. 2948 if (Leaf->isSubClassOf("ComplexPattern")) 2949 return true; 2950 2951 return false; 2952 } 2953 2954 const DAGInstruction &CodeGenDAGPatterns::parseInstructionPattern( 2955 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) { 2956 2957 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!"); 2958 2959 // Parse the instruction. 2960 TreePattern *I = new TreePattern(CGI.TheDef, Pat, true, *this); 2961 // Inline pattern fragments into it. 2962 I->InlinePatternFragments(); 2963 2964 // Infer as many types as possible. If we cannot infer all of them, we can 2965 // never do anything with this instruction pattern: report it to the user. 2966 if (!I->InferAllTypes()) 2967 I->error("Could not infer all types in pattern!"); 2968 2969 // InstInputs - Keep track of all of the inputs of the instruction, along 2970 // with the record they are declared as. 2971 std::map<std::string, TreePatternNode*> InstInputs; 2972 2973 // InstResults - Keep track of all the virtual registers that are 'set' 2974 // in the instruction, including what reg class they are. 2975 std::map<std::string, TreePatternNode*> InstResults; 2976 2977 std::vector<Record*> InstImpResults; 2978 2979 // Verify that the top-level forms in the instruction are of void type, and 2980 // fill in the InstResults map. 2981 for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) { 2982 TreePatternNode *Pat = I->getTree(j); 2983 if (Pat->getNumTypes() != 0) { 2984 std::string Types; 2985 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) { 2986 if (k > 0) 2987 Types += ", "; 2988 Types += Pat->getExtType(k).getName(); 2989 } 2990 I->error("Top-level forms in instruction pattern should have" 2991 " void types, has types " + Types); 2992 } 2993 2994 // Find inputs and outputs, and verify the structure of the uses/defs. 2995 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults, 2996 InstImpResults); 2997 } 2998 2999 // Now that we have inputs and outputs of the pattern, inspect the operands 3000 // list for the instruction. This determines the order that operands are 3001 // added to the machine instruction the node corresponds to. 3002 unsigned NumResults = InstResults.size(); 3003 3004 // Parse the operands list from the (ops) list, validating it. 3005 assert(I->getArgList().empty() && "Args list should still be empty here!"); 3006 3007 // Check that all of the results occur first in the list. 3008 std::vector<Record*> Results; 3009 SmallVector<TreePatternNode *, 2> ResNodes; 3010 for (unsigned i = 0; i != NumResults; ++i) { 3011 if (i == CGI.Operands.size()) 3012 I->error("'" + InstResults.begin()->first + 3013 "' set but does not appear in operand list!"); 3014 const std::string &OpName = CGI.Operands[i].Name; 3015 3016 // Check that it exists in InstResults. 3017 TreePatternNode *RNode = InstResults[OpName]; 3018 if (!RNode) 3019 I->error("Operand $" + OpName + " does not exist in operand list!"); 3020 3021 ResNodes.push_back(RNode); 3022 3023 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef(); 3024 if (!R) 3025 I->error("Operand $" + OpName + " should be a set destination: all " 3026 "outputs must occur before inputs in operand list!"); 3027 3028 if (!checkOperandClass(CGI.Operands[i], R)) 3029 I->error("Operand $" + OpName + " class mismatch!"); 3030 3031 // Remember the return type. 3032 Results.push_back(CGI.Operands[i].Rec); 3033 3034 // Okay, this one checks out. 3035 InstResults.erase(OpName); 3036 } 3037 3038 // Loop over the inputs next. Make a copy of InstInputs so we can destroy 3039 // the copy while we're checking the inputs. 3040 std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs); 3041 3042 std::vector<TreePatternNode*> ResultNodeOperands; 3043 std::vector<Record*> Operands; 3044 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) { 3045 CGIOperandList::OperandInfo &Op = CGI.Operands[i]; 3046 const std::string &OpName = Op.Name; 3047 if (OpName.empty()) 3048 I->error("Operand #" + utostr(i) + " in operands list has no name!"); 3049 3050 if (!InstInputsCheck.count(OpName)) { 3051 // If this is an operand with a DefaultOps set filled in, we can ignore 3052 // this. When we codegen it, we will do so as always executed. 3053 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) { 3054 // Does it have a non-empty DefaultOps field? If so, ignore this 3055 // operand. 3056 if (!getDefaultOperand(Op.Rec).DefaultOps.empty()) 3057 continue; 3058 } 3059 I->error("Operand $" + OpName + 3060 " does not appear in the instruction pattern"); 3061 } 3062 TreePatternNode *InVal = InstInputsCheck[OpName]; 3063 InstInputsCheck.erase(OpName); // It occurred, remove from map. 3064 3065 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) { 3066 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef(); 3067 if (!checkOperandClass(Op, InRec)) 3068 I->error("Operand $" + OpName + "'s register class disagrees" 3069 " between the operand and pattern"); 3070 } 3071 Operands.push_back(Op.Rec); 3072 3073 // Construct the result for the dest-pattern operand list. 3074 TreePatternNode *OpNode = InVal->clone(); 3075 3076 // No predicate is useful on the result. 3077 OpNode->clearPredicateFns(); 3078 3079 // Promote the xform function to be an explicit node if set. 3080 if (Record *Xform = OpNode->getTransformFn()) { 3081 OpNode->setTransformFn(nullptr); 3082 std::vector<TreePatternNode*> Children; 3083 Children.push_back(OpNode); 3084 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes()); 3085 } 3086 3087 ResultNodeOperands.push_back(OpNode); 3088 } 3089 3090 if (!InstInputsCheck.empty()) 3091 I->error("Input operand $" + InstInputsCheck.begin()->first + 3092 " occurs in pattern but not in operands list!"); 3093 3094 TreePatternNode *ResultPattern = 3095 new TreePatternNode(I->getRecord(), ResultNodeOperands, 3096 GetNumNodeResults(I->getRecord(), *this)); 3097 // Copy fully inferred output node types to instruction result pattern. 3098 for (unsigned i = 0; i != NumResults; ++i) { 3099 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled"); 3100 ResultPattern->setType(i, ResNodes[i]->getExtType(0)); 3101 } 3102 3103 // Create and insert the instruction. 3104 // FIXME: InstImpResults should not be part of DAGInstruction. 3105 DAGInstruction TheInst(I, Results, Operands, InstImpResults); 3106 DAGInsts.insert(std::make_pair(I->getRecord(), TheInst)); 3107 3108 // Use a temporary tree pattern to infer all types and make sure that the 3109 // constructed result is correct. This depends on the instruction already 3110 // being inserted into the DAGInsts map. 3111 TreePattern Temp(I->getRecord(), ResultPattern, false, *this); 3112 Temp.InferAllTypes(&I->getNamedNodesMap()); 3113 3114 DAGInstruction &TheInsertedInst = DAGInsts.find(I->getRecord())->second; 3115 TheInsertedInst.setResultPattern(Temp.getOnlyTree()); 3116 3117 return TheInsertedInst; 3118 } 3119 3120 /// ParseInstructions - Parse all of the instructions, inlining and resolving 3121 /// any fragments involved. This populates the Instructions list with fully 3122 /// resolved instructions. 3123 void CodeGenDAGPatterns::ParseInstructions() { 3124 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction"); 3125 3126 for (Record *Instr : Instrs) { 3127 ListInit *LI = nullptr; 3128 3129 if (isa<ListInit>(Instr->getValueInit("Pattern"))) 3130 LI = Instr->getValueAsListInit("Pattern"); 3131 3132 // If there is no pattern, only collect minimal information about the 3133 // instruction for its operand list. We have to assume that there is one 3134 // result, as we have no detailed info. A pattern which references the 3135 // null_frag operator is as-if no pattern were specified. Normally this 3136 // is from a multiclass expansion w/ a SDPatternOperator passed in as 3137 // null_frag. 3138 if (!LI || LI->empty() || hasNullFragReference(LI)) { 3139 std::vector<Record*> Results; 3140 std::vector<Record*> Operands; 3141 3142 CodeGenInstruction &InstInfo = Target.getInstruction(Instr); 3143 3144 if (InstInfo.Operands.size() != 0) { 3145 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j) 3146 Results.push_back(InstInfo.Operands[j].Rec); 3147 3148 // The rest are inputs. 3149 for (unsigned j = InstInfo.Operands.NumDefs, 3150 e = InstInfo.Operands.size(); j < e; ++j) 3151 Operands.push_back(InstInfo.Operands[j].Rec); 3152 } 3153 3154 // Create and insert the instruction. 3155 std::vector<Record*> ImpResults; 3156 Instructions.insert(std::make_pair(Instr, 3157 DAGInstruction(nullptr, Results, Operands, ImpResults))); 3158 continue; // no pattern. 3159 } 3160 3161 CodeGenInstruction &CGI = Target.getInstruction(Instr); 3162 const DAGInstruction &DI = parseInstructionPattern(CGI, LI, Instructions); 3163 3164 (void)DI; 3165 DEBUG(DI.getPattern()->dump()); 3166 } 3167 3168 // If we can, convert the instructions to be patterns that are matched! 3169 for (auto &Entry : Instructions) { 3170 DAGInstruction &TheInst = Entry.second; 3171 TreePattern *I = TheInst.getPattern(); 3172 if (!I) continue; // No pattern. 3173 3174 // FIXME: Assume only the first tree is the pattern. The others are clobber 3175 // nodes. 3176 TreePatternNode *Pattern = I->getTree(0); 3177 TreePatternNode *SrcPattern; 3178 if (Pattern->getOperator()->getName() == "set") { 3179 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone(); 3180 } else{ 3181 // Not a set (store or something?) 3182 SrcPattern = Pattern; 3183 } 3184 3185 Record *Instr = Entry.first; 3186 AddPatternToMatch(I, 3187 PatternToMatch(Instr, 3188 Instr->getValueAsListInit("Predicates"), 3189 SrcPattern, 3190 TheInst.getResultPattern(), 3191 TheInst.getImpResults(), 3192 Instr->getValueAsInt("AddedComplexity"), 3193 Instr->getID())); 3194 } 3195 } 3196 3197 3198 typedef std::pair<const TreePatternNode*, unsigned> NameRecord; 3199 3200 static void FindNames(const TreePatternNode *P, 3201 std::map<std::string, NameRecord> &Names, 3202 TreePattern *PatternTop) { 3203 if (!P->getName().empty()) { 3204 NameRecord &Rec = Names[P->getName()]; 3205 // If this is the first instance of the name, remember the node. 3206 if (Rec.second++ == 0) 3207 Rec.first = P; 3208 else if (Rec.first->getExtTypes() != P->getExtTypes()) 3209 PatternTop->error("repetition of value: $" + P->getName() + 3210 " where different uses have different types!"); 3211 } 3212 3213 if (!P->isLeaf()) { 3214 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) 3215 FindNames(P->getChild(i), Names, PatternTop); 3216 } 3217 } 3218 3219 void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern, 3220 const PatternToMatch &PTM) { 3221 // Do some sanity checking on the pattern we're about to match. 3222 std::string Reason; 3223 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) { 3224 PrintWarning(Pattern->getRecord()->getLoc(), 3225 Twine("Pattern can never match: ") + Reason); 3226 return; 3227 } 3228 3229 // If the source pattern's root is a complex pattern, that complex pattern 3230 // must specify the nodes it can potentially match. 3231 if (const ComplexPattern *CP = 3232 PTM.getSrcPattern()->getComplexPatternInfo(*this)) 3233 if (CP->getRootNodes().empty()) 3234 Pattern->error("ComplexPattern at root must specify list of opcodes it" 3235 " could match"); 3236 3237 3238 // Find all of the named values in the input and output, ensure they have the 3239 // same type. 3240 std::map<std::string, NameRecord> SrcNames, DstNames; 3241 FindNames(PTM.getSrcPattern(), SrcNames, Pattern); 3242 FindNames(PTM.getDstPattern(), DstNames, Pattern); 3243 3244 // Scan all of the named values in the destination pattern, rejecting them if 3245 // they don't exist in the input pattern. 3246 for (const auto &Entry : DstNames) { 3247 if (SrcNames[Entry.first].first == nullptr) 3248 Pattern->error("Pattern has input without matching name in output: $" + 3249 Entry.first); 3250 } 3251 3252 // Scan all of the named values in the source pattern, rejecting them if the 3253 // name isn't used in the dest, and isn't used to tie two values together. 3254 for (const auto &Entry : SrcNames) 3255 if (DstNames[Entry.first].first == nullptr && 3256 SrcNames[Entry.first].second == 1) 3257 Pattern->error("Pattern has dead named input: $" + Entry.first); 3258 3259 PatternsToMatch.push_back(PTM); 3260 } 3261 3262 3263 3264 void CodeGenDAGPatterns::InferInstructionFlags() { 3265 ArrayRef<const CodeGenInstruction*> Instructions = 3266 Target.getInstructionsByEnumValue(); 3267 3268 // First try to infer flags from the primary instruction pattern, if any. 3269 SmallVector<CodeGenInstruction*, 8> Revisit; 3270 unsigned Errors = 0; 3271 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) { 3272 CodeGenInstruction &InstInfo = 3273 const_cast<CodeGenInstruction &>(*Instructions[i]); 3274 3275 // Get the primary instruction pattern. 3276 const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern(); 3277 if (!Pattern) { 3278 if (InstInfo.hasUndefFlags()) 3279 Revisit.push_back(&InstInfo); 3280 continue; 3281 } 3282 InstAnalyzer PatInfo(*this); 3283 PatInfo.Analyze(Pattern); 3284 Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef); 3285 } 3286 3287 // Second, look for single-instruction patterns defined outside the 3288 // instruction. 3289 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) { 3290 const PatternToMatch &PTM = *I; 3291 3292 // We can only infer from single-instruction patterns, otherwise we won't 3293 // know which instruction should get the flags. 3294 SmallVector<Record*, 8> PatInstrs; 3295 getInstructionsInTree(PTM.getDstPattern(), PatInstrs); 3296 if (PatInstrs.size() != 1) 3297 continue; 3298 3299 // Get the single instruction. 3300 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front()); 3301 3302 // Only infer properties from the first pattern. We'll verify the others. 3303 if (InstInfo.InferredFrom) 3304 continue; 3305 3306 InstAnalyzer PatInfo(*this); 3307 PatInfo.Analyze(&PTM); 3308 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord()); 3309 } 3310 3311 if (Errors) 3312 PrintFatalError("pattern conflicts"); 3313 3314 // Revisit instructions with undefined flags and no pattern. 3315 if (Target.guessInstructionProperties()) { 3316 for (CodeGenInstruction *InstInfo : Revisit) { 3317 if (InstInfo->InferredFrom) 3318 continue; 3319 // The mayLoad and mayStore flags default to false. 3320 // Conservatively assume hasSideEffects if it wasn't explicit. 3321 if (InstInfo->hasSideEffects_Unset) 3322 InstInfo->hasSideEffects = true; 3323 } 3324 return; 3325 } 3326 3327 // Complain about any flags that are still undefined. 3328 for (CodeGenInstruction *InstInfo : Revisit) { 3329 if (InstInfo->InferredFrom) 3330 continue; 3331 if (InstInfo->hasSideEffects_Unset) 3332 PrintError(InstInfo->TheDef->getLoc(), 3333 "Can't infer hasSideEffects from patterns"); 3334 if (InstInfo->mayStore_Unset) 3335 PrintError(InstInfo->TheDef->getLoc(), 3336 "Can't infer mayStore from patterns"); 3337 if (InstInfo->mayLoad_Unset) 3338 PrintError(InstInfo->TheDef->getLoc(), 3339 "Can't infer mayLoad from patterns"); 3340 } 3341 } 3342 3343 3344 /// Verify instruction flags against pattern node properties. 3345 void CodeGenDAGPatterns::VerifyInstructionFlags() { 3346 unsigned Errors = 0; 3347 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) { 3348 const PatternToMatch &PTM = *I; 3349 SmallVector<Record*, 8> Instrs; 3350 getInstructionsInTree(PTM.getDstPattern(), Instrs); 3351 if (Instrs.empty()) 3352 continue; 3353 3354 // Count the number of instructions with each flag set. 3355 unsigned NumSideEffects = 0; 3356 unsigned NumStores = 0; 3357 unsigned NumLoads = 0; 3358 for (const Record *Instr : Instrs) { 3359 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr); 3360 NumSideEffects += InstInfo.hasSideEffects; 3361 NumStores += InstInfo.mayStore; 3362 NumLoads += InstInfo.mayLoad; 3363 } 3364 3365 // Analyze the source pattern. 3366 InstAnalyzer PatInfo(*this); 3367 PatInfo.Analyze(&PTM); 3368 3369 // Collect error messages. 3370 SmallVector<std::string, 4> Msgs; 3371 3372 // Check for missing flags in the output. 3373 // Permit extra flags for now at least. 3374 if (PatInfo.hasSideEffects && !NumSideEffects) 3375 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set"); 3376 3377 // Don't verify store flags on instructions with side effects. At least for 3378 // intrinsics, side effects implies mayStore. 3379 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores) 3380 Msgs.push_back("pattern may store, but mayStore isn't set"); 3381 3382 // Similarly, mayStore implies mayLoad on intrinsics. 3383 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads) 3384 Msgs.push_back("pattern may load, but mayLoad isn't set"); 3385 3386 // Print error messages. 3387 if (Msgs.empty()) 3388 continue; 3389 ++Errors; 3390 3391 for (const std::string &Msg : Msgs) 3392 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " + 3393 (Instrs.size() == 1 ? 3394 "instruction" : "output instructions")); 3395 // Provide the location of the relevant instruction definitions. 3396 for (const Record *Instr : Instrs) { 3397 if (Instr != PTM.getSrcRecord()) 3398 PrintError(Instr->getLoc(), "defined here"); 3399 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr); 3400 if (InstInfo.InferredFrom && 3401 InstInfo.InferredFrom != InstInfo.TheDef && 3402 InstInfo.InferredFrom != PTM.getSrcRecord()) 3403 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern"); 3404 } 3405 } 3406 if (Errors) 3407 PrintFatalError("Errors in DAG patterns"); 3408 } 3409 3410 /// Given a pattern result with an unresolved type, see if we can find one 3411 /// instruction with an unresolved result type. Force this result type to an 3412 /// arbitrary element if it's possible types to converge results. 3413 static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) { 3414 if (N->isLeaf()) 3415 return false; 3416 3417 // Analyze children. 3418 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) 3419 if (ForceArbitraryInstResultType(N->getChild(i), TP)) 3420 return true; 3421 3422 if (!N->getOperator()->isSubClassOf("Instruction")) 3423 return false; 3424 3425 // If this type is already concrete or completely unknown we can't do 3426 // anything. 3427 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) { 3428 if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete()) 3429 continue; 3430 3431 // Otherwise, force its type to the first possibility (an arbitrary choice). 3432 if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP)) 3433 return true; 3434 } 3435 3436 return false; 3437 } 3438 3439 void CodeGenDAGPatterns::ParsePatterns() { 3440 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern"); 3441 3442 for (Record *CurPattern : Patterns) { 3443 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch"); 3444 3445 // If the pattern references the null_frag, there's nothing to do. 3446 if (hasNullFragReference(Tree)) 3447 continue; 3448 3449 TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this); 3450 3451 // Inline pattern fragments into it. 3452 Pattern->InlinePatternFragments(); 3453 3454 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs"); 3455 if (LI->empty()) continue; // no pattern. 3456 3457 // Parse the instruction. 3458 TreePattern Result(CurPattern, LI, false, *this); 3459 3460 // Inline pattern fragments into it. 3461 Result.InlinePatternFragments(); 3462 3463 if (Result.getNumTrees() != 1) 3464 Result.error("Cannot handle instructions producing instructions " 3465 "with temporaries yet!"); 3466 3467 bool IterateInference; 3468 bool InferredAllPatternTypes, InferredAllResultTypes; 3469 do { 3470 // Infer as many types as possible. If we cannot infer all of them, we 3471 // can never do anything with this pattern: report it to the user. 3472 InferredAllPatternTypes = 3473 Pattern->InferAllTypes(&Pattern->getNamedNodesMap()); 3474 3475 // Infer as many types as possible. If we cannot infer all of them, we 3476 // can never do anything with this pattern: report it to the user. 3477 InferredAllResultTypes = 3478 Result.InferAllTypes(&Pattern->getNamedNodesMap()); 3479 3480 IterateInference = false; 3481 3482 // Apply the type of the result to the source pattern. This helps us 3483 // resolve cases where the input type is known to be a pointer type (which 3484 // is considered resolved), but the result knows it needs to be 32- or 3485 // 64-bits. Infer the other way for good measure. 3486 for (unsigned i = 0, e = std::min(Result.getTree(0)->getNumTypes(), 3487 Pattern->getTree(0)->getNumTypes()); 3488 i != e; ++i) { 3489 IterateInference = Pattern->getTree(0)->UpdateNodeType( 3490 i, Result.getTree(0)->getExtType(i), Result); 3491 IterateInference |= Result.getTree(0)->UpdateNodeType( 3492 i, Pattern->getTree(0)->getExtType(i), Result); 3493 } 3494 3495 // If our iteration has converged and the input pattern's types are fully 3496 // resolved but the result pattern is not fully resolved, we may have a 3497 // situation where we have two instructions in the result pattern and 3498 // the instructions require a common register class, but don't care about 3499 // what actual MVT is used. This is actually a bug in our modelling: 3500 // output patterns should have register classes, not MVTs. 3501 // 3502 // In any case, to handle this, we just go through and disambiguate some 3503 // arbitrary types to the result pattern's nodes. 3504 if (!IterateInference && InferredAllPatternTypes && 3505 !InferredAllResultTypes) 3506 IterateInference = 3507 ForceArbitraryInstResultType(Result.getTree(0), Result); 3508 } while (IterateInference); 3509 3510 // Verify that we inferred enough types that we can do something with the 3511 // pattern and result. If these fire the user has to add type casts. 3512 if (!InferredAllPatternTypes) 3513 Pattern->error("Could not infer all types in pattern!"); 3514 if (!InferredAllResultTypes) { 3515 Pattern->dump(); 3516 Result.error("Could not infer all types in pattern result!"); 3517 } 3518 3519 // Validate that the input pattern is correct. 3520 std::map<std::string, TreePatternNode*> InstInputs; 3521 std::map<std::string, TreePatternNode*> InstResults; 3522 std::vector<Record*> InstImpResults; 3523 for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j) 3524 FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j), 3525 InstInputs, InstResults, 3526 InstImpResults); 3527 3528 // Promote the xform function to be an explicit node if set. 3529 TreePatternNode *DstPattern = Result.getOnlyTree(); 3530 std::vector<TreePatternNode*> ResultNodeOperands; 3531 for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) { 3532 TreePatternNode *OpNode = DstPattern->getChild(ii); 3533 if (Record *Xform = OpNode->getTransformFn()) { 3534 OpNode->setTransformFn(nullptr); 3535 std::vector<TreePatternNode*> Children; 3536 Children.push_back(OpNode); 3537 OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes()); 3538 } 3539 ResultNodeOperands.push_back(OpNode); 3540 } 3541 DstPattern = Result.getOnlyTree(); 3542 if (!DstPattern->isLeaf()) 3543 DstPattern = new TreePatternNode(DstPattern->getOperator(), 3544 ResultNodeOperands, 3545 DstPattern->getNumTypes()); 3546 3547 for (unsigned i = 0, e = Result.getOnlyTree()->getNumTypes(); i != e; ++i) 3548 DstPattern->setType(i, Result.getOnlyTree()->getExtType(i)); 3549 3550 TreePattern Temp(Result.getRecord(), DstPattern, false, *this); 3551 Temp.InferAllTypes(); 3552 3553 3554 AddPatternToMatch(Pattern, 3555 PatternToMatch(CurPattern, 3556 CurPattern->getValueAsListInit("Predicates"), 3557 Pattern->getTree(0), 3558 Temp.getOnlyTree(), InstImpResults, 3559 CurPattern->getValueAsInt("AddedComplexity"), 3560 CurPattern->getID())); 3561 } 3562 } 3563 3564 /// CombineChildVariants - Given a bunch of permutations of each child of the 3565 /// 'operator' node, put them together in all possible ways. 3566 static void CombineChildVariants(TreePatternNode *Orig, 3567 const std::vector<std::vector<TreePatternNode*> > &ChildVariants, 3568 std::vector<TreePatternNode*> &OutVariants, 3569 CodeGenDAGPatterns &CDP, 3570 const MultipleUseVarSet &DepVars) { 3571 // Make sure that each operand has at least one variant to choose from. 3572 for (const auto &Variants : ChildVariants) 3573 if (Variants.empty()) 3574 return; 3575 3576 // The end result is an all-pairs construction of the resultant pattern. 3577 std::vector<unsigned> Idxs; 3578 Idxs.resize(ChildVariants.size()); 3579 bool NotDone; 3580 do { 3581 #ifndef NDEBUG 3582 DEBUG(if (!Idxs.empty()) { 3583 errs() << Orig->getOperator()->getName() << ": Idxs = [ "; 3584 for (unsigned Idx : Idxs) { 3585 errs() << Idx << " "; 3586 } 3587 errs() << "]\n"; 3588 }); 3589 #endif 3590 // Create the variant and add it to the output list. 3591 std::vector<TreePatternNode*> NewChildren; 3592 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i) 3593 NewChildren.push_back(ChildVariants[i][Idxs[i]]); 3594 auto R = llvm::make_unique<TreePatternNode>( 3595 Orig->getOperator(), NewChildren, Orig->getNumTypes()); 3596 3597 // Copy over properties. 3598 R->setName(Orig->getName()); 3599 R->setPredicateFns(Orig->getPredicateFns()); 3600 R->setTransformFn(Orig->getTransformFn()); 3601 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i) 3602 R->setType(i, Orig->getExtType(i)); 3603 3604 // If this pattern cannot match, do not include it as a variant. 3605 std::string ErrString; 3606 // Scan to see if this pattern has already been emitted. We can get 3607 // duplication due to things like commuting: 3608 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a) 3609 // which are the same pattern. Ignore the dups. 3610 if (R->canPatternMatch(ErrString, CDP) && 3611 none_of(OutVariants, [&](TreePatternNode *Variant) { 3612 return R->isIsomorphicTo(Variant, DepVars); 3613 })) 3614 OutVariants.push_back(R.release()); 3615 3616 // Increment indices to the next permutation by incrementing the 3617 // indices from last index backward, e.g., generate the sequence 3618 // [0, 0], [0, 1], [1, 0], [1, 1]. 3619 int IdxsIdx; 3620 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) { 3621 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size()) 3622 Idxs[IdxsIdx] = 0; 3623 else 3624 break; 3625 } 3626 NotDone = (IdxsIdx >= 0); 3627 } while (NotDone); 3628 } 3629 3630 /// CombineChildVariants - A helper function for binary operators. 3631 /// 3632 static void CombineChildVariants(TreePatternNode *Orig, 3633 const std::vector<TreePatternNode*> &LHS, 3634 const std::vector<TreePatternNode*> &RHS, 3635 std::vector<TreePatternNode*> &OutVariants, 3636 CodeGenDAGPatterns &CDP, 3637 const MultipleUseVarSet &DepVars) { 3638 std::vector<std::vector<TreePatternNode*> > ChildVariants; 3639 ChildVariants.push_back(LHS); 3640 ChildVariants.push_back(RHS); 3641 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars); 3642 } 3643 3644 3645 static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N, 3646 std::vector<TreePatternNode *> &Children) { 3647 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!"); 3648 Record *Operator = N->getOperator(); 3649 3650 // Only permit raw nodes. 3651 if (!N->getName().empty() || !N->getPredicateFns().empty() || 3652 N->getTransformFn()) { 3653 Children.push_back(N); 3654 return; 3655 } 3656 3657 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator) 3658 Children.push_back(N->getChild(0)); 3659 else 3660 GatherChildrenOfAssociativeOpcode(N->getChild(0), Children); 3661 3662 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator) 3663 Children.push_back(N->getChild(1)); 3664 else 3665 GatherChildrenOfAssociativeOpcode(N->getChild(1), Children); 3666 } 3667 3668 /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of 3669 /// the (potentially recursive) pattern by using algebraic laws. 3670 /// 3671 static void GenerateVariantsOf(TreePatternNode *N, 3672 std::vector<TreePatternNode*> &OutVariants, 3673 CodeGenDAGPatterns &CDP, 3674 const MultipleUseVarSet &DepVars) { 3675 // We cannot permute leaves or ComplexPattern uses. 3676 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) { 3677 OutVariants.push_back(N); 3678 return; 3679 } 3680 3681 // Look up interesting info about the node. 3682 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator()); 3683 3684 // If this node is associative, re-associate. 3685 if (NodeInfo.hasProperty(SDNPAssociative)) { 3686 // Re-associate by pulling together all of the linked operators 3687 std::vector<TreePatternNode*> MaximalChildren; 3688 GatherChildrenOfAssociativeOpcode(N, MaximalChildren); 3689 3690 // Only handle child sizes of 3. Otherwise we'll end up trying too many 3691 // permutations. 3692 if (MaximalChildren.size() == 3) { 3693 // Find the variants of all of our maximal children. 3694 std::vector<TreePatternNode*> AVariants, BVariants, CVariants; 3695 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars); 3696 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars); 3697 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars); 3698 3699 // There are only two ways we can permute the tree: 3700 // (A op B) op C and A op (B op C) 3701 // Within these forms, we can also permute A/B/C. 3702 3703 // Generate legal pair permutations of A/B/C. 3704 std::vector<TreePatternNode*> ABVariants; 3705 std::vector<TreePatternNode*> BAVariants; 3706 std::vector<TreePatternNode*> ACVariants; 3707 std::vector<TreePatternNode*> CAVariants; 3708 std::vector<TreePatternNode*> BCVariants; 3709 std::vector<TreePatternNode*> CBVariants; 3710 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars); 3711 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars); 3712 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars); 3713 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars); 3714 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars); 3715 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars); 3716 3717 // Combine those into the result: (x op x) op x 3718 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars); 3719 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars); 3720 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars); 3721 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars); 3722 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars); 3723 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars); 3724 3725 // Combine those into the result: x op (x op x) 3726 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars); 3727 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars); 3728 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars); 3729 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars); 3730 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars); 3731 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars); 3732 return; 3733 } 3734 } 3735 3736 // Compute permutations of all children. 3737 std::vector<std::vector<TreePatternNode*> > ChildVariants; 3738 ChildVariants.resize(N->getNumChildren()); 3739 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) 3740 GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars); 3741 3742 // Build all permutations based on how the children were formed. 3743 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars); 3744 3745 // If this node is commutative, consider the commuted order. 3746 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP); 3747 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) { 3748 assert((N->getNumChildren()==2 || isCommIntrinsic) && 3749 "Commutative but doesn't have 2 children!"); 3750 // Don't count children which are actually register references. 3751 unsigned NC = 0; 3752 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) { 3753 TreePatternNode *Child = N->getChild(i); 3754 if (Child->isLeaf()) 3755 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) { 3756 Record *RR = DI->getDef(); 3757 if (RR->isSubClassOf("Register")) 3758 continue; 3759 } 3760 NC++; 3761 } 3762 // Consider the commuted order. 3763 if (isCommIntrinsic) { 3764 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd 3765 // operands are the commutative operands, and there might be more operands 3766 // after those. 3767 assert(NC >= 3 && 3768 "Commutative intrinsic should have at least 3 children!"); 3769 std::vector<std::vector<TreePatternNode*> > Variants; 3770 Variants.push_back(ChildVariants[0]); // Intrinsic id. 3771 Variants.push_back(ChildVariants[2]); 3772 Variants.push_back(ChildVariants[1]); 3773 for (unsigned i = 3; i != NC; ++i) 3774 Variants.push_back(ChildVariants[i]); 3775 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars); 3776 } else if (NC == 2) 3777 CombineChildVariants(N, ChildVariants[1], ChildVariants[0], 3778 OutVariants, CDP, DepVars); 3779 } 3780 } 3781 3782 3783 // GenerateVariants - Generate variants. For example, commutative patterns can 3784 // match multiple ways. Add them to PatternsToMatch as well. 3785 void CodeGenDAGPatterns::GenerateVariants() { 3786 DEBUG(errs() << "Generating instruction variants.\n"); 3787 3788 // Loop over all of the patterns we've collected, checking to see if we can 3789 // generate variants of the instruction, through the exploitation of 3790 // identities. This permits the target to provide aggressive matching without 3791 // the .td file having to contain tons of variants of instructions. 3792 // 3793 // Note that this loop adds new patterns to the PatternsToMatch list, but we 3794 // intentionally do not reconsider these. Any variants of added patterns have 3795 // already been added. 3796 // 3797 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) { 3798 MultipleUseVarSet DepVars; 3799 std::vector<TreePatternNode*> Variants; 3800 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars); 3801 DEBUG(errs() << "Dependent/multiply used variables: "); 3802 DEBUG(DumpDepVars(DepVars)); 3803 DEBUG(errs() << "\n"); 3804 GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this, 3805 DepVars); 3806 3807 assert(!Variants.empty() && "Must create at least original variant!"); 3808 Variants.erase(Variants.begin()); // Remove the original pattern. 3809 3810 if (Variants.empty()) // No variants for this pattern. 3811 continue; 3812 3813 DEBUG(errs() << "FOUND VARIANTS OF: "; 3814 PatternsToMatch[i].getSrcPattern()->dump(); 3815 errs() << "\n"); 3816 3817 for (unsigned v = 0, e = Variants.size(); v != e; ++v) { 3818 TreePatternNode *Variant = Variants[v]; 3819 3820 DEBUG(errs() << " VAR#" << v << ": "; 3821 Variant->dump(); 3822 errs() << "\n"); 3823 3824 // Scan to see if an instruction or explicit pattern already matches this. 3825 bool AlreadyExists = false; 3826 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) { 3827 // Skip if the top level predicates do not match. 3828 if (PatternsToMatch[i].getPredicates() != 3829 PatternsToMatch[p].getPredicates()) 3830 continue; 3831 // Check to see if this variant already exists. 3832 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(), 3833 DepVars)) { 3834 DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n"); 3835 AlreadyExists = true; 3836 break; 3837 } 3838 } 3839 // If we already have it, ignore the variant. 3840 if (AlreadyExists) continue; 3841 3842 // Otherwise, add it to the list of patterns we have. 3843 PatternsToMatch.emplace_back( 3844 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(), 3845 Variant, PatternsToMatch[i].getDstPattern(), 3846 PatternsToMatch[i].getDstRegs(), 3847 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()); 3848 } 3849 3850 DEBUG(errs() << "\n"); 3851 } 3852 } 3853