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