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