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