1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines a pattern matching instruction selector for PowerPC, 10 // converting from a legalized dag to a PPC dag. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "MCTargetDesc/PPCMCTargetDesc.h" 15 #include "MCTargetDesc/PPCPredicates.h" 16 #include "PPC.h" 17 #include "PPCISelLowering.h" 18 #include "PPCMachineFunctionInfo.h" 19 #include "PPCSubtarget.h" 20 #include "PPCTargetMachine.h" 21 #include "llvm/ADT/APInt.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/Statistic.h" 27 #include "llvm/Analysis/BranchProbabilityInfo.h" 28 #include "llvm/CodeGen/FunctionLoweringInfo.h" 29 #include "llvm/CodeGen/ISDOpcodes.h" 30 #include "llvm/CodeGen/MachineBasicBlock.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/SelectionDAG.h" 35 #include "llvm/CodeGen/SelectionDAGISel.h" 36 #include "llvm/CodeGen/SelectionDAGNodes.h" 37 #include "llvm/CodeGen/TargetInstrInfo.h" 38 #include "llvm/CodeGen/TargetRegisterInfo.h" 39 #include "llvm/CodeGen/ValueTypes.h" 40 #include "llvm/IR/BasicBlock.h" 41 #include "llvm/IR/DebugLoc.h" 42 #include "llvm/IR/Function.h" 43 #include "llvm/IR/GlobalValue.h" 44 #include "llvm/IR/InlineAsm.h" 45 #include "llvm/IR/InstrTypes.h" 46 #include "llvm/IR/IntrinsicsPowerPC.h" 47 #include "llvm/IR/Module.h" 48 #include "llvm/Support/Casting.h" 49 #include "llvm/Support/CodeGen.h" 50 #include "llvm/Support/CommandLine.h" 51 #include "llvm/Support/Compiler.h" 52 #include "llvm/Support/Debug.h" 53 #include "llvm/Support/ErrorHandling.h" 54 #include "llvm/Support/KnownBits.h" 55 #include "llvm/Support/MachineValueType.h" 56 #include "llvm/Support/MathExtras.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include <algorithm> 59 #include <cassert> 60 #include <cstdint> 61 #include <iterator> 62 #include <limits> 63 #include <memory> 64 #include <new> 65 #include <tuple> 66 #include <utility> 67 68 using namespace llvm; 69 70 #define DEBUG_TYPE "ppc-codegen" 71 72 STATISTIC(NumSextSetcc, 73 "Number of (sext(setcc)) nodes expanded into GPR sequence."); 74 STATISTIC(NumZextSetcc, 75 "Number of (zext(setcc)) nodes expanded into GPR sequence."); 76 STATISTIC(SignExtensionsAdded, 77 "Number of sign extensions for compare inputs added."); 78 STATISTIC(ZeroExtensionsAdded, 79 "Number of zero extensions for compare inputs added."); 80 STATISTIC(NumLogicOpsOnComparison, 81 "Number of logical ops on i1 values calculated in GPR."); 82 STATISTIC(OmittedForNonExtendUses, 83 "Number of compares not eliminated as they have non-extending uses."); 84 STATISTIC(NumP9Setb, 85 "Number of compares lowered to setb."); 86 87 // FIXME: Remove this once the bug has been fixed! 88 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug", 89 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden); 90 91 static cl::opt<bool> 92 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true), 93 cl::desc("use aggressive ppc isel for bit permutations"), 94 cl::Hidden); 95 static cl::opt<bool> BPermRewriterNoMasking( 96 "ppc-bit-perm-rewriter-stress-rotates", 97 cl::desc("stress rotate selection in aggressive ppc isel for " 98 "bit permutations"), 99 cl::Hidden); 100 101 static cl::opt<bool> EnableBranchHint( 102 "ppc-use-branch-hint", cl::init(true), 103 cl::desc("Enable static hinting of branches on ppc"), 104 cl::Hidden); 105 106 static cl::opt<bool> EnableTLSOpt( 107 "ppc-tls-opt", cl::init(true), 108 cl::desc("Enable tls optimization peephole"), 109 cl::Hidden); 110 111 enum ICmpInGPRType { ICGPR_All, ICGPR_None, ICGPR_I32, ICGPR_I64, 112 ICGPR_NonExtIn, ICGPR_Zext, ICGPR_Sext, ICGPR_ZextI32, 113 ICGPR_SextI32, ICGPR_ZextI64, ICGPR_SextI64 }; 114 115 static cl::opt<ICmpInGPRType> CmpInGPR( 116 "ppc-gpr-icmps", cl::Hidden, cl::init(ICGPR_All), 117 cl::desc("Specify the types of comparisons to emit GPR-only code for."), 118 cl::values(clEnumValN(ICGPR_None, "none", "Do not modify integer comparisons."), 119 clEnumValN(ICGPR_All, "all", "All possible int comparisons in GPRs."), 120 clEnumValN(ICGPR_I32, "i32", "Only i32 comparisons in GPRs."), 121 clEnumValN(ICGPR_I64, "i64", "Only i64 comparisons in GPRs."), 122 clEnumValN(ICGPR_NonExtIn, "nonextin", 123 "Only comparisons where inputs don't need [sz]ext."), 124 clEnumValN(ICGPR_Zext, "zext", "Only comparisons with zext result."), 125 clEnumValN(ICGPR_ZextI32, "zexti32", 126 "Only i32 comparisons with zext result."), 127 clEnumValN(ICGPR_ZextI64, "zexti64", 128 "Only i64 comparisons with zext result."), 129 clEnumValN(ICGPR_Sext, "sext", "Only comparisons with sext result."), 130 clEnumValN(ICGPR_SextI32, "sexti32", 131 "Only i32 comparisons with sext result."), 132 clEnumValN(ICGPR_SextI64, "sexti64", 133 "Only i64 comparisons with sext result."))); 134 namespace { 135 136 //===--------------------------------------------------------------------===// 137 /// PPCDAGToDAGISel - PPC specific code to select PPC machine 138 /// instructions for SelectionDAG operations. 139 /// 140 class PPCDAGToDAGISel : public SelectionDAGISel { 141 const PPCTargetMachine &TM; 142 const PPCSubtarget *PPCSubTarget = nullptr; 143 const PPCSubtarget *Subtarget = nullptr; 144 const PPCTargetLowering *PPCLowering = nullptr; 145 unsigned GlobalBaseReg = 0; 146 147 public: 148 explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOpt::Level OptLevel) 149 : SelectionDAGISel(tm, OptLevel), TM(tm) {} 150 151 bool runOnMachineFunction(MachineFunction &MF) override { 152 // Make sure we re-emit a set of the global base reg if necessary 153 GlobalBaseReg = 0; 154 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>(); 155 Subtarget = &MF.getSubtarget<PPCSubtarget>(); 156 PPCLowering = Subtarget->getTargetLowering(); 157 SelectionDAGISel::runOnMachineFunction(MF); 158 159 return true; 160 } 161 162 void PreprocessISelDAG() override; 163 void PostprocessISelDAG() override; 164 165 /// getI16Imm - Return a target constant with the specified value, of type 166 /// i16. 167 inline SDValue getI16Imm(unsigned Imm, const SDLoc &dl) { 168 return CurDAG->getTargetConstant(Imm, dl, MVT::i16); 169 } 170 171 /// getI32Imm - Return a target constant with the specified value, of type 172 /// i32. 173 inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) { 174 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 175 } 176 177 /// getI64Imm - Return a target constant with the specified value, of type 178 /// i64. 179 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) { 180 return CurDAG->getTargetConstant(Imm, dl, MVT::i64); 181 } 182 183 /// getSmallIPtrImm - Return a target constant of pointer type. 184 inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) { 185 return CurDAG->getTargetConstant( 186 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout())); 187 } 188 189 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a 190 /// rotate and mask opcode and mask operation. 191 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask, 192 unsigned &SH, unsigned &MB, unsigned &ME); 193 194 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC 195 /// base register. Return the virtual register that holds this value. 196 SDNode *getGlobalBaseReg(); 197 198 void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0); 199 200 // Select - Convert the specified operand from a target-independent to a 201 // target-specific node if it hasn't already been changed. 202 void Select(SDNode *N) override; 203 204 bool tryBitfieldInsert(SDNode *N); 205 bool tryBitPermutation(SDNode *N); 206 bool tryIntCompareInGPR(SDNode *N); 207 208 // tryTLSXFormLoad - Convert an ISD::LOAD fed by a PPCISD::ADD_TLS into 209 // an X-Form load instruction with the offset being a relocation coming from 210 // the PPCISD::ADD_TLS. 211 bool tryTLSXFormLoad(LoadSDNode *N); 212 // tryTLSXFormStore - Convert an ISD::STORE fed by a PPCISD::ADD_TLS into 213 // an X-Form store instruction with the offset being a relocation coming from 214 // the PPCISD::ADD_TLS. 215 bool tryTLSXFormStore(StoreSDNode *N); 216 /// SelectCC - Select a comparison of the specified values with the 217 /// specified condition code, returning the CR# of the expression. 218 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, 219 const SDLoc &dl, SDValue Chain = SDValue()); 220 221 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc 222 /// immediate field. Note that the operand at this point is already the 223 /// result of a prior SelectAddressRegImm call. 224 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const { 225 if (N.getOpcode() == ISD::TargetConstant || 226 N.getOpcode() == ISD::TargetGlobalAddress) { 227 Out = N; 228 return true; 229 } 230 231 return false; 232 } 233 234 /// SelectAddrIdx - Given the specified address, check to see if it can be 235 /// represented as an indexed [r+r] operation. 236 /// This is for xform instructions whose associated displacement form is D. 237 /// The last parameter \p 0 means associated D form has no requirment for 16 238 /// bit signed displacement. 239 /// Returns false if it can be represented by [r+imm], which are preferred. 240 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) { 241 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG, None); 242 } 243 244 /// SelectAddrIdx4 - Given the specified address, check to see if it can be 245 /// represented as an indexed [r+r] operation. 246 /// This is for xform instructions whose associated displacement form is DS. 247 /// The last parameter \p 4 means associated DS form 16 bit signed 248 /// displacement must be a multiple of 4. 249 /// Returns false if it can be represented by [r+imm], which are preferred. 250 bool SelectAddrIdxX4(SDValue N, SDValue &Base, SDValue &Index) { 251 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG, 252 Align(4)); 253 } 254 255 /// SelectAddrIdx16 - Given the specified address, check to see if it can be 256 /// represented as an indexed [r+r] operation. 257 /// This is for xform instructions whose associated displacement form is DQ. 258 /// The last parameter \p 16 means associated DQ form 16 bit signed 259 /// displacement must be a multiple of 16. 260 /// Returns false if it can be represented by [r+imm], which are preferred. 261 bool SelectAddrIdxX16(SDValue N, SDValue &Base, SDValue &Index) { 262 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG, 263 Align(16)); 264 } 265 266 /// SelectAddrIdxOnly - Given the specified address, force it to be 267 /// represented as an indexed [r+r] operation. 268 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) { 269 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG); 270 } 271 272 /// SelectAddrImm - Returns true if the address N can be represented by 273 /// a base register plus a signed 16-bit displacement [r+imm]. 274 /// The last parameter \p 0 means D form has no requirment for 16 bit signed 275 /// displacement. 276 bool SelectAddrImm(SDValue N, SDValue &Disp, 277 SDValue &Base) { 278 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, None); 279 } 280 281 /// SelectAddrImmX4 - Returns true if the address N can be represented by 282 /// a base register plus a signed 16-bit displacement that is a multiple of 283 /// 4 (last parameter). Suitable for use by STD and friends. 284 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) { 285 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, Align(4)); 286 } 287 288 /// SelectAddrImmX16 - Returns true if the address N can be represented by 289 /// a base register plus a signed 16-bit displacement that is a multiple of 290 /// 16(last parameter). Suitable for use by STXV and friends. 291 bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) { 292 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 293 Align(16)); 294 } 295 296 /// SelectAddrImmX34 - Returns true if the address N can be represented by 297 /// a base register plus a signed 34-bit displacement. Suitable for use by 298 /// PSTXVP and friends. 299 bool SelectAddrImmX34(SDValue N, SDValue &Disp, SDValue &Base) { 300 return PPCLowering->SelectAddressRegImm34(N, Disp, Base, *CurDAG); 301 } 302 303 // Select an address into a single register. 304 bool SelectAddr(SDValue N, SDValue &Base) { 305 Base = N; 306 return true; 307 } 308 309 bool SelectAddrPCRel(SDValue N, SDValue &Base) { 310 return PPCLowering->SelectAddressPCRel(N, Base); 311 } 312 313 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for 314 /// inline asm expressions. It is always correct to compute the value into 315 /// a register. The case of adding a (possibly relocatable) constant to a 316 /// register can be improved, but it is wrong to substitute Reg+Reg for 317 /// Reg in an asm, because the load or store opcode would have to change. 318 bool SelectInlineAsmMemoryOperand(const SDValue &Op, 319 unsigned ConstraintID, 320 std::vector<SDValue> &OutOps) override { 321 switch(ConstraintID) { 322 default: 323 errs() << "ConstraintID: " << ConstraintID << "\n"; 324 llvm_unreachable("Unexpected asm memory constraint"); 325 case InlineAsm::Constraint_es: 326 case InlineAsm::Constraint_m: 327 case InlineAsm::Constraint_o: 328 case InlineAsm::Constraint_Q: 329 case InlineAsm::Constraint_Z: 330 case InlineAsm::Constraint_Zy: 331 // We need to make sure that this one operand does not end up in r0 332 // (because we might end up lowering this as 0(%op)). 333 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo(); 334 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1); 335 SDLoc dl(Op); 336 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32); 337 SDValue NewOp = 338 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 339 dl, Op.getValueType(), 340 Op, RC), 0); 341 342 OutOps.push_back(NewOp); 343 return false; 344 } 345 return true; 346 } 347 348 StringRef getPassName() const override { 349 return "PowerPC DAG->DAG Pattern Instruction Selection"; 350 } 351 352 // Include the pieces autogenerated from the target description. 353 #include "PPCGenDAGISel.inc" 354 355 private: 356 bool trySETCC(SDNode *N); 357 bool tryAsSingleRLDICL(SDNode *N); 358 bool tryAsSingleRLDICR(SDNode *N); 359 bool tryAsSingleRLWINM(SDNode *N); 360 bool tryAsSingleRLWINM8(SDNode *N); 361 bool tryAsSingleRLWIMI(SDNode *N); 362 bool tryAsPairOfRLDICL(SDNode *N); 363 bool tryAsSingleRLDIMI(SDNode *N); 364 365 void PeepholePPC64(); 366 void PeepholePPC64ZExt(); 367 void PeepholeCROps(); 368 369 SDValue combineToCMPB(SDNode *N); 370 void foldBoolExts(SDValue &Res, SDNode *&N); 371 372 bool AllUsersSelectZero(SDNode *N); 373 void SwapAllSelectUsers(SDNode *N); 374 375 bool isOffsetMultipleOf(SDNode *N, unsigned Val) const; 376 void transferMemOperands(SDNode *N, SDNode *Result); 377 }; 378 379 } // end anonymous namespace 380 381 /// getGlobalBaseReg - Output the instructions required to put the 382 /// base address to use for accessing globals into a register. 383 /// 384 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() { 385 if (!GlobalBaseReg) { 386 const TargetInstrInfo &TII = *Subtarget->getInstrInfo(); 387 // Insert the set of GlobalBaseReg into the first MBB of the function 388 MachineBasicBlock &FirstMBB = MF->front(); 389 MachineBasicBlock::iterator MBBI = FirstMBB.begin(); 390 const Module *M = MF->getFunction().getParent(); 391 DebugLoc dl; 392 393 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) { 394 if (Subtarget->isTargetELF()) { 395 GlobalBaseReg = PPC::R30; 396 if (!Subtarget->isSecurePlt() && 397 M->getPICLevel() == PICLevel::SmallPIC) { 398 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR)); 399 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 400 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true); 401 } else { 402 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR)); 403 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 404 Register TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass); 405 BuildMI(FirstMBB, MBBI, dl, 406 TII.get(PPC::UpdateGBR), GlobalBaseReg) 407 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg); 408 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true); 409 } 410 } else { 411 GlobalBaseReg = 412 RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass); 413 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR)); 414 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 415 } 416 } else { 417 // We must ensure that this sequence is dominated by the prologue. 418 // FIXME: This is a bit of a big hammer since we don't get the benefits 419 // of shrink-wrapping whenever we emit this instruction. Considering 420 // this is used in any function where we emit a jump table, this may be 421 // a significant limitation. We should consider inserting this in the 422 // block where it is used and then commoning this sequence up if it 423 // appears in multiple places. 424 // Note: on ISA 3.0 cores, we can use lnia (addpcis) instead of 425 // MovePCtoLR8. 426 MF->getInfo<PPCFunctionInfo>()->setShrinkWrapDisabled(true); 427 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass); 428 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8)); 429 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg); 430 } 431 } 432 return CurDAG->getRegister(GlobalBaseReg, 433 PPCLowering->getPointerTy(CurDAG->getDataLayout())) 434 .getNode(); 435 } 436 437 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant 438 /// operand. If so Imm will receive the 32-bit value. 439 static bool isInt32Immediate(SDNode *N, unsigned &Imm) { 440 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) { 441 Imm = cast<ConstantSDNode>(N)->getZExtValue(); 442 return true; 443 } 444 return false; 445 } 446 447 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant 448 /// operand. If so Imm will receive the 64-bit value. 449 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) { 450 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) { 451 Imm = cast<ConstantSDNode>(N)->getZExtValue(); 452 return true; 453 } 454 return false; 455 } 456 457 // isInt32Immediate - This method tests to see if a constant operand. 458 // If so Imm will receive the 32 bit value. 459 static bool isInt32Immediate(SDValue N, unsigned &Imm) { 460 return isInt32Immediate(N.getNode(), Imm); 461 } 462 463 /// isInt64Immediate - This method tests to see if the value is a 64-bit 464 /// constant operand. If so Imm will receive the 64-bit value. 465 static bool isInt64Immediate(SDValue N, uint64_t &Imm) { 466 return isInt64Immediate(N.getNode(), Imm); 467 } 468 469 static unsigned getBranchHint(unsigned PCC, 470 const FunctionLoweringInfo &FuncInfo, 471 const SDValue &DestMBB) { 472 assert(isa<BasicBlockSDNode>(DestMBB)); 473 474 if (!FuncInfo.BPI) return PPC::BR_NO_HINT; 475 476 const BasicBlock *BB = FuncInfo.MBB->getBasicBlock(); 477 const Instruction *BBTerm = BB->getTerminator(); 478 479 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT; 480 481 const BasicBlock *TBB = BBTerm->getSuccessor(0); 482 const BasicBlock *FBB = BBTerm->getSuccessor(1); 483 484 auto TProb = FuncInfo.BPI->getEdgeProbability(BB, TBB); 485 auto FProb = FuncInfo.BPI->getEdgeProbability(BB, FBB); 486 487 // We only want to handle cases which are easy to predict at static time, e.g. 488 // C++ throw statement, that is very likely not taken, or calling never 489 // returned function, e.g. stdlib exit(). So we set Threshold to filter 490 // unwanted cases. 491 // 492 // Below is LLVM branch weight table, we only want to handle case 1, 2 493 // 494 // Case Taken:Nontaken Example 495 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(), 496 // 2. Invoke-terminating 1:1048575 497 // 3. Coldblock 4:64 __builtin_expect 498 // 4. Loop Branch 124:4 For loop 499 // 5. PH/ZH/FPH 20:12 500 const uint32_t Threshold = 10000; 501 502 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb)) 503 return PPC::BR_NO_HINT; 504 505 LLVM_DEBUG(dbgs() << "Use branch hint for '" << FuncInfo.Fn->getName() 506 << "::" << BB->getName() << "'\n" 507 << " -> " << TBB->getName() << ": " << TProb << "\n" 508 << " -> " << FBB->getName() << ": " << FProb << "\n"); 509 510 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB); 511 512 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities, 513 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock 514 if (BBDN->getBasicBlock()->getBasicBlock() != TBB) 515 std::swap(TProb, FProb); 516 517 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT; 518 } 519 520 // isOpcWithIntImmediate - This method tests to see if the node is a specific 521 // opcode and that it has a immediate integer right operand. 522 // If so Imm will receive the 32 bit value. 523 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) { 524 return N->getOpcode() == Opc 525 && isInt32Immediate(N->getOperand(1).getNode(), Imm); 526 } 527 528 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) { 529 SDLoc dl(SN); 530 int FI = cast<FrameIndexSDNode>(N)->getIndex(); 531 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0)); 532 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8; 533 if (SN->hasOneUse()) 534 CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI, 535 getSmallIPtrImm(Offset, dl)); 536 else 537 ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI, 538 getSmallIPtrImm(Offset, dl))); 539 } 540 541 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask, 542 bool isShiftMask, unsigned &SH, 543 unsigned &MB, unsigned &ME) { 544 // Don't even go down this path for i64, since different logic will be 545 // necessary for rldicl/rldicr/rldimi. 546 if (N->getValueType(0) != MVT::i32) 547 return false; 548 549 unsigned Shift = 32; 550 unsigned Indeterminant = ~0; // bit mask marking indeterminant results 551 unsigned Opcode = N->getOpcode(); 552 if (N->getNumOperands() != 2 || 553 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31)) 554 return false; 555 556 if (Opcode == ISD::SHL) { 557 // apply shift left to mask if it comes first 558 if (isShiftMask) Mask = Mask << Shift; 559 // determine which bits are made indeterminant by shift 560 Indeterminant = ~(0xFFFFFFFFu << Shift); 561 } else if (Opcode == ISD::SRL) { 562 // apply shift right to mask if it comes first 563 if (isShiftMask) Mask = Mask >> Shift; 564 // determine which bits are made indeterminant by shift 565 Indeterminant = ~(0xFFFFFFFFu >> Shift); 566 // adjust for the left rotate 567 Shift = 32 - Shift; 568 } else if (Opcode == ISD::ROTL) { 569 Indeterminant = 0; 570 } else { 571 return false; 572 } 573 574 // if the mask doesn't intersect any Indeterminant bits 575 if (Mask && !(Mask & Indeterminant)) { 576 SH = Shift & 31; 577 // make sure the mask is still a mask (wrap arounds may not be) 578 return isRunOfOnes(Mask, MB, ME); 579 } 580 return false; 581 } 582 583 bool PPCDAGToDAGISel::tryTLSXFormStore(StoreSDNode *ST) { 584 SDValue Base = ST->getBasePtr(); 585 if (Base.getOpcode() != PPCISD::ADD_TLS) 586 return false; 587 SDValue Offset = ST->getOffset(); 588 if (!Offset.isUndef()) 589 return false; 590 if (Base.getOperand(1).getOpcode() == PPCISD::TLS_LOCAL_EXEC_MAT_ADDR) 591 return false; 592 593 SDLoc dl(ST); 594 EVT MemVT = ST->getMemoryVT(); 595 EVT RegVT = ST->getValue().getValueType(); 596 597 unsigned Opcode; 598 switch (MemVT.getSimpleVT().SimpleTy) { 599 default: 600 return false; 601 case MVT::i8: { 602 Opcode = (RegVT == MVT::i32) ? PPC::STBXTLS_32 : PPC::STBXTLS; 603 break; 604 } 605 case MVT::i16: { 606 Opcode = (RegVT == MVT::i32) ? PPC::STHXTLS_32 : PPC::STHXTLS; 607 break; 608 } 609 case MVT::i32: { 610 Opcode = (RegVT == MVT::i32) ? PPC::STWXTLS_32 : PPC::STWXTLS; 611 break; 612 } 613 case MVT::i64: { 614 Opcode = PPC::STDXTLS; 615 break; 616 } 617 } 618 SDValue Chain = ST->getChain(); 619 SDVTList VTs = ST->getVTList(); 620 SDValue Ops[] = {ST->getValue(), Base.getOperand(0), Base.getOperand(1), 621 Chain}; 622 SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops); 623 transferMemOperands(ST, MN); 624 ReplaceNode(ST, MN); 625 return true; 626 } 627 628 bool PPCDAGToDAGISel::tryTLSXFormLoad(LoadSDNode *LD) { 629 SDValue Base = LD->getBasePtr(); 630 if (Base.getOpcode() != PPCISD::ADD_TLS) 631 return false; 632 SDValue Offset = LD->getOffset(); 633 if (!Offset.isUndef()) 634 return false; 635 if (Base.getOperand(1).getOpcode() == PPCISD::TLS_LOCAL_EXEC_MAT_ADDR) 636 return false; 637 638 SDLoc dl(LD); 639 EVT MemVT = LD->getMemoryVT(); 640 EVT RegVT = LD->getValueType(0); 641 unsigned Opcode; 642 switch (MemVT.getSimpleVT().SimpleTy) { 643 default: 644 return false; 645 case MVT::i8: { 646 Opcode = (RegVT == MVT::i32) ? PPC::LBZXTLS_32 : PPC::LBZXTLS; 647 break; 648 } 649 case MVT::i16: { 650 Opcode = (RegVT == MVT::i32) ? PPC::LHZXTLS_32 : PPC::LHZXTLS; 651 break; 652 } 653 case MVT::i32: { 654 Opcode = (RegVT == MVT::i32) ? PPC::LWZXTLS_32 : PPC::LWZXTLS; 655 break; 656 } 657 case MVT::i64: { 658 Opcode = PPC::LDXTLS; 659 break; 660 } 661 } 662 SDValue Chain = LD->getChain(); 663 SDVTList VTs = LD->getVTList(); 664 SDValue Ops[] = {Base.getOperand(0), Base.getOperand(1), Chain}; 665 SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops); 666 transferMemOperands(LD, MN); 667 ReplaceNode(LD, MN); 668 return true; 669 } 670 671 /// Turn an or of two masked values into the rotate left word immediate then 672 /// mask insert (rlwimi) instruction. 673 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) { 674 SDValue Op0 = N->getOperand(0); 675 SDValue Op1 = N->getOperand(1); 676 SDLoc dl(N); 677 678 KnownBits LKnown = CurDAG->computeKnownBits(Op0); 679 KnownBits RKnown = CurDAG->computeKnownBits(Op1); 680 681 unsigned TargetMask = LKnown.Zero.getZExtValue(); 682 unsigned InsertMask = RKnown.Zero.getZExtValue(); 683 684 if ((TargetMask | InsertMask) == 0xFFFFFFFF) { 685 unsigned Op0Opc = Op0.getOpcode(); 686 unsigned Op1Opc = Op1.getOpcode(); 687 unsigned Value, SH = 0; 688 TargetMask = ~TargetMask; 689 InsertMask = ~InsertMask; 690 691 // If the LHS has a foldable shift and the RHS does not, then swap it to the 692 // RHS so that we can fold the shift into the insert. 693 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) { 694 if (Op0.getOperand(0).getOpcode() == ISD::SHL || 695 Op0.getOperand(0).getOpcode() == ISD::SRL) { 696 if (Op1.getOperand(0).getOpcode() != ISD::SHL && 697 Op1.getOperand(0).getOpcode() != ISD::SRL) { 698 std::swap(Op0, Op1); 699 std::swap(Op0Opc, Op1Opc); 700 std::swap(TargetMask, InsertMask); 701 } 702 } 703 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) { 704 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL && 705 Op1.getOperand(0).getOpcode() != ISD::SRL) { 706 std::swap(Op0, Op1); 707 std::swap(Op0Opc, Op1Opc); 708 std::swap(TargetMask, InsertMask); 709 } 710 } 711 712 unsigned MB, ME; 713 if (isRunOfOnes(InsertMask, MB, ME)) { 714 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) && 715 isInt32Immediate(Op1.getOperand(1), Value)) { 716 Op1 = Op1.getOperand(0); 717 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value; 718 } 719 if (Op1Opc == ISD::AND) { 720 // The AND mask might not be a constant, and we need to make sure that 721 // if we're going to fold the masking with the insert, all bits not 722 // know to be zero in the mask are known to be one. 723 KnownBits MKnown = CurDAG->computeKnownBits(Op1.getOperand(1)); 724 bool CanFoldMask = InsertMask == MKnown.One.getZExtValue(); 725 726 unsigned SHOpc = Op1.getOperand(0).getOpcode(); 727 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask && 728 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) { 729 // Note that Value must be in range here (less than 32) because 730 // otherwise there would not be any bits set in InsertMask. 731 Op1 = Op1.getOperand(0).getOperand(0); 732 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value; 733 } 734 } 735 736 SH &= 31; 737 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl), 738 getI32Imm(ME, dl) }; 739 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops)); 740 return true; 741 } 742 } 743 return false; 744 } 745 746 static unsigned allUsesTruncate(SelectionDAG *CurDAG, SDNode *N) { 747 unsigned MaxTruncation = 0; 748 // Cannot use range-based for loop here as we need the actual use (i.e. we 749 // need the operand number corresponding to the use). A range-based for 750 // will unbox the use and provide an SDNode*. 751 for (SDNode::use_iterator Use = N->use_begin(), UseEnd = N->use_end(); 752 Use != UseEnd; ++Use) { 753 unsigned Opc = 754 Use->isMachineOpcode() ? Use->getMachineOpcode() : Use->getOpcode(); 755 switch (Opc) { 756 default: return 0; 757 case ISD::TRUNCATE: 758 if (Use->isMachineOpcode()) 759 return 0; 760 MaxTruncation = 761 std::max(MaxTruncation, (unsigned)Use->getValueType(0).getSizeInBits()); 762 continue; 763 case ISD::STORE: { 764 if (Use->isMachineOpcode()) 765 return 0; 766 StoreSDNode *STN = cast<StoreSDNode>(*Use); 767 unsigned MemVTSize = STN->getMemoryVT().getSizeInBits(); 768 if (MemVTSize == 64 || Use.getOperandNo() != 0) 769 return 0; 770 MaxTruncation = std::max(MaxTruncation, MemVTSize); 771 continue; 772 } 773 case PPC::STW8: 774 case PPC::STWX8: 775 case PPC::STWU8: 776 case PPC::STWUX8: 777 if (Use.getOperandNo() != 0) 778 return 0; 779 MaxTruncation = std::max(MaxTruncation, 32u); 780 continue; 781 case PPC::STH8: 782 case PPC::STHX8: 783 case PPC::STHU8: 784 case PPC::STHUX8: 785 if (Use.getOperandNo() != 0) 786 return 0; 787 MaxTruncation = std::max(MaxTruncation, 16u); 788 continue; 789 case PPC::STB8: 790 case PPC::STBX8: 791 case PPC::STBU8: 792 case PPC::STBUX8: 793 if (Use.getOperandNo() != 0) 794 return 0; 795 MaxTruncation = std::max(MaxTruncation, 8u); 796 continue; 797 } 798 } 799 return MaxTruncation; 800 } 801 802 // For any 32 < Num < 64, check if the Imm contains at least Num consecutive 803 // zeros and return the number of bits by the left of these consecutive zeros. 804 static int findContiguousZerosAtLeast(uint64_t Imm, unsigned Num) { 805 unsigned HiTZ = countTrailingZeros<uint32_t>(Hi_32(Imm)); 806 unsigned LoLZ = countLeadingZeros<uint32_t>(Lo_32(Imm)); 807 if ((HiTZ + LoLZ) >= Num) 808 return (32 + HiTZ); 809 return 0; 810 } 811 812 // Direct materialization of 64-bit constants by enumerated patterns. 813 static SDNode *selectI64ImmDirect(SelectionDAG *CurDAG, const SDLoc &dl, 814 uint64_t Imm, unsigned &InstCnt) { 815 unsigned TZ = countTrailingZeros<uint64_t>(Imm); 816 unsigned LZ = countLeadingZeros<uint64_t>(Imm); 817 unsigned TO = countTrailingOnes<uint64_t>(Imm); 818 unsigned LO = countLeadingOnes<uint64_t>(Imm); 819 unsigned Hi32 = Hi_32(Imm); 820 unsigned Lo32 = Lo_32(Imm); 821 SDNode *Result = nullptr; 822 unsigned Shift = 0; 823 824 auto getI32Imm = [CurDAG, dl](unsigned Imm) { 825 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 826 }; 827 828 // Following patterns use 1 instructions to materialize the Imm. 829 InstCnt = 1; 830 // 1-1) Patterns : {zeros}{15-bit valve} 831 // {ones}{15-bit valve} 832 if (isInt<16>(Imm)) { 833 SDValue SDImm = CurDAG->getTargetConstant(Imm, dl, MVT::i64); 834 return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm); 835 } 836 // 1-2) Patterns : {zeros}{15-bit valve}{16 zeros} 837 // {ones}{15-bit valve}{16 zeros} 838 if (TZ > 15 && (LZ > 32 || LO > 32)) 839 return CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, 840 getI32Imm((Imm >> 16) & 0xffff)); 841 842 // Following patterns use 2 instructions to materialize the Imm. 843 InstCnt = 2; 844 assert(LZ < 64 && "Unexpected leading zeros here."); 845 // Count of ones follwing the leading zeros. 846 unsigned FO = countLeadingOnes<uint64_t>(Imm << LZ); 847 // 2-1) Patterns : {zeros}{31-bit value} 848 // {ones}{31-bit value} 849 if (isInt<32>(Imm)) { 850 uint64_t ImmHi16 = (Imm >> 16) & 0xffff; 851 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8; 852 Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16)); 853 return CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0), 854 getI32Imm(Imm & 0xffff)); 855 } 856 // 2-2) Patterns : {zeros}{ones}{15-bit value}{zeros} 857 // {zeros}{15-bit value}{zeros} 858 // {zeros}{ones}{15-bit value} 859 // {ones}{15-bit value}{zeros} 860 // We can take advantage of LI's sign-extension semantics to generate leading 861 // ones, and then use RLDIC to mask off the ones in both sides after rotation. 862 if ((LZ + FO + TZ) > 48) { 863 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, 864 getI32Imm((Imm >> TZ) & 0xffff)); 865 return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0), 866 getI32Imm(TZ), getI32Imm(LZ)); 867 } 868 // 2-3) Pattern : {zeros}{15-bit value}{ones} 869 // Shift right the Imm by (48 - LZ) bits to construct a negtive 16 bits value, 870 // therefore we can take advantage of LI's sign-extension semantics, and then 871 // mask them off after rotation. 872 // 873 // +--LZ--||-15-bit-||--TO--+ +-------------|--16-bit--+ 874 // |00000001bbbbbbbbb1111111| -> |00000000000001bbbbbbbbb1| 875 // +------------------------+ +------------------------+ 876 // 63 0 63 0 877 // Imm (Imm >> (48 - LZ) & 0xffff) 878 // +----sext-----|--16-bit--+ +clear-|-----------------+ 879 // |11111111111111bbbbbbbbb1| -> |00000001bbbbbbbbb1111111| 880 // +------------------------+ +------------------------+ 881 // 63 0 63 0 882 // LI8: sext many leading zeros RLDICL: rotate left (48 - LZ), clear left LZ 883 if ((LZ + TO) > 48) { 884 // Since the immediates with (LZ > 32) have been handled by previous 885 // patterns, here we have (LZ <= 32) to make sure we will not shift right 886 // the Imm by a negative value. 887 assert(LZ <= 32 && "Unexpected shift value."); 888 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, 889 getI32Imm((Imm >> (48 - LZ) & 0xffff))); 890 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0), 891 getI32Imm(48 - LZ), getI32Imm(LZ)); 892 } 893 // 2-4) Patterns : {zeros}{ones}{15-bit value}{ones} 894 // {ones}{15-bit value}{ones} 895 // We can take advantage of LI's sign-extension semantics to generate leading 896 // ones, and then use RLDICL to mask off the ones in left sides (if required) 897 // after rotation. 898 // 899 // +-LZ-FO||-15-bit-||--TO--+ +-------------|--16-bit--+ 900 // |00011110bbbbbbbbb1111111| -> |000000000011110bbbbbbbbb| 901 // +------------------------+ +------------------------+ 902 // 63 0 63 0 903 // Imm (Imm >> TO) & 0xffff 904 // +----sext-----|--16-bit--+ +LZ|---------------------+ 905 // |111111111111110bbbbbbbbb| -> |00011110bbbbbbbbb1111111| 906 // +------------------------+ +------------------------+ 907 // 63 0 63 0 908 // LI8: sext many leading zeros RLDICL: rotate left TO, clear left LZ 909 if ((LZ + FO + TO) > 48) { 910 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, 911 getI32Imm((Imm >> TO) & 0xffff)); 912 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0), 913 getI32Imm(TO), getI32Imm(LZ)); 914 } 915 // 2-5) Pattern : {32 zeros}{****}{0}{15-bit value} 916 // If Hi32 is zero and the Lo16(in Lo32) can be presented as a positive 16 bit 917 // value, we can use LI for Lo16 without generating leading ones then add the 918 // Hi16(in Lo32). 919 if (LZ == 32 && ((Lo32 & 0x8000) == 0)) { 920 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, 921 getI32Imm(Lo32 & 0xffff)); 922 return CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64, SDValue(Result, 0), 923 getI32Imm(Lo32 >> 16)); 924 } 925 // 2-6) Patterns : {******}{49 zeros}{******} 926 // {******}{49 ones}{******} 927 // If the Imm contains 49 consecutive zeros/ones, it means that a total of 15 928 // bits remain on both sides. Rotate right the Imm to construct an int<16> 929 // value, use LI for int<16> value and then use RLDICL without mask to rotate 930 // it back. 931 // 932 // 1) findContiguousZerosAtLeast(Imm, 49) 933 // +------|--zeros-|------+ +---ones--||---15 bit--+ 934 // |bbbbbb0000000000aaaaaa| -> |0000000000aaaaaabbbbbb| 935 // +----------------------+ +----------------------+ 936 // 63 0 63 0 937 // 938 // 2) findContiguousZerosAtLeast(~Imm, 49) 939 // +------|--ones--|------+ +---ones--||---15 bit--+ 940 // |bbbbbb1111111111aaaaaa| -> |1111111111aaaaaabbbbbb| 941 // +----------------------+ +----------------------+ 942 // 63 0 63 0 943 if ((Shift = findContiguousZerosAtLeast(Imm, 49)) || 944 (Shift = findContiguousZerosAtLeast(~Imm, 49))) { 945 uint64_t RotImm = (Imm >> Shift) | (Imm << (64 - Shift)); 946 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, 947 getI32Imm(RotImm & 0xffff)); 948 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0), 949 getI32Imm(Shift), getI32Imm(0)); 950 } 951 952 // Following patterns use 3 instructions to materialize the Imm. 953 InstCnt = 3; 954 // 3-1) Patterns : {zeros}{ones}{31-bit value}{zeros} 955 // {zeros}{31-bit value}{zeros} 956 // {zeros}{ones}{31-bit value} 957 // {ones}{31-bit value}{zeros} 958 // We can take advantage of LIS's sign-extension semantics to generate leading 959 // ones, add the remaining bits with ORI, and then use RLDIC to mask off the 960 // ones in both sides after rotation. 961 if ((LZ + FO + TZ) > 32) { 962 uint64_t ImmHi16 = (Imm >> (TZ + 16)) & 0xffff; 963 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8; 964 Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16)); 965 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0), 966 getI32Imm((Imm >> TZ) & 0xffff)); 967 return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0), 968 getI32Imm(TZ), getI32Imm(LZ)); 969 } 970 // 3-2) Pattern : {zeros}{31-bit value}{ones} 971 // Shift right the Imm by (32 - LZ) bits to construct a negtive 32 bits value, 972 // therefore we can take advantage of LIS's sign-extension semantics, add 973 // the remaining bits with ORI, and then mask them off after rotation. 974 // This is similar to Pattern 2-3, please refer to the diagram there. 975 if ((LZ + TO) > 32) { 976 // Since the immediates with (LZ > 32) have been handled by previous 977 // patterns, here we have (LZ <= 32) to make sure we will not shift right 978 // the Imm by a negative value. 979 assert(LZ <= 32 && "Unexpected shift value."); 980 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, 981 getI32Imm((Imm >> (48 - LZ)) & 0xffff)); 982 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0), 983 getI32Imm((Imm >> (32 - LZ)) & 0xffff)); 984 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0), 985 getI32Imm(32 - LZ), getI32Imm(LZ)); 986 } 987 // 3-3) Patterns : {zeros}{ones}{31-bit value}{ones} 988 // {ones}{31-bit value}{ones} 989 // We can take advantage of LIS's sign-extension semantics to generate leading 990 // ones, add the remaining bits with ORI, and then use RLDICL to mask off the 991 // ones in left sides (if required) after rotation. 992 // This is similar to Pattern 2-4, please refer to the diagram there. 993 if ((LZ + FO + TO) > 32) { 994 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, 995 getI32Imm((Imm >> (TO + 16)) & 0xffff)); 996 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0), 997 getI32Imm((Imm >> TO) & 0xffff)); 998 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0), 999 getI32Imm(TO), getI32Imm(LZ)); 1000 } 1001 // 3-4) Patterns : High word == Low word 1002 if (Hi32 == Lo32) { 1003 // Handle the first 32 bits. 1004 uint64_t ImmHi16 = (Lo32 >> 16) & 0xffff; 1005 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8; 1006 Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16)); 1007 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0), 1008 getI32Imm(Lo32 & 0xffff)); 1009 // Use rldimi to insert the Low word into High word. 1010 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32), 1011 getI32Imm(0)}; 1012 return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops); 1013 } 1014 // 3-5) Patterns : {******}{33 zeros}{******} 1015 // {******}{33 ones}{******} 1016 // If the Imm contains 33 consecutive zeros/ones, it means that a total of 31 1017 // bits remain on both sides. Rotate right the Imm to construct an int<32> 1018 // value, use LIS + ORI for int<32> value and then use RLDICL without mask to 1019 // rotate it back. 1020 // This is similar to Pattern 2-6, please refer to the diagram there. 1021 if ((Shift = findContiguousZerosAtLeast(Imm, 33)) || 1022 (Shift = findContiguousZerosAtLeast(~Imm, 33))) { 1023 uint64_t RotImm = (Imm >> Shift) | (Imm << (64 - Shift)); 1024 uint64_t ImmHi16 = (RotImm >> 16) & 0xffff; 1025 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8; 1026 Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16)); 1027 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0), 1028 getI32Imm(RotImm & 0xffff)); 1029 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0), 1030 getI32Imm(Shift), getI32Imm(0)); 1031 } 1032 1033 InstCnt = 0; 1034 return nullptr; 1035 } 1036 1037 static SDNode *selectI64Imm(SelectionDAG *CurDAG, const SDLoc &dl, uint64_t Imm, 1038 unsigned *InstCnt = nullptr) { 1039 unsigned InstCntDirect = 0; 1040 // No more than 3 instructions is used if we can select the i64 immediate 1041 // directly. 1042 SDNode *Result = selectI64ImmDirect(CurDAG, dl, Imm, InstCntDirect); 1043 if (Result) { 1044 if (InstCnt) 1045 *InstCnt = InstCntDirect; 1046 return Result; 1047 } 1048 auto getI32Imm = [CurDAG, dl](unsigned Imm) { 1049 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 1050 }; 1051 // Handle the upper 32 bit value. 1052 Result = 1053 selectI64ImmDirect(CurDAG, dl, Imm & 0xffffffff00000000, InstCntDirect); 1054 // Add in the last bits as required. 1055 if (uint32_t Hi16 = (Lo_32(Imm) >> 16) & 0xffff) { 1056 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64, 1057 SDValue(Result, 0), getI32Imm(Hi16)); 1058 ++InstCntDirect; 1059 } 1060 if (uint32_t Lo16 = Lo_32(Imm) & 0xffff) { 1061 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0), 1062 getI32Imm(Lo16)); 1063 ++InstCntDirect; 1064 } 1065 if (InstCnt) 1066 *InstCnt = InstCntDirect; 1067 return Result; 1068 } 1069 1070 // Select a 64-bit constant. 1071 static SDNode *selectI64Imm(SelectionDAG *CurDAG, SDNode *N) { 1072 SDLoc dl(N); 1073 1074 // Get 64 bit value. 1075 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue(); 1076 if (unsigned MinSize = allUsesTruncate(CurDAG, N)) { 1077 uint64_t SextImm = SignExtend64(Imm, MinSize); 1078 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64); 1079 if (isInt<16>(SextImm)) 1080 return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm); 1081 } 1082 return selectI64Imm(CurDAG, dl, Imm); 1083 } 1084 1085 namespace { 1086 1087 class BitPermutationSelector { 1088 struct ValueBit { 1089 SDValue V; 1090 1091 // The bit number in the value, using a convention where bit 0 is the 1092 // lowest-order bit. 1093 unsigned Idx; 1094 1095 // ConstZero means a bit we need to mask off. 1096 // Variable is a bit comes from an input variable. 1097 // VariableKnownToBeZero is also a bit comes from an input variable, 1098 // but it is known to be already zero. So we do not need to mask them. 1099 enum Kind { 1100 ConstZero, 1101 Variable, 1102 VariableKnownToBeZero 1103 } K; 1104 1105 ValueBit(SDValue V, unsigned I, Kind K = Variable) 1106 : V(V), Idx(I), K(K) {} 1107 ValueBit(Kind K = Variable) 1108 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {} 1109 1110 bool isZero() const { 1111 return K == ConstZero || K == VariableKnownToBeZero; 1112 } 1113 1114 bool hasValue() const { 1115 return K == Variable || K == VariableKnownToBeZero; 1116 } 1117 1118 SDValue getValue() const { 1119 assert(hasValue() && "Cannot get the value of a constant bit"); 1120 return V; 1121 } 1122 1123 unsigned getValueBitIndex() const { 1124 assert(hasValue() && "Cannot get the value bit index of a constant bit"); 1125 return Idx; 1126 } 1127 }; 1128 1129 // A bit group has the same underlying value and the same rotate factor. 1130 struct BitGroup { 1131 SDValue V; 1132 unsigned RLAmt; 1133 unsigned StartIdx, EndIdx; 1134 1135 // This rotation amount assumes that the lower 32 bits of the quantity are 1136 // replicated in the high 32 bits by the rotation operator (which is done 1137 // by rlwinm and friends in 64-bit mode). 1138 bool Repl32; 1139 // Did converting to Repl32 == true change the rotation factor? If it did, 1140 // it decreased it by 32. 1141 bool Repl32CR; 1142 // Was this group coalesced after setting Repl32 to true? 1143 bool Repl32Coalesced; 1144 1145 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E) 1146 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false), 1147 Repl32Coalesced(false) { 1148 LLVM_DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R 1149 << " [" << S << ", " << E << "]\n"); 1150 } 1151 }; 1152 1153 // Information on each (Value, RLAmt) pair (like the number of groups 1154 // associated with each) used to choose the lowering method. 1155 struct ValueRotInfo { 1156 SDValue V; 1157 unsigned RLAmt = std::numeric_limits<unsigned>::max(); 1158 unsigned NumGroups = 0; 1159 unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max(); 1160 bool Repl32 = false; 1161 1162 ValueRotInfo() = default; 1163 1164 // For sorting (in reverse order) by NumGroups, and then by 1165 // FirstGroupStartIdx. 1166 bool operator < (const ValueRotInfo &Other) const { 1167 // We need to sort so that the non-Repl32 come first because, when we're 1168 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit 1169 // masking operation. 1170 if (Repl32 < Other.Repl32) 1171 return true; 1172 else if (Repl32 > Other.Repl32) 1173 return false; 1174 else if (NumGroups > Other.NumGroups) 1175 return true; 1176 else if (NumGroups < Other.NumGroups) 1177 return false; 1178 else if (RLAmt == 0 && Other.RLAmt != 0) 1179 return true; 1180 else if (RLAmt != 0 && Other.RLAmt == 0) 1181 return false; 1182 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx) 1183 return true; 1184 return false; 1185 } 1186 }; 1187 1188 using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>; 1189 using ValueBitsMemoizer = 1190 DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>; 1191 ValueBitsMemoizer Memoizer; 1192 1193 // Return a pair of bool and a SmallVector pointer to a memoization entry. 1194 // The bool is true if something interesting was deduced, otherwise if we're 1195 // providing only a generic representation of V (or something else likewise 1196 // uninteresting for instruction selection) through the SmallVector. 1197 std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V, 1198 unsigned NumBits) { 1199 auto &ValueEntry = Memoizer[V]; 1200 if (ValueEntry) 1201 return std::make_pair(ValueEntry->first, &ValueEntry->second); 1202 ValueEntry.reset(new ValueBitsMemoizedValue()); 1203 bool &Interesting = ValueEntry->first; 1204 SmallVector<ValueBit, 64> &Bits = ValueEntry->second; 1205 Bits.resize(NumBits); 1206 1207 switch (V.getOpcode()) { 1208 default: break; 1209 case ISD::ROTL: 1210 if (isa<ConstantSDNode>(V.getOperand(1))) { 1211 unsigned RotAmt = V.getConstantOperandVal(1); 1212 1213 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second; 1214 1215 for (unsigned i = 0; i < NumBits; ++i) 1216 Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt]; 1217 1218 return std::make_pair(Interesting = true, &Bits); 1219 } 1220 break; 1221 case ISD::SHL: 1222 case PPCISD::SHL: 1223 if (isa<ConstantSDNode>(V.getOperand(1))) { 1224 unsigned ShiftAmt = V.getConstantOperandVal(1); 1225 1226 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second; 1227 1228 for (unsigned i = ShiftAmt; i < NumBits; ++i) 1229 Bits[i] = LHSBits[i - ShiftAmt]; 1230 1231 for (unsigned i = 0; i < ShiftAmt; ++i) 1232 Bits[i] = ValueBit(ValueBit::ConstZero); 1233 1234 return std::make_pair(Interesting = true, &Bits); 1235 } 1236 break; 1237 case ISD::SRL: 1238 case PPCISD::SRL: 1239 if (isa<ConstantSDNode>(V.getOperand(1))) { 1240 unsigned ShiftAmt = V.getConstantOperandVal(1); 1241 1242 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second; 1243 1244 for (unsigned i = 0; i < NumBits - ShiftAmt; ++i) 1245 Bits[i] = LHSBits[i + ShiftAmt]; 1246 1247 for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i) 1248 Bits[i] = ValueBit(ValueBit::ConstZero); 1249 1250 return std::make_pair(Interesting = true, &Bits); 1251 } 1252 break; 1253 case ISD::AND: 1254 if (isa<ConstantSDNode>(V.getOperand(1))) { 1255 uint64_t Mask = V.getConstantOperandVal(1); 1256 1257 const SmallVector<ValueBit, 64> *LHSBits; 1258 // Mark this as interesting, only if the LHS was also interesting. This 1259 // prevents the overall procedure from matching a single immediate 'and' 1260 // (which is non-optimal because such an and might be folded with other 1261 // things if we don't select it here). 1262 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits); 1263 1264 for (unsigned i = 0; i < NumBits; ++i) 1265 if (((Mask >> i) & 1) == 1) 1266 Bits[i] = (*LHSBits)[i]; 1267 else { 1268 // AND instruction masks this bit. If the input is already zero, 1269 // we have nothing to do here. Otherwise, make the bit ConstZero. 1270 if ((*LHSBits)[i].isZero()) 1271 Bits[i] = (*LHSBits)[i]; 1272 else 1273 Bits[i] = ValueBit(ValueBit::ConstZero); 1274 } 1275 1276 return std::make_pair(Interesting, &Bits); 1277 } 1278 break; 1279 case ISD::OR: { 1280 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second; 1281 const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second; 1282 1283 bool AllDisjoint = true; 1284 SDValue LastVal = SDValue(); 1285 unsigned LastIdx = 0; 1286 for (unsigned i = 0; i < NumBits; ++i) { 1287 if (LHSBits[i].isZero() && RHSBits[i].isZero()) { 1288 // If both inputs are known to be zero and one is ConstZero and 1289 // another is VariableKnownToBeZero, we can select whichever 1290 // we like. To minimize the number of bit groups, we select 1291 // VariableKnownToBeZero if this bit is the next bit of the same 1292 // input variable from the previous bit. Otherwise, we select 1293 // ConstZero. 1294 if (LHSBits[i].hasValue() && LHSBits[i].getValue() == LastVal && 1295 LHSBits[i].getValueBitIndex() == LastIdx + 1) 1296 Bits[i] = LHSBits[i]; 1297 else if (RHSBits[i].hasValue() && RHSBits[i].getValue() == LastVal && 1298 RHSBits[i].getValueBitIndex() == LastIdx + 1) 1299 Bits[i] = RHSBits[i]; 1300 else 1301 Bits[i] = ValueBit(ValueBit::ConstZero); 1302 } 1303 else if (LHSBits[i].isZero()) 1304 Bits[i] = RHSBits[i]; 1305 else if (RHSBits[i].isZero()) 1306 Bits[i] = LHSBits[i]; 1307 else { 1308 AllDisjoint = false; 1309 break; 1310 } 1311 // We remember the value and bit index of this bit. 1312 if (Bits[i].hasValue()) { 1313 LastVal = Bits[i].getValue(); 1314 LastIdx = Bits[i].getValueBitIndex(); 1315 } 1316 else { 1317 if (LastVal) LastVal = SDValue(); 1318 LastIdx = 0; 1319 } 1320 } 1321 1322 if (!AllDisjoint) 1323 break; 1324 1325 return std::make_pair(Interesting = true, &Bits); 1326 } 1327 case ISD::ZERO_EXTEND: { 1328 // We support only the case with zero extension from i32 to i64 so far. 1329 if (V.getValueType() != MVT::i64 || 1330 V.getOperand(0).getValueType() != MVT::i32) 1331 break; 1332 1333 const SmallVector<ValueBit, 64> *LHSBits; 1334 const unsigned NumOperandBits = 32; 1335 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), 1336 NumOperandBits); 1337 1338 for (unsigned i = 0; i < NumOperandBits; ++i) 1339 Bits[i] = (*LHSBits)[i]; 1340 1341 for (unsigned i = NumOperandBits; i < NumBits; ++i) 1342 Bits[i] = ValueBit(ValueBit::ConstZero); 1343 1344 return std::make_pair(Interesting, &Bits); 1345 } 1346 case ISD::TRUNCATE: { 1347 EVT FromType = V.getOperand(0).getValueType(); 1348 EVT ToType = V.getValueType(); 1349 // We support only the case with truncate from i64 to i32. 1350 if (FromType != MVT::i64 || ToType != MVT::i32) 1351 break; 1352 const unsigned NumAllBits = FromType.getSizeInBits(); 1353 SmallVector<ValueBit, 64> *InBits; 1354 std::tie(Interesting, InBits) = getValueBits(V.getOperand(0), 1355 NumAllBits); 1356 const unsigned NumValidBits = ToType.getSizeInBits(); 1357 1358 // A 32-bit instruction cannot touch upper 32-bit part of 64-bit value. 1359 // So, we cannot include this truncate. 1360 bool UseUpper32bit = false; 1361 for (unsigned i = 0; i < NumValidBits; ++i) 1362 if ((*InBits)[i].hasValue() && (*InBits)[i].getValueBitIndex() >= 32) { 1363 UseUpper32bit = true; 1364 break; 1365 } 1366 if (UseUpper32bit) 1367 break; 1368 1369 for (unsigned i = 0; i < NumValidBits; ++i) 1370 Bits[i] = (*InBits)[i]; 1371 1372 return std::make_pair(Interesting, &Bits); 1373 } 1374 case ISD::AssertZext: { 1375 // For AssertZext, we look through the operand and 1376 // mark the bits known to be zero. 1377 const SmallVector<ValueBit, 64> *LHSBits; 1378 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), 1379 NumBits); 1380 1381 EVT FromType = cast<VTSDNode>(V.getOperand(1))->getVT(); 1382 const unsigned NumValidBits = FromType.getSizeInBits(); 1383 for (unsigned i = 0; i < NumValidBits; ++i) 1384 Bits[i] = (*LHSBits)[i]; 1385 1386 // These bits are known to be zero but the AssertZext may be from a value 1387 // that already has some constant zero bits (i.e. from a masking and). 1388 for (unsigned i = NumValidBits; i < NumBits; ++i) 1389 Bits[i] = (*LHSBits)[i].hasValue() 1390 ? ValueBit((*LHSBits)[i].getValue(), 1391 (*LHSBits)[i].getValueBitIndex(), 1392 ValueBit::VariableKnownToBeZero) 1393 : ValueBit(ValueBit::ConstZero); 1394 1395 return std::make_pair(Interesting, &Bits); 1396 } 1397 case ISD::LOAD: 1398 LoadSDNode *LD = cast<LoadSDNode>(V); 1399 if (ISD::isZEXTLoad(V.getNode()) && V.getResNo() == 0) { 1400 EVT VT = LD->getMemoryVT(); 1401 const unsigned NumValidBits = VT.getSizeInBits(); 1402 1403 for (unsigned i = 0; i < NumValidBits; ++i) 1404 Bits[i] = ValueBit(V, i); 1405 1406 // These bits are known to be zero. 1407 for (unsigned i = NumValidBits; i < NumBits; ++i) 1408 Bits[i] = ValueBit(V, i, ValueBit::VariableKnownToBeZero); 1409 1410 // Zero-extending load itself cannot be optimized. So, it is not 1411 // interesting by itself though it gives useful information. 1412 return std::make_pair(Interesting = false, &Bits); 1413 } 1414 break; 1415 } 1416 1417 for (unsigned i = 0; i < NumBits; ++i) 1418 Bits[i] = ValueBit(V, i); 1419 1420 return std::make_pair(Interesting = false, &Bits); 1421 } 1422 1423 // For each value (except the constant ones), compute the left-rotate amount 1424 // to get it from its original to final position. 1425 void computeRotationAmounts() { 1426 NeedMask = false; 1427 RLAmt.resize(Bits.size()); 1428 for (unsigned i = 0; i < Bits.size(); ++i) 1429 if (Bits[i].hasValue()) { 1430 unsigned VBI = Bits[i].getValueBitIndex(); 1431 if (i >= VBI) 1432 RLAmt[i] = i - VBI; 1433 else 1434 RLAmt[i] = Bits.size() - (VBI - i); 1435 } else if (Bits[i].isZero()) { 1436 NeedMask = true; 1437 RLAmt[i] = UINT32_MAX; 1438 } else { 1439 llvm_unreachable("Unknown value bit type"); 1440 } 1441 } 1442 1443 // Collect groups of consecutive bits with the same underlying value and 1444 // rotation factor. If we're doing late masking, we ignore zeros, otherwise 1445 // they break up groups. 1446 void collectBitGroups(bool LateMask) { 1447 BitGroups.clear(); 1448 1449 unsigned LastRLAmt = RLAmt[0]; 1450 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue(); 1451 unsigned LastGroupStartIdx = 0; 1452 bool IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue(); 1453 for (unsigned i = 1; i < Bits.size(); ++i) { 1454 unsigned ThisRLAmt = RLAmt[i]; 1455 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue(); 1456 if (LateMask && !ThisValue) { 1457 ThisValue = LastValue; 1458 ThisRLAmt = LastRLAmt; 1459 // If we're doing late masking, then the first bit group always starts 1460 // at zero (even if the first bits were zero). 1461 if (BitGroups.empty()) 1462 LastGroupStartIdx = 0; 1463 } 1464 1465 // If this bit is known to be zero and the current group is a bit group 1466 // of zeros, we do not need to terminate the current bit group even the 1467 // Value or RLAmt does not match here. Instead, we terminate this group 1468 // when the first non-zero bit appears later. 1469 if (IsGroupOfZeros && Bits[i].isZero()) 1470 continue; 1471 1472 // If this bit has the same underlying value and the same rotate factor as 1473 // the last one, then they're part of the same group. 1474 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue) 1475 // We cannot continue the current group if this bits is not known to 1476 // be zero in a bit group of zeros. 1477 if (!(IsGroupOfZeros && ThisValue && !Bits[i].isZero())) 1478 continue; 1479 1480 if (LastValue.getNode()) 1481 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx, 1482 i-1)); 1483 LastRLAmt = ThisRLAmt; 1484 LastValue = ThisValue; 1485 LastGroupStartIdx = i; 1486 IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue(); 1487 } 1488 if (LastValue.getNode()) 1489 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx, 1490 Bits.size()-1)); 1491 1492 if (BitGroups.empty()) 1493 return; 1494 1495 // We might be able to combine the first and last groups. 1496 if (BitGroups.size() > 1) { 1497 // If the first and last groups are the same, then remove the first group 1498 // in favor of the last group, making the ending index of the last group 1499 // equal to the ending index of the to-be-removed first group. 1500 if (BitGroups[0].StartIdx == 0 && 1501 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 && 1502 BitGroups[0].V == BitGroups[BitGroups.size()-1].V && 1503 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) { 1504 LLVM_DEBUG(dbgs() << "\tcombining final bit group with initial one\n"); 1505 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx; 1506 BitGroups.erase(BitGroups.begin()); 1507 } 1508 } 1509 } 1510 1511 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups 1512 // associated with each. If the number of groups are same, we prefer a group 1513 // which does not require rotate, i.e. RLAmt is 0, to avoid the first rotate 1514 // instruction. If there is a degeneracy, pick the one that occurs 1515 // first (in the final value). 1516 void collectValueRotInfo() { 1517 ValueRots.clear(); 1518 1519 for (auto &BG : BitGroups) { 1520 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0); 1521 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)]; 1522 VRI.V = BG.V; 1523 VRI.RLAmt = BG.RLAmt; 1524 VRI.Repl32 = BG.Repl32; 1525 VRI.NumGroups += 1; 1526 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx); 1527 } 1528 1529 // Now that we've collected the various ValueRotInfo instances, we need to 1530 // sort them. 1531 ValueRotsVec.clear(); 1532 for (auto &I : ValueRots) { 1533 ValueRotsVec.push_back(I.second); 1534 } 1535 llvm::sort(ValueRotsVec); 1536 } 1537 1538 // In 64-bit mode, rlwinm and friends have a rotation operator that 1539 // replicates the low-order 32 bits into the high-order 32-bits. The mask 1540 // indices of these instructions can only be in the lower 32 bits, so they 1541 // can only represent some 64-bit bit groups. However, when they can be used, 1542 // the 32-bit replication can be used to represent, as a single bit group, 1543 // otherwise separate bit groups. We'll convert to replicated-32-bit bit 1544 // groups when possible. Returns true if any of the bit groups were 1545 // converted. 1546 void assignRepl32BitGroups() { 1547 // If we have bits like this: 1548 // 1549 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 1550 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24 1551 // Groups: | RLAmt = 8 | RLAmt = 40 | 1552 // 1553 // But, making use of a 32-bit operation that replicates the low-order 32 1554 // bits into the high-order 32 bits, this can be one bit group with a RLAmt 1555 // of 8. 1556 1557 auto IsAllLow32 = [this](BitGroup & BG) { 1558 if (BG.StartIdx <= BG.EndIdx) { 1559 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) { 1560 if (!Bits[i].hasValue()) 1561 continue; 1562 if (Bits[i].getValueBitIndex() >= 32) 1563 return false; 1564 } 1565 } else { 1566 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) { 1567 if (!Bits[i].hasValue()) 1568 continue; 1569 if (Bits[i].getValueBitIndex() >= 32) 1570 return false; 1571 } 1572 for (unsigned i = 0; i <= BG.EndIdx; ++i) { 1573 if (!Bits[i].hasValue()) 1574 continue; 1575 if (Bits[i].getValueBitIndex() >= 32) 1576 return false; 1577 } 1578 } 1579 1580 return true; 1581 }; 1582 1583 for (auto &BG : BitGroups) { 1584 // If this bit group has RLAmt of 0 and will not be merged with 1585 // another bit group, we don't benefit from Repl32. We don't mark 1586 // such group to give more freedom for later instruction selection. 1587 if (BG.RLAmt == 0) { 1588 auto PotentiallyMerged = [this](BitGroup & BG) { 1589 for (auto &BG2 : BitGroups) 1590 if (&BG != &BG2 && BG.V == BG2.V && 1591 (BG2.RLAmt == 0 || BG2.RLAmt == 32)) 1592 return true; 1593 return false; 1594 }; 1595 if (!PotentiallyMerged(BG)) 1596 continue; 1597 } 1598 if (BG.StartIdx < 32 && BG.EndIdx < 32) { 1599 if (IsAllLow32(BG)) { 1600 if (BG.RLAmt >= 32) { 1601 BG.RLAmt -= 32; 1602 BG.Repl32CR = true; 1603 } 1604 1605 BG.Repl32 = true; 1606 1607 LLVM_DEBUG(dbgs() << "\t32-bit replicated bit group for " 1608 << BG.V.getNode() << " RLAmt = " << BG.RLAmt << " [" 1609 << BG.StartIdx << ", " << BG.EndIdx << "]\n"); 1610 } 1611 } 1612 } 1613 1614 // Now walk through the bit groups, consolidating where possible. 1615 for (auto I = BitGroups.begin(); I != BitGroups.end();) { 1616 // We might want to remove this bit group by merging it with the previous 1617 // group (which might be the ending group). 1618 auto IP = (I == BitGroups.begin()) ? 1619 std::prev(BitGroups.end()) : std::prev(I); 1620 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt && 1621 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) { 1622 1623 LLVM_DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " 1624 << I->V.getNode() << " RLAmt = " << I->RLAmt << " [" 1625 << I->StartIdx << ", " << I->EndIdx 1626 << "] with group with range [" << IP->StartIdx << ", " 1627 << IP->EndIdx << "]\n"); 1628 1629 IP->EndIdx = I->EndIdx; 1630 IP->Repl32CR = IP->Repl32CR || I->Repl32CR; 1631 IP->Repl32Coalesced = true; 1632 I = BitGroups.erase(I); 1633 continue; 1634 } else { 1635 // There is a special case worth handling: If there is a single group 1636 // covering the entire upper 32 bits, and it can be merged with both 1637 // the next and previous groups (which might be the same group), then 1638 // do so. If it is the same group (so there will be only one group in 1639 // total), then we need to reverse the order of the range so that it 1640 // covers the entire 64 bits. 1641 if (I->StartIdx == 32 && I->EndIdx == 63) { 1642 assert(std::next(I) == BitGroups.end() && 1643 "bit group ends at index 63 but there is another?"); 1644 auto IN = BitGroups.begin(); 1645 1646 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V && 1647 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt && 1648 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP && 1649 IsAllLow32(*I)) { 1650 1651 LLVM_DEBUG(dbgs() << "\tcombining bit group for " << I->V.getNode() 1652 << " RLAmt = " << I->RLAmt << " [" << I->StartIdx 1653 << ", " << I->EndIdx 1654 << "] with 32-bit replicated groups with ranges [" 1655 << IP->StartIdx << ", " << IP->EndIdx << "] and [" 1656 << IN->StartIdx << ", " << IN->EndIdx << "]\n"); 1657 1658 if (IP == IN) { 1659 // There is only one other group; change it to cover the whole 1660 // range (backward, so that it can still be Repl32 but cover the 1661 // whole 64-bit range). 1662 IP->StartIdx = 31; 1663 IP->EndIdx = 30; 1664 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32; 1665 IP->Repl32Coalesced = true; 1666 I = BitGroups.erase(I); 1667 } else { 1668 // There are two separate groups, one before this group and one 1669 // after us (at the beginning). We're going to remove this group, 1670 // but also the group at the very beginning. 1671 IP->EndIdx = IN->EndIdx; 1672 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32; 1673 IP->Repl32Coalesced = true; 1674 I = BitGroups.erase(I); 1675 BitGroups.erase(BitGroups.begin()); 1676 } 1677 1678 // This must be the last group in the vector (and we might have 1679 // just invalidated the iterator above), so break here. 1680 break; 1681 } 1682 } 1683 } 1684 1685 ++I; 1686 } 1687 } 1688 1689 SDValue getI32Imm(unsigned Imm, const SDLoc &dl) { 1690 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 1691 } 1692 1693 uint64_t getZerosMask() { 1694 uint64_t Mask = 0; 1695 for (unsigned i = 0; i < Bits.size(); ++i) { 1696 if (Bits[i].hasValue()) 1697 continue; 1698 Mask |= (UINT64_C(1) << i); 1699 } 1700 1701 return ~Mask; 1702 } 1703 1704 // This method extends an input value to 64 bit if input is 32-bit integer. 1705 // While selecting instructions in BitPermutationSelector in 64-bit mode, 1706 // an input value can be a 32-bit integer if a ZERO_EXTEND node is included. 1707 // In such case, we extend it to 64 bit to be consistent with other values. 1708 SDValue ExtendToInt64(SDValue V, const SDLoc &dl) { 1709 if (V.getValueSizeInBits() == 64) 1710 return V; 1711 1712 assert(V.getValueSizeInBits() == 32); 1713 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32); 1714 SDValue ImDef = SDValue(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, 1715 MVT::i64), 0); 1716 SDValue ExtVal = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, 1717 MVT::i64, ImDef, V, 1718 SubRegIdx), 0); 1719 return ExtVal; 1720 } 1721 1722 SDValue TruncateToInt32(SDValue V, const SDLoc &dl) { 1723 if (V.getValueSizeInBits() == 32) 1724 return V; 1725 1726 assert(V.getValueSizeInBits() == 64); 1727 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32); 1728 SDValue SubVal = SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, 1729 MVT::i32, V, SubRegIdx), 0); 1730 return SubVal; 1731 } 1732 1733 // Depending on the number of groups for a particular value, it might be 1734 // better to rotate, mask explicitly (using andi/andis), and then or the 1735 // result. Select this part of the result first. 1736 void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) { 1737 if (BPermRewriterNoMasking) 1738 return; 1739 1740 for (ValueRotInfo &VRI : ValueRotsVec) { 1741 unsigned Mask = 0; 1742 for (unsigned i = 0; i < Bits.size(); ++i) { 1743 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V) 1744 continue; 1745 if (RLAmt[i] != VRI.RLAmt) 1746 continue; 1747 Mask |= (1u << i); 1748 } 1749 1750 // Compute the masks for andi/andis that would be necessary. 1751 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16; 1752 assert((ANDIMask != 0 || ANDISMask != 0) && 1753 "No set bits in mask for value bit groups"); 1754 bool NeedsRotate = VRI.RLAmt != 0; 1755 1756 // We're trying to minimize the number of instructions. If we have one 1757 // group, using one of andi/andis can break even. If we have three 1758 // groups, we can use both andi and andis and break even (to use both 1759 // andi and andis we also need to or the results together). We need four 1760 // groups if we also need to rotate. To use andi/andis we need to do more 1761 // than break even because rotate-and-mask instructions tend to be easier 1762 // to schedule. 1763 1764 // FIXME: We've biased here against using andi/andis, which is right for 1765 // POWER cores, but not optimal everywhere. For example, on the A2, 1766 // andi/andis have single-cycle latency whereas the rotate-and-mask 1767 // instructions take two cycles, and it would be better to bias toward 1768 // andi/andis in break-even cases. 1769 1770 unsigned NumAndInsts = (unsigned) NeedsRotate + 1771 (unsigned) (ANDIMask != 0) + 1772 (unsigned) (ANDISMask != 0) + 1773 (unsigned) (ANDIMask != 0 && ANDISMask != 0) + 1774 (unsigned) (bool) Res; 1775 1776 LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() 1777 << " RL: " << VRI.RLAmt << ":" 1778 << "\n\t\t\tisel using masking: " << NumAndInsts 1779 << " using rotates: " << VRI.NumGroups << "\n"); 1780 1781 if (NumAndInsts >= VRI.NumGroups) 1782 continue; 1783 1784 LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n"); 1785 1786 if (InstCnt) *InstCnt += NumAndInsts; 1787 1788 SDValue VRot; 1789 if (VRI.RLAmt) { 1790 SDValue Ops[] = 1791 { TruncateToInt32(VRI.V, dl), getI32Imm(VRI.RLAmt, dl), 1792 getI32Imm(0, dl), getI32Imm(31, dl) }; 1793 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, 1794 Ops), 0); 1795 } else { 1796 VRot = TruncateToInt32(VRI.V, dl); 1797 } 1798 1799 SDValue ANDIVal, ANDISVal; 1800 if (ANDIMask != 0) 1801 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32, 1802 VRot, getI32Imm(ANDIMask, dl)), 1803 0); 1804 if (ANDISMask != 0) 1805 ANDISVal = 1806 SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, VRot, 1807 getI32Imm(ANDISMask, dl)), 1808 0); 1809 1810 SDValue TotalVal; 1811 if (!ANDIVal) 1812 TotalVal = ANDISVal; 1813 else if (!ANDISVal) 1814 TotalVal = ANDIVal; 1815 else 1816 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1817 ANDIVal, ANDISVal), 0); 1818 1819 if (!Res) 1820 Res = TotalVal; 1821 else 1822 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1823 Res, TotalVal), 0); 1824 1825 // Now, remove all groups with this underlying value and rotation 1826 // factor. 1827 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 1828 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt; 1829 }); 1830 } 1831 } 1832 1833 // Instruction selection for the 32-bit case. 1834 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) { 1835 SDLoc dl(N); 1836 SDValue Res; 1837 1838 if (InstCnt) *InstCnt = 0; 1839 1840 // Take care of cases that should use andi/andis first. 1841 SelectAndParts32(dl, Res, InstCnt); 1842 1843 // If we've not yet selected a 'starting' instruction, and we have no zeros 1844 // to fill in, select the (Value, RLAmt) with the highest priority (largest 1845 // number of groups), and start with this rotated value. 1846 if ((!NeedMask || LateMask) && !Res) { 1847 ValueRotInfo &VRI = ValueRotsVec[0]; 1848 if (VRI.RLAmt) { 1849 if (InstCnt) *InstCnt += 1; 1850 SDValue Ops[] = 1851 { TruncateToInt32(VRI.V, dl), getI32Imm(VRI.RLAmt, dl), 1852 getI32Imm(0, dl), getI32Imm(31, dl) }; 1853 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 1854 0); 1855 } else { 1856 Res = TruncateToInt32(VRI.V, dl); 1857 } 1858 1859 // Now, remove all groups with this underlying value and rotation factor. 1860 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 1861 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt; 1862 }); 1863 } 1864 1865 if (InstCnt) *InstCnt += BitGroups.size(); 1866 1867 // Insert the other groups (one at a time). 1868 for (auto &BG : BitGroups) { 1869 if (!Res) { 1870 SDValue Ops[] = 1871 { TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl), 1872 getI32Imm(Bits.size() - BG.EndIdx - 1, dl), 1873 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) }; 1874 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 1875 } else { 1876 SDValue Ops[] = 1877 { Res, TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl), 1878 getI32Imm(Bits.size() - BG.EndIdx - 1, dl), 1879 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) }; 1880 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0); 1881 } 1882 } 1883 1884 if (LateMask) { 1885 unsigned Mask = (unsigned) getZerosMask(); 1886 1887 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16; 1888 assert((ANDIMask != 0 || ANDISMask != 0) && 1889 "No set bits in zeros mask?"); 1890 1891 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) + 1892 (unsigned) (ANDISMask != 0) + 1893 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 1894 1895 SDValue ANDIVal, ANDISVal; 1896 if (ANDIMask != 0) 1897 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32, 1898 Res, getI32Imm(ANDIMask, dl)), 1899 0); 1900 if (ANDISMask != 0) 1901 ANDISVal = 1902 SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, Res, 1903 getI32Imm(ANDISMask, dl)), 1904 0); 1905 1906 if (!ANDIVal) 1907 Res = ANDISVal; 1908 else if (!ANDISVal) 1909 Res = ANDIVal; 1910 else 1911 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1912 ANDIVal, ANDISVal), 0); 1913 } 1914 1915 return Res.getNode(); 1916 } 1917 1918 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32, 1919 unsigned MaskStart, unsigned MaskEnd, 1920 bool IsIns) { 1921 // In the notation used by the instructions, 'start' and 'end' are reversed 1922 // because bits are counted from high to low order. 1923 unsigned InstMaskStart = 64 - MaskEnd - 1, 1924 InstMaskEnd = 64 - MaskStart - 1; 1925 1926 if (Repl32) 1927 return 1; 1928 1929 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) || 1930 InstMaskEnd == 63 - RLAmt) 1931 return 1; 1932 1933 return 2; 1934 } 1935 1936 // For 64-bit values, not all combinations of rotates and masks are 1937 // available. Produce one if it is available. 1938 SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt, 1939 bool Repl32, unsigned MaskStart, unsigned MaskEnd, 1940 unsigned *InstCnt = nullptr) { 1941 // In the notation used by the instructions, 'start' and 'end' are reversed 1942 // because bits are counted from high to low order. 1943 unsigned InstMaskStart = 64 - MaskEnd - 1, 1944 InstMaskEnd = 64 - MaskStart - 1; 1945 1946 if (InstCnt) *InstCnt += 1; 1947 1948 if (Repl32) { 1949 // This rotation amount assumes that the lower 32 bits of the quantity 1950 // are replicated in the high 32 bits by the rotation operator (which is 1951 // done by rlwinm and friends). 1952 assert(InstMaskStart >= 32 && "Mask cannot start out of range"); 1953 assert(InstMaskEnd >= 32 && "Mask cannot end out of range"); 1954 SDValue Ops[] = 1955 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 1956 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) }; 1957 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64, 1958 Ops), 0); 1959 } 1960 1961 if (InstMaskEnd == 63) { 1962 SDValue Ops[] = 1963 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 1964 getI32Imm(InstMaskStart, dl) }; 1965 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0); 1966 } 1967 1968 if (InstMaskStart == 0) { 1969 SDValue Ops[] = 1970 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 1971 getI32Imm(InstMaskEnd, dl) }; 1972 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0); 1973 } 1974 1975 if (InstMaskEnd == 63 - RLAmt) { 1976 SDValue Ops[] = 1977 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 1978 getI32Imm(InstMaskStart, dl) }; 1979 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0); 1980 } 1981 1982 // We cannot do this with a single instruction, so we'll use two. The 1983 // problem is that we're not free to choose both a rotation amount and mask 1984 // start and end independently. We can choose an arbitrary mask start and 1985 // end, but then the rotation amount is fixed. Rotation, however, can be 1986 // inverted, and so by applying an "inverse" rotation first, we can get the 1987 // desired result. 1988 if (InstCnt) *InstCnt += 1; 1989 1990 // The rotation mask for the second instruction must be MaskStart. 1991 unsigned RLAmt2 = MaskStart; 1992 // The first instruction must rotate V so that the overall rotation amount 1993 // is RLAmt. 1994 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64; 1995 if (RLAmt1) 1996 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63); 1997 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd); 1998 } 1999 2000 // For 64-bit values, not all combinations of rotates and masks are 2001 // available. Produce a rotate-mask-and-insert if one is available. 2002 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl, 2003 unsigned RLAmt, bool Repl32, unsigned MaskStart, 2004 unsigned MaskEnd, unsigned *InstCnt = nullptr) { 2005 // In the notation used by the instructions, 'start' and 'end' are reversed 2006 // because bits are counted from high to low order. 2007 unsigned InstMaskStart = 64 - MaskEnd - 1, 2008 InstMaskEnd = 64 - MaskStart - 1; 2009 2010 if (InstCnt) *InstCnt += 1; 2011 2012 if (Repl32) { 2013 // This rotation amount assumes that the lower 32 bits of the quantity 2014 // are replicated in the high 32 bits by the rotation operator (which is 2015 // done by rlwinm and friends). 2016 assert(InstMaskStart >= 32 && "Mask cannot start out of range"); 2017 assert(InstMaskEnd >= 32 && "Mask cannot end out of range"); 2018 SDValue Ops[] = 2019 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 2020 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) }; 2021 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64, 2022 Ops), 0); 2023 } 2024 2025 if (InstMaskEnd == 63 - RLAmt) { 2026 SDValue Ops[] = 2027 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 2028 getI32Imm(InstMaskStart, dl) }; 2029 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0); 2030 } 2031 2032 // We cannot do this with a single instruction, so we'll use two. The 2033 // problem is that we're not free to choose both a rotation amount and mask 2034 // start and end independently. We can choose an arbitrary mask start and 2035 // end, but then the rotation amount is fixed. Rotation, however, can be 2036 // inverted, and so by applying an "inverse" rotation first, we can get the 2037 // desired result. 2038 if (InstCnt) *InstCnt += 1; 2039 2040 // The rotation mask for the second instruction must be MaskStart. 2041 unsigned RLAmt2 = MaskStart; 2042 // The first instruction must rotate V so that the overall rotation amount 2043 // is RLAmt. 2044 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64; 2045 if (RLAmt1) 2046 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63); 2047 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd); 2048 } 2049 2050 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) { 2051 if (BPermRewriterNoMasking) 2052 return; 2053 2054 // The idea here is the same as in the 32-bit version, but with additional 2055 // complications from the fact that Repl32 might be true. Because we 2056 // aggressively convert bit groups to Repl32 form (which, for small 2057 // rotation factors, involves no other change), and then coalesce, it might 2058 // be the case that a single 64-bit masking operation could handle both 2059 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32 2060 // form allowed coalescing, then we must use a 32-bit rotaton in order to 2061 // completely capture the new combined bit group. 2062 2063 for (ValueRotInfo &VRI : ValueRotsVec) { 2064 uint64_t Mask = 0; 2065 2066 // We need to add to the mask all bits from the associated bit groups. 2067 // If Repl32 is false, we need to add bits from bit groups that have 2068 // Repl32 true, but are trivially convertable to Repl32 false. Such a 2069 // group is trivially convertable if it overlaps only with the lower 32 2070 // bits, and the group has not been coalesced. 2071 auto MatchingBG = [VRI](const BitGroup &BG) { 2072 if (VRI.V != BG.V) 2073 return false; 2074 2075 unsigned EffRLAmt = BG.RLAmt; 2076 if (!VRI.Repl32 && BG.Repl32) { 2077 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx && 2078 !BG.Repl32Coalesced) { 2079 if (BG.Repl32CR) 2080 EffRLAmt += 32; 2081 } else { 2082 return false; 2083 } 2084 } else if (VRI.Repl32 != BG.Repl32) { 2085 return false; 2086 } 2087 2088 return VRI.RLAmt == EffRLAmt; 2089 }; 2090 2091 for (auto &BG : BitGroups) { 2092 if (!MatchingBG(BG)) 2093 continue; 2094 2095 if (BG.StartIdx <= BG.EndIdx) { 2096 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) 2097 Mask |= (UINT64_C(1) << i); 2098 } else { 2099 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) 2100 Mask |= (UINT64_C(1) << i); 2101 for (unsigned i = 0; i <= BG.EndIdx; ++i) 2102 Mask |= (UINT64_C(1) << i); 2103 } 2104 } 2105 2106 // We can use the 32-bit andi/andis technique if the mask does not 2107 // require any higher-order bits. This can save an instruction compared 2108 // to always using the general 64-bit technique. 2109 bool Use32BitInsts = isUInt<32>(Mask); 2110 // Compute the masks for andi/andis that would be necessary. 2111 unsigned ANDIMask = (Mask & UINT16_MAX), 2112 ANDISMask = (Mask >> 16) & UINT16_MAX; 2113 2114 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)); 2115 2116 unsigned NumAndInsts = (unsigned) NeedsRotate + 2117 (unsigned) (bool) Res; 2118 unsigned NumOfSelectInsts = 0; 2119 selectI64Imm(CurDAG, dl, Mask, &NumOfSelectInsts); 2120 assert(NumOfSelectInsts > 0 && "Failed to select an i64 constant."); 2121 if (Use32BitInsts) 2122 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) + 2123 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 2124 else 2125 NumAndInsts += NumOfSelectInsts + /* and */ 1; 2126 2127 unsigned NumRLInsts = 0; 2128 bool FirstBG = true; 2129 bool MoreBG = false; 2130 for (auto &BG : BitGroups) { 2131 if (!MatchingBG(BG)) { 2132 MoreBG = true; 2133 continue; 2134 } 2135 NumRLInsts += 2136 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx, 2137 !FirstBG); 2138 FirstBG = false; 2139 } 2140 2141 LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() 2142 << " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") 2143 << "\n\t\t\tisel using masking: " << NumAndInsts 2144 << " using rotates: " << NumRLInsts << "\n"); 2145 2146 // When we'd use andi/andis, we bias toward using the rotates (andi only 2147 // has a record form, and is cracked on POWER cores). However, when using 2148 // general 64-bit constant formation, bias toward the constant form, 2149 // because that exposes more opportunities for CSE. 2150 if (NumAndInsts > NumRLInsts) 2151 continue; 2152 // When merging multiple bit groups, instruction or is used. 2153 // But when rotate is used, rldimi can inert the rotated value into any 2154 // register, so instruction or can be avoided. 2155 if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts) 2156 continue; 2157 2158 LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n"); 2159 2160 if (InstCnt) *InstCnt += NumAndInsts; 2161 2162 SDValue VRot; 2163 // We actually need to generate a rotation if we have a non-zero rotation 2164 // factor or, in the Repl32 case, if we care about any of the 2165 // higher-order replicated bits. In the latter case, we generate a mask 2166 // backward so that it actually includes the entire 64 bits. 2167 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask))) 2168 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32, 2169 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63); 2170 else 2171 VRot = VRI.V; 2172 2173 SDValue TotalVal; 2174 if (Use32BitInsts) { 2175 assert((ANDIMask != 0 || ANDISMask != 0) && 2176 "No set bits in mask when using 32-bit ands for 64-bit value"); 2177 2178 SDValue ANDIVal, ANDISVal; 2179 if (ANDIMask != 0) 2180 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI8_rec, dl, MVT::i64, 2181 ExtendToInt64(VRot, dl), 2182 getI32Imm(ANDIMask, dl)), 2183 0); 2184 if (ANDISMask != 0) 2185 ANDISVal = 2186 SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64, 2187 ExtendToInt64(VRot, dl), 2188 getI32Imm(ANDISMask, dl)), 2189 0); 2190 2191 if (!ANDIVal) 2192 TotalVal = ANDISVal; 2193 else if (!ANDISVal) 2194 TotalVal = ANDIVal; 2195 else 2196 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 2197 ExtendToInt64(ANDIVal, dl), ANDISVal), 0); 2198 } else { 2199 TotalVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0); 2200 TotalVal = 2201 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64, 2202 ExtendToInt64(VRot, dl), TotalVal), 2203 0); 2204 } 2205 2206 if (!Res) 2207 Res = TotalVal; 2208 else 2209 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 2210 ExtendToInt64(Res, dl), TotalVal), 2211 0); 2212 2213 // Now, remove all groups with this underlying value and rotation 2214 // factor. 2215 eraseMatchingBitGroups(MatchingBG); 2216 } 2217 } 2218 2219 // Instruction selection for the 64-bit case. 2220 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) { 2221 SDLoc dl(N); 2222 SDValue Res; 2223 2224 if (InstCnt) *InstCnt = 0; 2225 2226 // Take care of cases that should use andi/andis first. 2227 SelectAndParts64(dl, Res, InstCnt); 2228 2229 // If we've not yet selected a 'starting' instruction, and we have no zeros 2230 // to fill in, select the (Value, RLAmt) with the highest priority (largest 2231 // number of groups), and start with this rotated value. 2232 if ((!NeedMask || LateMask) && !Res) { 2233 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32 2234 // groups will come first, and so the VRI representing the largest number 2235 // of groups might not be first (it might be the first Repl32 groups). 2236 unsigned MaxGroupsIdx = 0; 2237 if (!ValueRotsVec[0].Repl32) { 2238 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i) 2239 if (ValueRotsVec[i].Repl32) { 2240 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups) 2241 MaxGroupsIdx = i; 2242 break; 2243 } 2244 } 2245 2246 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx]; 2247 bool NeedsRotate = false; 2248 if (VRI.RLAmt) { 2249 NeedsRotate = true; 2250 } else if (VRI.Repl32) { 2251 for (auto &BG : BitGroups) { 2252 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt || 2253 BG.Repl32 != VRI.Repl32) 2254 continue; 2255 2256 // We don't need a rotate if the bit group is confined to the lower 2257 // 32 bits. 2258 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx) 2259 continue; 2260 2261 NeedsRotate = true; 2262 break; 2263 } 2264 } 2265 2266 if (NeedsRotate) 2267 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32, 2268 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63, 2269 InstCnt); 2270 else 2271 Res = VRI.V; 2272 2273 // Now, remove all groups with this underlying value and rotation factor. 2274 if (Res) 2275 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 2276 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt && 2277 BG.Repl32 == VRI.Repl32; 2278 }); 2279 } 2280 2281 // Because 64-bit rotates are more flexible than inserts, we might have a 2282 // preference regarding which one we do first (to save one instruction). 2283 if (!Res) 2284 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) { 2285 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx, 2286 false) < 2287 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx, 2288 true)) { 2289 if (I != BitGroups.begin()) { 2290 BitGroup BG = *I; 2291 BitGroups.erase(I); 2292 BitGroups.insert(BitGroups.begin(), BG); 2293 } 2294 2295 break; 2296 } 2297 } 2298 2299 // Insert the other groups (one at a time). 2300 for (auto &BG : BitGroups) { 2301 if (!Res) 2302 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx, 2303 BG.EndIdx, InstCnt); 2304 else 2305 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32, 2306 BG.StartIdx, BG.EndIdx, InstCnt); 2307 } 2308 2309 if (LateMask) { 2310 uint64_t Mask = getZerosMask(); 2311 2312 // We can use the 32-bit andi/andis technique if the mask does not 2313 // require any higher-order bits. This can save an instruction compared 2314 // to always using the general 64-bit technique. 2315 bool Use32BitInsts = isUInt<32>(Mask); 2316 // Compute the masks for andi/andis that would be necessary. 2317 unsigned ANDIMask = (Mask & UINT16_MAX), 2318 ANDISMask = (Mask >> 16) & UINT16_MAX; 2319 2320 if (Use32BitInsts) { 2321 assert((ANDIMask != 0 || ANDISMask != 0) && 2322 "No set bits in mask when using 32-bit ands for 64-bit value"); 2323 2324 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) + 2325 (unsigned) (ANDISMask != 0) + 2326 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 2327 2328 SDValue ANDIVal, ANDISVal; 2329 if (ANDIMask != 0) 2330 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI8_rec, dl, MVT::i64, 2331 ExtendToInt64(Res, dl), 2332 getI32Imm(ANDIMask, dl)), 2333 0); 2334 if (ANDISMask != 0) 2335 ANDISVal = 2336 SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64, 2337 ExtendToInt64(Res, dl), 2338 getI32Imm(ANDISMask, dl)), 2339 0); 2340 2341 if (!ANDIVal) 2342 Res = ANDISVal; 2343 else if (!ANDISVal) 2344 Res = ANDIVal; 2345 else 2346 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 2347 ExtendToInt64(ANDIVal, dl), ANDISVal), 0); 2348 } else { 2349 unsigned NumOfSelectInsts = 0; 2350 SDValue MaskVal = 2351 SDValue(selectI64Imm(CurDAG, dl, Mask, &NumOfSelectInsts), 0); 2352 Res = SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64, 2353 ExtendToInt64(Res, dl), MaskVal), 2354 0); 2355 if (InstCnt) 2356 *InstCnt += NumOfSelectInsts + /* and */ 1; 2357 } 2358 } 2359 2360 return Res.getNode(); 2361 } 2362 2363 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) { 2364 // Fill in BitGroups. 2365 collectBitGroups(LateMask); 2366 if (BitGroups.empty()) 2367 return nullptr; 2368 2369 // For 64-bit values, figure out when we can use 32-bit instructions. 2370 if (Bits.size() == 64) 2371 assignRepl32BitGroups(); 2372 2373 // Fill in ValueRotsVec. 2374 collectValueRotInfo(); 2375 2376 if (Bits.size() == 32) { 2377 return Select32(N, LateMask, InstCnt); 2378 } else { 2379 assert(Bits.size() == 64 && "Not 64 bits here?"); 2380 return Select64(N, LateMask, InstCnt); 2381 } 2382 2383 return nullptr; 2384 } 2385 2386 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) { 2387 erase_if(BitGroups, F); 2388 } 2389 2390 SmallVector<ValueBit, 64> Bits; 2391 2392 bool NeedMask = false; 2393 SmallVector<unsigned, 64> RLAmt; 2394 2395 SmallVector<BitGroup, 16> BitGroups; 2396 2397 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots; 2398 SmallVector<ValueRotInfo, 16> ValueRotsVec; 2399 2400 SelectionDAG *CurDAG = nullptr; 2401 2402 public: 2403 BitPermutationSelector(SelectionDAG *DAG) 2404 : CurDAG(DAG) {} 2405 2406 // Here we try to match complex bit permutations into a set of 2407 // rotate-and-shift/shift/and/or instructions, using a set of heuristics 2408 // known to produce optimal code for common cases (like i32 byte swapping). 2409 SDNode *Select(SDNode *N) { 2410 Memoizer.clear(); 2411 auto Result = 2412 getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits()); 2413 if (!Result.first) 2414 return nullptr; 2415 Bits = std::move(*Result.second); 2416 2417 LLVM_DEBUG(dbgs() << "Considering bit-permutation-based instruction" 2418 " selection for: "); 2419 LLVM_DEBUG(N->dump(CurDAG)); 2420 2421 // Fill it RLAmt and set NeedMask. 2422 computeRotationAmounts(); 2423 2424 if (!NeedMask) 2425 return Select(N, false); 2426 2427 // We currently have two techniques for handling results with zeros: early 2428 // masking (the default) and late masking. Late masking is sometimes more 2429 // efficient, but because the structure of the bit groups is different, it 2430 // is hard to tell without generating both and comparing the results. With 2431 // late masking, we ignore zeros in the resulting value when inserting each 2432 // set of bit groups, and then mask in the zeros at the end. With early 2433 // masking, we only insert the non-zero parts of the result at every step. 2434 2435 unsigned InstCnt = 0, InstCntLateMask = 0; 2436 LLVM_DEBUG(dbgs() << "\tEarly masking:\n"); 2437 SDNode *RN = Select(N, false, &InstCnt); 2438 LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n"); 2439 2440 LLVM_DEBUG(dbgs() << "\tLate masking:\n"); 2441 SDNode *RNLM = Select(N, true, &InstCntLateMask); 2442 LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask 2443 << " instructions\n"); 2444 2445 if (InstCnt <= InstCntLateMask) { 2446 LLVM_DEBUG(dbgs() << "\tUsing early-masking for isel\n"); 2447 return RN; 2448 } 2449 2450 LLVM_DEBUG(dbgs() << "\tUsing late-masking for isel\n"); 2451 return RNLM; 2452 } 2453 }; 2454 2455 class IntegerCompareEliminator { 2456 SelectionDAG *CurDAG; 2457 PPCDAGToDAGISel *S; 2458 // Conversion type for interpreting results of a 32-bit instruction as 2459 // a 64-bit value or vice versa. 2460 enum ExtOrTruncConversion { Ext, Trunc }; 2461 2462 // Modifiers to guide how an ISD::SETCC node's result is to be computed 2463 // in a GPR. 2464 // ZExtOrig - use the original condition code, zero-extend value 2465 // ZExtInvert - invert the condition code, zero-extend value 2466 // SExtOrig - use the original condition code, sign-extend value 2467 // SExtInvert - invert the condition code, sign-extend value 2468 enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert }; 2469 2470 // Comparisons against zero to emit GPR code sequences for. Each of these 2471 // sequences may need to be emitted for two or more equivalent patterns. 2472 // For example (a >= 0) == (a > -1). The direction of the comparison (</>) 2473 // matters as well as the extension type: sext (-1/0), zext (1/0). 2474 // GEZExt - (zext (LHS >= 0)) 2475 // GESExt - (sext (LHS >= 0)) 2476 // LEZExt - (zext (LHS <= 0)) 2477 // LESExt - (sext (LHS <= 0)) 2478 enum ZeroCompare { GEZExt, GESExt, LEZExt, LESExt }; 2479 2480 SDNode *tryEXTEND(SDNode *N); 2481 SDNode *tryLogicOpOfCompares(SDNode *N); 2482 SDValue computeLogicOpInGPR(SDValue LogicOp); 2483 SDValue signExtendInputIfNeeded(SDValue Input); 2484 SDValue zeroExtendInputIfNeeded(SDValue Input); 2485 SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv); 2486 SDValue getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl, 2487 ZeroCompare CmpTy); 2488 SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2489 int64_t RHSValue, SDLoc dl); 2490 SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2491 int64_t RHSValue, SDLoc dl); 2492 SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2493 int64_t RHSValue, SDLoc dl); 2494 SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2495 int64_t RHSValue, SDLoc dl); 2496 SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts); 2497 2498 public: 2499 IntegerCompareEliminator(SelectionDAG *DAG, 2500 PPCDAGToDAGISel *Sel) : CurDAG(DAG), S(Sel) { 2501 assert(CurDAG->getTargetLoweringInfo() 2502 .getPointerTy(CurDAG->getDataLayout()).getSizeInBits() == 64 && 2503 "Only expecting to use this on 64 bit targets."); 2504 } 2505 SDNode *Select(SDNode *N) { 2506 if (CmpInGPR == ICGPR_None) 2507 return nullptr; 2508 switch (N->getOpcode()) { 2509 default: break; 2510 case ISD::ZERO_EXTEND: 2511 if (CmpInGPR == ICGPR_Sext || CmpInGPR == ICGPR_SextI32 || 2512 CmpInGPR == ICGPR_SextI64) 2513 return nullptr; 2514 LLVM_FALLTHROUGH; 2515 case ISD::SIGN_EXTEND: 2516 if (CmpInGPR == ICGPR_Zext || CmpInGPR == ICGPR_ZextI32 || 2517 CmpInGPR == ICGPR_ZextI64) 2518 return nullptr; 2519 return tryEXTEND(N); 2520 case ISD::AND: 2521 case ISD::OR: 2522 case ISD::XOR: 2523 return tryLogicOpOfCompares(N); 2524 } 2525 return nullptr; 2526 } 2527 }; 2528 2529 static bool isLogicOp(unsigned Opc) { 2530 return Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR; 2531 } 2532 // The obvious case for wanting to keep the value in a GPR. Namely, the 2533 // result of the comparison is actually needed in a GPR. 2534 SDNode *IntegerCompareEliminator::tryEXTEND(SDNode *N) { 2535 assert((N->getOpcode() == ISD::ZERO_EXTEND || 2536 N->getOpcode() == ISD::SIGN_EXTEND) && 2537 "Expecting a zero/sign extend node!"); 2538 SDValue WideRes; 2539 // If we are zero-extending the result of a logical operation on i1 2540 // values, we can keep the values in GPRs. 2541 if (isLogicOp(N->getOperand(0).getOpcode()) && 2542 N->getOperand(0).getValueType() == MVT::i1 && 2543 N->getOpcode() == ISD::ZERO_EXTEND) 2544 WideRes = computeLogicOpInGPR(N->getOperand(0)); 2545 else if (N->getOperand(0).getOpcode() != ISD::SETCC) 2546 return nullptr; 2547 else 2548 WideRes = 2549 getSETCCInGPR(N->getOperand(0), 2550 N->getOpcode() == ISD::SIGN_EXTEND ? 2551 SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig); 2552 2553 if (!WideRes) 2554 return nullptr; 2555 2556 SDLoc dl(N); 2557 bool Input32Bit = WideRes.getValueType() == MVT::i32; 2558 bool Output32Bit = N->getValueType(0) == MVT::i32; 2559 2560 NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0; 2561 NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1; 2562 2563 SDValue ConvOp = WideRes; 2564 if (Input32Bit != Output32Bit) 2565 ConvOp = addExtOrTrunc(WideRes, Input32Bit ? ExtOrTruncConversion::Ext : 2566 ExtOrTruncConversion::Trunc); 2567 return ConvOp.getNode(); 2568 } 2569 2570 // Attempt to perform logical operations on the results of comparisons while 2571 // keeping the values in GPRs. Without doing so, these would end up being 2572 // lowered to CR-logical operations which suffer from significant latency and 2573 // low ILP. 2574 SDNode *IntegerCompareEliminator::tryLogicOpOfCompares(SDNode *N) { 2575 if (N->getValueType(0) != MVT::i1) 2576 return nullptr; 2577 assert(isLogicOp(N->getOpcode()) && 2578 "Expected a logic operation on setcc results."); 2579 SDValue LoweredLogical = computeLogicOpInGPR(SDValue(N, 0)); 2580 if (!LoweredLogical) 2581 return nullptr; 2582 2583 SDLoc dl(N); 2584 bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8; 2585 unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt; 2586 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32); 2587 SDValue LHS = LoweredLogical.getOperand(0); 2588 SDValue RHS = LoweredLogical.getOperand(1); 2589 SDValue WideOp; 2590 SDValue OpToConvToRecForm; 2591 2592 // Look through any 32-bit to 64-bit implicit extend nodes to find the 2593 // opcode that is input to the XORI. 2594 if (IsBitwiseNegate && 2595 LoweredLogical.getOperand(0).getMachineOpcode() == PPC::INSERT_SUBREG) 2596 OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(1); 2597 else if (IsBitwiseNegate) 2598 // If the input to the XORI isn't an extension, that's what we're after. 2599 OpToConvToRecForm = LoweredLogical.getOperand(0); 2600 else 2601 // If this is not an XORI, it is a reg-reg logical op and we can convert 2602 // it to record-form. 2603 OpToConvToRecForm = LoweredLogical; 2604 2605 // Get the record-form version of the node we're looking to use to get the 2606 // CR result from. 2607 uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode(); 2608 int NewOpc = PPCInstrInfo::getRecordFormOpcode(NonRecOpc); 2609 2610 // Convert the right node to record-form. This is either the logical we're 2611 // looking at or it is the input node to the negation (if we're looking at 2612 // a bitwise negation). 2613 if (NewOpc != -1 && IsBitwiseNegate) { 2614 // The input to the XORI has a record-form. Use it. 2615 assert(LoweredLogical.getConstantOperandVal(1) == 1 && 2616 "Expected a PPC::XORI8 only for bitwise negation."); 2617 // Emit the record-form instruction. 2618 std::vector<SDValue> Ops; 2619 for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++) 2620 Ops.push_back(OpToConvToRecForm.getOperand(i)); 2621 2622 WideOp = 2623 SDValue(CurDAG->getMachineNode(NewOpc, dl, 2624 OpToConvToRecForm.getValueType(), 2625 MVT::Glue, Ops), 0); 2626 } else { 2627 assert((NewOpc != -1 || !IsBitwiseNegate) && 2628 "No record form available for AND8/OR8/XOR8?"); 2629 WideOp = 2630 SDValue(CurDAG->getMachineNode(NewOpc == -1 ? PPC::ANDI8_rec : NewOpc, 2631 dl, MVT::i64, MVT::Glue, LHS, RHS), 2632 0); 2633 } 2634 2635 // Select this node to a single bit from CR0 set by the record-form node 2636 // just created. For bitwise negation, use the EQ bit which is the equivalent 2637 // of negating the result (i.e. it is a bit set when the result of the 2638 // operation is zero). 2639 SDValue SRIdxVal = 2640 CurDAG->getTargetConstant(SubRegToExtract, dl, MVT::i32); 2641 SDValue CRBit = 2642 SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, 2643 MVT::i1, CR0Reg, SRIdxVal, 2644 WideOp.getValue(1)), 0); 2645 return CRBit.getNode(); 2646 } 2647 2648 // Lower a logical operation on i1 values into a GPR sequence if possible. 2649 // The result can be kept in a GPR if requested. 2650 // Three types of inputs can be handled: 2651 // - SETCC 2652 // - TRUNCATE 2653 // - Logical operation (AND/OR/XOR) 2654 // There is also a special case that is handled (namely a complement operation 2655 // achieved with xor %a, -1). 2656 SDValue IntegerCompareEliminator::computeLogicOpInGPR(SDValue LogicOp) { 2657 assert(isLogicOp(LogicOp.getOpcode()) && 2658 "Can only handle logic operations here."); 2659 assert(LogicOp.getValueType() == MVT::i1 && 2660 "Can only handle logic operations on i1 values here."); 2661 SDLoc dl(LogicOp); 2662 SDValue LHS, RHS; 2663 2664 // Special case: xor %a, -1 2665 bool IsBitwiseNegation = isBitwiseNot(LogicOp); 2666 2667 // Produces a GPR sequence for each operand of the binary logic operation. 2668 // For SETCC, it produces the respective comparison, for TRUNCATE it truncates 2669 // the value in a GPR and for logic operations, it will recursively produce 2670 // a GPR sequence for the operation. 2671 auto getLogicOperand = [&] (SDValue Operand) -> SDValue { 2672 unsigned OperandOpcode = Operand.getOpcode(); 2673 if (OperandOpcode == ISD::SETCC) 2674 return getSETCCInGPR(Operand, SetccInGPROpts::ZExtOrig); 2675 else if (OperandOpcode == ISD::TRUNCATE) { 2676 SDValue InputOp = Operand.getOperand(0); 2677 EVT InVT = InputOp.getValueType(); 2678 return SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 : 2679 PPC::RLDICL, dl, InVT, InputOp, 2680 S->getI64Imm(0, dl), 2681 S->getI64Imm(63, dl)), 0); 2682 } else if (isLogicOp(OperandOpcode)) 2683 return computeLogicOpInGPR(Operand); 2684 return SDValue(); 2685 }; 2686 LHS = getLogicOperand(LogicOp.getOperand(0)); 2687 RHS = getLogicOperand(LogicOp.getOperand(1)); 2688 2689 // If a GPR sequence can't be produced for the LHS we can't proceed. 2690 // Not producing a GPR sequence for the RHS is only a problem if this isn't 2691 // a bitwise negation operation. 2692 if (!LHS || (!RHS && !IsBitwiseNegation)) 2693 return SDValue(); 2694 2695 NumLogicOpsOnComparison++; 2696 2697 // We will use the inputs as 64-bit values. 2698 if (LHS.getValueType() == MVT::i32) 2699 LHS = addExtOrTrunc(LHS, ExtOrTruncConversion::Ext); 2700 if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32) 2701 RHS = addExtOrTrunc(RHS, ExtOrTruncConversion::Ext); 2702 2703 unsigned NewOpc; 2704 switch (LogicOp.getOpcode()) { 2705 default: llvm_unreachable("Unknown logic operation."); 2706 case ISD::AND: NewOpc = PPC::AND8; break; 2707 case ISD::OR: NewOpc = PPC::OR8; break; 2708 case ISD::XOR: NewOpc = PPC::XOR8; break; 2709 } 2710 2711 if (IsBitwiseNegation) { 2712 RHS = S->getI64Imm(1, dl); 2713 NewOpc = PPC::XORI8; 2714 } 2715 2716 return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, RHS), 0); 2717 2718 } 2719 2720 /// If the value isn't guaranteed to be sign-extended to 64-bits, extend it. 2721 /// Otherwise just reinterpret it as a 64-bit value. 2722 /// Useful when emitting comparison code for 32-bit values without using 2723 /// the compare instruction (which only considers the lower 32-bits). 2724 SDValue IntegerCompareEliminator::signExtendInputIfNeeded(SDValue Input) { 2725 assert(Input.getValueType() == MVT::i32 && 2726 "Can only sign-extend 32-bit values here."); 2727 unsigned Opc = Input.getOpcode(); 2728 2729 // The value was sign extended and then truncated to 32-bits. No need to 2730 // sign extend it again. 2731 if (Opc == ISD::TRUNCATE && 2732 (Input.getOperand(0).getOpcode() == ISD::AssertSext || 2733 Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND)) 2734 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2735 2736 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input); 2737 // The input is a sign-extending load. All ppc sign-extending loads 2738 // sign-extend to the full 64-bits. 2739 if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD) 2740 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2741 2742 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input); 2743 // We don't sign-extend constants. 2744 if (InputConst) 2745 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2746 2747 SDLoc dl(Input); 2748 SignExtensionsAdded++; 2749 return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32_64, dl, 2750 MVT::i64, Input), 0); 2751 } 2752 2753 /// If the value isn't guaranteed to be zero-extended to 64-bits, extend it. 2754 /// Otherwise just reinterpret it as a 64-bit value. 2755 /// Useful when emitting comparison code for 32-bit values without using 2756 /// the compare instruction (which only considers the lower 32-bits). 2757 SDValue IntegerCompareEliminator::zeroExtendInputIfNeeded(SDValue Input) { 2758 assert(Input.getValueType() == MVT::i32 && 2759 "Can only zero-extend 32-bit values here."); 2760 unsigned Opc = Input.getOpcode(); 2761 2762 // The only condition under which we can omit the actual extend instruction: 2763 // - The value is a positive constant 2764 // - The value comes from a load that isn't a sign-extending load 2765 // An ISD::TRUNCATE needs to be zero-extended unless it is fed by a zext. 2766 bool IsTruncateOfZExt = Opc == ISD::TRUNCATE && 2767 (Input.getOperand(0).getOpcode() == ISD::AssertZext || 2768 Input.getOperand(0).getOpcode() == ISD::ZERO_EXTEND); 2769 if (IsTruncateOfZExt) 2770 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2771 2772 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input); 2773 if (InputConst && InputConst->getSExtValue() >= 0) 2774 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2775 2776 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input); 2777 // The input is a load that doesn't sign-extend (it will be zero-extended). 2778 if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD) 2779 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2780 2781 // None of the above, need to zero-extend. 2782 SDLoc dl(Input); 2783 ZeroExtensionsAdded++; 2784 return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32_64, dl, MVT::i64, Input, 2785 S->getI64Imm(0, dl), 2786 S->getI64Imm(32, dl)), 0); 2787 } 2788 2789 // Handle a 32-bit value in a 64-bit register and vice-versa. These are of 2790 // course not actual zero/sign extensions that will generate machine code, 2791 // they're just a way to reinterpret a 32 bit value in a register as a 2792 // 64 bit value and vice-versa. 2793 SDValue IntegerCompareEliminator::addExtOrTrunc(SDValue NatWidthRes, 2794 ExtOrTruncConversion Conv) { 2795 SDLoc dl(NatWidthRes); 2796 2797 // For reinterpreting 32-bit values as 64 bit values, we generate 2798 // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1> 2799 if (Conv == ExtOrTruncConversion::Ext) { 2800 SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0); 2801 SDValue SubRegIdx = 2802 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32); 2803 return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64, 2804 ImDef, NatWidthRes, SubRegIdx), 0); 2805 } 2806 2807 assert(Conv == ExtOrTruncConversion::Trunc && 2808 "Unknown convertion between 32 and 64 bit values."); 2809 // For reinterpreting 64-bit values as 32-bit values, we just need to 2810 // EXTRACT_SUBREG (i.e. extract the low word). 2811 SDValue SubRegIdx = 2812 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32); 2813 return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32, 2814 NatWidthRes, SubRegIdx), 0); 2815 } 2816 2817 // Produce a GPR sequence for compound comparisons (<=, >=) against zero. 2818 // Handle both zero-extensions and sign-extensions. 2819 SDValue 2820 IntegerCompareEliminator::getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl, 2821 ZeroCompare CmpTy) { 2822 EVT InVT = LHS.getValueType(); 2823 bool Is32Bit = InVT == MVT::i32; 2824 SDValue ToExtend; 2825 2826 // Produce the value that needs to be either zero or sign extended. 2827 switch (CmpTy) { 2828 case ZeroCompare::GEZExt: 2829 case ZeroCompare::GESExt: 2830 ToExtend = SDValue(CurDAG->getMachineNode(Is32Bit ? PPC::NOR : PPC::NOR8, 2831 dl, InVT, LHS, LHS), 0); 2832 break; 2833 case ZeroCompare::LEZExt: 2834 case ZeroCompare::LESExt: { 2835 if (Is32Bit) { 2836 // Upper 32 bits cannot be undefined for this sequence. 2837 LHS = signExtendInputIfNeeded(LHS); 2838 SDValue Neg = 2839 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0); 2840 ToExtend = 2841 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 2842 Neg, S->getI64Imm(1, dl), 2843 S->getI64Imm(63, dl)), 0); 2844 } else { 2845 SDValue Addi = 2846 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS, 2847 S->getI64Imm(~0ULL, dl)), 0); 2848 ToExtend = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 2849 Addi, LHS), 0); 2850 } 2851 break; 2852 } 2853 } 2854 2855 // For 64-bit sequences, the extensions are the same for the GE/LE cases. 2856 if (!Is32Bit && 2857 (CmpTy == ZeroCompare::GEZExt || CmpTy == ZeroCompare::LEZExt)) 2858 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 2859 ToExtend, S->getI64Imm(1, dl), 2860 S->getI64Imm(63, dl)), 0); 2861 if (!Is32Bit && 2862 (CmpTy == ZeroCompare::GESExt || CmpTy == ZeroCompare::LESExt)) 2863 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, ToExtend, 2864 S->getI64Imm(63, dl)), 0); 2865 2866 assert(Is32Bit && "Should have handled the 32-bit sequences above."); 2867 // For 32-bit sequences, the extensions differ between GE/LE cases. 2868 switch (CmpTy) { 2869 case ZeroCompare::GEZExt: { 2870 SDValue ShiftOps[] = { ToExtend, S->getI32Imm(1, dl), S->getI32Imm(31, dl), 2871 S->getI32Imm(31, dl) }; 2872 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, 2873 ShiftOps), 0); 2874 } 2875 case ZeroCompare::GESExt: 2876 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, ToExtend, 2877 S->getI32Imm(31, dl)), 0); 2878 case ZeroCompare::LEZExt: 2879 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, ToExtend, 2880 S->getI32Imm(1, dl)), 0); 2881 case ZeroCompare::LESExt: 2882 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, ToExtend, 2883 S->getI32Imm(-1, dl)), 0); 2884 } 2885 2886 // The above case covers all the enumerators so it can't have a default clause 2887 // to avoid compiler warnings. 2888 llvm_unreachable("Unknown zero-comparison type."); 2889 } 2890 2891 /// Produces a zero-extended result of comparing two 32-bit values according to 2892 /// the passed condition code. 2893 SDValue 2894 IntegerCompareEliminator::get32BitZExtCompare(SDValue LHS, SDValue RHS, 2895 ISD::CondCode CC, 2896 int64_t RHSValue, SDLoc dl) { 2897 if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 || 2898 CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Sext) 2899 return SDValue(); 2900 bool IsRHSZero = RHSValue == 0; 2901 bool IsRHSOne = RHSValue == 1; 2902 bool IsRHSNegOne = RHSValue == -1LL; 2903 switch (CC) { 2904 default: return SDValue(); 2905 case ISD::SETEQ: { 2906 // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5) 2907 // (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5) 2908 SDValue Xor = IsRHSZero ? LHS : 2909 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0); 2910 SDValue Clz = 2911 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0); 2912 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), 2913 S->getI32Imm(31, dl) }; 2914 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, 2915 ShiftOps), 0); 2916 } 2917 case ISD::SETNE: { 2918 // (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1) 2919 // (zext (setcc %a, 0, setne)) -> (xor (lshr (cntlzw %a), 5), 1) 2920 SDValue Xor = IsRHSZero ? LHS : 2921 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0); 2922 SDValue Clz = 2923 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0); 2924 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), 2925 S->getI32Imm(31, dl) }; 2926 SDValue Shift = 2927 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0); 2928 return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift, 2929 S->getI32Imm(1, dl)), 0); 2930 } 2931 case ISD::SETGE: { 2932 // (zext (setcc %a, %b, setge)) -> (xor (lshr (sub %a, %b), 63), 1) 2933 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 31) 2934 if(IsRHSZero) 2935 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt); 2936 2937 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a) 2938 // by swapping inputs and falling through. 2939 std::swap(LHS, RHS); 2940 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 2941 IsRHSZero = RHSConst && RHSConst->isNullValue(); 2942 LLVM_FALLTHROUGH; 2943 } 2944 case ISD::SETLE: { 2945 if (CmpInGPR == ICGPR_NonExtIn) 2946 return SDValue(); 2947 // (zext (setcc %a, %b, setle)) -> (xor (lshr (sub %b, %a), 63), 1) 2948 // (zext (setcc %a, 0, setle)) -> (xor (lshr (- %a), 63), 1) 2949 if(IsRHSZero) { 2950 if (CmpInGPR == ICGPR_NonExtIn) 2951 return SDValue(); 2952 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt); 2953 } 2954 2955 // The upper 32-bits of the register can't be undefined for this sequence. 2956 LHS = signExtendInputIfNeeded(LHS); 2957 RHS = signExtendInputIfNeeded(RHS); 2958 SDValue Sub = 2959 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0); 2960 SDValue Shift = 2961 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Sub, 2962 S->getI64Imm(1, dl), S->getI64Imm(63, dl)), 2963 0); 2964 return 2965 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, 2966 MVT::i64, Shift, S->getI32Imm(1, dl)), 0); 2967 } 2968 case ISD::SETGT: { 2969 // (zext (setcc %a, %b, setgt)) -> (lshr (sub %b, %a), 63) 2970 // (zext (setcc %a, -1, setgt)) -> (lshr (~ %a), 31) 2971 // (zext (setcc %a, 0, setgt)) -> (lshr (- %a), 63) 2972 // Handle SETLT -1 (which is equivalent to SETGE 0). 2973 if (IsRHSNegOne) 2974 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt); 2975 2976 if (IsRHSZero) { 2977 if (CmpInGPR == ICGPR_NonExtIn) 2978 return SDValue(); 2979 // The upper 32-bits of the register can't be undefined for this sequence. 2980 LHS = signExtendInputIfNeeded(LHS); 2981 RHS = signExtendInputIfNeeded(RHS); 2982 SDValue Neg = 2983 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0); 2984 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 2985 Neg, S->getI32Imm(1, dl), S->getI32Imm(63, dl)), 0); 2986 } 2987 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as 2988 // (%b < %a) by swapping inputs and falling through. 2989 std::swap(LHS, RHS); 2990 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 2991 IsRHSZero = RHSConst && RHSConst->isNullValue(); 2992 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1; 2993 LLVM_FALLTHROUGH; 2994 } 2995 case ISD::SETLT: { 2996 // (zext (setcc %a, %b, setlt)) -> (lshr (sub %a, %b), 63) 2997 // (zext (setcc %a, 1, setlt)) -> (xor (lshr (- %a), 63), 1) 2998 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 31) 2999 // Handle SETLT 1 (which is equivalent to SETLE 0). 3000 if (IsRHSOne) { 3001 if (CmpInGPR == ICGPR_NonExtIn) 3002 return SDValue(); 3003 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt); 3004 } 3005 3006 if (IsRHSZero) { 3007 SDValue ShiftOps[] = { LHS, S->getI32Imm(1, dl), S->getI32Imm(31, dl), 3008 S->getI32Imm(31, dl) }; 3009 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, 3010 ShiftOps), 0); 3011 } 3012 3013 if (CmpInGPR == ICGPR_NonExtIn) 3014 return SDValue(); 3015 // The upper 32-bits of the register can't be undefined for this sequence. 3016 LHS = signExtendInputIfNeeded(LHS); 3017 RHS = signExtendInputIfNeeded(RHS); 3018 SDValue SUBFNode = 3019 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0); 3020 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 3021 SUBFNode, S->getI64Imm(1, dl), 3022 S->getI64Imm(63, dl)), 0); 3023 } 3024 case ISD::SETUGE: 3025 // (zext (setcc %a, %b, setuge)) -> (xor (lshr (sub %b, %a), 63), 1) 3026 // (zext (setcc %a, %b, setule)) -> (xor (lshr (sub %a, %b), 63), 1) 3027 std::swap(LHS, RHS); 3028 LLVM_FALLTHROUGH; 3029 case ISD::SETULE: { 3030 if (CmpInGPR == ICGPR_NonExtIn) 3031 return SDValue(); 3032 // The upper 32-bits of the register can't be undefined for this sequence. 3033 LHS = zeroExtendInputIfNeeded(LHS); 3034 RHS = zeroExtendInputIfNeeded(RHS); 3035 SDValue Subtract = 3036 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0); 3037 SDValue SrdiNode = 3038 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 3039 Subtract, S->getI64Imm(1, dl), 3040 S->getI64Imm(63, dl)), 0); 3041 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, SrdiNode, 3042 S->getI32Imm(1, dl)), 0); 3043 } 3044 case ISD::SETUGT: 3045 // (zext (setcc %a, %b, setugt)) -> (lshr (sub %b, %a), 63) 3046 // (zext (setcc %a, %b, setult)) -> (lshr (sub %a, %b), 63) 3047 std::swap(LHS, RHS); 3048 LLVM_FALLTHROUGH; 3049 case ISD::SETULT: { 3050 if (CmpInGPR == ICGPR_NonExtIn) 3051 return SDValue(); 3052 // The upper 32-bits of the register can't be undefined for this sequence. 3053 LHS = zeroExtendInputIfNeeded(LHS); 3054 RHS = zeroExtendInputIfNeeded(RHS); 3055 SDValue Subtract = 3056 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0); 3057 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 3058 Subtract, S->getI64Imm(1, dl), 3059 S->getI64Imm(63, dl)), 0); 3060 } 3061 } 3062 } 3063 3064 /// Produces a sign-extended result of comparing two 32-bit values according to 3065 /// the passed condition code. 3066 SDValue 3067 IntegerCompareEliminator::get32BitSExtCompare(SDValue LHS, SDValue RHS, 3068 ISD::CondCode CC, 3069 int64_t RHSValue, SDLoc dl) { 3070 if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 || 3071 CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Zext) 3072 return SDValue(); 3073 bool IsRHSZero = RHSValue == 0; 3074 bool IsRHSOne = RHSValue == 1; 3075 bool IsRHSNegOne = RHSValue == -1LL; 3076 3077 switch (CC) { 3078 default: return SDValue(); 3079 case ISD::SETEQ: { 3080 // (sext (setcc %a, %b, seteq)) -> 3081 // (ashr (shl (ctlz (xor %a, %b)), 58), 63) 3082 // (sext (setcc %a, 0, seteq)) -> 3083 // (ashr (shl (ctlz %a), 58), 63) 3084 SDValue CountInput = IsRHSZero ? LHS : 3085 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0); 3086 SDValue Cntlzw = 3087 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0); 3088 SDValue SHLOps[] = { Cntlzw, S->getI32Imm(27, dl), 3089 S->getI32Imm(5, dl), S->getI32Imm(31, dl) }; 3090 SDValue Slwi = 3091 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, SHLOps), 0); 3092 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Slwi), 0); 3093 } 3094 case ISD::SETNE: { 3095 // Bitwise xor the operands, count leading zeros, shift right by 5 bits and 3096 // flip the bit, finally take 2's complement. 3097 // (sext (setcc %a, %b, setne)) -> 3098 // (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1)) 3099 // Same as above, but the first xor is not needed. 3100 // (sext (setcc %a, 0, setne)) -> 3101 // (neg (xor (lshr (ctlz %a), 5), 1)) 3102 SDValue Xor = IsRHSZero ? LHS : 3103 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0); 3104 SDValue Clz = 3105 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0); 3106 SDValue ShiftOps[] = 3107 { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), S->getI32Imm(31, dl) }; 3108 SDValue Shift = 3109 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0); 3110 SDValue Xori = 3111 SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift, 3112 S->getI32Imm(1, dl)), 0); 3113 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Xori), 0); 3114 } 3115 case ISD::SETGE: { 3116 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %a, %b), 63), -1) 3117 // (sext (setcc %a, 0, setge)) -> (ashr (~ %a), 31) 3118 if (IsRHSZero) 3119 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt); 3120 3121 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a) 3122 // by swapping inputs and falling through. 3123 std::swap(LHS, RHS); 3124 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3125 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3126 LLVM_FALLTHROUGH; 3127 } 3128 case ISD::SETLE: { 3129 if (CmpInGPR == ICGPR_NonExtIn) 3130 return SDValue(); 3131 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %b, %a), 63), -1) 3132 // (sext (setcc %a, 0, setle)) -> (add (lshr (- %a), 63), -1) 3133 if (IsRHSZero) 3134 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt); 3135 3136 // The upper 32-bits of the register can't be undefined for this sequence. 3137 LHS = signExtendInputIfNeeded(LHS); 3138 RHS = signExtendInputIfNeeded(RHS); 3139 SDValue SUBFNode = 3140 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, MVT::Glue, 3141 LHS, RHS), 0); 3142 SDValue Srdi = 3143 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 3144 SUBFNode, S->getI64Imm(1, dl), 3145 S->getI64Imm(63, dl)), 0); 3146 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Srdi, 3147 S->getI32Imm(-1, dl)), 0); 3148 } 3149 case ISD::SETGT: { 3150 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %b, %a), 63) 3151 // (sext (setcc %a, -1, setgt)) -> (ashr (~ %a), 31) 3152 // (sext (setcc %a, 0, setgt)) -> (ashr (- %a), 63) 3153 if (IsRHSNegOne) 3154 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt); 3155 if (IsRHSZero) { 3156 if (CmpInGPR == ICGPR_NonExtIn) 3157 return SDValue(); 3158 // The upper 32-bits of the register can't be undefined for this sequence. 3159 LHS = signExtendInputIfNeeded(LHS); 3160 RHS = signExtendInputIfNeeded(RHS); 3161 SDValue Neg = 3162 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0); 3163 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Neg, 3164 S->getI64Imm(63, dl)), 0); 3165 } 3166 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as 3167 // (%b < %a) by swapping inputs and falling through. 3168 std::swap(LHS, RHS); 3169 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3170 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3171 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1; 3172 LLVM_FALLTHROUGH; 3173 } 3174 case ISD::SETLT: { 3175 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %a, %b), 63) 3176 // (sext (setcc %a, 1, setgt)) -> (add (lshr (- %a), 63), -1) 3177 // (sext (setcc %a, 0, setgt)) -> (ashr %a, 31) 3178 if (IsRHSOne) { 3179 if (CmpInGPR == ICGPR_NonExtIn) 3180 return SDValue(); 3181 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt); 3182 } 3183 if (IsRHSZero) 3184 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, LHS, 3185 S->getI32Imm(31, dl)), 0); 3186 3187 if (CmpInGPR == ICGPR_NonExtIn) 3188 return SDValue(); 3189 // The upper 32-bits of the register can't be undefined for this sequence. 3190 LHS = signExtendInputIfNeeded(LHS); 3191 RHS = signExtendInputIfNeeded(RHS); 3192 SDValue SUBFNode = 3193 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0); 3194 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, 3195 SUBFNode, S->getI64Imm(63, dl)), 0); 3196 } 3197 case ISD::SETUGE: 3198 // (sext (setcc %a, %b, setuge)) -> (add (lshr (sub %a, %b), 63), -1) 3199 // (sext (setcc %a, %b, setule)) -> (add (lshr (sub %b, %a), 63), -1) 3200 std::swap(LHS, RHS); 3201 LLVM_FALLTHROUGH; 3202 case ISD::SETULE: { 3203 if (CmpInGPR == ICGPR_NonExtIn) 3204 return SDValue(); 3205 // The upper 32-bits of the register can't be undefined for this sequence. 3206 LHS = zeroExtendInputIfNeeded(LHS); 3207 RHS = zeroExtendInputIfNeeded(RHS); 3208 SDValue Subtract = 3209 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0); 3210 SDValue Shift = 3211 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Subtract, 3212 S->getI32Imm(1, dl), S->getI32Imm(63,dl)), 3213 0); 3214 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Shift, 3215 S->getI32Imm(-1, dl)), 0); 3216 } 3217 case ISD::SETUGT: 3218 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %b, %a), 63) 3219 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %a, %b), 63) 3220 std::swap(LHS, RHS); 3221 LLVM_FALLTHROUGH; 3222 case ISD::SETULT: { 3223 if (CmpInGPR == ICGPR_NonExtIn) 3224 return SDValue(); 3225 // The upper 32-bits of the register can't be undefined for this sequence. 3226 LHS = zeroExtendInputIfNeeded(LHS); 3227 RHS = zeroExtendInputIfNeeded(RHS); 3228 SDValue Subtract = 3229 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0); 3230 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, 3231 Subtract, S->getI64Imm(63, dl)), 0); 3232 } 3233 } 3234 } 3235 3236 /// Produces a zero-extended result of comparing two 64-bit values according to 3237 /// the passed condition code. 3238 SDValue 3239 IntegerCompareEliminator::get64BitZExtCompare(SDValue LHS, SDValue RHS, 3240 ISD::CondCode CC, 3241 int64_t RHSValue, SDLoc dl) { 3242 if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 || 3243 CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Sext) 3244 return SDValue(); 3245 bool IsRHSZero = RHSValue == 0; 3246 bool IsRHSOne = RHSValue == 1; 3247 bool IsRHSNegOne = RHSValue == -1LL; 3248 switch (CC) { 3249 default: return SDValue(); 3250 case ISD::SETEQ: { 3251 // (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6) 3252 // (zext (setcc %a, 0, seteq)) -> (lshr (ctlz %a), 6) 3253 SDValue Xor = IsRHSZero ? LHS : 3254 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0); 3255 SDValue Clz = 3256 SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0); 3257 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz, 3258 S->getI64Imm(58, dl), 3259 S->getI64Imm(63, dl)), 0); 3260 } 3261 case ISD::SETNE: { 3262 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1) 3263 // (zext (setcc %a, %b, setne)) -> (sube addc.reg, addc.reg, addc.CA) 3264 // {addcz.reg, addcz.CA} = (addcarry %a, -1) 3265 // (zext (setcc %a, 0, setne)) -> (sube addcz.reg, addcz.reg, addcz.CA) 3266 SDValue Xor = IsRHSZero ? LHS : 3267 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0); 3268 SDValue AC = 3269 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue, 3270 Xor, S->getI32Imm(~0U, dl)), 0); 3271 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, AC, 3272 Xor, AC.getValue(1)), 0); 3273 } 3274 case ISD::SETGE: { 3275 // {subc.reg, subc.CA} = (subcarry %a, %b) 3276 // (zext (setcc %a, %b, setge)) -> 3277 // (adde (lshr %b, 63), (ashr %a, 63), subc.CA) 3278 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 63) 3279 if (IsRHSZero) 3280 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt); 3281 std::swap(LHS, RHS); 3282 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3283 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3284 LLVM_FALLTHROUGH; 3285 } 3286 case ISD::SETLE: { 3287 // {subc.reg, subc.CA} = (subcarry %b, %a) 3288 // (zext (setcc %a, %b, setge)) -> 3289 // (adde (lshr %a, 63), (ashr %b, 63), subc.CA) 3290 // (zext (setcc %a, 0, setge)) -> (lshr (or %a, (add %a, -1)), 63) 3291 if (IsRHSZero) 3292 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt); 3293 SDValue ShiftL = 3294 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS, 3295 S->getI64Imm(1, dl), 3296 S->getI64Imm(63, dl)), 0); 3297 SDValue ShiftR = 3298 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS, 3299 S->getI64Imm(63, dl)), 0); 3300 SDValue SubtractCarry = 3301 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3302 LHS, RHS), 1); 3303 return SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue, 3304 ShiftR, ShiftL, SubtractCarry), 0); 3305 } 3306 case ISD::SETGT: { 3307 // {subc.reg, subc.CA} = (subcarry %b, %a) 3308 // (zext (setcc %a, %b, setgt)) -> 3309 // (xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1) 3310 // (zext (setcc %a, 0, setgt)) -> (lshr (nor (add %a, -1), %a), 63) 3311 if (IsRHSNegOne) 3312 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt); 3313 if (IsRHSZero) { 3314 SDValue Addi = 3315 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS, 3316 S->getI64Imm(~0ULL, dl)), 0); 3317 SDValue Nor = 3318 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Addi, LHS), 0); 3319 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Nor, 3320 S->getI64Imm(1, dl), 3321 S->getI64Imm(63, dl)), 0); 3322 } 3323 std::swap(LHS, RHS); 3324 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3325 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3326 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1; 3327 LLVM_FALLTHROUGH; 3328 } 3329 case ISD::SETLT: { 3330 // {subc.reg, subc.CA} = (subcarry %a, %b) 3331 // (zext (setcc %a, %b, setlt)) -> 3332 // (xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1) 3333 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 63) 3334 if (IsRHSOne) 3335 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt); 3336 if (IsRHSZero) 3337 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS, 3338 S->getI64Imm(1, dl), 3339 S->getI64Imm(63, dl)), 0); 3340 SDValue SRADINode = 3341 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, 3342 LHS, S->getI64Imm(63, dl)), 0); 3343 SDValue SRDINode = 3344 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 3345 RHS, S->getI64Imm(1, dl), 3346 S->getI64Imm(63, dl)), 0); 3347 SDValue SUBFC8Carry = 3348 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3349 RHS, LHS), 1); 3350 SDValue ADDE8Node = 3351 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue, 3352 SRDINode, SRADINode, SUBFC8Carry), 0); 3353 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, 3354 ADDE8Node, S->getI64Imm(1, dl)), 0); 3355 } 3356 case ISD::SETUGE: 3357 // {subc.reg, subc.CA} = (subcarry %a, %b) 3358 // (zext (setcc %a, %b, setuge)) -> (add (sube %b, %b, subc.CA), 1) 3359 std::swap(LHS, RHS); 3360 LLVM_FALLTHROUGH; 3361 case ISD::SETULE: { 3362 // {subc.reg, subc.CA} = (subcarry %b, %a) 3363 // (zext (setcc %a, %b, setule)) -> (add (sube %a, %a, subc.CA), 1) 3364 SDValue SUBFC8Carry = 3365 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3366 LHS, RHS), 1); 3367 SDValue SUBFE8Node = 3368 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue, 3369 LHS, LHS, SUBFC8Carry), 0); 3370 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, 3371 SUBFE8Node, S->getI64Imm(1, dl)), 0); 3372 } 3373 case ISD::SETUGT: 3374 // {subc.reg, subc.CA} = (subcarry %b, %a) 3375 // (zext (setcc %a, %b, setugt)) -> -(sube %b, %b, subc.CA) 3376 std::swap(LHS, RHS); 3377 LLVM_FALLTHROUGH; 3378 case ISD::SETULT: { 3379 // {subc.reg, subc.CA} = (subcarry %a, %b) 3380 // (zext (setcc %a, %b, setult)) -> -(sube %a, %a, subc.CA) 3381 SDValue SubtractCarry = 3382 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3383 RHS, LHS), 1); 3384 SDValue ExtSub = 3385 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, 3386 LHS, LHS, SubtractCarry), 0); 3387 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, 3388 ExtSub), 0); 3389 } 3390 } 3391 } 3392 3393 /// Produces a sign-extended result of comparing two 64-bit values according to 3394 /// the passed condition code. 3395 SDValue 3396 IntegerCompareEliminator::get64BitSExtCompare(SDValue LHS, SDValue RHS, 3397 ISD::CondCode CC, 3398 int64_t RHSValue, SDLoc dl) { 3399 if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 || 3400 CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Zext) 3401 return SDValue(); 3402 bool IsRHSZero = RHSValue == 0; 3403 bool IsRHSOne = RHSValue == 1; 3404 bool IsRHSNegOne = RHSValue == -1LL; 3405 switch (CC) { 3406 default: return SDValue(); 3407 case ISD::SETEQ: { 3408 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1) 3409 // (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA) 3410 // {addcz.reg, addcz.CA} = (addcarry %a, -1) 3411 // (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA) 3412 SDValue AddInput = IsRHSZero ? LHS : 3413 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0); 3414 SDValue Addic = 3415 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue, 3416 AddInput, S->getI32Imm(~0U, dl)), 0); 3417 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic, 3418 Addic, Addic.getValue(1)), 0); 3419 } 3420 case ISD::SETNE: { 3421 // {subfc.reg, subfc.CA} = (subcarry 0, (xor %a, %b)) 3422 // (sext (setcc %a, %b, setne)) -> (sube subfc.reg, subfc.reg, subfc.CA) 3423 // {subfcz.reg, subfcz.CA} = (subcarry 0, %a) 3424 // (sext (setcc %a, 0, setne)) -> (sube subfcz.reg, subfcz.reg, subfcz.CA) 3425 SDValue Xor = IsRHSZero ? LHS : 3426 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0); 3427 SDValue SC = 3428 SDValue(CurDAG->getMachineNode(PPC::SUBFIC8, dl, MVT::i64, MVT::Glue, 3429 Xor, S->getI32Imm(0, dl)), 0); 3430 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, SC, 3431 SC, SC.getValue(1)), 0); 3432 } 3433 case ISD::SETGE: { 3434 // {subc.reg, subc.CA} = (subcarry %a, %b) 3435 // (zext (setcc %a, %b, setge)) -> 3436 // (- (adde (lshr %b, 63), (ashr %a, 63), subc.CA)) 3437 // (zext (setcc %a, 0, setge)) -> (~ (ashr %a, 63)) 3438 if (IsRHSZero) 3439 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt); 3440 std::swap(LHS, RHS); 3441 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3442 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3443 LLVM_FALLTHROUGH; 3444 } 3445 case ISD::SETLE: { 3446 // {subc.reg, subc.CA} = (subcarry %b, %a) 3447 // (zext (setcc %a, %b, setge)) -> 3448 // (- (adde (lshr %a, 63), (ashr %b, 63), subc.CA)) 3449 // (zext (setcc %a, 0, setge)) -> (ashr (or %a, (add %a, -1)), 63) 3450 if (IsRHSZero) 3451 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt); 3452 SDValue ShiftR = 3453 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS, 3454 S->getI64Imm(63, dl)), 0); 3455 SDValue ShiftL = 3456 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS, 3457 S->getI64Imm(1, dl), 3458 S->getI64Imm(63, dl)), 0); 3459 SDValue SubtractCarry = 3460 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3461 LHS, RHS), 1); 3462 SDValue Adde = 3463 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue, 3464 ShiftR, ShiftL, SubtractCarry), 0); 3465 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, Adde), 0); 3466 } 3467 case ISD::SETGT: { 3468 // {subc.reg, subc.CA} = (subcarry %b, %a) 3469 // (zext (setcc %a, %b, setgt)) -> 3470 // -(xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1) 3471 // (zext (setcc %a, 0, setgt)) -> (ashr (nor (add %a, -1), %a), 63) 3472 if (IsRHSNegOne) 3473 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt); 3474 if (IsRHSZero) { 3475 SDValue Add = 3476 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS, 3477 S->getI64Imm(-1, dl)), 0); 3478 SDValue Nor = 3479 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Add, LHS), 0); 3480 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Nor, 3481 S->getI64Imm(63, dl)), 0); 3482 } 3483 std::swap(LHS, RHS); 3484 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3485 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3486 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1; 3487 LLVM_FALLTHROUGH; 3488 } 3489 case ISD::SETLT: { 3490 // {subc.reg, subc.CA} = (subcarry %a, %b) 3491 // (zext (setcc %a, %b, setlt)) -> 3492 // -(xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1) 3493 // (zext (setcc %a, 0, setlt)) -> (ashr %a, 63) 3494 if (IsRHSOne) 3495 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt); 3496 if (IsRHSZero) { 3497 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, LHS, 3498 S->getI64Imm(63, dl)), 0); 3499 } 3500 SDValue SRADINode = 3501 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, 3502 LHS, S->getI64Imm(63, dl)), 0); 3503 SDValue SRDINode = 3504 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 3505 RHS, S->getI64Imm(1, dl), 3506 S->getI64Imm(63, dl)), 0); 3507 SDValue SUBFC8Carry = 3508 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3509 RHS, LHS), 1); 3510 SDValue ADDE8Node = 3511 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, 3512 SRDINode, SRADINode, SUBFC8Carry), 0); 3513 SDValue XORI8Node = 3514 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, 3515 ADDE8Node, S->getI64Imm(1, dl)), 0); 3516 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, 3517 XORI8Node), 0); 3518 } 3519 case ISD::SETUGE: 3520 // {subc.reg, subc.CA} = (subcarry %a, %b) 3521 // (sext (setcc %a, %b, setuge)) -> ~(sube %b, %b, subc.CA) 3522 std::swap(LHS, RHS); 3523 LLVM_FALLTHROUGH; 3524 case ISD::SETULE: { 3525 // {subc.reg, subc.CA} = (subcarry %b, %a) 3526 // (sext (setcc %a, %b, setule)) -> ~(sube %a, %a, subc.CA) 3527 SDValue SubtractCarry = 3528 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3529 LHS, RHS), 1); 3530 SDValue ExtSub = 3531 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue, LHS, 3532 LHS, SubtractCarry), 0); 3533 return SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, 3534 ExtSub, ExtSub), 0); 3535 } 3536 case ISD::SETUGT: 3537 // {subc.reg, subc.CA} = (subcarry %b, %a) 3538 // (sext (setcc %a, %b, setugt)) -> (sube %b, %b, subc.CA) 3539 std::swap(LHS, RHS); 3540 LLVM_FALLTHROUGH; 3541 case ISD::SETULT: { 3542 // {subc.reg, subc.CA} = (subcarry %a, %b) 3543 // (sext (setcc %a, %b, setult)) -> (sube %a, %a, subc.CA) 3544 SDValue SubCarry = 3545 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3546 RHS, LHS), 1); 3547 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, 3548 LHS, LHS, SubCarry), 0); 3549 } 3550 } 3551 } 3552 3553 /// Do all uses of this SDValue need the result in a GPR? 3554 /// This is meant to be used on values that have type i1 since 3555 /// it is somewhat meaningless to ask if values of other types 3556 /// should be kept in GPR's. 3557 static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG) { 3558 assert(Compare.getOpcode() == ISD::SETCC && 3559 "An ISD::SETCC node required here."); 3560 3561 // For values that have a single use, the caller should obviously already have 3562 // checked if that use is an extending use. We check the other uses here. 3563 if (Compare.hasOneUse()) 3564 return true; 3565 // We want the value in a GPR if it is being extended, used for a select, or 3566 // used in logical operations. 3567 for (auto CompareUse : Compare.getNode()->uses()) 3568 if (CompareUse->getOpcode() != ISD::SIGN_EXTEND && 3569 CompareUse->getOpcode() != ISD::ZERO_EXTEND && 3570 CompareUse->getOpcode() != ISD::SELECT && 3571 !isLogicOp(CompareUse->getOpcode())) { 3572 OmittedForNonExtendUses++; 3573 return false; 3574 } 3575 return true; 3576 } 3577 3578 /// Returns an equivalent of a SETCC node but with the result the same width as 3579 /// the inputs. This can also be used for SELECT_CC if either the true or false 3580 /// values is a power of two while the other is zero. 3581 SDValue IntegerCompareEliminator::getSETCCInGPR(SDValue Compare, 3582 SetccInGPROpts ConvOpts) { 3583 assert((Compare.getOpcode() == ISD::SETCC || 3584 Compare.getOpcode() == ISD::SELECT_CC) && 3585 "An ISD::SETCC node required here."); 3586 3587 // Don't convert this comparison to a GPR sequence because there are uses 3588 // of the i1 result (i.e. uses that require the result in the CR). 3589 if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG)) 3590 return SDValue(); 3591 3592 SDValue LHS = Compare.getOperand(0); 3593 SDValue RHS = Compare.getOperand(1); 3594 3595 // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC. 3596 int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2; 3597 ISD::CondCode CC = 3598 cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get(); 3599 EVT InputVT = LHS.getValueType(); 3600 if (InputVT != MVT::i32 && InputVT != MVT::i64) 3601 return SDValue(); 3602 3603 if (ConvOpts == SetccInGPROpts::ZExtInvert || 3604 ConvOpts == SetccInGPROpts::SExtInvert) 3605 CC = ISD::getSetCCInverse(CC, InputVT); 3606 3607 bool Inputs32Bit = InputVT == MVT::i32; 3608 3609 SDLoc dl(Compare); 3610 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3611 int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX; 3612 bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig || 3613 ConvOpts == SetccInGPROpts::SExtInvert; 3614 3615 if (IsSext && Inputs32Bit) 3616 return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl); 3617 else if (Inputs32Bit) 3618 return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl); 3619 else if (IsSext) 3620 return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl); 3621 return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl); 3622 } 3623 3624 } // end anonymous namespace 3625 3626 bool PPCDAGToDAGISel::tryIntCompareInGPR(SDNode *N) { 3627 if (N->getValueType(0) != MVT::i32 && 3628 N->getValueType(0) != MVT::i64) 3629 return false; 3630 3631 // This optimization will emit code that assumes 64-bit registers 3632 // so we don't want to run it in 32-bit mode. Also don't run it 3633 // on functions that are not to be optimized. 3634 if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64()) 3635 return false; 3636 3637 // For POWER10, it is more profitable to use the set boolean extension 3638 // instructions rather than the integer compare elimination codegen. 3639 // Users can override this via the command line option, `--ppc-gpr-icmps`. 3640 if (!(CmpInGPR.getNumOccurrences() > 0) && Subtarget->isISA3_1()) 3641 return false; 3642 3643 switch (N->getOpcode()) { 3644 default: break; 3645 case ISD::ZERO_EXTEND: 3646 case ISD::SIGN_EXTEND: 3647 case ISD::AND: 3648 case ISD::OR: 3649 case ISD::XOR: { 3650 IntegerCompareEliminator ICmpElim(CurDAG, this); 3651 if (SDNode *New = ICmpElim.Select(N)) { 3652 ReplaceNode(N, New); 3653 return true; 3654 } 3655 } 3656 } 3657 return false; 3658 } 3659 3660 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) { 3661 if (N->getValueType(0) != MVT::i32 && 3662 N->getValueType(0) != MVT::i64) 3663 return false; 3664 3665 if (!UseBitPermRewriter) 3666 return false; 3667 3668 switch (N->getOpcode()) { 3669 default: break; 3670 case ISD::ROTL: 3671 case ISD::SHL: 3672 case ISD::SRL: 3673 case ISD::AND: 3674 case ISD::OR: { 3675 BitPermutationSelector BPS(CurDAG); 3676 if (SDNode *New = BPS.Select(N)) { 3677 ReplaceNode(N, New); 3678 return true; 3679 } 3680 return false; 3681 } 3682 } 3683 3684 return false; 3685 } 3686 3687 /// SelectCC - Select a comparison of the specified values with the specified 3688 /// condition code, returning the CR# of the expression. 3689 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3690 const SDLoc &dl, SDValue Chain) { 3691 // Always select the LHS. 3692 unsigned Opc; 3693 3694 if (LHS.getValueType() == MVT::i32) { 3695 unsigned Imm; 3696 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3697 if (isInt32Immediate(RHS, Imm)) { 3698 // SETEQ/SETNE comparison with 16-bit immediate, fold it. 3699 if (isUInt<16>(Imm)) 3700 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS, 3701 getI32Imm(Imm & 0xFFFF, dl)), 3702 0); 3703 // If this is a 16-bit signed immediate, fold it. 3704 if (isInt<16>((int)Imm)) 3705 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS, 3706 getI32Imm(Imm & 0xFFFF, dl)), 3707 0); 3708 3709 // For non-equality comparisons, the default code would materialize the 3710 // constant, then compare against it, like this: 3711 // lis r2, 4660 3712 // ori r2, r2, 22136 3713 // cmpw cr0, r3, r2 3714 // Since we are just comparing for equality, we can emit this instead: 3715 // xoris r0,r3,0x1234 3716 // cmplwi cr0,r0,0x5678 3717 // beq cr0,L6 3718 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS, 3719 getI32Imm(Imm >> 16, dl)), 0); 3720 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor, 3721 getI32Imm(Imm & 0xFFFF, dl)), 0); 3722 } 3723 Opc = PPC::CMPLW; 3724 } else if (ISD::isUnsignedIntSetCC(CC)) { 3725 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm)) 3726 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS, 3727 getI32Imm(Imm & 0xFFFF, dl)), 0); 3728 Opc = PPC::CMPLW; 3729 } else { 3730 int16_t SImm; 3731 if (isIntS16Immediate(RHS, SImm)) 3732 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS, 3733 getI32Imm((int)SImm & 0xFFFF, 3734 dl)), 3735 0); 3736 Opc = PPC::CMPW; 3737 } 3738 } else if (LHS.getValueType() == MVT::i64) { 3739 uint64_t Imm; 3740 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3741 if (isInt64Immediate(RHS.getNode(), Imm)) { 3742 // SETEQ/SETNE comparison with 16-bit immediate, fold it. 3743 if (isUInt<16>(Imm)) 3744 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS, 3745 getI32Imm(Imm & 0xFFFF, dl)), 3746 0); 3747 // If this is a 16-bit signed immediate, fold it. 3748 if (isInt<16>(Imm)) 3749 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS, 3750 getI32Imm(Imm & 0xFFFF, dl)), 3751 0); 3752 3753 // For non-equality comparisons, the default code would materialize the 3754 // constant, then compare against it, like this: 3755 // lis r2, 4660 3756 // ori r2, r2, 22136 3757 // cmpd cr0, r3, r2 3758 // Since we are just comparing for equality, we can emit this instead: 3759 // xoris r0,r3,0x1234 3760 // cmpldi cr0,r0,0x5678 3761 // beq cr0,L6 3762 if (isUInt<32>(Imm)) { 3763 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS, 3764 getI64Imm(Imm >> 16, dl)), 0); 3765 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor, 3766 getI64Imm(Imm & 0xFFFF, dl)), 3767 0); 3768 } 3769 } 3770 Opc = PPC::CMPLD; 3771 } else if (ISD::isUnsignedIntSetCC(CC)) { 3772 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm)) 3773 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS, 3774 getI64Imm(Imm & 0xFFFF, dl)), 0); 3775 Opc = PPC::CMPLD; 3776 } else { 3777 int16_t SImm; 3778 if (isIntS16Immediate(RHS, SImm)) 3779 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS, 3780 getI64Imm(SImm & 0xFFFF, dl)), 3781 0); 3782 Opc = PPC::CMPD; 3783 } 3784 } else if (LHS.getValueType() == MVT::f32) { 3785 if (Subtarget->hasSPE()) { 3786 switch (CC) { 3787 default: 3788 case ISD::SETEQ: 3789 case ISD::SETNE: 3790 Opc = PPC::EFSCMPEQ; 3791 break; 3792 case ISD::SETLT: 3793 case ISD::SETGE: 3794 case ISD::SETOLT: 3795 case ISD::SETOGE: 3796 case ISD::SETULT: 3797 case ISD::SETUGE: 3798 Opc = PPC::EFSCMPLT; 3799 break; 3800 case ISD::SETGT: 3801 case ISD::SETLE: 3802 case ISD::SETOGT: 3803 case ISD::SETOLE: 3804 case ISD::SETUGT: 3805 case ISD::SETULE: 3806 Opc = PPC::EFSCMPGT; 3807 break; 3808 } 3809 } else 3810 Opc = PPC::FCMPUS; 3811 } else if (LHS.getValueType() == MVT::f64) { 3812 if (Subtarget->hasSPE()) { 3813 switch (CC) { 3814 default: 3815 case ISD::SETEQ: 3816 case ISD::SETNE: 3817 Opc = PPC::EFDCMPEQ; 3818 break; 3819 case ISD::SETLT: 3820 case ISD::SETGE: 3821 case ISD::SETOLT: 3822 case ISD::SETOGE: 3823 case ISD::SETULT: 3824 case ISD::SETUGE: 3825 Opc = PPC::EFDCMPLT; 3826 break; 3827 case ISD::SETGT: 3828 case ISD::SETLE: 3829 case ISD::SETOGT: 3830 case ISD::SETOLE: 3831 case ISD::SETUGT: 3832 case ISD::SETULE: 3833 Opc = PPC::EFDCMPGT; 3834 break; 3835 } 3836 } else 3837 Opc = Subtarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD; 3838 } else { 3839 assert(LHS.getValueType() == MVT::f128 && "Unknown vt!"); 3840 assert(Subtarget->hasVSX() && "__float128 requires VSX"); 3841 Opc = PPC::XSCMPUQP; 3842 } 3843 if (Chain) 3844 return SDValue( 3845 CurDAG->getMachineNode(Opc, dl, MVT::i32, MVT::Other, LHS, RHS, Chain), 3846 0); 3847 else 3848 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0); 3849 } 3850 3851 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC, const EVT &VT, 3852 const PPCSubtarget *Subtarget) { 3853 // For SPE instructions, the result is in GT bit of the CR 3854 bool UseSPE = Subtarget->hasSPE() && VT.isFloatingPoint(); 3855 3856 switch (CC) { 3857 case ISD::SETUEQ: 3858 case ISD::SETONE: 3859 case ISD::SETOLE: 3860 case ISD::SETOGE: 3861 llvm_unreachable("Should be lowered by legalize!"); 3862 default: llvm_unreachable("Unknown condition!"); 3863 case ISD::SETOEQ: 3864 case ISD::SETEQ: 3865 return UseSPE ? PPC::PRED_GT : PPC::PRED_EQ; 3866 case ISD::SETUNE: 3867 case ISD::SETNE: 3868 return UseSPE ? PPC::PRED_LE : PPC::PRED_NE; 3869 case ISD::SETOLT: 3870 case ISD::SETLT: 3871 return UseSPE ? PPC::PRED_GT : PPC::PRED_LT; 3872 case ISD::SETULE: 3873 case ISD::SETLE: 3874 return PPC::PRED_LE; 3875 case ISD::SETOGT: 3876 case ISD::SETGT: 3877 return PPC::PRED_GT; 3878 case ISD::SETUGE: 3879 case ISD::SETGE: 3880 return UseSPE ? PPC::PRED_LE : PPC::PRED_GE; 3881 case ISD::SETO: return PPC::PRED_NU; 3882 case ISD::SETUO: return PPC::PRED_UN; 3883 // These two are invalid for floating point. Assume we have int. 3884 case ISD::SETULT: return PPC::PRED_LT; 3885 case ISD::SETUGT: return PPC::PRED_GT; 3886 } 3887 } 3888 3889 /// getCRIdxForSetCC - Return the index of the condition register field 3890 /// associated with the SetCC condition, and whether or not the field is 3891 /// treated as inverted. That is, lt = 0; ge = 0 inverted. 3892 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) { 3893 Invert = false; 3894 switch (CC) { 3895 default: llvm_unreachable("Unknown condition!"); 3896 case ISD::SETOLT: 3897 case ISD::SETLT: return 0; // Bit #0 = SETOLT 3898 case ISD::SETOGT: 3899 case ISD::SETGT: return 1; // Bit #1 = SETOGT 3900 case ISD::SETOEQ: 3901 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ 3902 case ISD::SETUO: return 3; // Bit #3 = SETUO 3903 case ISD::SETUGE: 3904 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE 3905 case ISD::SETULE: 3906 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE 3907 case ISD::SETUNE: 3908 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE 3909 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO 3910 case ISD::SETUEQ: 3911 case ISD::SETOGE: 3912 case ISD::SETOLE: 3913 case ISD::SETONE: 3914 llvm_unreachable("Invalid branch code: should be expanded by legalize"); 3915 // These are invalid for floating point. Assume integer. 3916 case ISD::SETULT: return 0; 3917 case ISD::SETUGT: return 1; 3918 } 3919 } 3920 3921 // getVCmpInst: return the vector compare instruction for the specified 3922 // vector type and condition code. Since this is for altivec specific code, 3923 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, v1i128, 3924 // and v4f32). 3925 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC, 3926 bool HasVSX, bool &Swap, bool &Negate) { 3927 Swap = false; 3928 Negate = false; 3929 3930 if (VecVT.isFloatingPoint()) { 3931 /* Handle some cases by swapping input operands. */ 3932 switch (CC) { 3933 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break; 3934 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break; 3935 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break; 3936 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break; 3937 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break; 3938 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break; 3939 default: break; 3940 } 3941 /* Handle some cases by negating the result. */ 3942 switch (CC) { 3943 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break; 3944 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break; 3945 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break; 3946 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break; 3947 default: break; 3948 } 3949 /* We have instructions implementing the remaining cases. */ 3950 switch (CC) { 3951 case ISD::SETEQ: 3952 case ISD::SETOEQ: 3953 if (VecVT == MVT::v4f32) 3954 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP; 3955 else if (VecVT == MVT::v2f64) 3956 return PPC::XVCMPEQDP; 3957 break; 3958 case ISD::SETGT: 3959 case ISD::SETOGT: 3960 if (VecVT == MVT::v4f32) 3961 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP; 3962 else if (VecVT == MVT::v2f64) 3963 return PPC::XVCMPGTDP; 3964 break; 3965 case ISD::SETGE: 3966 case ISD::SETOGE: 3967 if (VecVT == MVT::v4f32) 3968 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP; 3969 else if (VecVT == MVT::v2f64) 3970 return PPC::XVCMPGEDP; 3971 break; 3972 default: 3973 break; 3974 } 3975 llvm_unreachable("Invalid floating-point vector compare condition"); 3976 } else { 3977 /* Handle some cases by swapping input operands. */ 3978 switch (CC) { 3979 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break; 3980 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break; 3981 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break; 3982 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break; 3983 default: break; 3984 } 3985 /* Handle some cases by negating the result. */ 3986 switch (CC) { 3987 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break; 3988 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break; 3989 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break; 3990 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break; 3991 default: break; 3992 } 3993 /* We have instructions implementing the remaining cases. */ 3994 switch (CC) { 3995 case ISD::SETEQ: 3996 case ISD::SETUEQ: 3997 if (VecVT == MVT::v16i8) 3998 return PPC::VCMPEQUB; 3999 else if (VecVT == MVT::v8i16) 4000 return PPC::VCMPEQUH; 4001 else if (VecVT == MVT::v4i32) 4002 return PPC::VCMPEQUW; 4003 else if (VecVT == MVT::v2i64) 4004 return PPC::VCMPEQUD; 4005 else if (VecVT == MVT::v1i128) 4006 return PPC::VCMPEQUQ; 4007 break; 4008 case ISD::SETGT: 4009 if (VecVT == MVT::v16i8) 4010 return PPC::VCMPGTSB; 4011 else if (VecVT == MVT::v8i16) 4012 return PPC::VCMPGTSH; 4013 else if (VecVT == MVT::v4i32) 4014 return PPC::VCMPGTSW; 4015 else if (VecVT == MVT::v2i64) 4016 return PPC::VCMPGTSD; 4017 else if (VecVT == MVT::v1i128) 4018 return PPC::VCMPGTSQ; 4019 break; 4020 case ISD::SETUGT: 4021 if (VecVT == MVT::v16i8) 4022 return PPC::VCMPGTUB; 4023 else if (VecVT == MVT::v8i16) 4024 return PPC::VCMPGTUH; 4025 else if (VecVT == MVT::v4i32) 4026 return PPC::VCMPGTUW; 4027 else if (VecVT == MVT::v2i64) 4028 return PPC::VCMPGTUD; 4029 else if (VecVT == MVT::v1i128) 4030 return PPC::VCMPGTUQ; 4031 break; 4032 default: 4033 break; 4034 } 4035 llvm_unreachable("Invalid integer vector compare condition"); 4036 } 4037 } 4038 4039 bool PPCDAGToDAGISel::trySETCC(SDNode *N) { 4040 SDLoc dl(N); 4041 unsigned Imm; 4042 bool IsStrict = N->isStrictFPOpcode(); 4043 ISD::CondCode CC = 4044 cast<CondCodeSDNode>(N->getOperand(IsStrict ? 3 : 2))->get(); 4045 EVT PtrVT = 4046 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout()); 4047 bool isPPC64 = (PtrVT == MVT::i64); 4048 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 4049 4050 SDValue LHS = N->getOperand(IsStrict ? 1 : 0); 4051 SDValue RHS = N->getOperand(IsStrict ? 2 : 1); 4052 4053 if (!IsStrict && !Subtarget->useCRBits() && isInt32Immediate(RHS, Imm)) { 4054 // We can codegen setcc op, imm very efficiently compared to a brcond. 4055 // Check for those cases here. 4056 // setcc op, 0 4057 if (Imm == 0) { 4058 SDValue Op = LHS; 4059 switch (CC) { 4060 default: break; 4061 case ISD::SETEQ: { 4062 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0); 4063 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl), 4064 getI32Imm(31, dl) }; 4065 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4066 return true; 4067 } 4068 case ISD::SETNE: { 4069 if (isPPC64) break; 4070 SDValue AD = 4071 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 4072 Op, getI32Imm(~0U, dl)), 0); 4073 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1)); 4074 return true; 4075 } 4076 case ISD::SETLT: { 4077 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl), 4078 getI32Imm(31, dl) }; 4079 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4080 return true; 4081 } 4082 case ISD::SETGT: { 4083 SDValue T = 4084 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0); 4085 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0); 4086 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl), 4087 getI32Imm(31, dl) }; 4088 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4089 return true; 4090 } 4091 } 4092 } else if (Imm == ~0U) { // setcc op, -1 4093 SDValue Op = LHS; 4094 switch (CC) { 4095 default: break; 4096 case ISD::SETEQ: 4097 if (isPPC64) break; 4098 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 4099 Op, getI32Imm(1, dl)), 0); 4100 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 4101 SDValue(CurDAG->getMachineNode(PPC::LI, dl, 4102 MVT::i32, 4103 getI32Imm(0, dl)), 4104 0), Op.getValue(1)); 4105 return true; 4106 case ISD::SETNE: { 4107 if (isPPC64) break; 4108 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0); 4109 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 4110 Op, getI32Imm(~0U, dl)); 4111 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op, 4112 SDValue(AD, 1)); 4113 return true; 4114 } 4115 case ISD::SETLT: { 4116 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op, 4117 getI32Imm(1, dl)), 0); 4118 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD, 4119 Op), 0); 4120 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl), 4121 getI32Imm(31, dl) }; 4122 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4123 return true; 4124 } 4125 case ISD::SETGT: { 4126 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl), 4127 getI32Imm(31, dl) }; 4128 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 4129 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl)); 4130 return true; 4131 } 4132 } 4133 } 4134 } 4135 4136 // Altivec Vector compare instructions do not set any CR register by default and 4137 // vector compare operations return the same type as the operands. 4138 if (!IsStrict && LHS.getValueType().isVector()) { 4139 if (Subtarget->hasSPE()) 4140 return false; 4141 4142 EVT VecVT = LHS.getValueType(); 4143 bool Swap, Negate; 4144 unsigned int VCmpInst = 4145 getVCmpInst(VecVT.getSimpleVT(), CC, Subtarget->hasVSX(), Swap, Negate); 4146 if (Swap) 4147 std::swap(LHS, RHS); 4148 4149 EVT ResVT = VecVT.changeVectorElementTypeToInteger(); 4150 if (Negate) { 4151 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0); 4152 CurDAG->SelectNodeTo(N, Subtarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR, 4153 ResVT, VCmp, VCmp); 4154 return true; 4155 } 4156 4157 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS); 4158 return true; 4159 } 4160 4161 if (Subtarget->useCRBits()) 4162 return false; 4163 4164 bool Inv; 4165 unsigned Idx = getCRIdxForSetCC(CC, Inv); 4166 SDValue CCReg = SelectCC(LHS, RHS, CC, dl, Chain); 4167 if (IsStrict) 4168 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), CCReg.getValue(1)); 4169 SDValue IntCR; 4170 4171 // SPE e*cmp* instructions only set the 'gt' bit, so hard-code that 4172 // The correct compare instruction is already set by SelectCC() 4173 if (Subtarget->hasSPE() && LHS.getValueType().isFloatingPoint()) { 4174 Idx = 1; 4175 } 4176 4177 // Force the ccreg into CR7. 4178 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32); 4179 4180 SDValue InFlag(nullptr, 0); // Null incoming flag value. 4181 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg, 4182 InFlag).getValue(1); 4183 4184 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg, 4185 CCReg), 0); 4186 4187 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl), 4188 getI32Imm(31, dl), getI32Imm(31, dl) }; 4189 if (!Inv) { 4190 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4191 return true; 4192 } 4193 4194 // Get the specified bit. 4195 SDValue Tmp = 4196 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 4197 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl)); 4198 return true; 4199 } 4200 4201 /// Does this node represent a load/store node whose address can be represented 4202 /// with a register plus an immediate that's a multiple of \p Val: 4203 bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const { 4204 LoadSDNode *LDN = dyn_cast<LoadSDNode>(N); 4205 StoreSDNode *STN = dyn_cast<StoreSDNode>(N); 4206 SDValue AddrOp; 4207 if (LDN) 4208 AddrOp = LDN->getOperand(1); 4209 else if (STN) 4210 AddrOp = STN->getOperand(2); 4211 4212 // If the address points a frame object or a frame object with an offset, 4213 // we need to check the object alignment. 4214 short Imm = 0; 4215 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>( 4216 AddrOp.getOpcode() == ISD::ADD ? AddrOp.getOperand(0) : 4217 AddrOp)) { 4218 // If op0 is a frame index that is under aligned, we can't do it either, 4219 // because it is translated to r31 or r1 + slot + offset. We won't know the 4220 // slot number until the stack frame is finalized. 4221 const MachineFrameInfo &MFI = CurDAG->getMachineFunction().getFrameInfo(); 4222 unsigned SlotAlign = MFI.getObjectAlign(FI->getIndex()).value(); 4223 if ((SlotAlign % Val) != 0) 4224 return false; 4225 4226 // If we have an offset, we need further check on the offset. 4227 if (AddrOp.getOpcode() != ISD::ADD) 4228 return true; 4229 } 4230 4231 if (AddrOp.getOpcode() == ISD::ADD) 4232 return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val); 4233 4234 // If the address comes from the outside, the offset will be zero. 4235 return AddrOp.getOpcode() == ISD::CopyFromReg; 4236 } 4237 4238 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) { 4239 // Transfer memoperands. 4240 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 4241 CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp}); 4242 } 4243 4244 static bool mayUseP9Setb(SDNode *N, const ISD::CondCode &CC, SelectionDAG *DAG, 4245 bool &NeedSwapOps, bool &IsUnCmp) { 4246 4247 assert(N->getOpcode() == ISD::SELECT_CC && "Expecting a SELECT_CC here."); 4248 4249 SDValue LHS = N->getOperand(0); 4250 SDValue RHS = N->getOperand(1); 4251 SDValue TrueRes = N->getOperand(2); 4252 SDValue FalseRes = N->getOperand(3); 4253 ConstantSDNode *TrueConst = dyn_cast<ConstantSDNode>(TrueRes); 4254 if (!TrueConst || (N->getSimpleValueType(0) != MVT::i64 && 4255 N->getSimpleValueType(0) != MVT::i32)) 4256 return false; 4257 4258 // We are looking for any of: 4259 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, cc2)), cc1) 4260 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, cc2)), cc1) 4261 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, 1, -1, cc2), seteq) 4262 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, -1, 1, cc2), seteq) 4263 int64_t TrueResVal = TrueConst->getSExtValue(); 4264 if ((TrueResVal < -1 || TrueResVal > 1) || 4265 (TrueResVal == -1 && FalseRes.getOpcode() != ISD::ZERO_EXTEND) || 4266 (TrueResVal == 1 && FalseRes.getOpcode() != ISD::SIGN_EXTEND) || 4267 (TrueResVal == 0 && 4268 (FalseRes.getOpcode() != ISD::SELECT_CC || CC != ISD::SETEQ))) 4269 return false; 4270 4271 SDValue SetOrSelCC = FalseRes.getOpcode() == ISD::SELECT_CC 4272 ? FalseRes 4273 : FalseRes.getOperand(0); 4274 bool InnerIsSel = SetOrSelCC.getOpcode() == ISD::SELECT_CC; 4275 if (SetOrSelCC.getOpcode() != ISD::SETCC && 4276 SetOrSelCC.getOpcode() != ISD::SELECT_CC) 4277 return false; 4278 4279 // Without this setb optimization, the outer SELECT_CC will be manually 4280 // selected to SELECT_CC_I4/SELECT_CC_I8 Pseudo, then expand-isel-pseudos pass 4281 // transforms pseudo instruction to isel instruction. When there are more than 4282 // one use for result like zext/sext, with current optimization we only see 4283 // isel is replaced by setb but can't see any significant gain. Since 4284 // setb has longer latency than original isel, we should avoid this. Another 4285 // point is that setb requires comparison always kept, it can break the 4286 // opportunity to get the comparison away if we have in future. 4287 if (!SetOrSelCC.hasOneUse() || (!InnerIsSel && !FalseRes.hasOneUse())) 4288 return false; 4289 4290 SDValue InnerLHS = SetOrSelCC.getOperand(0); 4291 SDValue InnerRHS = SetOrSelCC.getOperand(1); 4292 ISD::CondCode InnerCC = 4293 cast<CondCodeSDNode>(SetOrSelCC.getOperand(InnerIsSel ? 4 : 2))->get(); 4294 // If the inner comparison is a select_cc, make sure the true/false values are 4295 // 1/-1 and canonicalize it if needed. 4296 if (InnerIsSel) { 4297 ConstantSDNode *SelCCTrueConst = 4298 dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(2)); 4299 ConstantSDNode *SelCCFalseConst = 4300 dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(3)); 4301 if (!SelCCTrueConst || !SelCCFalseConst) 4302 return false; 4303 int64_t SelCCTVal = SelCCTrueConst->getSExtValue(); 4304 int64_t SelCCFVal = SelCCFalseConst->getSExtValue(); 4305 // The values must be -1/1 (requiring a swap) or 1/-1. 4306 if (SelCCTVal == -1 && SelCCFVal == 1) { 4307 std::swap(InnerLHS, InnerRHS); 4308 } else if (SelCCTVal != 1 || SelCCFVal != -1) 4309 return false; 4310 } 4311 4312 // Canonicalize unsigned case 4313 if (InnerCC == ISD::SETULT || InnerCC == ISD::SETUGT) { 4314 IsUnCmp = true; 4315 InnerCC = (InnerCC == ISD::SETULT) ? ISD::SETLT : ISD::SETGT; 4316 } 4317 4318 bool InnerSwapped = false; 4319 if (LHS == InnerRHS && RHS == InnerLHS) 4320 InnerSwapped = true; 4321 else if (LHS != InnerLHS || RHS != InnerRHS) 4322 return false; 4323 4324 switch (CC) { 4325 // (select_cc lhs, rhs, 0, \ 4326 // (select_cc [lr]hs, [lr]hs, 1, -1, setlt/setgt), seteq) 4327 case ISD::SETEQ: 4328 if (!InnerIsSel) 4329 return false; 4330 if (InnerCC != ISD::SETLT && InnerCC != ISD::SETGT) 4331 return false; 4332 NeedSwapOps = (InnerCC == ISD::SETGT) ? InnerSwapped : !InnerSwapped; 4333 break; 4334 4335 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?lt) 4336 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setgt)), setu?lt) 4337 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setlt)), setu?lt) 4338 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?lt) 4339 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setgt)), setu?lt) 4340 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setlt)), setu?lt) 4341 case ISD::SETULT: 4342 if (!IsUnCmp && InnerCC != ISD::SETNE) 4343 return false; 4344 IsUnCmp = true; 4345 LLVM_FALLTHROUGH; 4346 case ISD::SETLT: 4347 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETGT && !InnerSwapped) || 4348 (InnerCC == ISD::SETLT && InnerSwapped)) 4349 NeedSwapOps = (TrueResVal == 1); 4350 else 4351 return false; 4352 break; 4353 4354 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?gt) 4355 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setlt)), setu?gt) 4356 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setgt)), setu?gt) 4357 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?gt) 4358 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setlt)), setu?gt) 4359 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setgt)), setu?gt) 4360 case ISD::SETUGT: 4361 if (!IsUnCmp && InnerCC != ISD::SETNE) 4362 return false; 4363 IsUnCmp = true; 4364 LLVM_FALLTHROUGH; 4365 case ISD::SETGT: 4366 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETLT && !InnerSwapped) || 4367 (InnerCC == ISD::SETGT && InnerSwapped)) 4368 NeedSwapOps = (TrueResVal == -1); 4369 else 4370 return false; 4371 break; 4372 4373 default: 4374 return false; 4375 } 4376 4377 LLVM_DEBUG(dbgs() << "Found a node that can be lowered to a SETB: "); 4378 LLVM_DEBUG(N->dump()); 4379 4380 return true; 4381 } 4382 4383 bool PPCDAGToDAGISel::tryAsSingleRLWINM(SDNode *N) { 4384 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected"); 4385 unsigned Imm; 4386 if (!isInt32Immediate(N->getOperand(1), Imm)) 4387 return false; 4388 4389 SDLoc dl(N); 4390 SDValue Val = N->getOperand(0); 4391 unsigned SH, MB, ME; 4392 // If this is an and of a value rotated between 0 and 31 bits and then and'd 4393 // with a mask, emit rlwinm 4394 if (isRotateAndMask(Val.getNode(), Imm, false, SH, MB, ME)) { 4395 Val = Val.getOperand(0); 4396 SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl), 4397 getI32Imm(ME, dl)}; 4398 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4399 return true; 4400 } 4401 4402 // If this is just a masked value where the input is not handled, and 4403 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm 4404 if (isRunOfOnes(Imm, MB, ME) && Val.getOpcode() != ISD::ROTL) { 4405 SDValue Ops[] = {Val, getI32Imm(0, dl), getI32Imm(MB, dl), 4406 getI32Imm(ME, dl)}; 4407 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4408 return true; 4409 } 4410 4411 // AND X, 0 -> 0, not "rlwinm 32". 4412 if (Imm == 0) { 4413 ReplaceUses(SDValue(N, 0), N->getOperand(1)); 4414 return true; 4415 } 4416 4417 return false; 4418 } 4419 4420 bool PPCDAGToDAGISel::tryAsSingleRLWINM8(SDNode *N) { 4421 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected"); 4422 uint64_t Imm64; 4423 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64)) 4424 return false; 4425 4426 unsigned MB, ME; 4427 if (isRunOfOnes64(Imm64, MB, ME) && MB >= 32 && MB <= ME) { 4428 // MB ME 4429 // +----------------------+ 4430 // |xxxxxxxxxxx00011111000| 4431 // +----------------------+ 4432 // 0 32 64 4433 // We can only do it if the MB is larger than 32 and MB <= ME 4434 // as RLWINM will replace the contents of [0 - 32) with [32 - 64) even 4435 // we didn't rotate it. 4436 SDLoc dl(N); 4437 SDValue Ops[] = {N->getOperand(0), getI64Imm(0, dl), getI64Imm(MB - 32, dl), 4438 getI64Imm(ME - 32, dl)}; 4439 CurDAG->SelectNodeTo(N, PPC::RLWINM8, MVT::i64, Ops); 4440 return true; 4441 } 4442 4443 return false; 4444 } 4445 4446 bool PPCDAGToDAGISel::tryAsPairOfRLDICL(SDNode *N) { 4447 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected"); 4448 uint64_t Imm64; 4449 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64)) 4450 return false; 4451 4452 // Do nothing if it is 16-bit imm as the pattern in the .td file handle 4453 // it well with "andi.". 4454 if (isUInt<16>(Imm64)) 4455 return false; 4456 4457 SDLoc Loc(N); 4458 SDValue Val = N->getOperand(0); 4459 4460 // Optimized with two rldicl's as follows: 4461 // Add missing bits on left to the mask and check that the mask is a 4462 // wrapped run of ones, i.e. 4463 // Change pattern |0001111100000011111111| 4464 // to |1111111100000011111111|. 4465 unsigned NumOfLeadingZeros = countLeadingZeros(Imm64); 4466 if (NumOfLeadingZeros != 0) 4467 Imm64 |= maskLeadingOnes<uint64_t>(NumOfLeadingZeros); 4468 4469 unsigned MB, ME; 4470 if (!isRunOfOnes64(Imm64, MB, ME)) 4471 return false; 4472 4473 // ME MB MB-ME+63 4474 // +----------------------+ +----------------------+ 4475 // |1111111100000011111111| -> |0000001111111111111111| 4476 // +----------------------+ +----------------------+ 4477 // 0 63 0 63 4478 // There are ME + 1 ones on the left and (MB - ME + 63) & 63 zeros in between. 4479 unsigned OnesOnLeft = ME + 1; 4480 unsigned ZerosInBetween = (MB - ME + 63) & 63; 4481 // Rotate left by OnesOnLeft (so leading ones are now trailing ones) and clear 4482 // on the left the bits that are already zeros in the mask. 4483 Val = SDValue(CurDAG->getMachineNode(PPC::RLDICL, Loc, MVT::i64, Val, 4484 getI64Imm(OnesOnLeft, Loc), 4485 getI64Imm(ZerosInBetween, Loc)), 4486 0); 4487 // MB-ME+63 ME MB 4488 // +----------------------+ +----------------------+ 4489 // |0000001111111111111111| -> |0001111100000011111111| 4490 // +----------------------+ +----------------------+ 4491 // 0 63 0 63 4492 // Rotate back by 64 - OnesOnLeft to undo previous rotate. Then clear on the 4493 // left the number of ones we previously added. 4494 SDValue Ops[] = {Val, getI64Imm(64 - OnesOnLeft, Loc), 4495 getI64Imm(NumOfLeadingZeros, Loc)}; 4496 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops); 4497 return true; 4498 } 4499 4500 bool PPCDAGToDAGISel::tryAsSingleRLWIMI(SDNode *N) { 4501 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected"); 4502 unsigned Imm; 4503 if (!isInt32Immediate(N->getOperand(1), Imm)) 4504 return false; 4505 4506 SDValue Val = N->getOperand(0); 4507 unsigned Imm2; 4508 // ISD::OR doesn't get all the bitfield insertion fun. 4509 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a 4510 // bitfield insert. 4511 if (Val.getOpcode() != ISD::OR || !isInt32Immediate(Val.getOperand(1), Imm2)) 4512 return false; 4513 4514 // The idea here is to check whether this is equivalent to: 4515 // (c1 & m) | (x & ~m) 4516 // where m is a run-of-ones mask. The logic here is that, for each bit in 4517 // c1 and c2: 4518 // - if both are 1, then the output will be 1. 4519 // - if both are 0, then the output will be 0. 4520 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will 4521 // come from x. 4522 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will 4523 // be 0. 4524 // If that last condition is never the case, then we can form m from the 4525 // bits that are the same between c1 and c2. 4526 unsigned MB, ME; 4527 if (isRunOfOnes(~(Imm ^ Imm2), MB, ME) && !(~Imm & Imm2)) { 4528 SDLoc dl(N); 4529 SDValue Ops[] = {Val.getOperand(0), Val.getOperand(1), getI32Imm(0, dl), 4530 getI32Imm(MB, dl), getI32Imm(ME, dl)}; 4531 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops)); 4532 return true; 4533 } 4534 4535 return false; 4536 } 4537 4538 bool PPCDAGToDAGISel::tryAsSingleRLDICL(SDNode *N) { 4539 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected"); 4540 uint64_t Imm64; 4541 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) || !isMask_64(Imm64)) 4542 return false; 4543 4544 // If this is a 64-bit zero-extension mask, emit rldicl. 4545 unsigned MB = 64 - countTrailingOnes(Imm64); 4546 unsigned SH = 0; 4547 unsigned Imm; 4548 SDValue Val = N->getOperand(0); 4549 SDLoc dl(N); 4550 4551 if (Val.getOpcode() == ISD::ANY_EXTEND) { 4552 auto Op0 = Val.getOperand(0); 4553 if (Op0.getOpcode() == ISD::SRL && 4554 isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) { 4555 4556 auto ResultType = Val.getNode()->getValueType(0); 4557 auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, ResultType); 4558 SDValue IDVal(ImDef, 0); 4559 4560 Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, ResultType, 4561 IDVal, Op0.getOperand(0), 4562 getI32Imm(1, dl)), 4563 0); 4564 SH = 64 - Imm; 4565 } 4566 } 4567 4568 // If the operand is a logical right shift, we can fold it into this 4569 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb) 4570 // for n <= mb. The right shift is really a left rotate followed by a 4571 // mask, and this mask is a more-restrictive sub-mask of the mask implied 4572 // by the shift. 4573 if (Val.getOpcode() == ISD::SRL && 4574 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) { 4575 assert(Imm < 64 && "Illegal shift amount"); 4576 Val = Val.getOperand(0); 4577 SH = 64 - Imm; 4578 } 4579 4580 SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl)}; 4581 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops); 4582 return true; 4583 } 4584 4585 bool PPCDAGToDAGISel::tryAsSingleRLDICR(SDNode *N) { 4586 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected"); 4587 uint64_t Imm64; 4588 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) || 4589 !isMask_64(~Imm64)) 4590 return false; 4591 4592 // If this is a negated 64-bit zero-extension mask, 4593 // i.e. the immediate is a sequence of ones from most significant side 4594 // and all zero for reminder, we should use rldicr. 4595 unsigned MB = 63 - countTrailingOnes(~Imm64); 4596 unsigned SH = 0; 4597 SDLoc dl(N); 4598 SDValue Ops[] = {N->getOperand(0), getI32Imm(SH, dl), getI32Imm(MB, dl)}; 4599 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops); 4600 return true; 4601 } 4602 4603 bool PPCDAGToDAGISel::tryAsSingleRLDIMI(SDNode *N) { 4604 assert(N->getOpcode() == ISD::OR && "ISD::OR SDNode expected"); 4605 uint64_t Imm64; 4606 unsigned MB, ME; 4607 SDValue N0 = N->getOperand(0); 4608 4609 // We won't get fewer instructions if the imm is 32-bit integer. 4610 // rldimi requires the imm to have consecutive ones with both sides zero. 4611 // Also, make sure the first Op has only one use, otherwise this may increase 4612 // register pressure since rldimi is destructive. 4613 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) || 4614 isUInt<32>(Imm64) || !isRunOfOnes64(Imm64, MB, ME) || !N0.hasOneUse()) 4615 return false; 4616 4617 unsigned SH = 63 - ME; 4618 SDLoc Dl(N); 4619 // Use select64Imm for making LI instr instead of directly putting Imm64 4620 SDValue Ops[] = { 4621 N->getOperand(0), 4622 SDValue(selectI64Imm(CurDAG, getI64Imm(-1, Dl).getNode()), 0), 4623 getI32Imm(SH, Dl), getI32Imm(MB, Dl)}; 4624 CurDAG->SelectNodeTo(N, PPC::RLDIMI, MVT::i64, Ops); 4625 return true; 4626 } 4627 4628 // Select - Convert the specified operand from a target-independent to a 4629 // target-specific node if it hasn't already been changed. 4630 void PPCDAGToDAGISel::Select(SDNode *N) { 4631 SDLoc dl(N); 4632 if (N->isMachineOpcode()) { 4633 N->setNodeId(-1); 4634 return; // Already selected. 4635 } 4636 4637 // In case any misguided DAG-level optimizations form an ADD with a 4638 // TargetConstant operand, crash here instead of miscompiling (by selecting 4639 // an r+r add instead of some kind of r+i add). 4640 if (N->getOpcode() == ISD::ADD && 4641 N->getOperand(1).getOpcode() == ISD::TargetConstant) 4642 llvm_unreachable("Invalid ADD with TargetConstant operand"); 4643 4644 // Try matching complex bit permutations before doing anything else. 4645 if (tryBitPermutation(N)) 4646 return; 4647 4648 // Try to emit integer compares as GPR-only sequences (i.e. no use of CR). 4649 if (tryIntCompareInGPR(N)) 4650 return; 4651 4652 switch (N->getOpcode()) { 4653 default: break; 4654 4655 case ISD::Constant: 4656 if (N->getValueType(0) == MVT::i64) { 4657 ReplaceNode(N, selectI64Imm(CurDAG, N)); 4658 return; 4659 } 4660 break; 4661 4662 case ISD::INTRINSIC_WO_CHAIN: { 4663 if (!Subtarget->isISA3_1()) 4664 break; 4665 unsigned Opcode = 0; 4666 switch (N->getConstantOperandVal(0)) { 4667 default: 4668 break; 4669 case Intrinsic::ppc_altivec_vstribr_p: 4670 Opcode = PPC::VSTRIBR_rec; 4671 break; 4672 case Intrinsic::ppc_altivec_vstribl_p: 4673 Opcode = PPC::VSTRIBL_rec; 4674 break; 4675 case Intrinsic::ppc_altivec_vstrihr_p: 4676 Opcode = PPC::VSTRIHR_rec; 4677 break; 4678 case Intrinsic::ppc_altivec_vstrihl_p: 4679 Opcode = PPC::VSTRIHL_rec; 4680 break; 4681 } 4682 if (!Opcode) 4683 break; 4684 4685 // Generate the appropriate vector string isolate intrinsic to match. 4686 EVT VTs[] = {MVT::v16i8, MVT::Glue}; 4687 SDValue VecStrOp = 4688 SDValue(CurDAG->getMachineNode(Opcode, dl, VTs, N->getOperand(2)), 0); 4689 // Vector string isolate instructions update the EQ bit of CR6. 4690 // Generate a SETBC instruction to extract the bit and place it in a GPR. 4691 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_eq, dl, MVT::i32); 4692 SDValue CR6Reg = CurDAG->getRegister(PPC::CR6, MVT::i32); 4693 SDValue CRBit = SDValue( 4694 CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1, 4695 CR6Reg, SubRegIdx, VecStrOp.getValue(1)), 4696 0); 4697 CurDAG->SelectNodeTo(N, PPC::SETBC, MVT::i32, CRBit); 4698 return; 4699 } 4700 4701 case ISD::SETCC: 4702 case ISD::STRICT_FSETCC: 4703 case ISD::STRICT_FSETCCS: 4704 if (trySETCC(N)) 4705 return; 4706 break; 4707 // These nodes will be transformed into GETtlsADDR32 node, which 4708 // later becomes BL_TLS __tls_get_addr(sym at tlsgd)@PLT 4709 case PPCISD::ADDI_TLSLD_L_ADDR: 4710 case PPCISD::ADDI_TLSGD_L_ADDR: { 4711 const Module *Mod = MF->getFunction().getParent(); 4712 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 || 4713 !Subtarget->isSecurePlt() || !Subtarget->isTargetELF() || 4714 Mod->getPICLevel() == PICLevel::SmallPIC) 4715 break; 4716 // Attach global base pointer on GETtlsADDR32 node in order to 4717 // generate secure plt code for TLS symbols. 4718 getGlobalBaseReg(); 4719 } break; 4720 case PPCISD::CALL: { 4721 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 || 4722 !TM.isPositionIndependent() || !Subtarget->isSecurePlt() || 4723 !Subtarget->isTargetELF()) 4724 break; 4725 4726 SDValue Op = N->getOperand(1); 4727 4728 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 4729 if (GA->getTargetFlags() == PPCII::MO_PLT) 4730 getGlobalBaseReg(); 4731 } 4732 else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) { 4733 if (ES->getTargetFlags() == PPCII::MO_PLT) 4734 getGlobalBaseReg(); 4735 } 4736 } 4737 break; 4738 4739 case PPCISD::GlobalBaseReg: 4740 ReplaceNode(N, getGlobalBaseReg()); 4741 return; 4742 4743 case ISD::FrameIndex: 4744 selectFrameIndex(N, N); 4745 return; 4746 4747 case PPCISD::MFOCRF: { 4748 SDValue InFlag = N->getOperand(1); 4749 ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, 4750 N->getOperand(0), InFlag)); 4751 return; 4752 } 4753 4754 case PPCISD::READ_TIME_BASE: 4755 ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32, 4756 MVT::Other, N->getOperand(0))); 4757 return; 4758 4759 case PPCISD::SRA_ADDZE: { 4760 SDValue N0 = N->getOperand(0); 4761 SDValue ShiftAmt = 4762 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))-> 4763 getConstantIntValue(), dl, 4764 N->getValueType(0)); 4765 if (N->getValueType(0) == MVT::i64) { 4766 SDNode *Op = 4767 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue, 4768 N0, ShiftAmt); 4769 CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0), 4770 SDValue(Op, 1)); 4771 return; 4772 } else { 4773 assert(N->getValueType(0) == MVT::i32 && 4774 "Expecting i64 or i32 in PPCISD::SRA_ADDZE"); 4775 SDNode *Op = 4776 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue, 4777 N0, ShiftAmt); 4778 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0), 4779 SDValue(Op, 1)); 4780 return; 4781 } 4782 } 4783 4784 case ISD::STORE: { 4785 // Change TLS initial-exec D-form stores to X-form stores. 4786 StoreSDNode *ST = cast<StoreSDNode>(N); 4787 if (EnableTLSOpt && Subtarget->isELFv2ABI() && 4788 ST->getAddressingMode() != ISD::PRE_INC) 4789 if (tryTLSXFormStore(ST)) 4790 return; 4791 break; 4792 } 4793 case ISD::LOAD: { 4794 // Handle preincrement loads. 4795 LoadSDNode *LD = cast<LoadSDNode>(N); 4796 EVT LoadedVT = LD->getMemoryVT(); 4797 4798 // Normal loads are handled by code generated from the .td file. 4799 if (LD->getAddressingMode() != ISD::PRE_INC) { 4800 // Change TLS initial-exec D-form loads to X-form loads. 4801 if (EnableTLSOpt && Subtarget->isELFv2ABI()) 4802 if (tryTLSXFormLoad(LD)) 4803 return; 4804 break; 4805 } 4806 4807 SDValue Offset = LD->getOffset(); 4808 if (Offset.getOpcode() == ISD::TargetConstant || 4809 Offset.getOpcode() == ISD::TargetGlobalAddress) { 4810 4811 unsigned Opcode; 4812 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD; 4813 if (LD->getValueType(0) != MVT::i64) { 4814 // Handle PPC32 integer and normal FP loads. 4815 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 4816 switch (LoadedVT.getSimpleVT().SimpleTy) { 4817 default: llvm_unreachable("Invalid PPC load type!"); 4818 case MVT::f64: Opcode = PPC::LFDU; break; 4819 case MVT::f32: Opcode = PPC::LFSU; break; 4820 case MVT::i32: Opcode = PPC::LWZU; break; 4821 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break; 4822 case MVT::i1: 4823 case MVT::i8: Opcode = PPC::LBZU; break; 4824 } 4825 } else { 4826 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!"); 4827 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 4828 switch (LoadedVT.getSimpleVT().SimpleTy) { 4829 default: llvm_unreachable("Invalid PPC load type!"); 4830 case MVT::i64: Opcode = PPC::LDU; break; 4831 case MVT::i32: Opcode = PPC::LWZU8; break; 4832 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break; 4833 case MVT::i1: 4834 case MVT::i8: Opcode = PPC::LBZU8; break; 4835 } 4836 } 4837 4838 SDValue Chain = LD->getChain(); 4839 SDValue Base = LD->getBasePtr(); 4840 SDValue Ops[] = { Offset, Base, Chain }; 4841 SDNode *MN = CurDAG->getMachineNode( 4842 Opcode, dl, LD->getValueType(0), 4843 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops); 4844 transferMemOperands(N, MN); 4845 ReplaceNode(N, MN); 4846 return; 4847 } else { 4848 unsigned Opcode; 4849 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD; 4850 if (LD->getValueType(0) != MVT::i64) { 4851 // Handle PPC32 integer and normal FP loads. 4852 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 4853 switch (LoadedVT.getSimpleVT().SimpleTy) { 4854 default: llvm_unreachable("Invalid PPC load type!"); 4855 case MVT::f64: Opcode = PPC::LFDUX; break; 4856 case MVT::f32: Opcode = PPC::LFSUX; break; 4857 case MVT::i32: Opcode = PPC::LWZUX; break; 4858 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break; 4859 case MVT::i1: 4860 case MVT::i8: Opcode = PPC::LBZUX; break; 4861 } 4862 } else { 4863 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!"); 4864 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) && 4865 "Invalid sext update load"); 4866 switch (LoadedVT.getSimpleVT().SimpleTy) { 4867 default: llvm_unreachable("Invalid PPC load type!"); 4868 case MVT::i64: Opcode = PPC::LDUX; break; 4869 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break; 4870 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break; 4871 case MVT::i1: 4872 case MVT::i8: Opcode = PPC::LBZUX8; break; 4873 } 4874 } 4875 4876 SDValue Chain = LD->getChain(); 4877 SDValue Base = LD->getBasePtr(); 4878 SDValue Ops[] = { Base, Offset, Chain }; 4879 SDNode *MN = CurDAG->getMachineNode( 4880 Opcode, dl, LD->getValueType(0), 4881 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops); 4882 transferMemOperands(N, MN); 4883 ReplaceNode(N, MN); 4884 return; 4885 } 4886 } 4887 4888 case ISD::AND: 4889 // If this is an 'and' with a mask, try to emit rlwinm/rldicl/rldicr 4890 if (tryAsSingleRLWINM(N) || tryAsSingleRLWIMI(N) || tryAsSingleRLDICL(N) || 4891 tryAsSingleRLDICR(N) || tryAsSingleRLWINM8(N) || tryAsPairOfRLDICL(N)) 4892 return; 4893 4894 // Other cases are autogenerated. 4895 break; 4896 case ISD::OR: { 4897 if (N->getValueType(0) == MVT::i32) 4898 if (tryBitfieldInsert(N)) 4899 return; 4900 4901 int16_t Imm; 4902 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex && 4903 isIntS16Immediate(N->getOperand(1), Imm)) { 4904 KnownBits LHSKnown = CurDAG->computeKnownBits(N->getOperand(0)); 4905 4906 // If this is equivalent to an add, then we can fold it with the 4907 // FrameIndex calculation. 4908 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) { 4909 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm); 4910 return; 4911 } 4912 } 4913 4914 // If this is 'or' against an imm with consecutive ones and both sides zero, 4915 // try to emit rldimi 4916 if (tryAsSingleRLDIMI(N)) 4917 return; 4918 4919 // OR with a 32-bit immediate can be handled by ori + oris 4920 // without creating an immediate in a GPR. 4921 uint64_t Imm64 = 0; 4922 bool IsPPC64 = Subtarget->isPPC64(); 4923 if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) && 4924 (Imm64 & ~0xFFFFFFFFuLL) == 0) { 4925 // If ImmHi (ImmHi) is zero, only one ori (oris) is generated later. 4926 uint64_t ImmHi = Imm64 >> 16; 4927 uint64_t ImmLo = Imm64 & 0xFFFF; 4928 if (ImmHi != 0 && ImmLo != 0) { 4929 SDNode *Lo = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, 4930 N->getOperand(0), 4931 getI16Imm(ImmLo, dl)); 4932 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)}; 4933 CurDAG->SelectNodeTo(N, PPC::ORIS8, MVT::i64, Ops1); 4934 return; 4935 } 4936 } 4937 4938 // Other cases are autogenerated. 4939 break; 4940 } 4941 case ISD::XOR: { 4942 // XOR with a 32-bit immediate can be handled by xori + xoris 4943 // without creating an immediate in a GPR. 4944 uint64_t Imm64 = 0; 4945 bool IsPPC64 = Subtarget->isPPC64(); 4946 if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) && 4947 (Imm64 & ~0xFFFFFFFFuLL) == 0) { 4948 // If ImmHi (ImmHi) is zero, only one xori (xoris) is generated later. 4949 uint64_t ImmHi = Imm64 >> 16; 4950 uint64_t ImmLo = Imm64 & 0xFFFF; 4951 if (ImmHi != 0 && ImmLo != 0) { 4952 SDNode *Lo = CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, 4953 N->getOperand(0), 4954 getI16Imm(ImmLo, dl)); 4955 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)}; 4956 CurDAG->SelectNodeTo(N, PPC::XORIS8, MVT::i64, Ops1); 4957 return; 4958 } 4959 } 4960 4961 break; 4962 } 4963 case ISD::ADD: { 4964 int16_t Imm; 4965 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex && 4966 isIntS16Immediate(N->getOperand(1), Imm)) { 4967 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm); 4968 return; 4969 } 4970 4971 break; 4972 } 4973 case ISD::SHL: { 4974 unsigned Imm, SH, MB, ME; 4975 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) && 4976 isRotateAndMask(N, Imm, true, SH, MB, ME)) { 4977 SDValue Ops[] = { N->getOperand(0).getOperand(0), 4978 getI32Imm(SH, dl), getI32Imm(MB, dl), 4979 getI32Imm(ME, dl) }; 4980 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4981 return; 4982 } 4983 4984 // Other cases are autogenerated. 4985 break; 4986 } 4987 case ISD::SRL: { 4988 unsigned Imm, SH, MB, ME; 4989 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) && 4990 isRotateAndMask(N, Imm, true, SH, MB, ME)) { 4991 SDValue Ops[] = { N->getOperand(0).getOperand(0), 4992 getI32Imm(SH, dl), getI32Imm(MB, dl), 4993 getI32Imm(ME, dl) }; 4994 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4995 return; 4996 } 4997 4998 // Other cases are autogenerated. 4999 break; 5000 } 5001 case ISD::MUL: { 5002 SDValue Op1 = N->getOperand(1); 5003 if (Op1.getOpcode() != ISD::Constant || Op1.getValueType() != MVT::i64) 5004 break; 5005 5006 // If the multiplier fits int16, we can handle it with mulli. 5007 int64_t Imm = cast<ConstantSDNode>(Op1)->getZExtValue(); 5008 unsigned Shift = countTrailingZeros<uint64_t>(Imm); 5009 if (isInt<16>(Imm) || !Shift) 5010 break; 5011 5012 // If the shifted value fits int16, we can do this transformation: 5013 // (mul X, c1 << c2) -> (rldicr (mulli X, c1) c2). We do this in ISEL due to 5014 // DAGCombiner prefers (shl (mul X, c1), c2) -> (mul X, c1 << c2). 5015 uint64_t ImmSh = Imm >> Shift; 5016 if (isInt<16>(ImmSh)) { 5017 uint64_t SextImm = SignExtend64(ImmSh & 0xFFFF, 16); 5018 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64); 5019 SDNode *MulNode = CurDAG->getMachineNode(PPC::MULLI8, dl, MVT::i64, 5020 N->getOperand(0), SDImm); 5021 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, SDValue(MulNode, 0), 5022 getI32Imm(Shift, dl), getI32Imm(63 - Shift, dl)); 5023 return; 5024 } 5025 break; 5026 } 5027 // FIXME: Remove this once the ANDI glue bug is fixed: 5028 case PPCISD::ANDI_rec_1_EQ_BIT: 5029 case PPCISD::ANDI_rec_1_GT_BIT: { 5030 if (!ANDIGlueBug) 5031 break; 5032 5033 EVT InVT = N->getOperand(0).getValueType(); 5034 assert((InVT == MVT::i64 || InVT == MVT::i32) && 5035 "Invalid input type for ANDI_rec_1_EQ_BIT"); 5036 5037 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDI8_rec : PPC::ANDI_rec; 5038 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue, 5039 N->getOperand(0), 5040 CurDAG->getTargetConstant(1, dl, InVT)), 5041 0); 5042 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32); 5043 SDValue SRIdxVal = CurDAG->getTargetConstant( 5044 N->getOpcode() == PPCISD::ANDI_rec_1_EQ_BIT ? PPC::sub_eq : PPC::sub_gt, 5045 dl, MVT::i32); 5046 5047 CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg, 5048 SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */); 5049 return; 5050 } 5051 case ISD::SELECT_CC: { 5052 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 5053 EVT PtrVT = 5054 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout()); 5055 bool isPPC64 = (PtrVT == MVT::i64); 5056 5057 // If this is a select of i1 operands, we'll pattern match it. 5058 if (Subtarget->useCRBits() && N->getOperand(0).getValueType() == MVT::i1) 5059 break; 5060 5061 if (Subtarget->isISA3_0() && Subtarget->isPPC64()) { 5062 bool NeedSwapOps = false; 5063 bool IsUnCmp = false; 5064 if (mayUseP9Setb(N, CC, CurDAG, NeedSwapOps, IsUnCmp)) { 5065 SDValue LHS = N->getOperand(0); 5066 SDValue RHS = N->getOperand(1); 5067 if (NeedSwapOps) 5068 std::swap(LHS, RHS); 5069 5070 // Make use of SelectCC to generate the comparison to set CR bits, for 5071 // equality comparisons having one literal operand, SelectCC probably 5072 // doesn't need to materialize the whole literal and just use xoris to 5073 // check it first, it leads the following comparison result can't 5074 // exactly represent GT/LT relationship. So to avoid this we specify 5075 // SETGT/SETUGT here instead of SETEQ. 5076 SDValue GenCC = 5077 SelectCC(LHS, RHS, IsUnCmp ? ISD::SETUGT : ISD::SETGT, dl); 5078 CurDAG->SelectNodeTo( 5079 N, N->getSimpleValueType(0) == MVT::i64 ? PPC::SETB8 : PPC::SETB, 5080 N->getValueType(0), GenCC); 5081 NumP9Setb++; 5082 return; 5083 } 5084 } 5085 5086 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc 5087 if (!isPPC64) 5088 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1))) 5089 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2))) 5090 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3))) 5091 if (N1C->isNullValue() && N3C->isNullValue() && 5092 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE && 5093 // FIXME: Implement this optzn for PPC64. 5094 N->getValueType(0) == MVT::i32) { 5095 SDNode *Tmp = 5096 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 5097 N->getOperand(0), getI32Imm(~0U, dl)); 5098 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0), 5099 N->getOperand(0), SDValue(Tmp, 1)); 5100 return; 5101 } 5102 5103 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl); 5104 5105 if (N->getValueType(0) == MVT::i1) { 5106 // An i1 select is: (c & t) | (!c & f). 5107 bool Inv; 5108 unsigned Idx = getCRIdxForSetCC(CC, Inv); 5109 5110 unsigned SRI; 5111 switch (Idx) { 5112 default: llvm_unreachable("Invalid CC index"); 5113 case 0: SRI = PPC::sub_lt; break; 5114 case 1: SRI = PPC::sub_gt; break; 5115 case 2: SRI = PPC::sub_eq; break; 5116 case 3: SRI = PPC::sub_un; break; 5117 } 5118 5119 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg); 5120 5121 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1, 5122 CCBit, CCBit), 0); 5123 SDValue C = Inv ? NotCCBit : CCBit, 5124 NotC = Inv ? CCBit : NotCCBit; 5125 5126 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1, 5127 C, N->getOperand(2)), 0); 5128 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1, 5129 NotC, N->getOperand(3)), 0); 5130 5131 CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF); 5132 return; 5133 } 5134 5135 unsigned BROpc = 5136 getPredicateForSetCC(CC, N->getOperand(0).getValueType(), Subtarget); 5137 5138 unsigned SelectCCOp; 5139 if (N->getValueType(0) == MVT::i32) 5140 SelectCCOp = PPC::SELECT_CC_I4; 5141 else if (N->getValueType(0) == MVT::i64) 5142 SelectCCOp = PPC::SELECT_CC_I8; 5143 else if (N->getValueType(0) == MVT::f32) { 5144 if (Subtarget->hasP8Vector()) 5145 SelectCCOp = PPC::SELECT_CC_VSSRC; 5146 else if (Subtarget->hasSPE()) 5147 SelectCCOp = PPC::SELECT_CC_SPE4; 5148 else 5149 SelectCCOp = PPC::SELECT_CC_F4; 5150 } else if (N->getValueType(0) == MVT::f64) { 5151 if (Subtarget->hasVSX()) 5152 SelectCCOp = PPC::SELECT_CC_VSFRC; 5153 else if (Subtarget->hasSPE()) 5154 SelectCCOp = PPC::SELECT_CC_SPE; 5155 else 5156 SelectCCOp = PPC::SELECT_CC_F8; 5157 } else if (N->getValueType(0) == MVT::f128) 5158 SelectCCOp = PPC::SELECT_CC_F16; 5159 else if (Subtarget->hasSPE()) 5160 SelectCCOp = PPC::SELECT_CC_SPE; 5161 else if (N->getValueType(0) == MVT::v2f64 || 5162 N->getValueType(0) == MVT::v2i64) 5163 SelectCCOp = PPC::SELECT_CC_VSRC; 5164 else 5165 SelectCCOp = PPC::SELECT_CC_VRRC; 5166 5167 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3), 5168 getI32Imm(BROpc, dl) }; 5169 CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops); 5170 return; 5171 } 5172 case ISD::VECTOR_SHUFFLE: 5173 if (Subtarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 || 5174 N->getValueType(0) == MVT::v2i64)) { 5175 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 5176 5177 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1), 5178 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1); 5179 unsigned DM[2]; 5180 5181 for (int i = 0; i < 2; ++i) 5182 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2) 5183 DM[i] = 0; 5184 else 5185 DM[i] = 1; 5186 5187 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 && 5188 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR && 5189 isa<LoadSDNode>(Op1.getOperand(0))) { 5190 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0)); 5191 SDValue Base, Offset; 5192 5193 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() && 5194 (LD->getMemoryVT() == MVT::f64 || 5195 LD->getMemoryVT() == MVT::i64) && 5196 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) { 5197 SDValue Chain = LD->getChain(); 5198 SDValue Ops[] = { Base, Offset, Chain }; 5199 MachineMemOperand *MemOp = LD->getMemOperand(); 5200 SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX, 5201 N->getValueType(0), Ops); 5202 CurDAG->setNodeMemRefs(cast<MachineSDNode>(NewN), {MemOp}); 5203 return; 5204 } 5205 } 5206 5207 // For little endian, we must swap the input operands and adjust 5208 // the mask elements (reverse and invert them). 5209 if (Subtarget->isLittleEndian()) { 5210 std::swap(Op1, Op2); 5211 unsigned tmp = DM[0]; 5212 DM[0] = 1 - DM[1]; 5213 DM[1] = 1 - tmp; 5214 } 5215 5216 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl, 5217 MVT::i32); 5218 SDValue Ops[] = { Op1, Op2, DMV }; 5219 CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops); 5220 return; 5221 } 5222 5223 break; 5224 case PPCISD::BDNZ: 5225 case PPCISD::BDZ: { 5226 bool IsPPC64 = Subtarget->isPPC64(); 5227 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) }; 5228 CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ 5229 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) 5230 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ), 5231 MVT::Other, Ops); 5232 return; 5233 } 5234 case PPCISD::COND_BRANCH: { 5235 // Op #0 is the Chain. 5236 // Op #1 is the PPC::PRED_* number. 5237 // Op #2 is the CR# 5238 // Op #3 is the Dest MBB 5239 // Op #4 is the Flag. 5240 // Prevent PPC::PRED_* from being selected into LI. 5241 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 5242 if (EnableBranchHint) 5243 PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(3)); 5244 5245 SDValue Pred = getI32Imm(PCC, dl); 5246 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3), 5247 N->getOperand(0), N->getOperand(4) }; 5248 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops); 5249 return; 5250 } 5251 case ISD::BR_CC: { 5252 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 5253 unsigned PCC = 5254 getPredicateForSetCC(CC, N->getOperand(2).getValueType(), Subtarget); 5255 5256 if (N->getOperand(2).getValueType() == MVT::i1) { 5257 unsigned Opc; 5258 bool Swap; 5259 switch (PCC) { 5260 default: llvm_unreachable("Unexpected Boolean-operand predicate"); 5261 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break; 5262 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break; 5263 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break; 5264 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break; 5265 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break; 5266 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break; 5267 } 5268 5269 // A signed comparison of i1 values produces the opposite result to an 5270 // unsigned one if the condition code includes less-than or greater-than. 5271 // This is because 1 is the most negative signed i1 number and the most 5272 // positive unsigned i1 number. The CR-logical operations used for such 5273 // comparisons are non-commutative so for signed comparisons vs. unsigned 5274 // ones, the input operands just need to be swapped. 5275 if (ISD::isSignedIntSetCC(CC)) 5276 Swap = !Swap; 5277 5278 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1, 5279 N->getOperand(Swap ? 3 : 2), 5280 N->getOperand(Swap ? 2 : 3)), 0); 5281 CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4), 5282 N->getOperand(0)); 5283 return; 5284 } 5285 5286 if (EnableBranchHint) 5287 PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(4)); 5288 5289 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl); 5290 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode, 5291 N->getOperand(4), N->getOperand(0) }; 5292 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops); 5293 return; 5294 } 5295 case ISD::BRIND: { 5296 // FIXME: Should custom lower this. 5297 SDValue Chain = N->getOperand(0); 5298 SDValue Target = N->getOperand(1); 5299 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8; 5300 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8; 5301 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target, 5302 Chain), 0); 5303 CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain); 5304 return; 5305 } 5306 case PPCISD::TOC_ENTRY: { 5307 const bool isPPC64 = Subtarget->isPPC64(); 5308 const bool isELFABI = Subtarget->isSVR4ABI(); 5309 const bool isAIXABI = Subtarget->isAIXABI(); 5310 5311 // PowerPC only support small, medium and large code model. 5312 const CodeModel::Model CModel = TM.getCodeModel(); 5313 assert(!(CModel == CodeModel::Tiny || CModel == CodeModel::Kernel) && 5314 "PowerPC doesn't support tiny or kernel code models."); 5315 5316 if (isAIXABI && CModel == CodeModel::Medium) 5317 report_fatal_error("Medium code model is not supported on AIX."); 5318 5319 // For 64-bit small code model, we allow SelectCodeCommon to handle this, 5320 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA. 5321 if (isPPC64 && CModel == CodeModel::Small) 5322 break; 5323 5324 // Handle 32-bit small code model. 5325 if (!isPPC64) { 5326 // Transforms the ISD::TOC_ENTRY node to a PPCISD::LWZtoc. 5327 auto replaceWithLWZtoc = [this, &dl](SDNode *TocEntry) { 5328 SDValue GA = TocEntry->getOperand(0); 5329 SDValue TocBase = TocEntry->getOperand(1); 5330 SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA, 5331 TocBase); 5332 transferMemOperands(TocEntry, MN); 5333 ReplaceNode(TocEntry, MN); 5334 }; 5335 5336 if (isELFABI) { 5337 assert(TM.isPositionIndependent() && 5338 "32-bit ELF can only have TOC entries in position independent" 5339 " code."); 5340 // 32-bit ELF always uses a small code model toc access. 5341 replaceWithLWZtoc(N); 5342 return; 5343 } 5344 5345 if (isAIXABI && CModel == CodeModel::Small) { 5346 replaceWithLWZtoc(N); 5347 return; 5348 } 5349 } 5350 5351 assert(CModel != CodeModel::Small && "All small code models handled."); 5352 5353 assert((isPPC64 || (isAIXABI && !isPPC64)) && "We are dealing with 64-bit" 5354 " ELF/AIX or 32-bit AIX in the following."); 5355 5356 // Transforms the ISD::TOC_ENTRY node for 32-bit AIX large code model mode 5357 // or 64-bit medium (ELF-only) or large (ELF and AIX) code model code. We 5358 // generate two instructions as described below. The first source operand 5359 // is a symbol reference. If it must be toc-referenced according to 5360 // Subtarget, we generate: 5361 // [32-bit AIX] 5362 // LWZtocL(@sym, ADDIStocHA(%r2, @sym)) 5363 // [64-bit ELF/AIX] 5364 // LDtocL(@sym, ADDIStocHA8(%x2, @sym)) 5365 // Otherwise we generate: 5366 // ADDItocL(ADDIStocHA8(%x2, @sym), @sym) 5367 SDValue GA = N->getOperand(0); 5368 SDValue TOCbase = N->getOperand(1); 5369 5370 EVT VT = isPPC64 ? MVT::i64 : MVT::i32; 5371 SDNode *Tmp = CurDAG->getMachineNode( 5372 isPPC64 ? PPC::ADDIStocHA8 : PPC::ADDIStocHA, dl, VT, TOCbase, GA); 5373 5374 if (PPCLowering->isAccessedAsGotIndirect(GA)) { 5375 // If it is accessed as got-indirect, we need an extra LWZ/LD to load 5376 // the address. 5377 SDNode *MN = CurDAG->getMachineNode( 5378 isPPC64 ? PPC::LDtocL : PPC::LWZtocL, dl, VT, GA, SDValue(Tmp, 0)); 5379 5380 transferMemOperands(N, MN); 5381 ReplaceNode(N, MN); 5382 return; 5383 } 5384 5385 // Build the address relative to the TOC-pointer. 5386 ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64, 5387 SDValue(Tmp, 0), GA)); 5388 return; 5389 } 5390 case PPCISD::PPC32_PICGOT: 5391 // Generate a PIC-safe GOT reference. 5392 assert(Subtarget->is32BitELFABI() && 5393 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4"); 5394 CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, 5395 PPCLowering->getPointerTy(CurDAG->getDataLayout()), 5396 MVT::i32); 5397 return; 5398 5399 case PPCISD::VADD_SPLAT: { 5400 // This expands into one of three sequences, depending on whether 5401 // the first operand is odd or even, positive or negative. 5402 assert(isa<ConstantSDNode>(N->getOperand(0)) && 5403 isa<ConstantSDNode>(N->getOperand(1)) && 5404 "Invalid operand on VADD_SPLAT!"); 5405 5406 int Elt = N->getConstantOperandVal(0); 5407 int EltSize = N->getConstantOperandVal(1); 5408 unsigned Opc1, Opc2, Opc3; 5409 EVT VT; 5410 5411 if (EltSize == 1) { 5412 Opc1 = PPC::VSPLTISB; 5413 Opc2 = PPC::VADDUBM; 5414 Opc3 = PPC::VSUBUBM; 5415 VT = MVT::v16i8; 5416 } else if (EltSize == 2) { 5417 Opc1 = PPC::VSPLTISH; 5418 Opc2 = PPC::VADDUHM; 5419 Opc3 = PPC::VSUBUHM; 5420 VT = MVT::v8i16; 5421 } else { 5422 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!"); 5423 Opc1 = PPC::VSPLTISW; 5424 Opc2 = PPC::VADDUWM; 5425 Opc3 = PPC::VSUBUWM; 5426 VT = MVT::v4i32; 5427 } 5428 5429 if ((Elt & 1) == 0) { 5430 // Elt is even, in the range [-32,-18] + [16,30]. 5431 // 5432 // Convert: VADD_SPLAT elt, size 5433 // Into: tmp = VSPLTIS[BHW] elt 5434 // VADDU[BHW]M tmp, tmp 5435 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4 5436 SDValue EltVal = getI32Imm(Elt >> 1, dl); 5437 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 5438 SDValue TmpVal = SDValue(Tmp, 0); 5439 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal)); 5440 return; 5441 } else if (Elt > 0) { 5442 // Elt is odd and positive, in the range [17,31]. 5443 // 5444 // Convert: VADD_SPLAT elt, size 5445 // Into: tmp1 = VSPLTIS[BHW] elt-16 5446 // tmp2 = VSPLTIS[BHW] -16 5447 // VSUBU[BHW]M tmp1, tmp2 5448 SDValue EltVal = getI32Imm(Elt - 16, dl); 5449 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 5450 EltVal = getI32Imm(-16, dl); 5451 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 5452 ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0), 5453 SDValue(Tmp2, 0))); 5454 return; 5455 } else { 5456 // Elt is odd and negative, in the range [-31,-17]. 5457 // 5458 // Convert: VADD_SPLAT elt, size 5459 // Into: tmp1 = VSPLTIS[BHW] elt+16 5460 // tmp2 = VSPLTIS[BHW] -16 5461 // VADDU[BHW]M tmp1, tmp2 5462 SDValue EltVal = getI32Imm(Elt + 16, dl); 5463 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 5464 EltVal = getI32Imm(-16, dl); 5465 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 5466 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0), 5467 SDValue(Tmp2, 0))); 5468 return; 5469 } 5470 } 5471 } 5472 5473 SelectCode(N); 5474 } 5475 5476 // If the target supports the cmpb instruction, do the idiom recognition here. 5477 // We don't do this as a DAG combine because we don't want to do it as nodes 5478 // are being combined (because we might miss part of the eventual idiom). We 5479 // don't want to do it during instruction selection because we want to reuse 5480 // the logic for lowering the masking operations already part of the 5481 // instruction selector. 5482 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) { 5483 SDLoc dl(N); 5484 5485 assert(N->getOpcode() == ISD::OR && 5486 "Only OR nodes are supported for CMPB"); 5487 5488 SDValue Res; 5489 if (!Subtarget->hasCMPB()) 5490 return Res; 5491 5492 if (N->getValueType(0) != MVT::i32 && 5493 N->getValueType(0) != MVT::i64) 5494 return Res; 5495 5496 EVT VT = N->getValueType(0); 5497 5498 SDValue RHS, LHS; 5499 bool BytesFound[8] = {false, false, false, false, false, false, false, false}; 5500 uint64_t Mask = 0, Alt = 0; 5501 5502 auto IsByteSelectCC = [this](SDValue O, unsigned &b, 5503 uint64_t &Mask, uint64_t &Alt, 5504 SDValue &LHS, SDValue &RHS) { 5505 if (O.getOpcode() != ISD::SELECT_CC) 5506 return false; 5507 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get(); 5508 5509 if (!isa<ConstantSDNode>(O.getOperand(2)) || 5510 !isa<ConstantSDNode>(O.getOperand(3))) 5511 return false; 5512 5513 uint64_t PM = O.getConstantOperandVal(2); 5514 uint64_t PAlt = O.getConstantOperandVal(3); 5515 for (b = 0; b < 8; ++b) { 5516 uint64_t Mask = UINT64_C(0xFF) << (8*b); 5517 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt) 5518 break; 5519 } 5520 5521 if (b == 8) 5522 return false; 5523 Mask |= PM; 5524 Alt |= PAlt; 5525 5526 if (!isa<ConstantSDNode>(O.getOperand(1)) || 5527 O.getConstantOperandVal(1) != 0) { 5528 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1); 5529 if (Op0.getOpcode() == ISD::TRUNCATE) 5530 Op0 = Op0.getOperand(0); 5531 if (Op1.getOpcode() == ISD::TRUNCATE) 5532 Op1 = Op1.getOperand(0); 5533 5534 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL && 5535 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ && 5536 isa<ConstantSDNode>(Op0.getOperand(1))) { 5537 5538 unsigned Bits = Op0.getValueSizeInBits(); 5539 if (b != Bits/8-1) 5540 return false; 5541 if (Op0.getConstantOperandVal(1) != Bits-8) 5542 return false; 5543 5544 LHS = Op0.getOperand(0); 5545 RHS = Op1.getOperand(0); 5546 return true; 5547 } 5548 5549 // When we have small integers (i16 to be specific), the form present 5550 // post-legalization uses SETULT in the SELECT_CC for the 5551 // higher-order byte, depending on the fact that the 5552 // even-higher-order bytes are known to all be zero, for example: 5553 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult 5554 // (so when the second byte is the same, because all higher-order 5555 // bits from bytes 3 and 4 are known to be zero, the result of the 5556 // xor can be at most 255) 5557 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT && 5558 isa<ConstantSDNode>(O.getOperand(1))) { 5559 5560 uint64_t ULim = O.getConstantOperandVal(1); 5561 if (ULim != (UINT64_C(1) << b*8)) 5562 return false; 5563 5564 // Now we need to make sure that the upper bytes are known to be 5565 // zero. 5566 unsigned Bits = Op0.getValueSizeInBits(); 5567 if (!CurDAG->MaskedValueIsZero( 5568 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8))) 5569 return false; 5570 5571 LHS = Op0.getOperand(0); 5572 RHS = Op0.getOperand(1); 5573 return true; 5574 } 5575 5576 return false; 5577 } 5578 5579 if (CC != ISD::SETEQ) 5580 return false; 5581 5582 SDValue Op = O.getOperand(0); 5583 if (Op.getOpcode() == ISD::AND) { 5584 if (!isa<ConstantSDNode>(Op.getOperand(1))) 5585 return false; 5586 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b))) 5587 return false; 5588 5589 SDValue XOR = Op.getOperand(0); 5590 if (XOR.getOpcode() == ISD::TRUNCATE) 5591 XOR = XOR.getOperand(0); 5592 if (XOR.getOpcode() != ISD::XOR) 5593 return false; 5594 5595 LHS = XOR.getOperand(0); 5596 RHS = XOR.getOperand(1); 5597 return true; 5598 } else if (Op.getOpcode() == ISD::SRL) { 5599 if (!isa<ConstantSDNode>(Op.getOperand(1))) 5600 return false; 5601 unsigned Bits = Op.getValueSizeInBits(); 5602 if (b != Bits/8-1) 5603 return false; 5604 if (Op.getConstantOperandVal(1) != Bits-8) 5605 return false; 5606 5607 SDValue XOR = Op.getOperand(0); 5608 if (XOR.getOpcode() == ISD::TRUNCATE) 5609 XOR = XOR.getOperand(0); 5610 if (XOR.getOpcode() != ISD::XOR) 5611 return false; 5612 5613 LHS = XOR.getOperand(0); 5614 RHS = XOR.getOperand(1); 5615 return true; 5616 } 5617 5618 return false; 5619 }; 5620 5621 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0)); 5622 while (!Queue.empty()) { 5623 SDValue V = Queue.pop_back_val(); 5624 5625 for (const SDValue &O : V.getNode()->ops()) { 5626 unsigned b = 0; 5627 uint64_t M = 0, A = 0; 5628 SDValue OLHS, ORHS; 5629 if (O.getOpcode() == ISD::OR) { 5630 Queue.push_back(O); 5631 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) { 5632 if (!LHS) { 5633 LHS = OLHS; 5634 RHS = ORHS; 5635 BytesFound[b] = true; 5636 Mask |= M; 5637 Alt |= A; 5638 } else if ((LHS == ORHS && RHS == OLHS) || 5639 (RHS == ORHS && LHS == OLHS)) { 5640 BytesFound[b] = true; 5641 Mask |= M; 5642 Alt |= A; 5643 } else { 5644 return Res; 5645 } 5646 } else { 5647 return Res; 5648 } 5649 } 5650 } 5651 5652 unsigned LastB = 0, BCnt = 0; 5653 for (unsigned i = 0; i < 8; ++i) 5654 if (BytesFound[LastB]) { 5655 ++BCnt; 5656 LastB = i; 5657 } 5658 5659 if (!LastB || BCnt < 2) 5660 return Res; 5661 5662 // Because we'll be zero-extending the output anyway if don't have a specific 5663 // value for each input byte (via the Mask), we can 'anyext' the inputs. 5664 if (LHS.getValueType() != VT) { 5665 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT); 5666 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT); 5667 } 5668 5669 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS); 5670 5671 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1); 5672 if (NonTrivialMask && !Alt) { 5673 // Res = Mask & CMPB 5674 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, 5675 CurDAG->getConstant(Mask, dl, VT)); 5676 } else if (Alt) { 5677 // Res = (CMPB & Mask) | (~CMPB & Alt) 5678 // Which, as suggested here: 5679 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge 5680 // can be written as: 5681 // Res = Alt ^ ((Alt ^ Mask) & CMPB) 5682 // useful because the (Alt ^ Mask) can be pre-computed. 5683 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, 5684 CurDAG->getConstant(Mask ^ Alt, dl, VT)); 5685 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res, 5686 CurDAG->getConstant(Alt, dl, VT)); 5687 } 5688 5689 return Res; 5690 } 5691 5692 // When CR bit registers are enabled, an extension of an i1 variable to a i32 5693 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus 5694 // involves constant materialization of a 0 or a 1 or both. If the result of 5695 // the extension is then operated upon by some operator that can be constant 5696 // folded with a constant 0 or 1, and that constant can be materialized using 5697 // only one instruction (like a zero or one), then we should fold in those 5698 // operations with the select. 5699 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) { 5700 if (!Subtarget->useCRBits()) 5701 return; 5702 5703 if (N->getOpcode() != ISD::ZERO_EXTEND && 5704 N->getOpcode() != ISD::SIGN_EXTEND && 5705 N->getOpcode() != ISD::ANY_EXTEND) 5706 return; 5707 5708 if (N->getOperand(0).getValueType() != MVT::i1) 5709 return; 5710 5711 if (!N->hasOneUse()) 5712 return; 5713 5714 SDLoc dl(N); 5715 EVT VT = N->getValueType(0); 5716 SDValue Cond = N->getOperand(0); 5717 SDValue ConstTrue = 5718 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT); 5719 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT); 5720 5721 do { 5722 SDNode *User = *N->use_begin(); 5723 if (User->getNumOperands() != 2) 5724 break; 5725 5726 auto TryFold = [this, N, User, dl](SDValue Val) { 5727 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1); 5728 SDValue O0 = UserO0.getNode() == N ? Val : UserO0; 5729 SDValue O1 = UserO1.getNode() == N ? Val : UserO1; 5730 5731 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl, 5732 User->getValueType(0), {O0, O1}); 5733 }; 5734 5735 // FIXME: When the semantics of the interaction between select and undef 5736 // are clearly defined, it may turn out to be unnecessary to break here. 5737 SDValue TrueRes = TryFold(ConstTrue); 5738 if (!TrueRes || TrueRes.isUndef()) 5739 break; 5740 SDValue FalseRes = TryFold(ConstFalse); 5741 if (!FalseRes || FalseRes.isUndef()) 5742 break; 5743 5744 // For us to materialize these using one instruction, we must be able to 5745 // represent them as signed 16-bit integers. 5746 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(), 5747 False = cast<ConstantSDNode>(FalseRes)->getZExtValue(); 5748 if (!isInt<16>(True) || !isInt<16>(False)) 5749 break; 5750 5751 // We can replace User with a new SELECT node, and try again to see if we 5752 // can fold the select with its user. 5753 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes); 5754 N = User; 5755 ConstTrue = TrueRes; 5756 ConstFalse = FalseRes; 5757 } while (N->hasOneUse()); 5758 } 5759 5760 void PPCDAGToDAGISel::PreprocessISelDAG() { 5761 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end(); 5762 5763 bool MadeChange = false; 5764 while (Position != CurDAG->allnodes_begin()) { 5765 SDNode *N = &*--Position; 5766 if (N->use_empty()) 5767 continue; 5768 5769 SDValue Res; 5770 switch (N->getOpcode()) { 5771 default: break; 5772 case ISD::OR: 5773 Res = combineToCMPB(N); 5774 break; 5775 } 5776 5777 if (!Res) 5778 foldBoolExts(Res, N); 5779 5780 if (Res) { 5781 LLVM_DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: "); 5782 LLVM_DEBUG(N->dump(CurDAG)); 5783 LLVM_DEBUG(dbgs() << "\nNew: "); 5784 LLVM_DEBUG(Res.getNode()->dump(CurDAG)); 5785 LLVM_DEBUG(dbgs() << "\n"); 5786 5787 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); 5788 MadeChange = true; 5789 } 5790 } 5791 5792 if (MadeChange) 5793 CurDAG->RemoveDeadNodes(); 5794 } 5795 5796 /// PostprocessISelDAG - Perform some late peephole optimizations 5797 /// on the DAG representation. 5798 void PPCDAGToDAGISel::PostprocessISelDAG() { 5799 // Skip peepholes at -O0. 5800 if (TM.getOptLevel() == CodeGenOpt::None) 5801 return; 5802 5803 PeepholePPC64(); 5804 PeepholeCROps(); 5805 PeepholePPC64ZExt(); 5806 } 5807 5808 // Check if all users of this node will become isel where the second operand 5809 // is the constant zero. If this is so, and if we can negate the condition, 5810 // then we can flip the true and false operands. This will allow the zero to 5811 // be folded with the isel so that we don't need to materialize a register 5812 // containing zero. 5813 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) { 5814 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5815 UI != UE; ++UI) { 5816 SDNode *User = *UI; 5817 if (!User->isMachineOpcode()) 5818 return false; 5819 if (User->getMachineOpcode() != PPC::SELECT_I4 && 5820 User->getMachineOpcode() != PPC::SELECT_I8) 5821 return false; 5822 5823 SDNode *Op2 = User->getOperand(2).getNode(); 5824 if (!Op2->isMachineOpcode()) 5825 return false; 5826 5827 if (Op2->getMachineOpcode() != PPC::LI && 5828 Op2->getMachineOpcode() != PPC::LI8) 5829 return false; 5830 5831 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0)); 5832 if (!C) 5833 return false; 5834 5835 if (!C->isNullValue()) 5836 return false; 5837 } 5838 5839 return true; 5840 } 5841 5842 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) { 5843 SmallVector<SDNode *, 4> ToReplace; 5844 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5845 UI != UE; ++UI) { 5846 SDNode *User = *UI; 5847 assert((User->getMachineOpcode() == PPC::SELECT_I4 || 5848 User->getMachineOpcode() == PPC::SELECT_I8) && 5849 "Must have all select users"); 5850 ToReplace.push_back(User); 5851 } 5852 5853 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(), 5854 UE = ToReplace.end(); UI != UE; ++UI) { 5855 SDNode *User = *UI; 5856 SDNode *ResNode = 5857 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User), 5858 User->getValueType(0), User->getOperand(0), 5859 User->getOperand(2), 5860 User->getOperand(1)); 5861 5862 LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: "); 5863 LLVM_DEBUG(User->dump(CurDAG)); 5864 LLVM_DEBUG(dbgs() << "\nNew: "); 5865 LLVM_DEBUG(ResNode->dump(CurDAG)); 5866 LLVM_DEBUG(dbgs() << "\n"); 5867 5868 ReplaceUses(User, ResNode); 5869 } 5870 } 5871 5872 void PPCDAGToDAGISel::PeepholeCROps() { 5873 bool IsModified; 5874 do { 5875 IsModified = false; 5876 for (SDNode &Node : CurDAG->allnodes()) { 5877 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node); 5878 if (!MachineNode || MachineNode->use_empty()) 5879 continue; 5880 SDNode *ResNode = MachineNode; 5881 5882 bool Op1Set = false, Op1Unset = false, 5883 Op1Not = false, 5884 Op2Set = false, Op2Unset = false, 5885 Op2Not = false; 5886 5887 unsigned Opcode = MachineNode->getMachineOpcode(); 5888 switch (Opcode) { 5889 default: break; 5890 case PPC::CRAND: 5891 case PPC::CRNAND: 5892 case PPC::CROR: 5893 case PPC::CRXOR: 5894 case PPC::CRNOR: 5895 case PPC::CREQV: 5896 case PPC::CRANDC: 5897 case PPC::CRORC: { 5898 SDValue Op = MachineNode->getOperand(1); 5899 if (Op.isMachineOpcode()) { 5900 if (Op.getMachineOpcode() == PPC::CRSET) 5901 Op2Set = true; 5902 else if (Op.getMachineOpcode() == PPC::CRUNSET) 5903 Op2Unset = true; 5904 else if (Op.getMachineOpcode() == PPC::CRNOR && 5905 Op.getOperand(0) == Op.getOperand(1)) 5906 Op2Not = true; 5907 } 5908 LLVM_FALLTHROUGH; 5909 } 5910 case PPC::BC: 5911 case PPC::BCn: 5912 case PPC::SELECT_I4: 5913 case PPC::SELECT_I8: 5914 case PPC::SELECT_F4: 5915 case PPC::SELECT_F8: 5916 case PPC::SELECT_SPE: 5917 case PPC::SELECT_SPE4: 5918 case PPC::SELECT_VRRC: 5919 case PPC::SELECT_VSFRC: 5920 case PPC::SELECT_VSSRC: 5921 case PPC::SELECT_VSRC: { 5922 SDValue Op = MachineNode->getOperand(0); 5923 if (Op.isMachineOpcode()) { 5924 if (Op.getMachineOpcode() == PPC::CRSET) 5925 Op1Set = true; 5926 else if (Op.getMachineOpcode() == PPC::CRUNSET) 5927 Op1Unset = true; 5928 else if (Op.getMachineOpcode() == PPC::CRNOR && 5929 Op.getOperand(0) == Op.getOperand(1)) 5930 Op1Not = true; 5931 } 5932 } 5933 break; 5934 } 5935 5936 bool SelectSwap = false; 5937 switch (Opcode) { 5938 default: break; 5939 case PPC::CRAND: 5940 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 5941 // x & x = x 5942 ResNode = MachineNode->getOperand(0).getNode(); 5943 else if (Op1Set) 5944 // 1 & y = y 5945 ResNode = MachineNode->getOperand(1).getNode(); 5946 else if (Op2Set) 5947 // x & 1 = x 5948 ResNode = MachineNode->getOperand(0).getNode(); 5949 else if (Op1Unset || Op2Unset) 5950 // x & 0 = 0 & y = 0 5951 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 5952 MVT::i1); 5953 else if (Op1Not) 5954 // ~x & y = andc(y, x) 5955 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 5956 MVT::i1, MachineNode->getOperand(1), 5957 MachineNode->getOperand(0). 5958 getOperand(0)); 5959 else if (Op2Not) 5960 // x & ~y = andc(x, y) 5961 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 5962 MVT::i1, MachineNode->getOperand(0), 5963 MachineNode->getOperand(1). 5964 getOperand(0)); 5965 else if (AllUsersSelectZero(MachineNode)) { 5966 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode), 5967 MVT::i1, MachineNode->getOperand(0), 5968 MachineNode->getOperand(1)); 5969 SelectSwap = true; 5970 } 5971 break; 5972 case PPC::CRNAND: 5973 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 5974 // nand(x, x) -> nor(x, x) 5975 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5976 MVT::i1, MachineNode->getOperand(0), 5977 MachineNode->getOperand(0)); 5978 else if (Op1Set) 5979 // nand(1, y) -> nor(y, y) 5980 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5981 MVT::i1, MachineNode->getOperand(1), 5982 MachineNode->getOperand(1)); 5983 else if (Op2Set) 5984 // nand(x, 1) -> nor(x, x) 5985 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5986 MVT::i1, MachineNode->getOperand(0), 5987 MachineNode->getOperand(0)); 5988 else if (Op1Unset || Op2Unset) 5989 // nand(x, 0) = nand(0, y) = 1 5990 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 5991 MVT::i1); 5992 else if (Op1Not) 5993 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y) 5994 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 5995 MVT::i1, MachineNode->getOperand(0). 5996 getOperand(0), 5997 MachineNode->getOperand(1)); 5998 else if (Op2Not) 5999 // nand(x, ~y) = ~x | y = orc(y, x) 6000 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 6001 MVT::i1, MachineNode->getOperand(1). 6002 getOperand(0), 6003 MachineNode->getOperand(0)); 6004 else if (AllUsersSelectZero(MachineNode)) { 6005 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode), 6006 MVT::i1, MachineNode->getOperand(0), 6007 MachineNode->getOperand(1)); 6008 SelectSwap = true; 6009 } 6010 break; 6011 case PPC::CROR: 6012 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 6013 // x | x = x 6014 ResNode = MachineNode->getOperand(0).getNode(); 6015 else if (Op1Set || Op2Set) 6016 // x | 1 = 1 | y = 1 6017 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 6018 MVT::i1); 6019 else if (Op1Unset) 6020 // 0 | y = y 6021 ResNode = MachineNode->getOperand(1).getNode(); 6022 else if (Op2Unset) 6023 // x | 0 = x 6024 ResNode = MachineNode->getOperand(0).getNode(); 6025 else if (Op1Not) 6026 // ~x | y = orc(y, x) 6027 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 6028 MVT::i1, MachineNode->getOperand(1), 6029 MachineNode->getOperand(0). 6030 getOperand(0)); 6031 else if (Op2Not) 6032 // x | ~y = orc(x, y) 6033 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 6034 MVT::i1, MachineNode->getOperand(0), 6035 MachineNode->getOperand(1). 6036 getOperand(0)); 6037 else if (AllUsersSelectZero(MachineNode)) { 6038 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 6039 MVT::i1, MachineNode->getOperand(0), 6040 MachineNode->getOperand(1)); 6041 SelectSwap = true; 6042 } 6043 break; 6044 case PPC::CRXOR: 6045 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 6046 // xor(x, x) = 0 6047 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 6048 MVT::i1); 6049 else if (Op1Set) 6050 // xor(1, y) -> nor(y, y) 6051 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 6052 MVT::i1, MachineNode->getOperand(1), 6053 MachineNode->getOperand(1)); 6054 else if (Op2Set) 6055 // xor(x, 1) -> nor(x, x) 6056 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 6057 MVT::i1, MachineNode->getOperand(0), 6058 MachineNode->getOperand(0)); 6059 else if (Op1Unset) 6060 // xor(0, y) = y 6061 ResNode = MachineNode->getOperand(1).getNode(); 6062 else if (Op2Unset) 6063 // xor(x, 0) = x 6064 ResNode = MachineNode->getOperand(0).getNode(); 6065 else if (Op1Not) 6066 // xor(~x, y) = eqv(x, y) 6067 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 6068 MVT::i1, MachineNode->getOperand(0). 6069 getOperand(0), 6070 MachineNode->getOperand(1)); 6071 else if (Op2Not) 6072 // xor(x, ~y) = eqv(x, y) 6073 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 6074 MVT::i1, MachineNode->getOperand(0), 6075 MachineNode->getOperand(1). 6076 getOperand(0)); 6077 else if (AllUsersSelectZero(MachineNode)) { 6078 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 6079 MVT::i1, MachineNode->getOperand(0), 6080 MachineNode->getOperand(1)); 6081 SelectSwap = true; 6082 } 6083 break; 6084 case PPC::CRNOR: 6085 if (Op1Set || Op2Set) 6086 // nor(1, y) -> 0 6087 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 6088 MVT::i1); 6089 else if (Op1Unset) 6090 // nor(0, y) = ~y -> nor(y, y) 6091 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 6092 MVT::i1, MachineNode->getOperand(1), 6093 MachineNode->getOperand(1)); 6094 else if (Op2Unset) 6095 // nor(x, 0) = ~x 6096 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 6097 MVT::i1, MachineNode->getOperand(0), 6098 MachineNode->getOperand(0)); 6099 else if (Op1Not) 6100 // nor(~x, y) = andc(x, y) 6101 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 6102 MVT::i1, MachineNode->getOperand(0). 6103 getOperand(0), 6104 MachineNode->getOperand(1)); 6105 else if (Op2Not) 6106 // nor(x, ~y) = andc(y, x) 6107 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 6108 MVT::i1, MachineNode->getOperand(1). 6109 getOperand(0), 6110 MachineNode->getOperand(0)); 6111 else if (AllUsersSelectZero(MachineNode)) { 6112 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode), 6113 MVT::i1, MachineNode->getOperand(0), 6114 MachineNode->getOperand(1)); 6115 SelectSwap = true; 6116 } 6117 break; 6118 case PPC::CREQV: 6119 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 6120 // eqv(x, x) = 1 6121 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 6122 MVT::i1); 6123 else if (Op1Set) 6124 // eqv(1, y) = y 6125 ResNode = MachineNode->getOperand(1).getNode(); 6126 else if (Op2Set) 6127 // eqv(x, 1) = x 6128 ResNode = MachineNode->getOperand(0).getNode(); 6129 else if (Op1Unset) 6130 // eqv(0, y) = ~y -> nor(y, y) 6131 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 6132 MVT::i1, MachineNode->getOperand(1), 6133 MachineNode->getOperand(1)); 6134 else if (Op2Unset) 6135 // eqv(x, 0) = ~x 6136 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 6137 MVT::i1, MachineNode->getOperand(0), 6138 MachineNode->getOperand(0)); 6139 else if (Op1Not) 6140 // eqv(~x, y) = xor(x, y) 6141 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 6142 MVT::i1, MachineNode->getOperand(0). 6143 getOperand(0), 6144 MachineNode->getOperand(1)); 6145 else if (Op2Not) 6146 // eqv(x, ~y) = xor(x, y) 6147 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 6148 MVT::i1, MachineNode->getOperand(0), 6149 MachineNode->getOperand(1). 6150 getOperand(0)); 6151 else if (AllUsersSelectZero(MachineNode)) { 6152 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 6153 MVT::i1, MachineNode->getOperand(0), 6154 MachineNode->getOperand(1)); 6155 SelectSwap = true; 6156 } 6157 break; 6158 case PPC::CRANDC: 6159 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 6160 // andc(x, x) = 0 6161 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 6162 MVT::i1); 6163 else if (Op1Set) 6164 // andc(1, y) = ~y 6165 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 6166 MVT::i1, MachineNode->getOperand(1), 6167 MachineNode->getOperand(1)); 6168 else if (Op1Unset || Op2Set) 6169 // andc(0, y) = andc(x, 1) = 0 6170 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 6171 MVT::i1); 6172 else if (Op2Unset) 6173 // andc(x, 0) = x 6174 ResNode = MachineNode->getOperand(0).getNode(); 6175 else if (Op1Not) 6176 // andc(~x, y) = ~(x | y) = nor(x, y) 6177 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 6178 MVT::i1, MachineNode->getOperand(0). 6179 getOperand(0), 6180 MachineNode->getOperand(1)); 6181 else if (Op2Not) 6182 // andc(x, ~y) = x & y 6183 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode), 6184 MVT::i1, MachineNode->getOperand(0), 6185 MachineNode->getOperand(1). 6186 getOperand(0)); 6187 else if (AllUsersSelectZero(MachineNode)) { 6188 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 6189 MVT::i1, MachineNode->getOperand(1), 6190 MachineNode->getOperand(0)); 6191 SelectSwap = true; 6192 } 6193 break; 6194 case PPC::CRORC: 6195 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 6196 // orc(x, x) = 1 6197 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 6198 MVT::i1); 6199 else if (Op1Set || Op2Unset) 6200 // orc(1, y) = orc(x, 0) = 1 6201 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 6202 MVT::i1); 6203 else if (Op2Set) 6204 // orc(x, 1) = x 6205 ResNode = MachineNode->getOperand(0).getNode(); 6206 else if (Op1Unset) 6207 // orc(0, y) = ~y 6208 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 6209 MVT::i1, MachineNode->getOperand(1), 6210 MachineNode->getOperand(1)); 6211 else if (Op1Not) 6212 // orc(~x, y) = ~(x & y) = nand(x, y) 6213 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode), 6214 MVT::i1, MachineNode->getOperand(0). 6215 getOperand(0), 6216 MachineNode->getOperand(1)); 6217 else if (Op2Not) 6218 // orc(x, ~y) = x | y 6219 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode), 6220 MVT::i1, MachineNode->getOperand(0), 6221 MachineNode->getOperand(1). 6222 getOperand(0)); 6223 else if (AllUsersSelectZero(MachineNode)) { 6224 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 6225 MVT::i1, MachineNode->getOperand(1), 6226 MachineNode->getOperand(0)); 6227 SelectSwap = true; 6228 } 6229 break; 6230 case PPC::SELECT_I4: 6231 case PPC::SELECT_I8: 6232 case PPC::SELECT_F4: 6233 case PPC::SELECT_F8: 6234 case PPC::SELECT_SPE: 6235 case PPC::SELECT_SPE4: 6236 case PPC::SELECT_VRRC: 6237 case PPC::SELECT_VSFRC: 6238 case PPC::SELECT_VSSRC: 6239 case PPC::SELECT_VSRC: 6240 if (Op1Set) 6241 ResNode = MachineNode->getOperand(1).getNode(); 6242 else if (Op1Unset) 6243 ResNode = MachineNode->getOperand(2).getNode(); 6244 else if (Op1Not) 6245 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(), 6246 SDLoc(MachineNode), 6247 MachineNode->getValueType(0), 6248 MachineNode->getOperand(0). 6249 getOperand(0), 6250 MachineNode->getOperand(2), 6251 MachineNode->getOperand(1)); 6252 break; 6253 case PPC::BC: 6254 case PPC::BCn: 6255 if (Op1Not) 6256 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn : 6257 PPC::BC, 6258 SDLoc(MachineNode), 6259 MVT::Other, 6260 MachineNode->getOperand(0). 6261 getOperand(0), 6262 MachineNode->getOperand(1), 6263 MachineNode->getOperand(2)); 6264 // FIXME: Handle Op1Set, Op1Unset here too. 6265 break; 6266 } 6267 6268 // If we're inverting this node because it is used only by selects that 6269 // we'd like to swap, then swap the selects before the node replacement. 6270 if (SelectSwap) 6271 SwapAllSelectUsers(MachineNode); 6272 6273 if (ResNode != MachineNode) { 6274 LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: "); 6275 LLVM_DEBUG(MachineNode->dump(CurDAG)); 6276 LLVM_DEBUG(dbgs() << "\nNew: "); 6277 LLVM_DEBUG(ResNode->dump(CurDAG)); 6278 LLVM_DEBUG(dbgs() << "\n"); 6279 6280 ReplaceUses(MachineNode, ResNode); 6281 IsModified = true; 6282 } 6283 } 6284 if (IsModified) 6285 CurDAG->RemoveDeadNodes(); 6286 } while (IsModified); 6287 } 6288 6289 // Gather the set of 32-bit operations that are known to have their 6290 // higher-order 32 bits zero, where ToPromote contains all such operations. 6291 static bool PeepholePPC64ZExtGather(SDValue Op32, 6292 SmallPtrSetImpl<SDNode *> &ToPromote) { 6293 if (!Op32.isMachineOpcode()) 6294 return false; 6295 6296 // First, check for the "frontier" instructions (those that will clear the 6297 // higher-order 32 bits. 6298 6299 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap 6300 // around. If it does not, then these instructions will clear the 6301 // higher-order bits. 6302 if ((Op32.getMachineOpcode() == PPC::RLWINM || 6303 Op32.getMachineOpcode() == PPC::RLWNM) && 6304 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) { 6305 ToPromote.insert(Op32.getNode()); 6306 return true; 6307 } 6308 6309 // SLW and SRW always clear the higher-order bits. 6310 if (Op32.getMachineOpcode() == PPC::SLW || 6311 Op32.getMachineOpcode() == PPC::SRW) { 6312 ToPromote.insert(Op32.getNode()); 6313 return true; 6314 } 6315 6316 // For LI and LIS, we need the immediate to be positive (so that it is not 6317 // sign extended). 6318 if (Op32.getMachineOpcode() == PPC::LI || 6319 Op32.getMachineOpcode() == PPC::LIS) { 6320 if (!isUInt<15>(Op32.getConstantOperandVal(0))) 6321 return false; 6322 6323 ToPromote.insert(Op32.getNode()); 6324 return true; 6325 } 6326 6327 // LHBRX and LWBRX always clear the higher-order bits. 6328 if (Op32.getMachineOpcode() == PPC::LHBRX || 6329 Op32.getMachineOpcode() == PPC::LWBRX) { 6330 ToPromote.insert(Op32.getNode()); 6331 return true; 6332 } 6333 6334 // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended. 6335 if (Op32.getMachineOpcode() == PPC::CNTLZW || 6336 Op32.getMachineOpcode() == PPC::CNTTZW) { 6337 ToPromote.insert(Op32.getNode()); 6338 return true; 6339 } 6340 6341 // Next, check for those instructions we can look through. 6342 6343 // Assuming the mask does not wrap around, then the higher-order bits are 6344 // taken directly from the first operand. 6345 if (Op32.getMachineOpcode() == PPC::RLWIMI && 6346 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) { 6347 SmallPtrSet<SDNode *, 16> ToPromote1; 6348 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1)) 6349 return false; 6350 6351 ToPromote.insert(Op32.getNode()); 6352 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 6353 return true; 6354 } 6355 6356 // For OR, the higher-order bits are zero if that is true for both operands. 6357 // For SELECT_I4, the same is true (but the relevant operand numbers are 6358 // shifted by 1). 6359 if (Op32.getMachineOpcode() == PPC::OR || 6360 Op32.getMachineOpcode() == PPC::SELECT_I4) { 6361 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0; 6362 SmallPtrSet<SDNode *, 16> ToPromote1; 6363 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1)) 6364 return false; 6365 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1)) 6366 return false; 6367 6368 ToPromote.insert(Op32.getNode()); 6369 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 6370 return true; 6371 } 6372 6373 // For ORI and ORIS, we need the higher-order bits of the first operand to be 6374 // zero, and also for the constant to be positive (so that it is not sign 6375 // extended). 6376 if (Op32.getMachineOpcode() == PPC::ORI || 6377 Op32.getMachineOpcode() == PPC::ORIS) { 6378 SmallPtrSet<SDNode *, 16> ToPromote1; 6379 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1)) 6380 return false; 6381 if (!isUInt<15>(Op32.getConstantOperandVal(1))) 6382 return false; 6383 6384 ToPromote.insert(Op32.getNode()); 6385 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 6386 return true; 6387 } 6388 6389 // The higher-order bits of AND are zero if that is true for at least one of 6390 // the operands. 6391 if (Op32.getMachineOpcode() == PPC::AND) { 6392 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2; 6393 bool Op0OK = 6394 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1); 6395 bool Op1OK = 6396 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2); 6397 if (!Op0OK && !Op1OK) 6398 return false; 6399 6400 ToPromote.insert(Op32.getNode()); 6401 6402 if (Op0OK) 6403 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 6404 6405 if (Op1OK) 6406 ToPromote.insert(ToPromote2.begin(), ToPromote2.end()); 6407 6408 return true; 6409 } 6410 6411 // For ANDI and ANDIS, the higher-order bits are zero if either that is true 6412 // of the first operand, or if the second operand is positive (so that it is 6413 // not sign extended). 6414 if (Op32.getMachineOpcode() == PPC::ANDI_rec || 6415 Op32.getMachineOpcode() == PPC::ANDIS_rec) { 6416 SmallPtrSet<SDNode *, 16> ToPromote1; 6417 bool Op0OK = 6418 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1); 6419 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1)); 6420 if (!Op0OK && !Op1OK) 6421 return false; 6422 6423 ToPromote.insert(Op32.getNode()); 6424 6425 if (Op0OK) 6426 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 6427 6428 return true; 6429 } 6430 6431 return false; 6432 } 6433 6434 void PPCDAGToDAGISel::PeepholePPC64ZExt() { 6435 if (!Subtarget->isPPC64()) 6436 return; 6437 6438 // When we zero-extend from i32 to i64, we use a pattern like this: 6439 // def : Pat<(i64 (zext i32:$in)), 6440 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32), 6441 // 0, 32)>; 6442 // There are several 32-bit shift/rotate instructions, however, that will 6443 // clear the higher-order bits of their output, rendering the RLDICL 6444 // unnecessary. When that happens, we remove it here, and redefine the 6445 // relevant 32-bit operation to be a 64-bit operation. 6446 6447 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end(); 6448 6449 bool MadeChange = false; 6450 while (Position != CurDAG->allnodes_begin()) { 6451 SDNode *N = &*--Position; 6452 // Skip dead nodes and any non-machine opcodes. 6453 if (N->use_empty() || !N->isMachineOpcode()) 6454 continue; 6455 6456 if (N->getMachineOpcode() != PPC::RLDICL) 6457 continue; 6458 6459 if (N->getConstantOperandVal(1) != 0 || 6460 N->getConstantOperandVal(2) != 32) 6461 continue; 6462 6463 SDValue ISR = N->getOperand(0); 6464 if (!ISR.isMachineOpcode() || 6465 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG) 6466 continue; 6467 6468 if (!ISR.hasOneUse()) 6469 continue; 6470 6471 if (ISR.getConstantOperandVal(2) != PPC::sub_32) 6472 continue; 6473 6474 SDValue IDef = ISR.getOperand(0); 6475 if (!IDef.isMachineOpcode() || 6476 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF) 6477 continue; 6478 6479 // We now know that we're looking at a canonical i32 -> i64 zext. See if we 6480 // can get rid of it. 6481 6482 SDValue Op32 = ISR->getOperand(1); 6483 if (!Op32.isMachineOpcode()) 6484 continue; 6485 6486 // There are some 32-bit instructions that always clear the high-order 32 6487 // bits, there are also some instructions (like AND) that we can look 6488 // through. 6489 SmallPtrSet<SDNode *, 16> ToPromote; 6490 if (!PeepholePPC64ZExtGather(Op32, ToPromote)) 6491 continue; 6492 6493 // If the ToPromote set contains nodes that have uses outside of the set 6494 // (except for the original INSERT_SUBREG), then abort the transformation. 6495 bool OutsideUse = false; 6496 for (SDNode *PN : ToPromote) { 6497 for (SDNode *UN : PN->uses()) { 6498 if (!ToPromote.count(UN) && UN != ISR.getNode()) { 6499 OutsideUse = true; 6500 break; 6501 } 6502 } 6503 6504 if (OutsideUse) 6505 break; 6506 } 6507 if (OutsideUse) 6508 continue; 6509 6510 MadeChange = true; 6511 6512 // We now know that this zero extension can be removed by promoting to 6513 // nodes in ToPromote to 64-bit operations, where for operations in the 6514 // frontier of the set, we need to insert INSERT_SUBREGs for their 6515 // operands. 6516 for (SDNode *PN : ToPromote) { 6517 unsigned NewOpcode; 6518 switch (PN->getMachineOpcode()) { 6519 default: 6520 llvm_unreachable("Don't know the 64-bit variant of this instruction"); 6521 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break; 6522 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break; 6523 case PPC::SLW: NewOpcode = PPC::SLW8; break; 6524 case PPC::SRW: NewOpcode = PPC::SRW8; break; 6525 case PPC::LI: NewOpcode = PPC::LI8; break; 6526 case PPC::LIS: NewOpcode = PPC::LIS8; break; 6527 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break; 6528 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break; 6529 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break; 6530 case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break; 6531 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break; 6532 case PPC::OR: NewOpcode = PPC::OR8; break; 6533 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break; 6534 case PPC::ORI: NewOpcode = PPC::ORI8; break; 6535 case PPC::ORIS: NewOpcode = PPC::ORIS8; break; 6536 case PPC::AND: NewOpcode = PPC::AND8; break; 6537 case PPC::ANDI_rec: 6538 NewOpcode = PPC::ANDI8_rec; 6539 break; 6540 case PPC::ANDIS_rec: 6541 NewOpcode = PPC::ANDIS8_rec; 6542 break; 6543 } 6544 6545 // Note: During the replacement process, the nodes will be in an 6546 // inconsistent state (some instructions will have operands with values 6547 // of the wrong type). Once done, however, everything should be right 6548 // again. 6549 6550 SmallVector<SDValue, 4> Ops; 6551 for (const SDValue &V : PN->ops()) { 6552 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 && 6553 !isa<ConstantSDNode>(V)) { 6554 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) }; 6555 SDNode *ReplOp = 6556 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V), 6557 ISR.getNode()->getVTList(), ReplOpOps); 6558 Ops.push_back(SDValue(ReplOp, 0)); 6559 } else { 6560 Ops.push_back(V); 6561 } 6562 } 6563 6564 // Because all to-be-promoted nodes only have users that are other 6565 // promoted nodes (or the original INSERT_SUBREG), we can safely replace 6566 // the i32 result value type with i64. 6567 6568 SmallVector<EVT, 2> NewVTs; 6569 SDVTList VTs = PN->getVTList(); 6570 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i) 6571 if (VTs.VTs[i] == MVT::i32) 6572 NewVTs.push_back(MVT::i64); 6573 else 6574 NewVTs.push_back(VTs.VTs[i]); 6575 6576 LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: "); 6577 LLVM_DEBUG(PN->dump(CurDAG)); 6578 6579 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops); 6580 6581 LLVM_DEBUG(dbgs() << "\nNew: "); 6582 LLVM_DEBUG(PN->dump(CurDAG)); 6583 LLVM_DEBUG(dbgs() << "\n"); 6584 } 6585 6586 // Now we replace the original zero extend and its associated INSERT_SUBREG 6587 // with the value feeding the INSERT_SUBREG (which has now been promoted to 6588 // return an i64). 6589 6590 LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: "); 6591 LLVM_DEBUG(N->dump(CurDAG)); 6592 LLVM_DEBUG(dbgs() << "\nNew: "); 6593 LLVM_DEBUG(Op32.getNode()->dump(CurDAG)); 6594 LLVM_DEBUG(dbgs() << "\n"); 6595 6596 ReplaceUses(N, Op32.getNode()); 6597 } 6598 6599 if (MadeChange) 6600 CurDAG->RemoveDeadNodes(); 6601 } 6602 6603 void PPCDAGToDAGISel::PeepholePPC64() { 6604 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end(); 6605 6606 while (Position != CurDAG->allnodes_begin()) { 6607 SDNode *N = &*--Position; 6608 // Skip dead nodes and any non-machine opcodes. 6609 if (N->use_empty() || !N->isMachineOpcode()) 6610 continue; 6611 6612 unsigned FirstOp; 6613 unsigned StorageOpcode = N->getMachineOpcode(); 6614 bool RequiresMod4Offset = false; 6615 6616 switch (StorageOpcode) { 6617 default: continue; 6618 6619 case PPC::LWA: 6620 case PPC::LD: 6621 case PPC::DFLOADf64: 6622 case PPC::DFLOADf32: 6623 RequiresMod4Offset = true; 6624 LLVM_FALLTHROUGH; 6625 case PPC::LBZ: 6626 case PPC::LBZ8: 6627 case PPC::LFD: 6628 case PPC::LFS: 6629 case PPC::LHA: 6630 case PPC::LHA8: 6631 case PPC::LHZ: 6632 case PPC::LHZ8: 6633 case PPC::LWZ: 6634 case PPC::LWZ8: 6635 FirstOp = 0; 6636 break; 6637 6638 case PPC::STD: 6639 case PPC::DFSTOREf64: 6640 case PPC::DFSTOREf32: 6641 RequiresMod4Offset = true; 6642 LLVM_FALLTHROUGH; 6643 case PPC::STB: 6644 case PPC::STB8: 6645 case PPC::STFD: 6646 case PPC::STFS: 6647 case PPC::STH: 6648 case PPC::STH8: 6649 case PPC::STW: 6650 case PPC::STW8: 6651 FirstOp = 1; 6652 break; 6653 } 6654 6655 // If this is a load or store with a zero offset, or within the alignment, 6656 // we may be able to fold an add-immediate into the memory operation. 6657 // The check against alignment is below, as it can't occur until we check 6658 // the arguments to N 6659 if (!isa<ConstantSDNode>(N->getOperand(FirstOp))) 6660 continue; 6661 6662 SDValue Base = N->getOperand(FirstOp + 1); 6663 if (!Base.isMachineOpcode()) 6664 continue; 6665 6666 unsigned Flags = 0; 6667 bool ReplaceFlags = true; 6668 6669 // When the feeding operation is an add-immediate of some sort, 6670 // determine whether we need to add relocation information to the 6671 // target flags on the immediate operand when we fold it into the 6672 // load instruction. 6673 // 6674 // For something like ADDItocL, the relocation information is 6675 // inferred from the opcode; when we process it in the AsmPrinter, 6676 // we add the necessary relocation there. A load, though, can receive 6677 // relocation from various flavors of ADDIxxx, so we need to carry 6678 // the relocation information in the target flags. 6679 switch (Base.getMachineOpcode()) { 6680 default: continue; 6681 6682 case PPC::ADDI8: 6683 case PPC::ADDI: 6684 // In some cases (such as TLS) the relocation information 6685 // is already in place on the operand, so copying the operand 6686 // is sufficient. 6687 ReplaceFlags = false; 6688 // For these cases, the immediate may not be divisible by 4, in 6689 // which case the fold is illegal for DS-form instructions. (The 6690 // other cases provide aligned addresses and are always safe.) 6691 if (RequiresMod4Offset && 6692 (!isa<ConstantSDNode>(Base.getOperand(1)) || 6693 Base.getConstantOperandVal(1) % 4 != 0)) 6694 continue; 6695 break; 6696 case PPC::ADDIdtprelL: 6697 Flags = PPCII::MO_DTPREL_LO; 6698 break; 6699 case PPC::ADDItlsldL: 6700 Flags = PPCII::MO_TLSLD_LO; 6701 break; 6702 case PPC::ADDItocL: 6703 Flags = PPCII::MO_TOC_LO; 6704 break; 6705 } 6706 6707 SDValue ImmOpnd = Base.getOperand(1); 6708 6709 // On PPC64, the TOC base pointer is guaranteed by the ABI only to have 6710 // 8-byte alignment, and so we can only use offsets less than 8 (otherwise, 6711 // we might have needed different @ha relocation values for the offset 6712 // pointers). 6713 int MaxDisplacement = 7; 6714 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) { 6715 const GlobalValue *GV = GA->getGlobal(); 6716 Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout()); 6717 MaxDisplacement = std::min((int)Alignment.value() - 1, MaxDisplacement); 6718 } 6719 6720 bool UpdateHBase = false; 6721 SDValue HBase = Base.getOperand(0); 6722 6723 int Offset = N->getConstantOperandVal(FirstOp); 6724 if (ReplaceFlags) { 6725 if (Offset < 0 || Offset > MaxDisplacement) { 6726 // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only 6727 // one use, then we can do this for any offset, we just need to also 6728 // update the offset (i.e. the symbol addend) on the addis also. 6729 if (Base.getMachineOpcode() != PPC::ADDItocL) 6730 continue; 6731 6732 if (!HBase.isMachineOpcode() || 6733 HBase.getMachineOpcode() != PPC::ADDIStocHA8) 6734 continue; 6735 6736 if (!Base.hasOneUse() || !HBase.hasOneUse()) 6737 continue; 6738 6739 SDValue HImmOpnd = HBase.getOperand(1); 6740 if (HImmOpnd != ImmOpnd) 6741 continue; 6742 6743 UpdateHBase = true; 6744 } 6745 } else { 6746 // If we're directly folding the addend from an addi instruction, then: 6747 // 1. In general, the offset on the memory access must be zero. 6748 // 2. If the addend is a constant, then it can be combined with a 6749 // non-zero offset, but only if the result meets the encoding 6750 // requirements. 6751 if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) { 6752 Offset += C->getSExtValue(); 6753 6754 if (RequiresMod4Offset && (Offset % 4) != 0) 6755 continue; 6756 6757 if (!isInt<16>(Offset)) 6758 continue; 6759 6760 ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd), 6761 ImmOpnd.getValueType()); 6762 } else if (Offset != 0) { 6763 continue; 6764 } 6765 } 6766 6767 // We found an opportunity. Reverse the operands from the add 6768 // immediate and substitute them into the load or store. If 6769 // needed, update the target flags for the immediate operand to 6770 // reflect the necessary relocation information. 6771 LLVM_DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: "); 6772 LLVM_DEBUG(Base->dump(CurDAG)); 6773 LLVM_DEBUG(dbgs() << "\nN: "); 6774 LLVM_DEBUG(N->dump(CurDAG)); 6775 LLVM_DEBUG(dbgs() << "\n"); 6776 6777 // If the relocation information isn't already present on the 6778 // immediate operand, add it now. 6779 if (ReplaceFlags) { 6780 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) { 6781 SDLoc dl(GA); 6782 const GlobalValue *GV = GA->getGlobal(); 6783 Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout()); 6784 // We can't perform this optimization for data whose alignment 6785 // is insufficient for the instruction encoding. 6786 if (Alignment < 4 && (RequiresMod4Offset || (Offset % 4) != 0)) { 6787 LLVM_DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n"); 6788 continue; 6789 } 6790 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags); 6791 } else if (ConstantPoolSDNode *CP = 6792 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) { 6793 const Constant *C = CP->getConstVal(); 6794 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64, CP->getAlign(), 6795 Offset, Flags); 6796 } 6797 } 6798 6799 if (FirstOp == 1) // Store 6800 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd, 6801 Base.getOperand(0), N->getOperand(3)); 6802 else // Load 6803 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0), 6804 N->getOperand(2)); 6805 6806 if (UpdateHBase) 6807 (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0), 6808 ImmOpnd); 6809 6810 // The add-immediate may now be dead, in which case remove it. 6811 if (Base.getNode()->use_empty()) 6812 CurDAG->RemoveDeadNode(Base.getNode()); 6813 } 6814 } 6815 6816 /// createPPCISelDag - This pass converts a legalized DAG into a 6817 /// PowerPC-specific DAG, ready for instruction scheduling. 6818 /// 6819 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM, 6820 CodeGenOpt::Level OptLevel) { 6821 return new PPCDAGToDAGISel(TM, OptLevel); 6822 } 6823