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