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