1 //===- HexagonConstPropagation.cpp ----------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "HexagonInstrInfo.h" 10 #include "HexagonRegisterInfo.h" 11 #include "HexagonSubtarget.h" 12 #include "llvm/ADT/APFloat.h" 13 #include "llvm/ADT/APInt.h" 14 #include "llvm/ADT/PostOrderIterator.h" 15 #include "llvm/ADT/SetVector.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/CodeGen/MachineBasicBlock.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineFunctionPass.h" 21 #include "llvm/CodeGen/MachineInstr.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineOperand.h" 24 #include "llvm/CodeGen/MachineRegisterInfo.h" 25 #include "llvm/CodeGen/TargetRegisterInfo.h" 26 #include "llvm/CodeGen/TargetSubtargetInfo.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/Type.h" 29 #include "llvm/Pass.h" 30 #include "llvm/Support/Casting.h" 31 #include "llvm/Support/Compiler.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include <cassert> 37 #include <cstdint> 38 #include <cstring> 39 #include <iterator> 40 #include <map> 41 #include <queue> 42 #include <set> 43 #include <utility> 44 #include <vector> 45 46 #define DEBUG_TYPE "hcp" 47 48 using namespace llvm; 49 50 namespace { 51 52 // Properties of a value that are tracked by the propagation. 53 // A property that is marked as present (i.e. bit is set) dentes that the 54 // value is known (proven) to have this property. Not all combinations 55 // of bits make sense, for example Zero and NonZero are mutually exclusive, 56 // but on the other hand, Zero implies Finite. In this case, whenever 57 // the Zero property is present, Finite should also be present. 58 class ConstantProperties { 59 public: 60 enum { 61 Unknown = 0x0000, 62 Zero = 0x0001, 63 NonZero = 0x0002, 64 Finite = 0x0004, 65 Infinity = 0x0008, 66 NaN = 0x0010, 67 SignedZero = 0x0020, 68 NumericProperties = (Zero|NonZero|Finite|Infinity|NaN|SignedZero), 69 PosOrZero = 0x0100, 70 NegOrZero = 0x0200, 71 SignProperties = (PosOrZero|NegOrZero), 72 Everything = (NumericProperties|SignProperties) 73 }; 74 75 // For a given constant, deduce the set of trackable properties that this 76 // constant has. 77 static uint32_t deduce(const Constant *C); 78 }; 79 80 // A representation of a register as it can appear in a MachineOperand, 81 // i.e. a pair register:subregister. 82 83 // FIXME: Use TargetInstrInfo::RegSubRegPair. Also duplicated in 84 // HexagonGenPredicate 85 struct RegisterSubReg { 86 Register Reg; 87 unsigned SubReg; 88 89 explicit RegisterSubReg(unsigned R, unsigned SR = 0) : Reg(R), SubReg(SR) {} 90 explicit RegisterSubReg(const MachineOperand &MO) 91 : Reg(MO.getReg()), SubReg(MO.getSubReg()) {} 92 93 void print(const TargetRegisterInfo *TRI = nullptr) const { 94 dbgs() << printReg(Reg, TRI, SubReg); 95 } 96 97 bool operator== (const RegisterSubReg &R) const { 98 return (Reg == R.Reg) && (SubReg == R.SubReg); 99 } 100 }; 101 102 // Lattice cell, based on that was described in the W-Z paper on constant 103 // propagation. 104 // Latice cell will be allowed to hold multiple constant values. While 105 // multiple values would normally indicate "bottom", we can still derive 106 // some useful information from them. For example, comparison X > 0 107 // could be folded if all the values in the cell associated with X are 108 // positive. 109 class LatticeCell { 110 private: 111 enum { Normal, Top, Bottom }; 112 113 static const unsigned MaxCellSize = 4; 114 115 unsigned Kind:2; 116 unsigned Size:3; 117 unsigned IsSpecial:1; 118 unsigned :0; 119 120 public: 121 union { 122 uint32_t Properties; 123 const Constant *Value; 124 const Constant *Values[MaxCellSize]; 125 }; 126 127 LatticeCell() : Kind(Top), Size(0), IsSpecial(false) { 128 for (unsigned i = 0; i < MaxCellSize; ++i) 129 Values[i] = nullptr; 130 } 131 132 bool meet(const LatticeCell &L); 133 bool add(const Constant *C); 134 bool add(uint32_t Property); 135 uint32_t properties() const; 136 unsigned size() const { return Size; } 137 138 LatticeCell(const LatticeCell &L) { 139 // This memcpy also copies Properties (when L.Size == 0). 140 uint32_t N = 141 L.IsSpecial ? sizeof L.Properties : L.Size * sizeof(const Constant *); 142 memcpy(Values, L.Values, N); 143 Kind = L.Kind; 144 Size = L.Size; 145 IsSpecial = L.IsSpecial; 146 } 147 148 LatticeCell &operator=(const LatticeCell &L) { 149 if (this != &L) { 150 // This memcpy also copies Properties (when L.Size == 0). 151 uint32_t N = L.IsSpecial ? sizeof L.Properties 152 : L.Size * sizeof(const Constant *); 153 memcpy(Values, L.Values, N); 154 Kind = L.Kind; 155 Size = L.Size; 156 IsSpecial = L.IsSpecial; 157 } 158 return *this; 159 } 160 161 bool isSingle() const { return size() == 1; } 162 bool isProperty() const { return IsSpecial; } 163 bool isTop() const { return Kind == Top; } 164 bool isBottom() const { return Kind == Bottom; } 165 166 bool setBottom() { 167 bool Changed = (Kind != Bottom); 168 Kind = Bottom; 169 Size = 0; 170 IsSpecial = false; 171 return Changed; 172 } 173 174 void print(raw_ostream &os) const; 175 176 private: 177 void setProperty() { 178 IsSpecial = true; 179 Size = 0; 180 Kind = Normal; 181 } 182 183 bool convertToProperty(); 184 }; 185 186 #ifndef NDEBUG 187 raw_ostream &operator<< (raw_ostream &os, const LatticeCell &L) { 188 L.print(os); 189 return os; 190 } 191 #endif 192 193 class MachineConstEvaluator; 194 195 class MachineConstPropagator { 196 public: 197 MachineConstPropagator(MachineConstEvaluator &E) : MCE(E) { 198 Bottom.setBottom(); 199 } 200 201 // Mapping: vreg -> cell 202 // The keys are registers _without_ subregisters. This won't allow 203 // definitions in the form of "vreg:subreg = ...". Such definitions 204 // would be questionable from the point of view of SSA, since the "vreg" 205 // could not be initialized in its entirety (specifically, an instruction 206 // defining the "other part" of "vreg" would also count as a definition 207 // of "vreg", which would violate the SSA). 208 // If a value of a pair vreg:subreg needs to be obtained, the cell for 209 // "vreg" needs to be looked up, and then the value of subregister "subreg" 210 // needs to be evaluated. 211 class CellMap { 212 public: 213 CellMap() { 214 assert(Top.isTop()); 215 Bottom.setBottom(); 216 } 217 218 void clear() { Map.clear(); } 219 220 bool has(Register R) const { 221 // All non-virtual registers are considered "bottom". 222 if (!R.isVirtual()) 223 return true; 224 MapType::const_iterator F = Map.find(R); 225 return F != Map.end(); 226 } 227 228 const LatticeCell &get(Register R) const { 229 if (!R.isVirtual()) 230 return Bottom; 231 MapType::const_iterator F = Map.find(R); 232 if (F != Map.end()) 233 return F->second; 234 return Top; 235 } 236 237 // Invalidates any const references. 238 void update(Register R, const LatticeCell &L) { Map[R] = L; } 239 240 void print(raw_ostream &os, const TargetRegisterInfo &TRI) const; 241 242 private: 243 using MapType = std::map<Register, LatticeCell>; 244 245 MapType Map; 246 // To avoid creating "top" entries, return a const reference to 247 // this cell in "get". Also, have a "Bottom" cell to return from 248 // get when a value of a physical register is requested. 249 LatticeCell Top, Bottom; 250 251 public: 252 using const_iterator = MapType::const_iterator; 253 254 const_iterator begin() const { return Map.begin(); } 255 const_iterator end() const { return Map.end(); } 256 }; 257 258 bool run(MachineFunction &MF); 259 260 private: 261 void visitPHI(const MachineInstr &PN); 262 void visitNonBranch(const MachineInstr &MI); 263 void visitBranchesFrom(const MachineInstr &BrI); 264 void visitUsesOf(unsigned R); 265 bool computeBlockSuccessors(const MachineBasicBlock *MB, 266 SetVector<const MachineBasicBlock*> &Targets); 267 void removeCFGEdge(MachineBasicBlock *From, MachineBasicBlock *To); 268 269 void propagate(MachineFunction &MF); 270 bool rewrite(MachineFunction &MF); 271 272 MachineRegisterInfo *MRI = nullptr; 273 MachineConstEvaluator &MCE; 274 275 using CFGEdge = std::pair<unsigned, unsigned>; 276 using SetOfCFGEdge = std::set<CFGEdge>; 277 using SetOfInstr = std::set<const MachineInstr *>; 278 using QueueOfCFGEdge = std::queue<CFGEdge>; 279 280 LatticeCell Bottom; 281 CellMap Cells; 282 SetOfCFGEdge EdgeExec; 283 SetOfInstr InstrExec; 284 QueueOfCFGEdge FlowQ; 285 }; 286 287 // The "evaluator/rewriter" of machine instructions. This is an abstract 288 // base class that provides the interface that the propagator will use, 289 // as well as some helper functions that are target-independent. 290 class MachineConstEvaluator { 291 public: 292 MachineConstEvaluator(MachineFunction &Fn) 293 : TRI(*Fn.getSubtarget().getRegisterInfo()), 294 MF(Fn), CX(Fn.getFunction().getContext()) {} 295 virtual ~MachineConstEvaluator() = default; 296 297 // The required interface: 298 // - A set of three "evaluate" functions. Each returns "true" if the 299 // computation succeeded, "false" otherwise. 300 // (1) Given an instruction MI, and the map with input values "Inputs", 301 // compute the set of output values "Outputs". An example of when 302 // the computation can "fail" is if MI is not an instruction that 303 // is recognized by the evaluator. 304 // (2) Given a register R (as reg:subreg), compute the cell that 305 // corresponds to the "subreg" part of the given register. 306 // (3) Given a branch instruction BrI, compute the set of target blocks. 307 // If the branch can fall-through, add null (0) to the list of 308 // possible targets. 309 // - A function "rewrite", that given the cell map after propagation, 310 // could rewrite instruction MI in a more beneficial form. Return 311 // "true" if a change has been made, "false" otherwise. 312 using CellMap = MachineConstPropagator::CellMap; 313 virtual bool evaluate(const MachineInstr &MI, const CellMap &Inputs, 314 CellMap &Outputs) = 0; 315 virtual bool evaluate(const RegisterSubReg &R, const LatticeCell &SrcC, 316 LatticeCell &Result) = 0; 317 virtual bool evaluate(const MachineInstr &BrI, const CellMap &Inputs, 318 SetVector<const MachineBasicBlock*> &Targets, 319 bool &CanFallThru) = 0; 320 virtual bool rewrite(MachineInstr &MI, const CellMap &Inputs) = 0; 321 322 const TargetRegisterInfo &TRI; 323 324 protected: 325 MachineFunction &MF; 326 LLVMContext &CX; 327 328 struct Comparison { 329 enum { 330 Unk = 0x00, 331 EQ = 0x01, 332 NE = 0x02, 333 L = 0x04, // Less-than property. 334 G = 0x08, // Greater-than property. 335 U = 0x40, // Unsigned property. 336 LTs = L, 337 LEs = L | EQ, 338 GTs = G, 339 GEs = G | EQ, 340 LTu = L | U, 341 LEu = L | EQ | U, 342 GTu = G | U, 343 GEu = G | EQ | U 344 }; 345 346 static uint32_t negate(uint32_t Cmp) { 347 if (Cmp == EQ) 348 return NE; 349 if (Cmp == NE) 350 return EQ; 351 assert((Cmp & (L|G)) != (L|G)); 352 return Cmp ^ (L|G); 353 } 354 }; 355 356 // Helper functions. 357 358 bool getCell(const RegisterSubReg &R, const CellMap &Inputs, LatticeCell &RC); 359 bool constToInt(const Constant *C, APInt &Val) const; 360 bool constToFloat(const Constant *C, APFloat &Val) const; 361 const ConstantInt *intToConst(const APInt &Val) const; 362 363 // Compares. 364 bool evaluateCMPrr(uint32_t Cmp, const RegisterSubReg &R1, const RegisterSubReg &R2, 365 const CellMap &Inputs, bool &Result); 366 bool evaluateCMPri(uint32_t Cmp, const RegisterSubReg &R1, const APInt &A2, 367 const CellMap &Inputs, bool &Result); 368 bool evaluateCMPrp(uint32_t Cmp, const RegisterSubReg &R1, uint64_t Props2, 369 const CellMap &Inputs, bool &Result); 370 bool evaluateCMPii(uint32_t Cmp, const APInt &A1, const APInt &A2, 371 bool &Result); 372 bool evaluateCMPpi(uint32_t Cmp, uint32_t Props, const APInt &A2, 373 bool &Result); 374 bool evaluateCMPpp(uint32_t Cmp, uint32_t Props1, uint32_t Props2, 375 bool &Result); 376 377 bool evaluateCOPY(const RegisterSubReg &R1, const CellMap &Inputs, 378 LatticeCell &Result); 379 380 // Logical operations. 381 bool evaluateANDrr(const RegisterSubReg &R1, const RegisterSubReg &R2, 382 const CellMap &Inputs, LatticeCell &Result); 383 bool evaluateANDri(const RegisterSubReg &R1, const APInt &A2, 384 const CellMap &Inputs, LatticeCell &Result); 385 bool evaluateANDii(const APInt &A1, const APInt &A2, APInt &Result); 386 bool evaluateORrr(const RegisterSubReg &R1, const RegisterSubReg &R2, 387 const CellMap &Inputs, LatticeCell &Result); 388 bool evaluateORri(const RegisterSubReg &R1, const APInt &A2, 389 const CellMap &Inputs, LatticeCell &Result); 390 bool evaluateORii(const APInt &A1, const APInt &A2, APInt &Result); 391 bool evaluateXORrr(const RegisterSubReg &R1, const RegisterSubReg &R2, 392 const CellMap &Inputs, LatticeCell &Result); 393 bool evaluateXORri(const RegisterSubReg &R1, const APInt &A2, 394 const CellMap &Inputs, LatticeCell &Result); 395 bool evaluateXORii(const APInt &A1, const APInt &A2, APInt &Result); 396 397 // Extensions. 398 bool evaluateZEXTr(const RegisterSubReg &R1, unsigned Width, unsigned Bits, 399 const CellMap &Inputs, LatticeCell &Result); 400 bool evaluateZEXTi(const APInt &A1, unsigned Width, unsigned Bits, 401 APInt &Result); 402 bool evaluateSEXTr(const RegisterSubReg &R1, unsigned Width, unsigned Bits, 403 const CellMap &Inputs, LatticeCell &Result); 404 bool evaluateSEXTi(const APInt &A1, unsigned Width, unsigned Bits, 405 APInt &Result); 406 407 // Leading/trailing bits. 408 bool evaluateCLBr(const RegisterSubReg &R1, bool Zeros, bool Ones, 409 const CellMap &Inputs, LatticeCell &Result); 410 bool evaluateCLBi(const APInt &A1, bool Zeros, bool Ones, APInt &Result); 411 bool evaluateCTBr(const RegisterSubReg &R1, bool Zeros, bool Ones, 412 const CellMap &Inputs, LatticeCell &Result); 413 bool evaluateCTBi(const APInt &A1, bool Zeros, bool Ones, APInt &Result); 414 415 // Bitfield extract. 416 bool evaluateEXTRACTr(const RegisterSubReg &R1, unsigned Width, unsigned Bits, 417 unsigned Offset, bool Signed, const CellMap &Inputs, 418 LatticeCell &Result); 419 bool evaluateEXTRACTi(const APInt &A1, unsigned Bits, unsigned Offset, 420 bool Signed, APInt &Result); 421 // Vector operations. 422 bool evaluateSplatr(const RegisterSubReg &R1, unsigned Bits, unsigned Count, 423 const CellMap &Inputs, LatticeCell &Result); 424 bool evaluateSplati(const APInt &A1, unsigned Bits, unsigned Count, 425 APInt &Result); 426 }; 427 428 } // end anonymous namespace 429 430 uint32_t ConstantProperties::deduce(const Constant *C) { 431 if (isa<ConstantInt>(C)) { 432 const ConstantInt *CI = cast<ConstantInt>(C); 433 if (CI->isZero()) 434 return Zero | PosOrZero | NegOrZero | Finite; 435 uint32_t Props = (NonZero | Finite); 436 if (CI->isNegative()) 437 return Props | NegOrZero; 438 return Props | PosOrZero; 439 } 440 441 if (isa<ConstantFP>(C)) { 442 const ConstantFP *CF = cast<ConstantFP>(C); 443 uint32_t Props = CF->isNegative() ? (NegOrZero|NonZero) 444 : PosOrZero; 445 if (CF->isZero()) 446 return (Props & ~NumericProperties) | (Zero|Finite); 447 Props = (Props & ~NumericProperties) | NonZero; 448 if (CF->isNaN()) 449 return (Props & ~NumericProperties) | NaN; 450 const APFloat &Val = CF->getValueAPF(); 451 if (Val.isInfinity()) 452 return (Props & ~NumericProperties) | Infinity; 453 Props |= Finite; 454 return Props; 455 } 456 457 return Unknown; 458 } 459 460 // Convert a cell from a set of specific values to a cell that tracks 461 // properties. 462 bool LatticeCell::convertToProperty() { 463 if (isProperty()) 464 return false; 465 // Corner case: converting a fresh (top) cell to "special". 466 // This can happen, when adding a property to a top cell. 467 uint32_t Everything = ConstantProperties::Everything; 468 uint32_t Ps = !isTop() ? properties() 469 : Everything; 470 if (Ps != ConstantProperties::Unknown) { 471 Properties = Ps; 472 setProperty(); 473 } else { 474 setBottom(); 475 } 476 return true; 477 } 478 479 #ifndef NDEBUG 480 void LatticeCell::print(raw_ostream &os) const { 481 if (isProperty()) { 482 os << "{ "; 483 uint32_t Ps = properties(); 484 if (Ps & ConstantProperties::Zero) 485 os << "zero "; 486 if (Ps & ConstantProperties::NonZero) 487 os << "nonzero "; 488 if (Ps & ConstantProperties::Finite) 489 os << "finite "; 490 if (Ps & ConstantProperties::Infinity) 491 os << "infinity "; 492 if (Ps & ConstantProperties::NaN) 493 os << "nan "; 494 if (Ps & ConstantProperties::PosOrZero) 495 os << "poz "; 496 if (Ps & ConstantProperties::NegOrZero) 497 os << "nez "; 498 os << '}'; 499 return; 500 } 501 502 os << "{ "; 503 if (isBottom()) { 504 os << "bottom"; 505 } else if (isTop()) { 506 os << "top"; 507 } else { 508 for (unsigned i = 0; i < size(); ++i) { 509 const Constant *C = Values[i]; 510 if (i != 0) 511 os << ", "; 512 C->print(os); 513 } 514 } 515 os << " }"; 516 } 517 #endif 518 519 // "Meet" operation on two cells. This is the key of the propagation 520 // algorithm. 521 bool LatticeCell::meet(const LatticeCell &L) { 522 bool Changed = false; 523 if (L.isBottom()) 524 Changed = setBottom(); 525 if (isBottom() || L.isTop()) 526 return Changed; 527 if (isTop()) { 528 *this = L; 529 // L can be neither Top nor Bottom, so *this must have changed. 530 return true; 531 } 532 533 // Top/bottom cases covered. Need to integrate L's set into ours. 534 if (L.isProperty()) 535 return add(L.properties()); 536 for (unsigned i = 0; i < L.size(); ++i) { 537 const Constant *LC = L.Values[i]; 538 Changed |= add(LC); 539 } 540 return Changed; 541 } 542 543 // Add a new constant to the cell. This is actually where the cell update 544 // happens. If a cell has room for more constants, the new constant is added. 545 // Otherwise, the cell is converted to a "property" cell (i.e. a cell that 546 // will track properties of the associated values, and not the values 547 // themselves. Care is taken to handle special cases, like "bottom", etc. 548 bool LatticeCell::add(const Constant *LC) { 549 assert(LC); 550 if (isBottom()) 551 return false; 552 553 if (!isProperty()) { 554 // Cell is not special. Try to add the constant here first, 555 // if there is room. 556 unsigned Index = 0; 557 while (Index < Size) { 558 const Constant *C = Values[Index]; 559 // If the constant is already here, no change is needed. 560 if (C == LC) 561 return false; 562 Index++; 563 } 564 if (Index < MaxCellSize) { 565 Values[Index] = LC; 566 Kind = Normal; 567 Size++; 568 return true; 569 } 570 } 571 572 bool Changed = false; 573 574 // This cell is special, or is not special, but is full. After this 575 // it will be special. 576 Changed = convertToProperty(); 577 uint32_t Ps = properties(); 578 uint32_t NewPs = Ps & ConstantProperties::deduce(LC); 579 if (NewPs == ConstantProperties::Unknown) { 580 setBottom(); 581 return true; 582 } 583 if (Ps != NewPs) { 584 Properties = NewPs; 585 Changed = true; 586 } 587 return Changed; 588 } 589 590 // Add a property to the cell. This will force the cell to become a property- 591 // tracking cell. 592 bool LatticeCell::add(uint32_t Property) { 593 bool Changed = convertToProperty(); 594 uint32_t Ps = properties(); 595 if (Ps == (Ps & Property)) 596 return Changed; 597 Properties = Property & Ps; 598 return true; 599 } 600 601 // Return the properties of the values in the cell. This is valid for any 602 // cell, and does not alter the cell itself. 603 uint32_t LatticeCell::properties() const { 604 if (isProperty()) 605 return Properties; 606 assert(!isTop() && "Should not call this for a top cell"); 607 if (isBottom()) 608 return ConstantProperties::Unknown; 609 610 assert(size() > 0 && "Empty cell"); 611 uint32_t Ps = ConstantProperties::deduce(Values[0]); 612 for (unsigned i = 1; i < size(); ++i) { 613 if (Ps == ConstantProperties::Unknown) 614 break; 615 Ps &= ConstantProperties::deduce(Values[i]); 616 } 617 return Ps; 618 } 619 620 #ifndef NDEBUG 621 void MachineConstPropagator::CellMap::print(raw_ostream &os, 622 const TargetRegisterInfo &TRI) const { 623 for (auto &I : Map) 624 dbgs() << " " << printReg(I.first, &TRI) << " -> " << I.second << '\n'; 625 } 626 #endif 627 628 void MachineConstPropagator::visitPHI(const MachineInstr &PN) { 629 const MachineBasicBlock *MB = PN.getParent(); 630 unsigned MBN = MB->getNumber(); 631 LLVM_DEBUG(dbgs() << "Visiting FI(" << printMBBReference(*MB) << "): " << PN); 632 633 const MachineOperand &MD = PN.getOperand(0); 634 RegisterSubReg DefR(MD); 635 assert(DefR.Reg.isVirtual()); 636 637 bool Changed = false; 638 639 // If the def has a sub-register, set the corresponding cell to "bottom". 640 if (DefR.SubReg) { 641 Bottomize: 642 const LatticeCell &T = Cells.get(DefR.Reg); 643 Changed = !T.isBottom(); 644 Cells.update(DefR.Reg, Bottom); 645 if (Changed) 646 visitUsesOf(DefR.Reg); 647 return; 648 } 649 650 LatticeCell DefC = Cells.get(DefR.Reg); 651 652 for (unsigned i = 1, n = PN.getNumOperands(); i < n; i += 2) { 653 const MachineBasicBlock *PB = PN.getOperand(i+1).getMBB(); 654 unsigned PBN = PB->getNumber(); 655 if (!EdgeExec.count(CFGEdge(PBN, MBN))) { 656 LLVM_DEBUG(dbgs() << " edge " << printMBBReference(*PB) << "->" 657 << printMBBReference(*MB) << " not executable\n"); 658 continue; 659 } 660 const MachineOperand &SO = PN.getOperand(i); 661 RegisterSubReg UseR(SO); 662 // If the input is not a virtual register, we don't really know what 663 // value it holds. 664 if (!UseR.Reg.isVirtual()) 665 goto Bottomize; 666 // If there is no cell for an input register, it means top. 667 if (!Cells.has(UseR.Reg)) 668 continue; 669 670 LatticeCell SrcC; 671 bool Eval = MCE.evaluate(UseR, Cells.get(UseR.Reg), SrcC); 672 LLVM_DEBUG(dbgs() << " edge from " << printMBBReference(*PB) << ": " 673 << printReg(UseR.Reg, &MCE.TRI, UseR.SubReg) << SrcC 674 << '\n'); 675 Changed |= Eval ? DefC.meet(SrcC) 676 : DefC.setBottom(); 677 Cells.update(DefR.Reg, DefC); 678 if (DefC.isBottom()) 679 break; 680 } 681 if (Changed) 682 visitUsesOf(DefR.Reg); 683 } 684 685 void MachineConstPropagator::visitNonBranch(const MachineInstr &MI) { 686 LLVM_DEBUG(dbgs() << "Visiting MI(" << printMBBReference(*MI.getParent()) 687 << "): " << MI); 688 CellMap Outputs; 689 bool Eval = MCE.evaluate(MI, Cells, Outputs); 690 LLVM_DEBUG({ 691 if (Eval) { 692 dbgs() << " outputs:"; 693 for (auto &I : Outputs) 694 dbgs() << ' ' << I.second; 695 dbgs() << '\n'; 696 } 697 }); 698 699 // Update outputs. If the value was not computed, set all the 700 // def cells to bottom. 701 for (const MachineOperand &MO : MI.operands()) { 702 if (!MO.isReg() || !MO.isDef()) 703 continue; 704 RegisterSubReg DefR(MO); 705 // Only track virtual registers. 706 if (!DefR.Reg.isVirtual()) 707 continue; 708 bool Changed = false; 709 // If the evaluation failed, set cells for all output registers to bottom. 710 if (!Eval) { 711 const LatticeCell &T = Cells.get(DefR.Reg); 712 Changed = !T.isBottom(); 713 Cells.update(DefR.Reg, Bottom); 714 } else { 715 // Find the corresponding cell in the computed outputs. 716 // If it's not there, go on to the next def. 717 if (!Outputs.has(DefR.Reg)) 718 continue; 719 LatticeCell RC = Cells.get(DefR.Reg); 720 Changed = RC.meet(Outputs.get(DefR.Reg)); 721 Cells.update(DefR.Reg, RC); 722 } 723 if (Changed) 724 visitUsesOf(DefR.Reg); 725 } 726 } 727 728 // Starting at a given branch, visit remaining branches in the block. 729 // Traverse over the subsequent branches for as long as the preceding one 730 // can fall through. Add all the possible targets to the flow work queue, 731 // including the potential fall-through to the layout-successor block. 732 void MachineConstPropagator::visitBranchesFrom(const MachineInstr &BrI) { 733 const MachineBasicBlock &B = *BrI.getParent(); 734 unsigned MBN = B.getNumber(); 735 MachineBasicBlock::const_iterator It = BrI.getIterator(); 736 MachineBasicBlock::const_iterator End = B.end(); 737 738 SetVector<const MachineBasicBlock*> Targets; 739 bool EvalOk = true, FallsThru = true; 740 while (It != End) { 741 const MachineInstr &MI = *It; 742 InstrExec.insert(&MI); 743 LLVM_DEBUG(dbgs() << "Visiting " << (EvalOk ? "BR" : "br") << "(" 744 << printMBBReference(B) << "): " << MI); 745 // Do not evaluate subsequent branches if the evaluation of any of the 746 // previous branches failed. Keep iterating over the branches only 747 // to mark them as executable. 748 EvalOk = EvalOk && MCE.evaluate(MI, Cells, Targets, FallsThru); 749 if (!EvalOk) 750 FallsThru = true; 751 if (!FallsThru) 752 break; 753 ++It; 754 } 755 756 if (B.mayHaveInlineAsmBr()) 757 EvalOk = false; 758 759 if (EvalOk) { 760 // Need to add all CFG successors that lead to EH landing pads. 761 // There won't be explicit branches to these blocks, but they must 762 // be processed. 763 for (const MachineBasicBlock *SB : B.successors()) { 764 if (SB->isEHPad()) 765 Targets.insert(SB); 766 } 767 if (FallsThru) { 768 const MachineFunction &MF = *B.getParent(); 769 MachineFunction::const_iterator BI = B.getIterator(); 770 MachineFunction::const_iterator Next = std::next(BI); 771 if (Next != MF.end()) 772 Targets.insert(&*Next); 773 } 774 } else { 775 // If the evaluation of the branches failed, make "Targets" to be the 776 // set of all successors of the block from the CFG. 777 // If the evaluation succeeded for all visited branches, then if the 778 // last one set "FallsThru", then add an edge to the layout successor 779 // to the targets. 780 Targets.clear(); 781 LLVM_DEBUG(dbgs() << " failed to evaluate a branch...adding all CFG " 782 "successors\n"); 783 for (const MachineBasicBlock *SB : B.successors()) 784 Targets.insert(SB); 785 } 786 787 for (const MachineBasicBlock *TB : Targets) { 788 unsigned TBN = TB->getNumber(); 789 LLVM_DEBUG(dbgs() << " pushing edge " << printMBBReference(B) << " -> " 790 << printMBBReference(*TB) << "\n"); 791 FlowQ.push(CFGEdge(MBN, TBN)); 792 } 793 } 794 795 void MachineConstPropagator::visitUsesOf(unsigned Reg) { 796 LLVM_DEBUG(dbgs() << "Visiting uses of " << printReg(Reg, &MCE.TRI) 797 << Cells.get(Reg) << '\n'); 798 for (MachineInstr &MI : MRI->use_nodbg_instructions(Reg)) { 799 // Do not process non-executable instructions. They can become exceutable 800 // later (via a flow-edge in the work queue). In such case, the instruc- 801 // tion will be visited at that time. 802 if (!InstrExec.count(&MI)) 803 continue; 804 if (MI.isPHI()) 805 visitPHI(MI); 806 else if (!MI.isBranch()) 807 visitNonBranch(MI); 808 else 809 visitBranchesFrom(MI); 810 } 811 } 812 813 bool MachineConstPropagator::computeBlockSuccessors(const MachineBasicBlock *MB, 814 SetVector<const MachineBasicBlock*> &Targets) { 815 Targets.clear(); 816 817 MachineBasicBlock::const_iterator FirstBr = MB->end(); 818 for (const MachineInstr &MI : *MB) { 819 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR) 820 return false; 821 if (MI.isDebugInstr()) 822 continue; 823 if (MI.isBranch()) { 824 FirstBr = MI.getIterator(); 825 break; 826 } 827 } 828 829 MachineBasicBlock::const_iterator End = MB->end(); 830 831 bool DoNext = true; 832 for (MachineBasicBlock::const_iterator I = FirstBr; I != End; ++I) { 833 const MachineInstr &MI = *I; 834 // Can there be debug instructions between branches? 835 if (MI.isDebugInstr()) 836 continue; 837 if (!InstrExec.count(&MI)) 838 continue; 839 bool Eval = MCE.evaluate(MI, Cells, Targets, DoNext); 840 if (!Eval) 841 return false; 842 if (!DoNext) 843 break; 844 } 845 // If the last branch could fall-through, add block's layout successor. 846 if (DoNext) { 847 MachineFunction::const_iterator BI = MB->getIterator(); 848 MachineFunction::const_iterator NextI = std::next(BI); 849 if (NextI != MB->getParent()->end()) 850 Targets.insert(&*NextI); 851 } 852 853 // Add all the EH landing pads. 854 for (const MachineBasicBlock *SB : MB->successors()) 855 if (SB->isEHPad()) 856 Targets.insert(SB); 857 858 return true; 859 } 860 861 void MachineConstPropagator::removeCFGEdge(MachineBasicBlock *From, 862 MachineBasicBlock *To) { 863 // First, remove the CFG successor/predecessor information. 864 From->removeSuccessor(To); 865 // Remove all corresponding PHI operands in the To block. 866 for (MachineInstr &PN : To->phis()) { 867 // reg0 = PHI reg1, bb2, reg3, bb4, ... 868 int N = PN.getNumOperands() - 2; 869 while (N > 0) { 870 if (PN.getOperand(N + 1).getMBB() == From) { 871 PN.RemoveOperand(N + 1); 872 PN.RemoveOperand(N); 873 } 874 N -= 2; 875 } 876 } 877 } 878 879 void MachineConstPropagator::propagate(MachineFunction &MF) { 880 MachineBasicBlock *Entry = GraphTraits<MachineFunction*>::getEntryNode(&MF); 881 unsigned EntryNum = Entry->getNumber(); 882 883 // Start with a fake edge, just to process the entry node. 884 FlowQ.push(CFGEdge(EntryNum, EntryNum)); 885 886 while (!FlowQ.empty()) { 887 CFGEdge Edge = FlowQ.front(); 888 FlowQ.pop(); 889 890 LLVM_DEBUG( 891 dbgs() << "Picked edge " 892 << printMBBReference(*MF.getBlockNumbered(Edge.first)) << "->" 893 << printMBBReference(*MF.getBlockNumbered(Edge.second)) << '\n'); 894 if (Edge.first != EntryNum) 895 if (EdgeExec.count(Edge)) 896 continue; 897 EdgeExec.insert(Edge); 898 MachineBasicBlock *SB = MF.getBlockNumbered(Edge.second); 899 900 // Process the block in three stages: 901 // - visit all PHI nodes, 902 // - visit all non-branch instructions, 903 // - visit block branches. 904 MachineBasicBlock::const_iterator It = SB->begin(), End = SB->end(); 905 906 // Visit PHI nodes in the successor block. 907 while (It != End && It->isPHI()) { 908 InstrExec.insert(&*It); 909 visitPHI(*It); 910 ++It; 911 } 912 913 // If the successor block just became executable, visit all instructions. 914 // To see if this is the first time we're visiting it, check the first 915 // non-debug instruction to see if it is executable. 916 while (It != End && It->isDebugInstr()) 917 ++It; 918 assert(It == End || !It->isPHI()); 919 // If this block has been visited, go on to the next one. 920 if (It != End && InstrExec.count(&*It)) 921 continue; 922 // For now, scan all non-branch instructions. Branches require different 923 // processing. 924 while (It != End && !It->isBranch()) { 925 if (!It->isDebugInstr()) { 926 InstrExec.insert(&*It); 927 visitNonBranch(*It); 928 } 929 ++It; 930 } 931 932 // Time to process the end of the block. This is different from 933 // processing regular (non-branch) instructions, because there can 934 // be multiple branches in a block, and they can cause the block to 935 // terminate early. 936 if (It != End) { 937 visitBranchesFrom(*It); 938 } else { 939 // If the block didn't have a branch, add all successor edges to the 940 // work queue. (There should really be only one successor in such case.) 941 unsigned SBN = SB->getNumber(); 942 for (const MachineBasicBlock *SSB : SB->successors()) 943 FlowQ.push(CFGEdge(SBN, SSB->getNumber())); 944 } 945 } // while (FlowQ) 946 947 LLVM_DEBUG({ 948 dbgs() << "Cells after propagation:\n"; 949 Cells.print(dbgs(), MCE.TRI); 950 dbgs() << "Dead CFG edges:\n"; 951 for (const MachineBasicBlock &B : MF) { 952 unsigned BN = B.getNumber(); 953 for (const MachineBasicBlock *SB : B.successors()) { 954 unsigned SN = SB->getNumber(); 955 if (!EdgeExec.count(CFGEdge(BN, SN))) 956 dbgs() << " " << printMBBReference(B) << " -> " 957 << printMBBReference(*SB) << '\n'; 958 } 959 } 960 }); 961 } 962 963 bool MachineConstPropagator::rewrite(MachineFunction &MF) { 964 bool Changed = false; 965 // Rewrite all instructions based on the collected cell information. 966 // 967 // Traverse the instructions in a post-order, so that rewriting an 968 // instruction can make changes "downstream" in terms of control-flow 969 // without affecting the rewriting process. (We should not change 970 // instructions that have not yet been visited by the rewriter.) 971 // The reason for this is that the rewriter can introduce new vregs, 972 // and replace uses of old vregs (which had corresponding cells 973 // computed during propagation) with these new vregs (which at this 974 // point would not have any cells, and would appear to be "top"). 975 // If an attempt was made to evaluate an instruction with a fresh 976 // "top" vreg, it would cause an error (abend) in the evaluator. 977 978 // Collect the post-order-traversal block ordering. The subsequent 979 // traversal/rewrite will update block successors, so it's safer 980 // if the visiting order it computed ahead of time. 981 std::vector<MachineBasicBlock*> POT; 982 for (MachineBasicBlock *B : post_order(&MF)) 983 if (!B->empty()) 984 POT.push_back(B); 985 986 for (MachineBasicBlock *B : POT) { 987 // Walk the block backwards (which usually begin with the branches). 988 // If any branch is rewritten, we may need to update the successor 989 // information for this block. Unless the block's successors can be 990 // precisely determined (which may not be the case for indirect 991 // branches), we cannot modify any branch. 992 993 // Compute the successor information. 994 SetVector<const MachineBasicBlock*> Targets; 995 bool HaveTargets = computeBlockSuccessors(B, Targets); 996 // Rewrite the executable instructions. Skip branches if we don't 997 // have block successor information. 998 for (auto I = B->rbegin(), E = B->rend(); I != E; ++I) { 999 MachineInstr &MI = *I; 1000 if (InstrExec.count(&MI)) { 1001 if (MI.isBranch() && !HaveTargets) 1002 continue; 1003 Changed |= MCE.rewrite(MI, Cells); 1004 } 1005 } 1006 // The rewriting could rewrite PHI nodes to non-PHI nodes, causing 1007 // regular instructions to appear in between PHI nodes. Bring all 1008 // the PHI nodes to the beginning of the block. 1009 for (auto I = B->begin(), E = B->end(); I != E; ++I) { 1010 if (I->isPHI()) 1011 continue; 1012 // I is not PHI. Find the next PHI node P. 1013 auto P = I; 1014 while (++P != E) 1015 if (P->isPHI()) 1016 break; 1017 // Not found. 1018 if (P == E) 1019 break; 1020 // Splice P right before I. 1021 B->splice(I, B, P); 1022 // Reset I to point at the just spliced PHI node. 1023 --I; 1024 } 1025 // Update the block successor information: remove unnecessary successors. 1026 if (HaveTargets) { 1027 SmallVector<MachineBasicBlock*,2> ToRemove; 1028 for (MachineBasicBlock *SB : B->successors()) { 1029 if (!Targets.count(SB)) 1030 ToRemove.push_back(const_cast<MachineBasicBlock*>(SB)); 1031 Targets.remove(SB); 1032 } 1033 for (unsigned i = 0, n = ToRemove.size(); i < n; ++i) 1034 removeCFGEdge(B, ToRemove[i]); 1035 // If there are any blocks left in the computed targets, it means that 1036 // we think that the block could go somewhere, but the CFG does not. 1037 // This could legitimately happen in blocks that have non-returning 1038 // calls---we would think that the execution can continue, but the 1039 // CFG will not have a successor edge. 1040 } 1041 } 1042 // Need to do some final post-processing. 1043 // If a branch was not executable, it will not get rewritten, but should 1044 // be removed (or replaced with something equivalent to a A2_nop). We can't 1045 // erase instructions during rewriting, so this needs to be delayed until 1046 // now. 1047 for (MachineBasicBlock &B : MF) { 1048 MachineBasicBlock::iterator I = B.begin(), E = B.end(); 1049 while (I != E) { 1050 auto Next = std::next(I); 1051 if (I->isBranch() && !InstrExec.count(&*I)) 1052 B.erase(I); 1053 I = Next; 1054 } 1055 } 1056 return Changed; 1057 } 1058 1059 // This is the constant propagation algorithm as described by Wegman-Zadeck. 1060 // Most of the terminology comes from there. 1061 bool MachineConstPropagator::run(MachineFunction &MF) { 1062 LLVM_DEBUG(MF.print(dbgs() << "Starting MachineConstPropagator\n", nullptr)); 1063 1064 MRI = &MF.getRegInfo(); 1065 1066 Cells.clear(); 1067 EdgeExec.clear(); 1068 InstrExec.clear(); 1069 assert(FlowQ.empty()); 1070 1071 propagate(MF); 1072 bool Changed = rewrite(MF); 1073 1074 LLVM_DEBUG({ 1075 dbgs() << "End of MachineConstPropagator (Changed=" << Changed << ")\n"; 1076 if (Changed) 1077 MF.print(dbgs(), nullptr); 1078 }); 1079 return Changed; 1080 } 1081 1082 // -------------------------------------------------------------------- 1083 // Machine const evaluator. 1084 1085 bool MachineConstEvaluator::getCell(const RegisterSubReg &R, const CellMap &Inputs, 1086 LatticeCell &RC) { 1087 if (!R.Reg.isVirtual()) 1088 return false; 1089 const LatticeCell &L = Inputs.get(R.Reg); 1090 if (!R.SubReg) { 1091 RC = L; 1092 return !RC.isBottom(); 1093 } 1094 bool Eval = evaluate(R, L, RC); 1095 return Eval && !RC.isBottom(); 1096 } 1097 1098 bool MachineConstEvaluator::constToInt(const Constant *C, 1099 APInt &Val) const { 1100 const ConstantInt *CI = dyn_cast<ConstantInt>(C); 1101 if (!CI) 1102 return false; 1103 Val = CI->getValue(); 1104 return true; 1105 } 1106 1107 const ConstantInt *MachineConstEvaluator::intToConst(const APInt &Val) const { 1108 return ConstantInt::get(CX, Val); 1109 } 1110 1111 bool MachineConstEvaluator::evaluateCMPrr(uint32_t Cmp, const RegisterSubReg &R1, 1112 const RegisterSubReg &R2, const CellMap &Inputs, bool &Result) { 1113 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg)); 1114 LatticeCell LS1, LS2; 1115 if (!getCell(R1, Inputs, LS1) || !getCell(R2, Inputs, LS2)) 1116 return false; 1117 1118 bool IsProp1 = LS1.isProperty(); 1119 bool IsProp2 = LS2.isProperty(); 1120 if (IsProp1) { 1121 uint32_t Prop1 = LS1.properties(); 1122 if (IsProp2) 1123 return evaluateCMPpp(Cmp, Prop1, LS2.properties(), Result); 1124 uint32_t NegCmp = Comparison::negate(Cmp); 1125 return evaluateCMPrp(NegCmp, R2, Prop1, Inputs, Result); 1126 } 1127 if (IsProp2) { 1128 uint32_t Prop2 = LS2.properties(); 1129 return evaluateCMPrp(Cmp, R1, Prop2, Inputs, Result); 1130 } 1131 1132 APInt A; 1133 bool IsTrue = true, IsFalse = true; 1134 for (unsigned i = 0; i < LS2.size(); ++i) { 1135 bool Res; 1136 bool Computed = constToInt(LS2.Values[i], A) && 1137 evaluateCMPri(Cmp, R1, A, Inputs, Res); 1138 if (!Computed) 1139 return false; 1140 IsTrue &= Res; 1141 IsFalse &= !Res; 1142 } 1143 assert(!IsTrue || !IsFalse); 1144 // The actual logical value of the comparison is same as IsTrue. 1145 Result = IsTrue; 1146 // Return true if the result was proven to be true or proven to be false. 1147 return IsTrue || IsFalse; 1148 } 1149 1150 bool MachineConstEvaluator::evaluateCMPri(uint32_t Cmp, const RegisterSubReg &R1, 1151 const APInt &A2, const CellMap &Inputs, bool &Result) { 1152 assert(Inputs.has(R1.Reg)); 1153 LatticeCell LS; 1154 if (!getCell(R1, Inputs, LS)) 1155 return false; 1156 if (LS.isProperty()) 1157 return evaluateCMPpi(Cmp, LS.properties(), A2, Result); 1158 1159 APInt A; 1160 bool IsTrue = true, IsFalse = true; 1161 for (unsigned i = 0; i < LS.size(); ++i) { 1162 bool Res; 1163 bool Computed = constToInt(LS.Values[i], A) && 1164 evaluateCMPii(Cmp, A, A2, Res); 1165 if (!Computed) 1166 return false; 1167 IsTrue &= Res; 1168 IsFalse &= !Res; 1169 } 1170 assert(!IsTrue || !IsFalse); 1171 // The actual logical value of the comparison is same as IsTrue. 1172 Result = IsTrue; 1173 // Return true if the result was proven to be true or proven to be false. 1174 return IsTrue || IsFalse; 1175 } 1176 1177 bool MachineConstEvaluator::evaluateCMPrp(uint32_t Cmp, const RegisterSubReg &R1, 1178 uint64_t Props2, const CellMap &Inputs, bool &Result) { 1179 assert(Inputs.has(R1.Reg)); 1180 LatticeCell LS; 1181 if (!getCell(R1, Inputs, LS)) 1182 return false; 1183 if (LS.isProperty()) 1184 return evaluateCMPpp(Cmp, LS.properties(), Props2, Result); 1185 1186 APInt A; 1187 uint32_t NegCmp = Comparison::negate(Cmp); 1188 bool IsTrue = true, IsFalse = true; 1189 for (unsigned i = 0; i < LS.size(); ++i) { 1190 bool Res; 1191 bool Computed = constToInt(LS.Values[i], A) && 1192 evaluateCMPpi(NegCmp, Props2, A, Res); 1193 if (!Computed) 1194 return false; 1195 IsTrue &= Res; 1196 IsFalse &= !Res; 1197 } 1198 assert(!IsTrue || !IsFalse); 1199 Result = IsTrue; 1200 return IsTrue || IsFalse; 1201 } 1202 1203 bool MachineConstEvaluator::evaluateCMPii(uint32_t Cmp, const APInt &A1, 1204 const APInt &A2, bool &Result) { 1205 // NE is a special kind of comparison (not composed of smaller properties). 1206 if (Cmp == Comparison::NE) { 1207 Result = !APInt::isSameValue(A1, A2); 1208 return true; 1209 } 1210 if (Cmp == Comparison::EQ) { 1211 Result = APInt::isSameValue(A1, A2); 1212 return true; 1213 } 1214 if (Cmp & Comparison::EQ) { 1215 if (APInt::isSameValue(A1, A2)) 1216 return (Result = true); 1217 } 1218 assert((Cmp & (Comparison::L | Comparison::G)) && "Malformed comparison"); 1219 Result = false; 1220 1221 unsigned W1 = A1.getBitWidth(); 1222 unsigned W2 = A2.getBitWidth(); 1223 unsigned MaxW = (W1 >= W2) ? W1 : W2; 1224 if (Cmp & Comparison::U) { 1225 const APInt Zx1 = A1.zextOrSelf(MaxW); 1226 const APInt Zx2 = A2.zextOrSelf(MaxW); 1227 if (Cmp & Comparison::L) 1228 Result = Zx1.ult(Zx2); 1229 else if (Cmp & Comparison::G) 1230 Result = Zx2.ult(Zx1); 1231 return true; 1232 } 1233 1234 // Signed comparison. 1235 const APInt Sx1 = A1.sextOrSelf(MaxW); 1236 const APInt Sx2 = A2.sextOrSelf(MaxW); 1237 if (Cmp & Comparison::L) 1238 Result = Sx1.slt(Sx2); 1239 else if (Cmp & Comparison::G) 1240 Result = Sx2.slt(Sx1); 1241 return true; 1242 } 1243 1244 bool MachineConstEvaluator::evaluateCMPpi(uint32_t Cmp, uint32_t Props, 1245 const APInt &A2, bool &Result) { 1246 if (Props == ConstantProperties::Unknown) 1247 return false; 1248 1249 // Should never see NaN here, but check for it for completeness. 1250 if (Props & ConstantProperties::NaN) 1251 return false; 1252 // Infinity could theoretically be compared to a number, but the 1253 // presence of infinity here would be very suspicious. If we don't 1254 // know for sure that the number is finite, bail out. 1255 if (!(Props & ConstantProperties::Finite)) 1256 return false; 1257 1258 // Let X be a number that has properties Props. 1259 1260 if (Cmp & Comparison::U) { 1261 // In case of unsigned comparisons, we can only compare against 0. 1262 if (A2 == 0) { 1263 // Any x!=0 will be considered >0 in an unsigned comparison. 1264 if (Props & ConstantProperties::Zero) 1265 Result = (Cmp & Comparison::EQ); 1266 else if (Props & ConstantProperties::NonZero) 1267 Result = (Cmp & Comparison::G) || (Cmp == Comparison::NE); 1268 else 1269 return false; 1270 return true; 1271 } 1272 // A2 is not zero. The only handled case is if X = 0. 1273 if (Props & ConstantProperties::Zero) { 1274 Result = (Cmp & Comparison::L) || (Cmp == Comparison::NE); 1275 return true; 1276 } 1277 return false; 1278 } 1279 1280 // Signed comparisons are different. 1281 if (Props & ConstantProperties::Zero) { 1282 if (A2 == 0) 1283 Result = (Cmp & Comparison::EQ); 1284 else 1285 Result = (Cmp == Comparison::NE) || 1286 ((Cmp & Comparison::L) && !A2.isNegative()) || 1287 ((Cmp & Comparison::G) && A2.isNegative()); 1288 return true; 1289 } 1290 if (Props & ConstantProperties::PosOrZero) { 1291 // X >= 0 and !(A2 < 0) => cannot compare 1292 if (!A2.isNegative()) 1293 return false; 1294 // X >= 0 and A2 < 0 1295 Result = (Cmp & Comparison::G) || (Cmp == Comparison::NE); 1296 return true; 1297 } 1298 if (Props & ConstantProperties::NegOrZero) { 1299 // X <= 0 and Src1 < 0 => cannot compare 1300 if (A2 == 0 || A2.isNegative()) 1301 return false; 1302 // X <= 0 and A2 > 0 1303 Result = (Cmp & Comparison::L) || (Cmp == Comparison::NE); 1304 return true; 1305 } 1306 1307 return false; 1308 } 1309 1310 bool MachineConstEvaluator::evaluateCMPpp(uint32_t Cmp, uint32_t Props1, 1311 uint32_t Props2, bool &Result) { 1312 using P = ConstantProperties; 1313 1314 if ((Props1 & P::NaN) && (Props2 & P::NaN)) 1315 return false; 1316 if (!(Props1 & P::Finite) || !(Props2 & P::Finite)) 1317 return false; 1318 1319 bool Zero1 = (Props1 & P::Zero), Zero2 = (Props2 & P::Zero); 1320 bool NonZero1 = (Props1 & P::NonZero), NonZero2 = (Props2 & P::NonZero); 1321 if (Zero1 && Zero2) { 1322 Result = (Cmp & Comparison::EQ); 1323 return true; 1324 } 1325 if (Cmp == Comparison::NE) { 1326 if ((Zero1 && NonZero2) || (NonZero1 && Zero2)) 1327 return (Result = true); 1328 return false; 1329 } 1330 1331 if (Cmp & Comparison::U) { 1332 // In unsigned comparisons, we can only compare against a known zero, 1333 // or a known non-zero. 1334 if (Zero1 && NonZero2) { 1335 Result = (Cmp & Comparison::L); 1336 return true; 1337 } 1338 if (NonZero1 && Zero2) { 1339 Result = (Cmp & Comparison::G); 1340 return true; 1341 } 1342 return false; 1343 } 1344 1345 // Signed comparison. The comparison is not NE. 1346 bool Poz1 = (Props1 & P::PosOrZero), Poz2 = (Props2 & P::PosOrZero); 1347 bool Nez1 = (Props1 & P::NegOrZero), Nez2 = (Props2 & P::NegOrZero); 1348 if (Nez1 && Poz2) { 1349 if (NonZero1 || NonZero2) { 1350 Result = (Cmp & Comparison::L); 1351 return true; 1352 } 1353 // Either (or both) could be zero. Can only say that X <= Y. 1354 if ((Cmp & Comparison::EQ) && (Cmp & Comparison::L)) 1355 return (Result = true); 1356 } 1357 if (Poz1 && Nez2) { 1358 if (NonZero1 || NonZero2) { 1359 Result = (Cmp & Comparison::G); 1360 return true; 1361 } 1362 // Either (or both) could be zero. Can only say that X >= Y. 1363 if ((Cmp & Comparison::EQ) && (Cmp & Comparison::G)) 1364 return (Result = true); 1365 } 1366 1367 return false; 1368 } 1369 1370 bool MachineConstEvaluator::evaluateCOPY(const RegisterSubReg &R1, 1371 const CellMap &Inputs, LatticeCell &Result) { 1372 return getCell(R1, Inputs, Result); 1373 } 1374 1375 bool MachineConstEvaluator::evaluateANDrr(const RegisterSubReg &R1, 1376 const RegisterSubReg &R2, const CellMap &Inputs, LatticeCell &Result) { 1377 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg)); 1378 const LatticeCell &L1 = Inputs.get(R2.Reg); 1379 const LatticeCell &L2 = Inputs.get(R2.Reg); 1380 // If both sources are bottom, exit. Otherwise try to evaluate ANDri 1381 // with the non-bottom argument passed as the immediate. This is to 1382 // catch cases of ANDing with 0. 1383 if (L2.isBottom()) { 1384 if (L1.isBottom()) 1385 return false; 1386 return evaluateANDrr(R2, R1, Inputs, Result); 1387 } 1388 LatticeCell LS2; 1389 if (!evaluate(R2, L2, LS2)) 1390 return false; 1391 if (LS2.isBottom() || LS2.isProperty()) 1392 return false; 1393 1394 APInt A; 1395 for (unsigned i = 0; i < LS2.size(); ++i) { 1396 LatticeCell RC; 1397 bool Eval = constToInt(LS2.Values[i], A) && 1398 evaluateANDri(R1, A, Inputs, RC); 1399 if (!Eval) 1400 return false; 1401 Result.meet(RC); 1402 } 1403 return !Result.isBottom(); 1404 } 1405 1406 bool MachineConstEvaluator::evaluateANDri(const RegisterSubReg &R1, 1407 const APInt &A2, const CellMap &Inputs, LatticeCell &Result) { 1408 assert(Inputs.has(R1.Reg)); 1409 if (A2 == -1) 1410 return getCell(R1, Inputs, Result); 1411 if (A2 == 0) { 1412 LatticeCell RC; 1413 RC.add(intToConst(A2)); 1414 // Overwrite Result. 1415 Result = RC; 1416 return true; 1417 } 1418 LatticeCell LS1; 1419 if (!getCell(R1, Inputs, LS1)) 1420 return false; 1421 if (LS1.isBottom() || LS1.isProperty()) 1422 return false; 1423 1424 APInt A, ResA; 1425 for (unsigned i = 0; i < LS1.size(); ++i) { 1426 bool Eval = constToInt(LS1.Values[i], A) && 1427 evaluateANDii(A, A2, ResA); 1428 if (!Eval) 1429 return false; 1430 const Constant *C = intToConst(ResA); 1431 Result.add(C); 1432 } 1433 return !Result.isBottom(); 1434 } 1435 1436 bool MachineConstEvaluator::evaluateANDii(const APInt &A1, 1437 const APInt &A2, APInt &Result) { 1438 Result = A1 & A2; 1439 return true; 1440 } 1441 1442 bool MachineConstEvaluator::evaluateORrr(const RegisterSubReg &R1, 1443 const RegisterSubReg &R2, const CellMap &Inputs, LatticeCell &Result) { 1444 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg)); 1445 const LatticeCell &L1 = Inputs.get(R2.Reg); 1446 const LatticeCell &L2 = Inputs.get(R2.Reg); 1447 // If both sources are bottom, exit. Otherwise try to evaluate ORri 1448 // with the non-bottom argument passed as the immediate. This is to 1449 // catch cases of ORing with -1. 1450 if (L2.isBottom()) { 1451 if (L1.isBottom()) 1452 return false; 1453 return evaluateORrr(R2, R1, Inputs, Result); 1454 } 1455 LatticeCell LS2; 1456 if (!evaluate(R2, L2, LS2)) 1457 return false; 1458 if (LS2.isBottom() || LS2.isProperty()) 1459 return false; 1460 1461 APInt A; 1462 for (unsigned i = 0; i < LS2.size(); ++i) { 1463 LatticeCell RC; 1464 bool Eval = constToInt(LS2.Values[i], A) && 1465 evaluateORri(R1, A, Inputs, RC); 1466 if (!Eval) 1467 return false; 1468 Result.meet(RC); 1469 } 1470 return !Result.isBottom(); 1471 } 1472 1473 bool MachineConstEvaluator::evaluateORri(const RegisterSubReg &R1, 1474 const APInt &A2, const CellMap &Inputs, LatticeCell &Result) { 1475 assert(Inputs.has(R1.Reg)); 1476 if (A2 == 0) 1477 return getCell(R1, Inputs, Result); 1478 if (A2 == -1) { 1479 LatticeCell RC; 1480 RC.add(intToConst(A2)); 1481 // Overwrite Result. 1482 Result = RC; 1483 return true; 1484 } 1485 LatticeCell LS1; 1486 if (!getCell(R1, Inputs, LS1)) 1487 return false; 1488 if (LS1.isBottom() || LS1.isProperty()) 1489 return false; 1490 1491 APInt A, ResA; 1492 for (unsigned i = 0; i < LS1.size(); ++i) { 1493 bool Eval = constToInt(LS1.Values[i], A) && 1494 evaluateORii(A, A2, ResA); 1495 if (!Eval) 1496 return false; 1497 const Constant *C = intToConst(ResA); 1498 Result.add(C); 1499 } 1500 return !Result.isBottom(); 1501 } 1502 1503 bool MachineConstEvaluator::evaluateORii(const APInt &A1, 1504 const APInt &A2, APInt &Result) { 1505 Result = A1 | A2; 1506 return true; 1507 } 1508 1509 bool MachineConstEvaluator::evaluateXORrr(const RegisterSubReg &R1, 1510 const RegisterSubReg &R2, const CellMap &Inputs, LatticeCell &Result) { 1511 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg)); 1512 LatticeCell LS1, LS2; 1513 if (!getCell(R1, Inputs, LS1) || !getCell(R2, Inputs, LS2)) 1514 return false; 1515 if (LS1.isProperty()) { 1516 if (LS1.properties() & ConstantProperties::Zero) 1517 return !(Result = LS2).isBottom(); 1518 return false; 1519 } 1520 if (LS2.isProperty()) { 1521 if (LS2.properties() & ConstantProperties::Zero) 1522 return !(Result = LS1).isBottom(); 1523 return false; 1524 } 1525 1526 APInt A; 1527 for (unsigned i = 0; i < LS2.size(); ++i) { 1528 LatticeCell RC; 1529 bool Eval = constToInt(LS2.Values[i], A) && 1530 evaluateXORri(R1, A, Inputs, RC); 1531 if (!Eval) 1532 return false; 1533 Result.meet(RC); 1534 } 1535 return !Result.isBottom(); 1536 } 1537 1538 bool MachineConstEvaluator::evaluateXORri(const RegisterSubReg &R1, 1539 const APInt &A2, const CellMap &Inputs, LatticeCell &Result) { 1540 assert(Inputs.has(R1.Reg)); 1541 LatticeCell LS1; 1542 if (!getCell(R1, Inputs, LS1)) 1543 return false; 1544 if (LS1.isProperty()) { 1545 if (LS1.properties() & ConstantProperties::Zero) { 1546 const Constant *C = intToConst(A2); 1547 Result.add(C); 1548 return !Result.isBottom(); 1549 } 1550 return false; 1551 } 1552 1553 APInt A, XA; 1554 for (unsigned i = 0; i < LS1.size(); ++i) { 1555 bool Eval = constToInt(LS1.Values[i], A) && 1556 evaluateXORii(A, A2, XA); 1557 if (!Eval) 1558 return false; 1559 const Constant *C = intToConst(XA); 1560 Result.add(C); 1561 } 1562 return !Result.isBottom(); 1563 } 1564 1565 bool MachineConstEvaluator::evaluateXORii(const APInt &A1, 1566 const APInt &A2, APInt &Result) { 1567 Result = A1 ^ A2; 1568 return true; 1569 } 1570 1571 bool MachineConstEvaluator::evaluateZEXTr(const RegisterSubReg &R1, unsigned Width, 1572 unsigned Bits, const CellMap &Inputs, LatticeCell &Result) { 1573 assert(Inputs.has(R1.Reg)); 1574 LatticeCell LS1; 1575 if (!getCell(R1, Inputs, LS1)) 1576 return false; 1577 if (LS1.isProperty()) 1578 return false; 1579 1580 APInt A, XA; 1581 for (unsigned i = 0; i < LS1.size(); ++i) { 1582 bool Eval = constToInt(LS1.Values[i], A) && 1583 evaluateZEXTi(A, Width, Bits, XA); 1584 if (!Eval) 1585 return false; 1586 const Constant *C = intToConst(XA); 1587 Result.add(C); 1588 } 1589 return true; 1590 } 1591 1592 bool MachineConstEvaluator::evaluateZEXTi(const APInt &A1, unsigned Width, 1593 unsigned Bits, APInt &Result) { 1594 unsigned BW = A1.getBitWidth(); 1595 (void)BW; 1596 assert(Width >= Bits && BW >= Bits); 1597 APInt Mask = APInt::getLowBitsSet(Width, Bits); 1598 Result = A1.zextOrTrunc(Width) & Mask; 1599 return true; 1600 } 1601 1602 bool MachineConstEvaluator::evaluateSEXTr(const RegisterSubReg &R1, unsigned Width, 1603 unsigned Bits, const CellMap &Inputs, LatticeCell &Result) { 1604 assert(Inputs.has(R1.Reg)); 1605 LatticeCell LS1; 1606 if (!getCell(R1, Inputs, LS1)) 1607 return false; 1608 if (LS1.isBottom() || LS1.isProperty()) 1609 return false; 1610 1611 APInt A, XA; 1612 for (unsigned i = 0; i < LS1.size(); ++i) { 1613 bool Eval = constToInt(LS1.Values[i], A) && 1614 evaluateSEXTi(A, Width, Bits, XA); 1615 if (!Eval) 1616 return false; 1617 const Constant *C = intToConst(XA); 1618 Result.add(C); 1619 } 1620 return true; 1621 } 1622 1623 bool MachineConstEvaluator::evaluateSEXTi(const APInt &A1, unsigned Width, 1624 unsigned Bits, APInt &Result) { 1625 unsigned BW = A1.getBitWidth(); 1626 assert(Width >= Bits && BW >= Bits); 1627 // Special case to make things faster for smaller source widths. 1628 // Sign extension of 0 bits generates 0 as a result. This is consistent 1629 // with what the HW does. 1630 if (Bits == 0) { 1631 Result = APInt(Width, 0); 1632 return true; 1633 } 1634 // In C, shifts by 64 invoke undefined behavior: handle that case in APInt. 1635 if (BW <= 64 && Bits != 0) { 1636 int64_t V = A1.getSExtValue(); 1637 switch (Bits) { 1638 case 8: 1639 V = static_cast<int8_t>(V); 1640 break; 1641 case 16: 1642 V = static_cast<int16_t>(V); 1643 break; 1644 case 32: 1645 V = static_cast<int32_t>(V); 1646 break; 1647 default: 1648 // Shift left to lose all bits except lower "Bits" bits, then shift 1649 // the value back, replicating what was a sign bit after the first 1650 // shift. 1651 V = (V << (64-Bits)) >> (64-Bits); 1652 break; 1653 } 1654 // V is a 64-bit sign-extended value. Convert it to APInt of desired 1655 // width. 1656 Result = APInt(Width, V, true); 1657 return true; 1658 } 1659 // Slow case: the value doesn't fit in int64_t. 1660 if (Bits < BW) 1661 Result = A1.trunc(Bits).sext(Width); 1662 else // Bits == BW 1663 Result = A1.sext(Width); 1664 return true; 1665 } 1666 1667 bool MachineConstEvaluator::evaluateCLBr(const RegisterSubReg &R1, bool Zeros, 1668 bool Ones, const CellMap &Inputs, LatticeCell &Result) { 1669 assert(Inputs.has(R1.Reg)); 1670 LatticeCell LS1; 1671 if (!getCell(R1, Inputs, LS1)) 1672 return false; 1673 if (LS1.isBottom() || LS1.isProperty()) 1674 return false; 1675 1676 APInt A, CA; 1677 for (unsigned i = 0; i < LS1.size(); ++i) { 1678 bool Eval = constToInt(LS1.Values[i], A) && 1679 evaluateCLBi(A, Zeros, Ones, CA); 1680 if (!Eval) 1681 return false; 1682 const Constant *C = intToConst(CA); 1683 Result.add(C); 1684 } 1685 return true; 1686 } 1687 1688 bool MachineConstEvaluator::evaluateCLBi(const APInt &A1, bool Zeros, 1689 bool Ones, APInt &Result) { 1690 unsigned BW = A1.getBitWidth(); 1691 if (!Zeros && !Ones) 1692 return false; 1693 unsigned Count = 0; 1694 if (Zeros && (Count == 0)) 1695 Count = A1.countLeadingZeros(); 1696 if (Ones && (Count == 0)) 1697 Count = A1.countLeadingOnes(); 1698 Result = APInt(BW, static_cast<uint64_t>(Count), false); 1699 return true; 1700 } 1701 1702 bool MachineConstEvaluator::evaluateCTBr(const RegisterSubReg &R1, bool Zeros, 1703 bool Ones, const CellMap &Inputs, LatticeCell &Result) { 1704 assert(Inputs.has(R1.Reg)); 1705 LatticeCell LS1; 1706 if (!getCell(R1, Inputs, LS1)) 1707 return false; 1708 if (LS1.isBottom() || LS1.isProperty()) 1709 return false; 1710 1711 APInt A, CA; 1712 for (unsigned i = 0; i < LS1.size(); ++i) { 1713 bool Eval = constToInt(LS1.Values[i], A) && 1714 evaluateCTBi(A, Zeros, Ones, CA); 1715 if (!Eval) 1716 return false; 1717 const Constant *C = intToConst(CA); 1718 Result.add(C); 1719 } 1720 return true; 1721 } 1722 1723 bool MachineConstEvaluator::evaluateCTBi(const APInt &A1, bool Zeros, 1724 bool Ones, APInt &Result) { 1725 unsigned BW = A1.getBitWidth(); 1726 if (!Zeros && !Ones) 1727 return false; 1728 unsigned Count = 0; 1729 if (Zeros && (Count == 0)) 1730 Count = A1.countTrailingZeros(); 1731 if (Ones && (Count == 0)) 1732 Count = A1.countTrailingOnes(); 1733 Result = APInt(BW, static_cast<uint64_t>(Count), false); 1734 return true; 1735 } 1736 1737 bool MachineConstEvaluator::evaluateEXTRACTr(const RegisterSubReg &R1, 1738 unsigned Width, unsigned Bits, unsigned Offset, bool Signed, 1739 const CellMap &Inputs, LatticeCell &Result) { 1740 assert(Inputs.has(R1.Reg)); 1741 assert(Bits+Offset <= Width); 1742 LatticeCell LS1; 1743 if (!getCell(R1, Inputs, LS1)) 1744 return false; 1745 if (LS1.isBottom()) 1746 return false; 1747 if (LS1.isProperty()) { 1748 uint32_t Ps = LS1.properties(); 1749 if (Ps & ConstantProperties::Zero) { 1750 const Constant *C = intToConst(APInt(Width, 0, false)); 1751 Result.add(C); 1752 return true; 1753 } 1754 return false; 1755 } 1756 1757 APInt A, CA; 1758 for (unsigned i = 0; i < LS1.size(); ++i) { 1759 bool Eval = constToInt(LS1.Values[i], A) && 1760 evaluateEXTRACTi(A, Bits, Offset, Signed, CA); 1761 if (!Eval) 1762 return false; 1763 const Constant *C = intToConst(CA); 1764 Result.add(C); 1765 } 1766 return true; 1767 } 1768 1769 bool MachineConstEvaluator::evaluateEXTRACTi(const APInt &A1, unsigned Bits, 1770 unsigned Offset, bool Signed, APInt &Result) { 1771 unsigned BW = A1.getBitWidth(); 1772 assert(Bits+Offset <= BW); 1773 // Extracting 0 bits generates 0 as a result (as indicated by the HW people). 1774 if (Bits == 0) { 1775 Result = APInt(BW, 0); 1776 return true; 1777 } 1778 if (BW <= 64) { 1779 int64_t V = A1.getZExtValue(); 1780 V <<= (64-Bits-Offset); 1781 if (Signed) 1782 V >>= (64-Bits); 1783 else 1784 V = static_cast<uint64_t>(V) >> (64-Bits); 1785 Result = APInt(BW, V, Signed); 1786 return true; 1787 } 1788 if (Signed) 1789 Result = A1.shl(BW-Bits-Offset).ashr(BW-Bits); 1790 else 1791 Result = A1.shl(BW-Bits-Offset).lshr(BW-Bits); 1792 return true; 1793 } 1794 1795 bool MachineConstEvaluator::evaluateSplatr(const RegisterSubReg &R1, 1796 unsigned Bits, unsigned Count, const CellMap &Inputs, 1797 LatticeCell &Result) { 1798 assert(Inputs.has(R1.Reg)); 1799 LatticeCell LS1; 1800 if (!getCell(R1, Inputs, LS1)) 1801 return false; 1802 if (LS1.isBottom() || LS1.isProperty()) 1803 return false; 1804 1805 APInt A, SA; 1806 for (unsigned i = 0; i < LS1.size(); ++i) { 1807 bool Eval = constToInt(LS1.Values[i], A) && 1808 evaluateSplati(A, Bits, Count, SA); 1809 if (!Eval) 1810 return false; 1811 const Constant *C = intToConst(SA); 1812 Result.add(C); 1813 } 1814 return true; 1815 } 1816 1817 bool MachineConstEvaluator::evaluateSplati(const APInt &A1, unsigned Bits, 1818 unsigned Count, APInt &Result) { 1819 assert(Count > 0); 1820 unsigned BW = A1.getBitWidth(), SW = Count*Bits; 1821 APInt LoBits = (Bits < BW) ? A1.trunc(Bits) : A1.zextOrSelf(Bits); 1822 if (Count > 1) 1823 LoBits = LoBits.zext(SW); 1824 1825 APInt Res(SW, 0, false); 1826 for (unsigned i = 0; i < Count; ++i) { 1827 Res <<= Bits; 1828 Res |= LoBits; 1829 } 1830 Result = Res; 1831 return true; 1832 } 1833 1834 // ---------------------------------------------------------------------- 1835 // Hexagon-specific code. 1836 1837 namespace llvm { 1838 1839 FunctionPass *createHexagonConstPropagationPass(); 1840 void initializeHexagonConstPropagationPass(PassRegistry &Registry); 1841 1842 } // end namespace llvm 1843 1844 namespace { 1845 1846 class HexagonConstEvaluator : public MachineConstEvaluator { 1847 public: 1848 HexagonConstEvaluator(MachineFunction &Fn); 1849 1850 bool evaluate(const MachineInstr &MI, const CellMap &Inputs, 1851 CellMap &Outputs) override; 1852 bool evaluate(const RegisterSubReg &R, const LatticeCell &SrcC, 1853 LatticeCell &Result) override; 1854 bool evaluate(const MachineInstr &BrI, const CellMap &Inputs, 1855 SetVector<const MachineBasicBlock*> &Targets, bool &FallsThru) 1856 override; 1857 bool rewrite(MachineInstr &MI, const CellMap &Inputs) override; 1858 1859 private: 1860 unsigned getRegBitWidth(unsigned Reg) const; 1861 1862 static uint32_t getCmp(unsigned Opc); 1863 static APInt getCmpImm(unsigned Opc, unsigned OpX, 1864 const MachineOperand &MO); 1865 void replaceWithNop(MachineInstr &MI); 1866 1867 bool evaluateHexRSEQ32(RegisterSubReg RL, RegisterSubReg RH, const CellMap &Inputs, 1868 LatticeCell &Result); 1869 bool evaluateHexCompare(const MachineInstr &MI, const CellMap &Inputs, 1870 CellMap &Outputs); 1871 // This is suitable to be called for compare-and-jump instructions. 1872 bool evaluateHexCompare2(uint32_t Cmp, const MachineOperand &Src1, 1873 const MachineOperand &Src2, const CellMap &Inputs, bool &Result); 1874 bool evaluateHexLogical(const MachineInstr &MI, const CellMap &Inputs, 1875 CellMap &Outputs); 1876 bool evaluateHexCondMove(const MachineInstr &MI, const CellMap &Inputs, 1877 CellMap &Outputs); 1878 bool evaluateHexExt(const MachineInstr &MI, const CellMap &Inputs, 1879 CellMap &Outputs); 1880 bool evaluateHexVector1(const MachineInstr &MI, const CellMap &Inputs, 1881 CellMap &Outputs); 1882 bool evaluateHexVector2(const MachineInstr &MI, const CellMap &Inputs, 1883 CellMap &Outputs); 1884 1885 void replaceAllRegUsesWith(Register FromReg, Register ToReg); 1886 bool rewriteHexBranch(MachineInstr &BrI, const CellMap &Inputs); 1887 bool rewriteHexConstDefs(MachineInstr &MI, const CellMap &Inputs, 1888 bool &AllDefs); 1889 bool rewriteHexConstUses(MachineInstr &MI, const CellMap &Inputs); 1890 1891 MachineRegisterInfo *MRI; 1892 const HexagonInstrInfo &HII; 1893 const HexagonRegisterInfo &HRI; 1894 }; 1895 1896 class HexagonConstPropagation : public MachineFunctionPass { 1897 public: 1898 static char ID; 1899 1900 HexagonConstPropagation() : MachineFunctionPass(ID) {} 1901 1902 StringRef getPassName() const override { 1903 return "Hexagon Constant Propagation"; 1904 } 1905 1906 bool runOnMachineFunction(MachineFunction &MF) override { 1907 const Function &F = MF.getFunction(); 1908 if (skipFunction(F)) 1909 return false; 1910 1911 HexagonConstEvaluator HCE(MF); 1912 return MachineConstPropagator(HCE).run(MF); 1913 } 1914 }; 1915 1916 } // end anonymous namespace 1917 1918 char HexagonConstPropagation::ID = 0; 1919 1920 INITIALIZE_PASS(HexagonConstPropagation, "hexagon-constp", 1921 "Hexagon Constant Propagation", false, false) 1922 1923 HexagonConstEvaluator::HexagonConstEvaluator(MachineFunction &Fn) 1924 : MachineConstEvaluator(Fn), 1925 HII(*Fn.getSubtarget<HexagonSubtarget>().getInstrInfo()), 1926 HRI(*Fn.getSubtarget<HexagonSubtarget>().getRegisterInfo()) { 1927 MRI = &Fn.getRegInfo(); 1928 } 1929 1930 bool HexagonConstEvaluator::evaluate(const MachineInstr &MI, 1931 const CellMap &Inputs, CellMap &Outputs) { 1932 if (MI.isCall()) 1933 return false; 1934 if (MI.getNumOperands() == 0 || !MI.getOperand(0).isReg()) 1935 return false; 1936 const MachineOperand &MD = MI.getOperand(0); 1937 if (!MD.isDef()) 1938 return false; 1939 1940 unsigned Opc = MI.getOpcode(); 1941 RegisterSubReg DefR(MD); 1942 assert(!DefR.SubReg); 1943 if (!DefR.Reg.isVirtual()) 1944 return false; 1945 1946 if (MI.isCopy()) { 1947 LatticeCell RC; 1948 RegisterSubReg SrcR(MI.getOperand(1)); 1949 bool Eval = evaluateCOPY(SrcR, Inputs, RC); 1950 if (!Eval) 1951 return false; 1952 Outputs.update(DefR.Reg, RC); 1953 return true; 1954 } 1955 if (MI.isRegSequence()) { 1956 unsigned Sub1 = MI.getOperand(2).getImm(); 1957 unsigned Sub2 = MI.getOperand(4).getImm(); 1958 const TargetRegisterClass &DefRC = *MRI->getRegClass(DefR.Reg); 1959 unsigned SubLo = HRI.getHexagonSubRegIndex(DefRC, Hexagon::ps_sub_lo); 1960 unsigned SubHi = HRI.getHexagonSubRegIndex(DefRC, Hexagon::ps_sub_hi); 1961 if (Sub1 != SubLo && Sub1 != SubHi) 1962 return false; 1963 if (Sub2 != SubLo && Sub2 != SubHi) 1964 return false; 1965 assert(Sub1 != Sub2); 1966 bool LoIs1 = (Sub1 == SubLo); 1967 const MachineOperand &OpLo = LoIs1 ? MI.getOperand(1) : MI.getOperand(3); 1968 const MachineOperand &OpHi = LoIs1 ? MI.getOperand(3) : MI.getOperand(1); 1969 LatticeCell RC; 1970 RegisterSubReg SrcRL(OpLo), SrcRH(OpHi); 1971 bool Eval = evaluateHexRSEQ32(SrcRL, SrcRH, Inputs, RC); 1972 if (!Eval) 1973 return false; 1974 Outputs.update(DefR.Reg, RC); 1975 return true; 1976 } 1977 if (MI.isCompare()) { 1978 bool Eval = evaluateHexCompare(MI, Inputs, Outputs); 1979 return Eval; 1980 } 1981 1982 switch (Opc) { 1983 default: 1984 return false; 1985 case Hexagon::A2_tfrsi: 1986 case Hexagon::A2_tfrpi: 1987 case Hexagon::CONST32: 1988 case Hexagon::CONST64: 1989 { 1990 const MachineOperand &VO = MI.getOperand(1); 1991 // The operand of CONST32 can be a blockaddress, e.g. 1992 // %0 = CONST32 <blockaddress(@eat, %l)> 1993 // Do this check for all instructions for safety. 1994 if (!VO.isImm()) 1995 return false; 1996 int64_t V = MI.getOperand(1).getImm(); 1997 unsigned W = getRegBitWidth(DefR.Reg); 1998 if (W != 32 && W != 64) 1999 return false; 2000 IntegerType *Ty = (W == 32) ? Type::getInt32Ty(CX) 2001 : Type::getInt64Ty(CX); 2002 const ConstantInt *CI = ConstantInt::get(Ty, V, true); 2003 LatticeCell RC = Outputs.get(DefR.Reg); 2004 RC.add(CI); 2005 Outputs.update(DefR.Reg, RC); 2006 break; 2007 } 2008 2009 case Hexagon::PS_true: 2010 case Hexagon::PS_false: 2011 { 2012 LatticeCell RC = Outputs.get(DefR.Reg); 2013 bool NonZero = (Opc == Hexagon::PS_true); 2014 uint32_t P = NonZero ? ConstantProperties::NonZero 2015 : ConstantProperties::Zero; 2016 RC.add(P); 2017 Outputs.update(DefR.Reg, RC); 2018 break; 2019 } 2020 2021 case Hexagon::A2_and: 2022 case Hexagon::A2_andir: 2023 case Hexagon::A2_andp: 2024 case Hexagon::A2_or: 2025 case Hexagon::A2_orir: 2026 case Hexagon::A2_orp: 2027 case Hexagon::A2_xor: 2028 case Hexagon::A2_xorp: 2029 { 2030 bool Eval = evaluateHexLogical(MI, Inputs, Outputs); 2031 if (!Eval) 2032 return false; 2033 break; 2034 } 2035 2036 case Hexagon::A2_combineii: // combine(#s8Ext, #s8) 2037 case Hexagon::A4_combineii: // combine(#s8, #u6Ext) 2038 { 2039 if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isImm()) 2040 return false; 2041 uint64_t Hi = MI.getOperand(1).getImm(); 2042 uint64_t Lo = MI.getOperand(2).getImm(); 2043 uint64_t Res = (Hi << 32) | (Lo & 0xFFFFFFFF); 2044 IntegerType *Ty = Type::getInt64Ty(CX); 2045 const ConstantInt *CI = ConstantInt::get(Ty, Res, false); 2046 LatticeCell RC = Outputs.get(DefR.Reg); 2047 RC.add(CI); 2048 Outputs.update(DefR.Reg, RC); 2049 break; 2050 } 2051 2052 case Hexagon::S2_setbit_i: 2053 { 2054 int64_t B = MI.getOperand(2).getImm(); 2055 assert(B >=0 && B < 32); 2056 APInt A(32, (1ull << B), false); 2057 RegisterSubReg R(MI.getOperand(1)); 2058 LatticeCell RC = Outputs.get(DefR.Reg); 2059 bool Eval = evaluateORri(R, A, Inputs, RC); 2060 if (!Eval) 2061 return false; 2062 Outputs.update(DefR.Reg, RC); 2063 break; 2064 } 2065 2066 case Hexagon::C2_mux: 2067 case Hexagon::C2_muxir: 2068 case Hexagon::C2_muxri: 2069 case Hexagon::C2_muxii: 2070 { 2071 bool Eval = evaluateHexCondMove(MI, Inputs, Outputs); 2072 if (!Eval) 2073 return false; 2074 break; 2075 } 2076 2077 case Hexagon::A2_sxtb: 2078 case Hexagon::A2_sxth: 2079 case Hexagon::A2_sxtw: 2080 case Hexagon::A2_zxtb: 2081 case Hexagon::A2_zxth: 2082 { 2083 bool Eval = evaluateHexExt(MI, Inputs, Outputs); 2084 if (!Eval) 2085 return false; 2086 break; 2087 } 2088 2089 case Hexagon::S2_ct0: 2090 case Hexagon::S2_ct0p: 2091 case Hexagon::S2_ct1: 2092 case Hexagon::S2_ct1p: 2093 { 2094 using namespace Hexagon; 2095 2096 bool Ones = (Opc == S2_ct1) || (Opc == S2_ct1p); 2097 RegisterSubReg R1(MI.getOperand(1)); 2098 assert(Inputs.has(R1.Reg)); 2099 LatticeCell T; 2100 bool Eval = evaluateCTBr(R1, !Ones, Ones, Inputs, T); 2101 if (!Eval) 2102 return false; 2103 // All of these instructions return a 32-bit value. The evaluate 2104 // will generate the same type as the operand, so truncate the 2105 // result if necessary. 2106 APInt C; 2107 LatticeCell RC = Outputs.get(DefR.Reg); 2108 for (unsigned i = 0; i < T.size(); ++i) { 2109 const Constant *CI = T.Values[i]; 2110 if (constToInt(CI, C) && C.getBitWidth() > 32) 2111 CI = intToConst(C.trunc(32)); 2112 RC.add(CI); 2113 } 2114 Outputs.update(DefR.Reg, RC); 2115 break; 2116 } 2117 2118 case Hexagon::S2_cl0: 2119 case Hexagon::S2_cl0p: 2120 case Hexagon::S2_cl1: 2121 case Hexagon::S2_cl1p: 2122 case Hexagon::S2_clb: 2123 case Hexagon::S2_clbp: 2124 { 2125 using namespace Hexagon; 2126 2127 bool OnlyZeros = (Opc == S2_cl0) || (Opc == S2_cl0p); 2128 bool OnlyOnes = (Opc == S2_cl1) || (Opc == S2_cl1p); 2129 RegisterSubReg R1(MI.getOperand(1)); 2130 assert(Inputs.has(R1.Reg)); 2131 LatticeCell T; 2132 bool Eval = evaluateCLBr(R1, !OnlyOnes, !OnlyZeros, Inputs, T); 2133 if (!Eval) 2134 return false; 2135 // All of these instructions return a 32-bit value. The evaluate 2136 // will generate the same type as the operand, so truncate the 2137 // result if necessary. 2138 APInt C; 2139 LatticeCell RC = Outputs.get(DefR.Reg); 2140 for (unsigned i = 0; i < T.size(); ++i) { 2141 const Constant *CI = T.Values[i]; 2142 if (constToInt(CI, C) && C.getBitWidth() > 32) 2143 CI = intToConst(C.trunc(32)); 2144 RC.add(CI); 2145 } 2146 Outputs.update(DefR.Reg, RC); 2147 break; 2148 } 2149 2150 case Hexagon::S4_extract: 2151 case Hexagon::S4_extractp: 2152 case Hexagon::S2_extractu: 2153 case Hexagon::S2_extractup: 2154 { 2155 bool Signed = (Opc == Hexagon::S4_extract) || 2156 (Opc == Hexagon::S4_extractp); 2157 RegisterSubReg R1(MI.getOperand(1)); 2158 unsigned BW = getRegBitWidth(R1.Reg); 2159 unsigned Bits = MI.getOperand(2).getImm(); 2160 unsigned Offset = MI.getOperand(3).getImm(); 2161 LatticeCell RC = Outputs.get(DefR.Reg); 2162 if (Offset >= BW) { 2163 APInt Zero(BW, 0, false); 2164 RC.add(intToConst(Zero)); 2165 break; 2166 } 2167 if (Offset+Bits > BW) { 2168 // If the requested bitfield extends beyond the most significant bit, 2169 // the extra bits are treated as 0s. To emulate this behavior, reduce 2170 // the number of requested bits, and make the extract unsigned. 2171 Bits = BW-Offset; 2172 Signed = false; 2173 } 2174 bool Eval = evaluateEXTRACTr(R1, BW, Bits, Offset, Signed, Inputs, RC); 2175 if (!Eval) 2176 return false; 2177 Outputs.update(DefR.Reg, RC); 2178 break; 2179 } 2180 2181 case Hexagon::S2_vsplatrb: 2182 case Hexagon::S2_vsplatrh: 2183 // vabsh, vabsh:sat 2184 // vabsw, vabsw:sat 2185 // vconj:sat 2186 // vrndwh, vrndwh:sat 2187 // vsathb, vsathub, vsatwuh 2188 // vsxtbh, vsxthw 2189 // vtrunehb, vtrunohb 2190 // vzxtbh, vzxthw 2191 { 2192 bool Eval = evaluateHexVector1(MI, Inputs, Outputs); 2193 if (!Eval) 2194 return false; 2195 break; 2196 } 2197 2198 // TODO: 2199 // A2_vaddh 2200 // A2_vaddhs 2201 // A2_vaddw 2202 // A2_vaddws 2203 } 2204 2205 return true; 2206 } 2207 2208 bool HexagonConstEvaluator::evaluate(const RegisterSubReg &R, 2209 const LatticeCell &Input, LatticeCell &Result) { 2210 if (!R.SubReg) { 2211 Result = Input; 2212 return true; 2213 } 2214 const TargetRegisterClass *RC = MRI->getRegClass(R.Reg); 2215 if (RC != &Hexagon::DoubleRegsRegClass) 2216 return false; 2217 if (R.SubReg != Hexagon::isub_lo && R.SubReg != Hexagon::isub_hi) 2218 return false; 2219 2220 assert(!Input.isTop()); 2221 if (Input.isBottom()) 2222 return false; 2223 2224 using P = ConstantProperties; 2225 2226 if (Input.isProperty()) { 2227 uint32_t Ps = Input.properties(); 2228 if (Ps & (P::Zero|P::NaN)) { 2229 uint32_t Ns = (Ps & (P::Zero|P::NaN|P::SignProperties)); 2230 Result.add(Ns); 2231 return true; 2232 } 2233 if (R.SubReg == Hexagon::isub_hi) { 2234 uint32_t Ns = (Ps & P::SignProperties); 2235 Result.add(Ns); 2236 return true; 2237 } 2238 return false; 2239 } 2240 2241 // The Input cell contains some known values. Pick the word corresponding 2242 // to the subregister. 2243 APInt A; 2244 for (unsigned i = 0; i < Input.size(); ++i) { 2245 const Constant *C = Input.Values[i]; 2246 if (!constToInt(C, A)) 2247 return false; 2248 if (!A.isIntN(64)) 2249 return false; 2250 uint64_t U = A.getZExtValue(); 2251 if (R.SubReg == Hexagon::isub_hi) 2252 U >>= 32; 2253 U &= 0xFFFFFFFFULL; 2254 uint32_t U32 = Lo_32(U); 2255 int32_t V32; 2256 memcpy(&V32, &U32, sizeof V32); 2257 IntegerType *Ty = Type::getInt32Ty(CX); 2258 const ConstantInt *C32 = ConstantInt::get(Ty, static_cast<int64_t>(V32)); 2259 Result.add(C32); 2260 } 2261 return true; 2262 } 2263 2264 bool HexagonConstEvaluator::evaluate(const MachineInstr &BrI, 2265 const CellMap &Inputs, SetVector<const MachineBasicBlock*> &Targets, 2266 bool &FallsThru) { 2267 // We need to evaluate one branch at a time. TII::analyzeBranch checks 2268 // all the branches in a basic block at once, so we cannot use it. 2269 unsigned Opc = BrI.getOpcode(); 2270 bool SimpleBranch = false; 2271 bool Negated = false; 2272 switch (Opc) { 2273 case Hexagon::J2_jumpf: 2274 case Hexagon::J2_jumpfnew: 2275 case Hexagon::J2_jumpfnewpt: 2276 Negated = true; 2277 LLVM_FALLTHROUGH; 2278 case Hexagon::J2_jumpt: 2279 case Hexagon::J2_jumptnew: 2280 case Hexagon::J2_jumptnewpt: 2281 // Simple branch: if([!]Pn) jump ... 2282 // i.e. Op0 = predicate, Op1 = branch target. 2283 SimpleBranch = true; 2284 break; 2285 case Hexagon::J2_jump: 2286 Targets.insert(BrI.getOperand(0).getMBB()); 2287 FallsThru = false; 2288 return true; 2289 default: 2290 Undetermined: 2291 // If the branch is of unknown type, assume that all successors are 2292 // executable. 2293 FallsThru = !BrI.isUnconditionalBranch(); 2294 return false; 2295 } 2296 2297 if (SimpleBranch) { 2298 const MachineOperand &MD = BrI.getOperand(0); 2299 RegisterSubReg PR(MD); 2300 // If the condition operand has a subregister, this is not something 2301 // we currently recognize. 2302 if (PR.SubReg) 2303 goto Undetermined; 2304 assert(Inputs.has(PR.Reg)); 2305 const LatticeCell &PredC = Inputs.get(PR.Reg); 2306 if (PredC.isBottom()) 2307 goto Undetermined; 2308 2309 uint32_t Props = PredC.properties(); 2310 bool CTrue = false, CFalse = false; 2311 if (Props & ConstantProperties::Zero) 2312 CFalse = true; 2313 else if (Props & ConstantProperties::NonZero) 2314 CTrue = true; 2315 // If the condition is not known to be either, bail out. 2316 if (!CTrue && !CFalse) 2317 goto Undetermined; 2318 2319 const MachineBasicBlock *BranchTarget = BrI.getOperand(1).getMBB(); 2320 2321 FallsThru = false; 2322 if ((!Negated && CTrue) || (Negated && CFalse)) 2323 Targets.insert(BranchTarget); 2324 else if ((!Negated && CFalse) || (Negated && CTrue)) 2325 FallsThru = true; 2326 else 2327 goto Undetermined; 2328 } 2329 2330 return true; 2331 } 2332 2333 bool HexagonConstEvaluator::rewrite(MachineInstr &MI, const CellMap &Inputs) { 2334 if (MI.isBranch()) 2335 return rewriteHexBranch(MI, Inputs); 2336 2337 unsigned Opc = MI.getOpcode(); 2338 switch (Opc) { 2339 default: 2340 break; 2341 case Hexagon::A2_tfrsi: 2342 case Hexagon::A2_tfrpi: 2343 case Hexagon::CONST32: 2344 case Hexagon::CONST64: 2345 case Hexagon::PS_true: 2346 case Hexagon::PS_false: 2347 return false; 2348 } 2349 2350 unsigned NumOp = MI.getNumOperands(); 2351 if (NumOp == 0) 2352 return false; 2353 2354 bool AllDefs, Changed; 2355 Changed = rewriteHexConstDefs(MI, Inputs, AllDefs); 2356 // If not all defs have been rewritten (i.e. the instruction defines 2357 // a register that is not compile-time constant), then try to rewrite 2358 // register operands that are known to be constant with immediates. 2359 if (!AllDefs) 2360 Changed |= rewriteHexConstUses(MI, Inputs); 2361 2362 return Changed; 2363 } 2364 2365 unsigned HexagonConstEvaluator::getRegBitWidth(unsigned Reg) const { 2366 const TargetRegisterClass *RC = MRI->getRegClass(Reg); 2367 if (Hexagon::IntRegsRegClass.hasSubClassEq(RC)) 2368 return 32; 2369 if (Hexagon::DoubleRegsRegClass.hasSubClassEq(RC)) 2370 return 64; 2371 if (Hexagon::PredRegsRegClass.hasSubClassEq(RC)) 2372 return 8; 2373 llvm_unreachable("Invalid register"); 2374 return 0; 2375 } 2376 2377 uint32_t HexagonConstEvaluator::getCmp(unsigned Opc) { 2378 switch (Opc) { 2379 case Hexagon::C2_cmpeq: 2380 case Hexagon::C2_cmpeqp: 2381 case Hexagon::A4_cmpbeq: 2382 case Hexagon::A4_cmpheq: 2383 case Hexagon::A4_cmpbeqi: 2384 case Hexagon::A4_cmpheqi: 2385 case Hexagon::C2_cmpeqi: 2386 case Hexagon::J4_cmpeqn1_t_jumpnv_nt: 2387 case Hexagon::J4_cmpeqn1_t_jumpnv_t: 2388 case Hexagon::J4_cmpeqi_t_jumpnv_nt: 2389 case Hexagon::J4_cmpeqi_t_jumpnv_t: 2390 case Hexagon::J4_cmpeq_t_jumpnv_nt: 2391 case Hexagon::J4_cmpeq_t_jumpnv_t: 2392 return Comparison::EQ; 2393 2394 case Hexagon::C4_cmpneq: 2395 case Hexagon::C4_cmpneqi: 2396 case Hexagon::J4_cmpeqn1_f_jumpnv_nt: 2397 case Hexagon::J4_cmpeqn1_f_jumpnv_t: 2398 case Hexagon::J4_cmpeqi_f_jumpnv_nt: 2399 case Hexagon::J4_cmpeqi_f_jumpnv_t: 2400 case Hexagon::J4_cmpeq_f_jumpnv_nt: 2401 case Hexagon::J4_cmpeq_f_jumpnv_t: 2402 return Comparison::NE; 2403 2404 case Hexagon::C2_cmpgt: 2405 case Hexagon::C2_cmpgtp: 2406 case Hexagon::A4_cmpbgt: 2407 case Hexagon::A4_cmphgt: 2408 case Hexagon::A4_cmpbgti: 2409 case Hexagon::A4_cmphgti: 2410 case Hexagon::C2_cmpgti: 2411 case Hexagon::J4_cmpgtn1_t_jumpnv_nt: 2412 case Hexagon::J4_cmpgtn1_t_jumpnv_t: 2413 case Hexagon::J4_cmpgti_t_jumpnv_nt: 2414 case Hexagon::J4_cmpgti_t_jumpnv_t: 2415 case Hexagon::J4_cmpgt_t_jumpnv_nt: 2416 case Hexagon::J4_cmpgt_t_jumpnv_t: 2417 return Comparison::GTs; 2418 2419 case Hexagon::C4_cmplte: 2420 case Hexagon::C4_cmpltei: 2421 case Hexagon::J4_cmpgtn1_f_jumpnv_nt: 2422 case Hexagon::J4_cmpgtn1_f_jumpnv_t: 2423 case Hexagon::J4_cmpgti_f_jumpnv_nt: 2424 case Hexagon::J4_cmpgti_f_jumpnv_t: 2425 case Hexagon::J4_cmpgt_f_jumpnv_nt: 2426 case Hexagon::J4_cmpgt_f_jumpnv_t: 2427 return Comparison::LEs; 2428 2429 case Hexagon::C2_cmpgtu: 2430 case Hexagon::C2_cmpgtup: 2431 case Hexagon::A4_cmpbgtu: 2432 case Hexagon::A4_cmpbgtui: 2433 case Hexagon::A4_cmphgtu: 2434 case Hexagon::A4_cmphgtui: 2435 case Hexagon::C2_cmpgtui: 2436 case Hexagon::J4_cmpgtui_t_jumpnv_nt: 2437 case Hexagon::J4_cmpgtui_t_jumpnv_t: 2438 case Hexagon::J4_cmpgtu_t_jumpnv_nt: 2439 case Hexagon::J4_cmpgtu_t_jumpnv_t: 2440 return Comparison::GTu; 2441 2442 case Hexagon::J4_cmpltu_f_jumpnv_nt: 2443 case Hexagon::J4_cmpltu_f_jumpnv_t: 2444 return Comparison::GEu; 2445 2446 case Hexagon::J4_cmpltu_t_jumpnv_nt: 2447 case Hexagon::J4_cmpltu_t_jumpnv_t: 2448 return Comparison::LTu; 2449 2450 case Hexagon::J4_cmplt_f_jumpnv_nt: 2451 case Hexagon::J4_cmplt_f_jumpnv_t: 2452 return Comparison::GEs; 2453 2454 case Hexagon::C4_cmplteu: 2455 case Hexagon::C4_cmplteui: 2456 case Hexagon::J4_cmpgtui_f_jumpnv_nt: 2457 case Hexagon::J4_cmpgtui_f_jumpnv_t: 2458 case Hexagon::J4_cmpgtu_f_jumpnv_nt: 2459 case Hexagon::J4_cmpgtu_f_jumpnv_t: 2460 return Comparison::LEu; 2461 2462 case Hexagon::J4_cmplt_t_jumpnv_nt: 2463 case Hexagon::J4_cmplt_t_jumpnv_t: 2464 return Comparison::LTs; 2465 2466 default: 2467 break; 2468 } 2469 return Comparison::Unk; 2470 } 2471 2472 APInt HexagonConstEvaluator::getCmpImm(unsigned Opc, unsigned OpX, 2473 const MachineOperand &MO) { 2474 bool Signed = false; 2475 switch (Opc) { 2476 case Hexagon::A4_cmpbgtui: // u7 2477 case Hexagon::A4_cmphgtui: // u7 2478 break; 2479 case Hexagon::A4_cmpheqi: // s8 2480 case Hexagon::C4_cmpneqi: // s8 2481 Signed = true; 2482 break; 2483 case Hexagon::A4_cmpbeqi: // u8 2484 break; 2485 case Hexagon::C2_cmpgtui: // u9 2486 case Hexagon::C4_cmplteui: // u9 2487 break; 2488 case Hexagon::C2_cmpeqi: // s10 2489 case Hexagon::C2_cmpgti: // s10 2490 case Hexagon::C4_cmpltei: // s10 2491 Signed = true; 2492 break; 2493 case Hexagon::J4_cmpeqi_f_jumpnv_nt: // u5 2494 case Hexagon::J4_cmpeqi_f_jumpnv_t: // u5 2495 case Hexagon::J4_cmpeqi_t_jumpnv_nt: // u5 2496 case Hexagon::J4_cmpeqi_t_jumpnv_t: // u5 2497 case Hexagon::J4_cmpgti_f_jumpnv_nt: // u5 2498 case Hexagon::J4_cmpgti_f_jumpnv_t: // u5 2499 case Hexagon::J4_cmpgti_t_jumpnv_nt: // u5 2500 case Hexagon::J4_cmpgti_t_jumpnv_t: // u5 2501 case Hexagon::J4_cmpgtui_f_jumpnv_nt: // u5 2502 case Hexagon::J4_cmpgtui_f_jumpnv_t: // u5 2503 case Hexagon::J4_cmpgtui_t_jumpnv_nt: // u5 2504 case Hexagon::J4_cmpgtui_t_jumpnv_t: // u5 2505 break; 2506 default: 2507 llvm_unreachable("Unhandled instruction"); 2508 break; 2509 } 2510 2511 uint64_t Val = MO.getImm(); 2512 return APInt(32, Val, Signed); 2513 } 2514 2515 void HexagonConstEvaluator::replaceWithNop(MachineInstr &MI) { 2516 MI.setDesc(HII.get(Hexagon::A2_nop)); 2517 while (MI.getNumOperands() > 0) 2518 MI.RemoveOperand(0); 2519 } 2520 2521 bool HexagonConstEvaluator::evaluateHexRSEQ32(RegisterSubReg RL, RegisterSubReg RH, 2522 const CellMap &Inputs, LatticeCell &Result) { 2523 assert(Inputs.has(RL.Reg) && Inputs.has(RH.Reg)); 2524 LatticeCell LSL, LSH; 2525 if (!getCell(RL, Inputs, LSL) || !getCell(RH, Inputs, LSH)) 2526 return false; 2527 if (LSL.isProperty() || LSH.isProperty()) 2528 return false; 2529 2530 unsigned LN = LSL.size(), HN = LSH.size(); 2531 SmallVector<APInt,4> LoVs(LN), HiVs(HN); 2532 for (unsigned i = 0; i < LN; ++i) { 2533 bool Eval = constToInt(LSL.Values[i], LoVs[i]); 2534 if (!Eval) 2535 return false; 2536 assert(LoVs[i].getBitWidth() == 32); 2537 } 2538 for (unsigned i = 0; i < HN; ++i) { 2539 bool Eval = constToInt(LSH.Values[i], HiVs[i]); 2540 if (!Eval) 2541 return false; 2542 assert(HiVs[i].getBitWidth() == 32); 2543 } 2544 2545 for (unsigned i = 0; i < HiVs.size(); ++i) { 2546 APInt HV = HiVs[i].zextOrSelf(64) << 32; 2547 for (unsigned j = 0; j < LoVs.size(); ++j) { 2548 APInt LV = LoVs[j].zextOrSelf(64); 2549 const Constant *C = intToConst(HV | LV); 2550 Result.add(C); 2551 if (Result.isBottom()) 2552 return false; 2553 } 2554 } 2555 return !Result.isBottom(); 2556 } 2557 2558 bool HexagonConstEvaluator::evaluateHexCompare(const MachineInstr &MI, 2559 const CellMap &Inputs, CellMap &Outputs) { 2560 unsigned Opc = MI.getOpcode(); 2561 bool Classic = false; 2562 switch (Opc) { 2563 case Hexagon::C2_cmpeq: 2564 case Hexagon::C2_cmpeqp: 2565 case Hexagon::C2_cmpgt: 2566 case Hexagon::C2_cmpgtp: 2567 case Hexagon::C2_cmpgtu: 2568 case Hexagon::C2_cmpgtup: 2569 case Hexagon::C2_cmpeqi: 2570 case Hexagon::C2_cmpgti: 2571 case Hexagon::C2_cmpgtui: 2572 // Classic compare: Dst0 = CMP Src1, Src2 2573 Classic = true; 2574 break; 2575 default: 2576 // Not handling other compare instructions now. 2577 return false; 2578 } 2579 2580 if (Classic) { 2581 const MachineOperand &Src1 = MI.getOperand(1); 2582 const MachineOperand &Src2 = MI.getOperand(2); 2583 2584 bool Result; 2585 unsigned Opc = MI.getOpcode(); 2586 bool Computed = evaluateHexCompare2(Opc, Src1, Src2, Inputs, Result); 2587 if (Computed) { 2588 // Only create a zero/non-zero cell. At this time there isn't really 2589 // much need for specific values. 2590 RegisterSubReg DefR(MI.getOperand(0)); 2591 LatticeCell L = Outputs.get(DefR.Reg); 2592 uint32_t P = Result ? ConstantProperties::NonZero 2593 : ConstantProperties::Zero; 2594 L.add(P); 2595 Outputs.update(DefR.Reg, L); 2596 return true; 2597 } 2598 } 2599 2600 return false; 2601 } 2602 2603 bool HexagonConstEvaluator::evaluateHexCompare2(unsigned Opc, 2604 const MachineOperand &Src1, const MachineOperand &Src2, 2605 const CellMap &Inputs, bool &Result) { 2606 uint32_t Cmp = getCmp(Opc); 2607 bool Reg1 = Src1.isReg(), Reg2 = Src2.isReg(); 2608 bool Imm1 = Src1.isImm(), Imm2 = Src2.isImm(); 2609 if (Reg1) { 2610 RegisterSubReg R1(Src1); 2611 if (Reg2) { 2612 RegisterSubReg R2(Src2); 2613 return evaluateCMPrr(Cmp, R1, R2, Inputs, Result); 2614 } else if (Imm2) { 2615 APInt A2 = getCmpImm(Opc, 2, Src2); 2616 return evaluateCMPri(Cmp, R1, A2, Inputs, Result); 2617 } 2618 } else if (Imm1) { 2619 APInt A1 = getCmpImm(Opc, 1, Src1); 2620 if (Reg2) { 2621 RegisterSubReg R2(Src2); 2622 uint32_t NegCmp = Comparison::negate(Cmp); 2623 return evaluateCMPri(NegCmp, R2, A1, Inputs, Result); 2624 } else if (Imm2) { 2625 APInt A2 = getCmpImm(Opc, 2, Src2); 2626 return evaluateCMPii(Cmp, A1, A2, Result); 2627 } 2628 } 2629 // Unknown kind of comparison. 2630 return false; 2631 } 2632 2633 bool HexagonConstEvaluator::evaluateHexLogical(const MachineInstr &MI, 2634 const CellMap &Inputs, CellMap &Outputs) { 2635 unsigned Opc = MI.getOpcode(); 2636 if (MI.getNumOperands() != 3) 2637 return false; 2638 const MachineOperand &Src1 = MI.getOperand(1); 2639 const MachineOperand &Src2 = MI.getOperand(2); 2640 RegisterSubReg R1(Src1); 2641 bool Eval = false; 2642 LatticeCell RC; 2643 switch (Opc) { 2644 default: 2645 return false; 2646 case Hexagon::A2_and: 2647 case Hexagon::A2_andp: 2648 Eval = evaluateANDrr(R1, RegisterSubReg(Src2), Inputs, RC); 2649 break; 2650 case Hexagon::A2_andir: { 2651 if (!Src2.isImm()) 2652 return false; 2653 APInt A(32, Src2.getImm(), true); 2654 Eval = evaluateANDri(R1, A, Inputs, RC); 2655 break; 2656 } 2657 case Hexagon::A2_or: 2658 case Hexagon::A2_orp: 2659 Eval = evaluateORrr(R1, RegisterSubReg(Src2), Inputs, RC); 2660 break; 2661 case Hexagon::A2_orir: { 2662 if (!Src2.isImm()) 2663 return false; 2664 APInt A(32, Src2.getImm(), true); 2665 Eval = evaluateORri(R1, A, Inputs, RC); 2666 break; 2667 } 2668 case Hexagon::A2_xor: 2669 case Hexagon::A2_xorp: 2670 Eval = evaluateXORrr(R1, RegisterSubReg(Src2), Inputs, RC); 2671 break; 2672 } 2673 if (Eval) { 2674 RegisterSubReg DefR(MI.getOperand(0)); 2675 Outputs.update(DefR.Reg, RC); 2676 } 2677 return Eval; 2678 } 2679 2680 bool HexagonConstEvaluator::evaluateHexCondMove(const MachineInstr &MI, 2681 const CellMap &Inputs, CellMap &Outputs) { 2682 // Dst0 = Cond1 ? Src2 : Src3 2683 RegisterSubReg CR(MI.getOperand(1)); 2684 assert(Inputs.has(CR.Reg)); 2685 LatticeCell LS; 2686 if (!getCell(CR, Inputs, LS)) 2687 return false; 2688 uint32_t Ps = LS.properties(); 2689 unsigned TakeOp; 2690 if (Ps & ConstantProperties::Zero) 2691 TakeOp = 3; 2692 else if (Ps & ConstantProperties::NonZero) 2693 TakeOp = 2; 2694 else 2695 return false; 2696 2697 const MachineOperand &ValOp = MI.getOperand(TakeOp); 2698 RegisterSubReg DefR(MI.getOperand(0)); 2699 LatticeCell RC = Outputs.get(DefR.Reg); 2700 2701 if (ValOp.isImm()) { 2702 int64_t V = ValOp.getImm(); 2703 unsigned W = getRegBitWidth(DefR.Reg); 2704 APInt A(W, V, true); 2705 const Constant *C = intToConst(A); 2706 RC.add(C); 2707 Outputs.update(DefR.Reg, RC); 2708 return true; 2709 } 2710 if (ValOp.isReg()) { 2711 RegisterSubReg R(ValOp); 2712 const LatticeCell &LR = Inputs.get(R.Reg); 2713 LatticeCell LSR; 2714 if (!evaluate(R, LR, LSR)) 2715 return false; 2716 RC.meet(LSR); 2717 Outputs.update(DefR.Reg, RC); 2718 return true; 2719 } 2720 return false; 2721 } 2722 2723 bool HexagonConstEvaluator::evaluateHexExt(const MachineInstr &MI, 2724 const CellMap &Inputs, CellMap &Outputs) { 2725 // Dst0 = ext R1 2726 RegisterSubReg R1(MI.getOperand(1)); 2727 assert(Inputs.has(R1.Reg)); 2728 2729 unsigned Opc = MI.getOpcode(); 2730 unsigned Bits; 2731 switch (Opc) { 2732 case Hexagon::A2_sxtb: 2733 case Hexagon::A2_zxtb: 2734 Bits = 8; 2735 break; 2736 case Hexagon::A2_sxth: 2737 case Hexagon::A2_zxth: 2738 Bits = 16; 2739 break; 2740 case Hexagon::A2_sxtw: 2741 Bits = 32; 2742 break; 2743 default: 2744 llvm_unreachable("Unhandled extension opcode"); 2745 } 2746 2747 bool Signed = false; 2748 switch (Opc) { 2749 case Hexagon::A2_sxtb: 2750 case Hexagon::A2_sxth: 2751 case Hexagon::A2_sxtw: 2752 Signed = true; 2753 break; 2754 } 2755 2756 RegisterSubReg DefR(MI.getOperand(0)); 2757 unsigned BW = getRegBitWidth(DefR.Reg); 2758 LatticeCell RC = Outputs.get(DefR.Reg); 2759 bool Eval = Signed ? evaluateSEXTr(R1, BW, Bits, Inputs, RC) 2760 : evaluateZEXTr(R1, BW, Bits, Inputs, RC); 2761 if (!Eval) 2762 return false; 2763 Outputs.update(DefR.Reg, RC); 2764 return true; 2765 } 2766 2767 bool HexagonConstEvaluator::evaluateHexVector1(const MachineInstr &MI, 2768 const CellMap &Inputs, CellMap &Outputs) { 2769 // DefR = op R1 2770 RegisterSubReg DefR(MI.getOperand(0)); 2771 RegisterSubReg R1(MI.getOperand(1)); 2772 assert(Inputs.has(R1.Reg)); 2773 LatticeCell RC = Outputs.get(DefR.Reg); 2774 bool Eval; 2775 2776 unsigned Opc = MI.getOpcode(); 2777 switch (Opc) { 2778 case Hexagon::S2_vsplatrb: 2779 // Rd = 4 times Rs:0..7 2780 Eval = evaluateSplatr(R1, 8, 4, Inputs, RC); 2781 break; 2782 case Hexagon::S2_vsplatrh: 2783 // Rdd = 4 times Rs:0..15 2784 Eval = evaluateSplatr(R1, 16, 4, Inputs, RC); 2785 break; 2786 default: 2787 return false; 2788 } 2789 2790 if (!Eval) 2791 return false; 2792 Outputs.update(DefR.Reg, RC); 2793 return true; 2794 } 2795 2796 bool HexagonConstEvaluator::rewriteHexConstDefs(MachineInstr &MI, 2797 const CellMap &Inputs, bool &AllDefs) { 2798 AllDefs = false; 2799 2800 // Some diagnostics. 2801 // LLVM_DEBUG({...}) gets confused with all this code as an argument. 2802 #ifndef NDEBUG 2803 bool Debugging = DebugFlag && isCurrentDebugType(DEBUG_TYPE); 2804 if (Debugging) { 2805 bool Const = true, HasUse = false; 2806 for (const MachineOperand &MO : MI.operands()) { 2807 if (!MO.isReg() || !MO.isUse() || MO.isImplicit()) 2808 continue; 2809 RegisterSubReg R(MO); 2810 if (!R.Reg.isVirtual()) 2811 continue; 2812 HasUse = true; 2813 // PHIs can legitimately have "top" cells after propagation. 2814 if (!MI.isPHI() && !Inputs.has(R.Reg)) { 2815 dbgs() << "Top " << printReg(R.Reg, &HRI, R.SubReg) 2816 << " in MI: " << MI; 2817 continue; 2818 } 2819 const LatticeCell &L = Inputs.get(R.Reg); 2820 Const &= L.isSingle(); 2821 if (!Const) 2822 break; 2823 } 2824 if (HasUse && Const) { 2825 if (!MI.isCopy()) { 2826 dbgs() << "CONST: " << MI; 2827 for (const MachineOperand &MO : MI.operands()) { 2828 if (!MO.isReg() || !MO.isUse() || MO.isImplicit()) 2829 continue; 2830 Register R = MO.getReg(); 2831 dbgs() << printReg(R, &TRI) << ": " << Inputs.get(R) << "\n"; 2832 } 2833 } 2834 } 2835 } 2836 #endif 2837 2838 // Avoid generating TFRIs for register transfers---this will keep the 2839 // coalescing opportunities. 2840 if (MI.isCopy()) 2841 return false; 2842 2843 MachineFunction *MF = MI.getParent()->getParent(); 2844 auto &HST = MF->getSubtarget<HexagonSubtarget>(); 2845 2846 // Collect all virtual register-def operands. 2847 SmallVector<unsigned,2> DefRegs; 2848 for (const MachineOperand &MO : MI.operands()) { 2849 if (!MO.isReg() || !MO.isDef()) 2850 continue; 2851 Register R = MO.getReg(); 2852 if (!R.isVirtual()) 2853 continue; 2854 assert(!MO.getSubReg()); 2855 assert(Inputs.has(R)); 2856 DefRegs.push_back(R); 2857 } 2858 2859 MachineBasicBlock &B = *MI.getParent(); 2860 const DebugLoc &DL = MI.getDebugLoc(); 2861 unsigned ChangedNum = 0; 2862 #ifndef NDEBUG 2863 SmallVector<const MachineInstr*,4> NewInstrs; 2864 #endif 2865 2866 // For each defined register, if it is a constant, create an instruction 2867 // NewR = const 2868 // and replace all uses of the defined register with NewR. 2869 for (unsigned i = 0, n = DefRegs.size(); i < n; ++i) { 2870 unsigned R = DefRegs[i]; 2871 const LatticeCell &L = Inputs.get(R); 2872 if (L.isBottom()) 2873 continue; 2874 const TargetRegisterClass *RC = MRI->getRegClass(R); 2875 MachineBasicBlock::iterator At = MI.getIterator(); 2876 2877 if (!L.isSingle()) { 2878 // If this a zero/non-zero cell, we can fold a definition 2879 // of a predicate register. 2880 using P = ConstantProperties; 2881 2882 uint64_t Ps = L.properties(); 2883 if (!(Ps & (P::Zero|P::NonZero))) 2884 continue; 2885 const TargetRegisterClass *PredRC = &Hexagon::PredRegsRegClass; 2886 if (RC != PredRC) 2887 continue; 2888 const MCInstrDesc *NewD = (Ps & P::Zero) ? 2889 &HII.get(Hexagon::PS_false) : 2890 &HII.get(Hexagon::PS_true); 2891 Register NewR = MRI->createVirtualRegister(PredRC); 2892 const MachineInstrBuilder &MIB = BuildMI(B, At, DL, *NewD, NewR); 2893 (void)MIB; 2894 #ifndef NDEBUG 2895 NewInstrs.push_back(&*MIB); 2896 #endif 2897 replaceAllRegUsesWith(R, NewR); 2898 } else { 2899 // This cell has a single value. 2900 APInt A; 2901 if (!constToInt(L.Value, A) || !A.isSignedIntN(64)) 2902 continue; 2903 const TargetRegisterClass *NewRC; 2904 const MCInstrDesc *NewD; 2905 2906 unsigned W = getRegBitWidth(R); 2907 int64_t V = A.getSExtValue(); 2908 assert(W == 32 || W == 64); 2909 if (W == 32) 2910 NewRC = &Hexagon::IntRegsRegClass; 2911 else 2912 NewRC = &Hexagon::DoubleRegsRegClass; 2913 Register NewR = MRI->createVirtualRegister(NewRC); 2914 const MachineInstr *NewMI; 2915 2916 if (W == 32) { 2917 NewD = &HII.get(Hexagon::A2_tfrsi); 2918 NewMI = BuildMI(B, At, DL, *NewD, NewR) 2919 .addImm(V); 2920 } else { 2921 if (A.isSignedIntN(8)) { 2922 NewD = &HII.get(Hexagon::A2_tfrpi); 2923 NewMI = BuildMI(B, At, DL, *NewD, NewR) 2924 .addImm(V); 2925 } else { 2926 int32_t Hi = V >> 32; 2927 int32_t Lo = V & 0xFFFFFFFFLL; 2928 if (isInt<8>(Hi) && isInt<8>(Lo)) { 2929 NewD = &HII.get(Hexagon::A2_combineii); 2930 NewMI = BuildMI(B, At, DL, *NewD, NewR) 2931 .addImm(Hi) 2932 .addImm(Lo); 2933 } else if (MF->getFunction().hasOptSize() || !HST.isTinyCore()) { 2934 // Disable CONST64 for tiny core since it takes a LD resource. 2935 NewD = &HII.get(Hexagon::CONST64); 2936 NewMI = BuildMI(B, At, DL, *NewD, NewR) 2937 .addImm(V); 2938 } else 2939 return false; 2940 } 2941 } 2942 (void)NewMI; 2943 #ifndef NDEBUG 2944 NewInstrs.push_back(NewMI); 2945 #endif 2946 replaceAllRegUsesWith(R, NewR); 2947 } 2948 ChangedNum++; 2949 } 2950 2951 LLVM_DEBUG({ 2952 if (!NewInstrs.empty()) { 2953 MachineFunction &MF = *MI.getParent()->getParent(); 2954 dbgs() << "In function: " << MF.getName() << "\n"; 2955 dbgs() << "Rewrite: for " << MI << " created " << *NewInstrs[0]; 2956 for (unsigned i = 1; i < NewInstrs.size(); ++i) 2957 dbgs() << " " << *NewInstrs[i]; 2958 } 2959 }); 2960 2961 AllDefs = (ChangedNum == DefRegs.size()); 2962 return ChangedNum > 0; 2963 } 2964 2965 bool HexagonConstEvaluator::rewriteHexConstUses(MachineInstr &MI, 2966 const CellMap &Inputs) { 2967 bool Changed = false; 2968 unsigned Opc = MI.getOpcode(); 2969 MachineBasicBlock &B = *MI.getParent(); 2970 const DebugLoc &DL = MI.getDebugLoc(); 2971 MachineBasicBlock::iterator At = MI.getIterator(); 2972 MachineInstr *NewMI = nullptr; 2973 2974 switch (Opc) { 2975 case Hexagon::M2_maci: 2976 // Convert DefR += mpyi(R2, R3) 2977 // to DefR += mpyi(R, #imm), 2978 // or DefR -= mpyi(R, #imm). 2979 { 2980 RegisterSubReg DefR(MI.getOperand(0)); 2981 assert(!DefR.SubReg); 2982 RegisterSubReg R2(MI.getOperand(2)); 2983 RegisterSubReg R3(MI.getOperand(3)); 2984 assert(Inputs.has(R2.Reg) && Inputs.has(R3.Reg)); 2985 LatticeCell LS2, LS3; 2986 // It is enough to get one of the input cells, since we will only try 2987 // to replace one argument---whichever happens to be a single constant. 2988 bool HasC2 = getCell(R2, Inputs, LS2), HasC3 = getCell(R3, Inputs, LS3); 2989 if (!HasC2 && !HasC3) 2990 return false; 2991 bool Zero = ((HasC2 && (LS2.properties() & ConstantProperties::Zero)) || 2992 (HasC3 && (LS3.properties() & ConstantProperties::Zero))); 2993 // If one of the operands is zero, eliminate the multiplication. 2994 if (Zero) { 2995 // DefR == R1 (tied operands). 2996 MachineOperand &Acc = MI.getOperand(1); 2997 RegisterSubReg R1(Acc); 2998 unsigned NewR = R1.Reg; 2999 if (R1.SubReg) { 3000 // Generate COPY. FIXME: Replace with the register:subregister. 3001 const TargetRegisterClass *RC = MRI->getRegClass(DefR.Reg); 3002 NewR = MRI->createVirtualRegister(RC); 3003 NewMI = BuildMI(B, At, DL, HII.get(TargetOpcode::COPY), NewR) 3004 .addReg(R1.Reg, getRegState(Acc), R1.SubReg); 3005 } 3006 replaceAllRegUsesWith(DefR.Reg, NewR); 3007 MRI->clearKillFlags(NewR); 3008 Changed = true; 3009 break; 3010 } 3011 3012 bool Swap = false; 3013 if (!LS3.isSingle()) { 3014 if (!LS2.isSingle()) 3015 return false; 3016 Swap = true; 3017 } 3018 const LatticeCell &LI = Swap ? LS2 : LS3; 3019 const MachineOperand &OpR2 = Swap ? MI.getOperand(3) 3020 : MI.getOperand(2); 3021 // LI is single here. 3022 APInt A; 3023 if (!constToInt(LI.Value, A) || !A.isSignedIntN(8)) 3024 return false; 3025 int64_t V = A.getSExtValue(); 3026 const MCInstrDesc &D = (V >= 0) ? HII.get(Hexagon::M2_macsip) 3027 : HII.get(Hexagon::M2_macsin); 3028 if (V < 0) 3029 V = -V; 3030 const TargetRegisterClass *RC = MRI->getRegClass(DefR.Reg); 3031 Register NewR = MRI->createVirtualRegister(RC); 3032 const MachineOperand &Src1 = MI.getOperand(1); 3033 NewMI = BuildMI(B, At, DL, D, NewR) 3034 .addReg(Src1.getReg(), getRegState(Src1), Src1.getSubReg()) 3035 .addReg(OpR2.getReg(), getRegState(OpR2), OpR2.getSubReg()) 3036 .addImm(V); 3037 replaceAllRegUsesWith(DefR.Reg, NewR); 3038 Changed = true; 3039 break; 3040 } 3041 3042 case Hexagon::A2_and: 3043 { 3044 RegisterSubReg R1(MI.getOperand(1)); 3045 RegisterSubReg R2(MI.getOperand(2)); 3046 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg)); 3047 LatticeCell LS1, LS2; 3048 unsigned CopyOf = 0; 3049 // Check if any of the operands is -1 (i.e. all bits set). 3050 if (getCell(R1, Inputs, LS1) && LS1.isSingle()) { 3051 APInt M1; 3052 if (constToInt(LS1.Value, M1) && !~M1) 3053 CopyOf = 2; 3054 } 3055 else if (getCell(R2, Inputs, LS2) && LS2.isSingle()) { 3056 APInt M1; 3057 if (constToInt(LS2.Value, M1) && !~M1) 3058 CopyOf = 1; 3059 } 3060 if (!CopyOf) 3061 return false; 3062 MachineOperand &SO = MI.getOperand(CopyOf); 3063 RegisterSubReg SR(SO); 3064 RegisterSubReg DefR(MI.getOperand(0)); 3065 unsigned NewR = SR.Reg; 3066 if (SR.SubReg) { 3067 const TargetRegisterClass *RC = MRI->getRegClass(DefR.Reg); 3068 NewR = MRI->createVirtualRegister(RC); 3069 NewMI = BuildMI(B, At, DL, HII.get(TargetOpcode::COPY), NewR) 3070 .addReg(SR.Reg, getRegState(SO), SR.SubReg); 3071 } 3072 replaceAllRegUsesWith(DefR.Reg, NewR); 3073 MRI->clearKillFlags(NewR); 3074 Changed = true; 3075 } 3076 break; 3077 3078 case Hexagon::A2_or: 3079 { 3080 RegisterSubReg R1(MI.getOperand(1)); 3081 RegisterSubReg R2(MI.getOperand(2)); 3082 assert(Inputs.has(R1.Reg) && Inputs.has(R2.Reg)); 3083 LatticeCell LS1, LS2; 3084 unsigned CopyOf = 0; 3085 3086 using P = ConstantProperties; 3087 3088 if (getCell(R1, Inputs, LS1) && (LS1.properties() & P::Zero)) 3089 CopyOf = 2; 3090 else if (getCell(R2, Inputs, LS2) && (LS2.properties() & P::Zero)) 3091 CopyOf = 1; 3092 if (!CopyOf) 3093 return false; 3094 MachineOperand &SO = MI.getOperand(CopyOf); 3095 RegisterSubReg SR(SO); 3096 RegisterSubReg DefR(MI.getOperand(0)); 3097 unsigned NewR = SR.Reg; 3098 if (SR.SubReg) { 3099 const TargetRegisterClass *RC = MRI->getRegClass(DefR.Reg); 3100 NewR = MRI->createVirtualRegister(RC); 3101 NewMI = BuildMI(B, At, DL, HII.get(TargetOpcode::COPY), NewR) 3102 .addReg(SR.Reg, getRegState(SO), SR.SubReg); 3103 } 3104 replaceAllRegUsesWith(DefR.Reg, NewR); 3105 MRI->clearKillFlags(NewR); 3106 Changed = true; 3107 } 3108 break; 3109 } 3110 3111 if (NewMI) { 3112 // clear all the kill flags of this new instruction. 3113 for (MachineOperand &MO : NewMI->operands()) 3114 if (MO.isReg() && MO.isUse()) 3115 MO.setIsKill(false); 3116 } 3117 3118 LLVM_DEBUG({ 3119 if (NewMI) { 3120 dbgs() << "Rewrite: for " << MI; 3121 if (NewMI != &MI) 3122 dbgs() << " created " << *NewMI; 3123 else 3124 dbgs() << " modified the instruction itself and created:" << *NewMI; 3125 } 3126 }); 3127 3128 return Changed; 3129 } 3130 3131 void HexagonConstEvaluator::replaceAllRegUsesWith(Register FromReg, 3132 Register ToReg) { 3133 assert(FromReg.isVirtual()); 3134 assert(ToReg.isVirtual()); 3135 for (auto I = MRI->use_begin(FromReg), E = MRI->use_end(); I != E;) { 3136 MachineOperand &O = *I; 3137 ++I; 3138 O.setReg(ToReg); 3139 } 3140 } 3141 3142 bool HexagonConstEvaluator::rewriteHexBranch(MachineInstr &BrI, 3143 const CellMap &Inputs) { 3144 MachineBasicBlock &B = *BrI.getParent(); 3145 unsigned NumOp = BrI.getNumOperands(); 3146 if (!NumOp) 3147 return false; 3148 3149 bool FallsThru; 3150 SetVector<const MachineBasicBlock*> Targets; 3151 bool Eval = evaluate(BrI, Inputs, Targets, FallsThru); 3152 unsigned NumTargets = Targets.size(); 3153 if (!Eval || NumTargets > 1 || (NumTargets == 1 && FallsThru)) 3154 return false; 3155 if (BrI.getOpcode() == Hexagon::J2_jump) 3156 return false; 3157 3158 LLVM_DEBUG(dbgs() << "Rewrite(" << printMBBReference(B) << "):" << BrI); 3159 bool Rewritten = false; 3160 if (NumTargets > 0) { 3161 assert(!FallsThru && "This should have been checked before"); 3162 // MIB.addMBB needs non-const pointer. 3163 MachineBasicBlock *TargetB = const_cast<MachineBasicBlock*>(Targets[0]); 3164 bool Moot = B.isLayoutSuccessor(TargetB); 3165 if (!Moot) { 3166 // If we build a branch here, we must make sure that it won't be 3167 // erased as "non-executable". We can't mark any new instructions 3168 // as executable here, so we need to overwrite the BrI, which we 3169 // know is executable. 3170 const MCInstrDesc &JD = HII.get(Hexagon::J2_jump); 3171 auto NI = BuildMI(B, BrI.getIterator(), BrI.getDebugLoc(), JD) 3172 .addMBB(TargetB); 3173 BrI.setDesc(JD); 3174 while (BrI.getNumOperands() > 0) 3175 BrI.RemoveOperand(0); 3176 // This ensures that all implicit operands (e.g. implicit-def %r31, etc) 3177 // are present in the rewritten branch. 3178 for (auto &Op : NI->operands()) 3179 BrI.addOperand(Op); 3180 NI->eraseFromParent(); 3181 Rewritten = true; 3182 } 3183 } 3184 3185 // Do not erase instructions. A newly created instruction could get 3186 // the same address as an instruction marked as executable during the 3187 // propagation. 3188 if (!Rewritten) 3189 replaceWithNop(BrI); 3190 return true; 3191 } 3192 3193 FunctionPass *llvm::createHexagonConstPropagationPass() { 3194 return new HexagonConstPropagation(); 3195 } 3196