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