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