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