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