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