1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines a pattern matching instruction selector for PowerPC, 11 // converting from a legalized dag to a PPC dag. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "PPC.h" 16 #include "MCTargetDesc/PPCPredicates.h" 17 #include "PPCMachineFunctionInfo.h" 18 #include "PPCTargetMachine.h" 19 #include "llvm/Analysis/BranchProbabilityInfo.h" 20 #include "llvm/CodeGen/FunctionLoweringInfo.h" 21 #include "llvm/CodeGen/MachineFunction.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineRegisterInfo.h" 24 #include "llvm/CodeGen/SelectionDAG.h" 25 #include "llvm/CodeGen/SelectionDAGISel.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/GlobalAlias.h" 29 #include "llvm/IR/GlobalValue.h" 30 #include "llvm/IR/GlobalVariable.h" 31 #include "llvm/IR/Intrinsics.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/MathExtras.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include "llvm/Target/TargetOptions.h" 39 using namespace llvm; 40 41 #define DEBUG_TYPE "ppc-codegen" 42 43 // FIXME: Remove this once the bug has been fixed! 44 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug", 45 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden); 46 47 static cl::opt<bool> 48 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true), 49 cl::desc("use aggressive ppc isel for bit permutations"), 50 cl::Hidden); 51 static cl::opt<bool> BPermRewriterNoMasking( 52 "ppc-bit-perm-rewriter-stress-rotates", 53 cl::desc("stress rotate selection in aggressive ppc isel for " 54 "bit permutations"), 55 cl::Hidden); 56 57 static cl::opt<bool> EnableBranchHint( 58 "ppc-use-branch-hint", cl::init(true), 59 cl::desc("Enable static hinting of branches on ppc"), 60 cl::Hidden); 61 62 namespace { 63 //===--------------------------------------------------------------------===// 64 /// PPCDAGToDAGISel - PPC specific code to select PPC machine 65 /// instructions for SelectionDAG operations. 66 /// 67 class PPCDAGToDAGISel : public SelectionDAGISel { 68 const PPCTargetMachine &TM; 69 const PPCSubtarget *PPCSubTarget; 70 const PPCTargetLowering *PPCLowering; 71 unsigned GlobalBaseReg; 72 public: 73 explicit PPCDAGToDAGISel(PPCTargetMachine &tm) 74 : SelectionDAGISel(tm), TM(tm) {} 75 76 bool runOnMachineFunction(MachineFunction &MF) override { 77 // Make sure we re-emit a set of the global base reg if necessary 78 GlobalBaseReg = 0; 79 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>(); 80 PPCLowering = PPCSubTarget->getTargetLowering(); 81 SelectionDAGISel::runOnMachineFunction(MF); 82 83 if (!PPCSubTarget->isSVR4ABI()) 84 InsertVRSaveCode(MF); 85 86 return true; 87 } 88 89 void PreprocessISelDAG() override; 90 void PostprocessISelDAG() override; 91 92 /// getI32Imm - Return a target constant with the specified value, of type 93 /// i32. 94 inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) { 95 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 96 } 97 98 /// getI64Imm - Return a target constant with the specified value, of type 99 /// i64. 100 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) { 101 return CurDAG->getTargetConstant(Imm, dl, MVT::i64); 102 } 103 104 /// getSmallIPtrImm - Return a target constant of pointer type. 105 inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) { 106 return CurDAG->getTargetConstant( 107 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout())); 108 } 109 110 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a 111 /// rotate and mask opcode and mask operation. 112 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask, 113 unsigned &SH, unsigned &MB, unsigned &ME); 114 115 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC 116 /// base register. Return the virtual register that holds this value. 117 SDNode *getGlobalBaseReg(); 118 119 void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0); 120 121 // Select - Convert the specified operand from a target-independent to a 122 // target-specific node if it hasn't already been changed. 123 void Select(SDNode *N) override; 124 125 bool tryBitfieldInsert(SDNode *N); 126 bool tryBitPermutation(SDNode *N); 127 128 /// SelectCC - Select a comparison of the specified values with the 129 /// specified condition code, returning the CR# of the expression. 130 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, 131 const SDLoc &dl); 132 133 /// SelectAddrImm - Returns true if the address N can be represented by 134 /// a base register plus a signed 16-bit displacement [r+imm]. 135 bool SelectAddrImm(SDValue N, SDValue &Disp, 136 SDValue &Base) { 137 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false); 138 } 139 140 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc 141 /// immediate field. Note that the operand at this point is already the 142 /// result of a prior SelectAddressRegImm call. 143 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const { 144 if (N.getOpcode() == ISD::TargetConstant || 145 N.getOpcode() == ISD::TargetGlobalAddress) { 146 Out = N; 147 return true; 148 } 149 150 return false; 151 } 152 153 /// SelectAddrIdx - Given the specified addressed, check to see if it can be 154 /// represented as an indexed [r+r] operation. Returns false if it can 155 /// be represented by [r+imm], which are preferred. 156 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) { 157 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG); 158 } 159 160 /// SelectAddrIdxOnly - Given the specified addressed, force it to be 161 /// represented as an indexed [r+r] operation. 162 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) { 163 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG); 164 } 165 166 /// SelectAddrImmX4 - Returns true if the address N can be represented by 167 /// a base register plus a signed 16-bit displacement that is a multiple of 4. 168 /// Suitable for use by STD and friends. 169 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) { 170 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true); 171 } 172 173 // Select an address into a single register. 174 bool SelectAddr(SDValue N, SDValue &Base) { 175 Base = N; 176 return true; 177 } 178 179 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for 180 /// inline asm expressions. It is always correct to compute the value into 181 /// a register. The case of adding a (possibly relocatable) constant to a 182 /// register can be improved, but it is wrong to substitute Reg+Reg for 183 /// Reg in an asm, because the load or store opcode would have to change. 184 bool SelectInlineAsmMemoryOperand(const SDValue &Op, 185 unsigned ConstraintID, 186 std::vector<SDValue> &OutOps) override { 187 188 switch(ConstraintID) { 189 default: 190 errs() << "ConstraintID: " << ConstraintID << "\n"; 191 llvm_unreachable("Unexpected asm memory constraint"); 192 case InlineAsm::Constraint_es: 193 case InlineAsm::Constraint_i: 194 case InlineAsm::Constraint_m: 195 case InlineAsm::Constraint_o: 196 case InlineAsm::Constraint_Q: 197 case InlineAsm::Constraint_Z: 198 case InlineAsm::Constraint_Zy: 199 // We need to make sure that this one operand does not end up in r0 200 // (because we might end up lowering this as 0(%op)). 201 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo(); 202 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1); 203 SDLoc dl(Op); 204 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32); 205 SDValue NewOp = 206 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 207 dl, Op.getValueType(), 208 Op, RC), 0); 209 210 OutOps.push_back(NewOp); 211 return false; 212 } 213 return true; 214 } 215 216 void InsertVRSaveCode(MachineFunction &MF); 217 218 const char *getPassName() const override { 219 return "PowerPC DAG->DAG Pattern Instruction Selection"; 220 } 221 222 // Include the pieces autogenerated from the target description. 223 #include "PPCGenDAGISel.inc" 224 225 private: 226 bool trySETCC(SDNode *N); 227 228 void PeepholePPC64(); 229 void PeepholePPC64ZExt(); 230 void PeepholeCROps(); 231 232 SDValue combineToCMPB(SDNode *N); 233 void foldBoolExts(SDValue &Res, SDNode *&N); 234 235 bool AllUsersSelectZero(SDNode *N); 236 void SwapAllSelectUsers(SDNode *N); 237 238 void transferMemOperands(SDNode *N, SDNode *Result); 239 }; 240 } 241 242 /// InsertVRSaveCode - Once the entire function has been instruction selected, 243 /// all virtual registers are created and all machine instructions are built, 244 /// check to see if we need to save/restore VRSAVE. If so, do it. 245 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) { 246 // Check to see if this function uses vector registers, which means we have to 247 // save and restore the VRSAVE register and update it with the regs we use. 248 // 249 // In this case, there will be virtual registers of vector type created 250 // by the scheduler. Detect them now. 251 bool HasVectorVReg = false; 252 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) { 253 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 254 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) { 255 HasVectorVReg = true; 256 break; 257 } 258 } 259 if (!HasVectorVReg) return; // nothing to do. 260 261 // If we have a vector register, we want to emit code into the entry and exit 262 // blocks to save and restore the VRSAVE register. We do this here (instead 263 // of marking all vector instructions as clobbering VRSAVE) for two reasons: 264 // 265 // 1. This (trivially) reduces the load on the register allocator, by not 266 // having to represent the live range of the VRSAVE register. 267 // 2. This (more significantly) allows us to create a temporary virtual 268 // register to hold the saved VRSAVE value, allowing this temporary to be 269 // register allocated, instead of forcing it to be spilled to the stack. 270 271 // Create two vregs - one to hold the VRSAVE register that is live-in to the 272 // function and one for the value after having bits or'd into it. 273 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass); 274 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass); 275 276 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo(); 277 MachineBasicBlock &EntryBB = *Fn.begin(); 278 DebugLoc dl; 279 // Emit the following code into the entry block: 280 // InVRSAVE = MFVRSAVE 281 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE 282 // MTVRSAVE UpdatedVRSAVE 283 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point 284 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE); 285 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE), 286 UpdatedVRSAVE).addReg(InVRSAVE); 287 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE); 288 289 // Find all return blocks, outputting a restore in each epilog. 290 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) { 291 if (BB->isReturnBlock()) { 292 IP = BB->end(); --IP; 293 294 // Skip over all terminator instructions, which are part of the return 295 // sequence. 296 MachineBasicBlock::iterator I2 = IP; 297 while (I2 != BB->begin() && (--I2)->isTerminator()) 298 IP = I2; 299 300 // Emit: MTVRSAVE InVRSave 301 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE); 302 } 303 } 304 } 305 306 307 /// getGlobalBaseReg - Output the instructions required to put the 308 /// base address to use for accessing globals into a register. 309 /// 310 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() { 311 if (!GlobalBaseReg) { 312 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo(); 313 // Insert the set of GlobalBaseReg into the first MBB of the function 314 MachineBasicBlock &FirstMBB = MF->front(); 315 MachineBasicBlock::iterator MBBI = FirstMBB.begin(); 316 const Module *M = MF->getFunction()->getParent(); 317 DebugLoc dl; 318 319 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) { 320 if (PPCSubTarget->isTargetELF()) { 321 GlobalBaseReg = PPC::R30; 322 if (M->getPICLevel() == PICLevel::SmallPIC) { 323 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR)); 324 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 325 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true); 326 } else { 327 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR)); 328 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 329 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass); 330 BuildMI(FirstMBB, MBBI, dl, 331 TII.get(PPC::UpdateGBR), GlobalBaseReg) 332 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg); 333 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true); 334 } 335 } else { 336 GlobalBaseReg = 337 RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass); 338 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR)); 339 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 340 } 341 } else { 342 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass); 343 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8)); 344 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg); 345 } 346 } 347 return CurDAG->getRegister(GlobalBaseReg, 348 PPCLowering->getPointerTy(CurDAG->getDataLayout())) 349 .getNode(); 350 } 351 352 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 353 /// or 64-bit immediate, and if the value can be accurately represented as a 354 /// sign extension from a 16-bit value. If so, this returns true and the 355 /// immediate. 356 static bool isIntS16Immediate(SDNode *N, short &Imm) { 357 if (N->getOpcode() != ISD::Constant) 358 return false; 359 360 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue(); 361 if (N->getValueType(0) == MVT::i32) 362 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 363 else 364 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 365 } 366 367 static bool isIntS16Immediate(SDValue Op, short &Imm) { 368 return isIntS16Immediate(Op.getNode(), Imm); 369 } 370 371 372 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant 373 /// operand. If so Imm will receive the 32-bit value. 374 static bool isInt32Immediate(SDNode *N, unsigned &Imm) { 375 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) { 376 Imm = cast<ConstantSDNode>(N)->getZExtValue(); 377 return true; 378 } 379 return false; 380 } 381 382 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant 383 /// operand. If so Imm will receive the 64-bit value. 384 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) { 385 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) { 386 Imm = cast<ConstantSDNode>(N)->getZExtValue(); 387 return true; 388 } 389 return false; 390 } 391 392 // isInt32Immediate - This method tests to see if a constant operand. 393 // If so Imm will receive the 32 bit value. 394 static bool isInt32Immediate(SDValue N, unsigned &Imm) { 395 return isInt32Immediate(N.getNode(), Imm); 396 } 397 398 static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo, 399 const SDValue &DestMBB) { 400 assert(isa<BasicBlockSDNode>(DestMBB)); 401 402 if (!FuncInfo->BPI) return PPC::BR_NO_HINT; 403 404 const BasicBlock *BB = FuncInfo->MBB->getBasicBlock(); 405 const TerminatorInst *BBTerm = BB->getTerminator(); 406 407 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT; 408 409 const BasicBlock *TBB = BBTerm->getSuccessor(0); 410 const BasicBlock *FBB = BBTerm->getSuccessor(1); 411 412 auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB); 413 auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB); 414 415 // We only want to handle cases which are easy to predict at static time, e.g. 416 // C++ throw statement, that is very likely not taken, or calling never 417 // returned function, e.g. stdlib exit(). So we set Threshold to filter 418 // unwanted cases. 419 // 420 // Below is LLVM branch weight table, we only want to handle case 1, 2 421 // 422 // Case Taken:Nontaken Example 423 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(), 424 // 2. Invoke-terminating 1:1048575 425 // 3. Coldblock 4:64 __builtin_expect 426 // 4. Loop Branch 124:4 For loop 427 // 5. PH/ZH/FPH 20:12 428 const uint32_t Threshold = 10000; 429 430 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb)) 431 return PPC::BR_NO_HINT; 432 433 DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() << "::" 434 << BB->getName() << "'\n" 435 << " -> " << TBB->getName() << ": " << TProb << "\n" 436 << " -> " << FBB->getName() << ": " << FProb << "\n"); 437 438 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB); 439 440 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities, 441 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock 442 if (BBDN->getBasicBlock()->getBasicBlock() != TBB) 443 std::swap(TProb, FProb); 444 445 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT; 446 } 447 448 // isOpcWithIntImmediate - This method tests to see if the node is a specific 449 // opcode and that it has a immediate integer right operand. 450 // If so Imm will receive the 32 bit value. 451 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) { 452 return N->getOpcode() == Opc 453 && isInt32Immediate(N->getOperand(1).getNode(), Imm); 454 } 455 456 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) { 457 SDLoc dl(SN); 458 int FI = cast<FrameIndexSDNode>(N)->getIndex(); 459 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0)); 460 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8; 461 if (SN->hasOneUse()) 462 CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI, 463 getSmallIPtrImm(Offset, dl)); 464 else 465 ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI, 466 getSmallIPtrImm(Offset, dl))); 467 } 468 469 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask, 470 bool isShiftMask, unsigned &SH, 471 unsigned &MB, unsigned &ME) { 472 // Don't even go down this path for i64, since different logic will be 473 // necessary for rldicl/rldicr/rldimi. 474 if (N->getValueType(0) != MVT::i32) 475 return false; 476 477 unsigned Shift = 32; 478 unsigned Indeterminant = ~0; // bit mask marking indeterminant results 479 unsigned Opcode = N->getOpcode(); 480 if (N->getNumOperands() != 2 || 481 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31)) 482 return false; 483 484 if (Opcode == ISD::SHL) { 485 // apply shift left to mask if it comes first 486 if (isShiftMask) Mask = Mask << Shift; 487 // determine which bits are made indeterminant by shift 488 Indeterminant = ~(0xFFFFFFFFu << Shift); 489 } else if (Opcode == ISD::SRL) { 490 // apply shift right to mask if it comes first 491 if (isShiftMask) Mask = Mask >> Shift; 492 // determine which bits are made indeterminant by shift 493 Indeterminant = ~(0xFFFFFFFFu >> Shift); 494 // adjust for the left rotate 495 Shift = 32 - Shift; 496 } else if (Opcode == ISD::ROTL) { 497 Indeterminant = 0; 498 } else { 499 return false; 500 } 501 502 // if the mask doesn't intersect any Indeterminant bits 503 if (Mask && !(Mask & Indeterminant)) { 504 SH = Shift & 31; 505 // make sure the mask is still a mask (wrap arounds may not be) 506 return isRunOfOnes(Mask, MB, ME); 507 } 508 return false; 509 } 510 511 /// Turn an or of two masked values into the rotate left word immediate then 512 /// mask insert (rlwimi) instruction. 513 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) { 514 SDValue Op0 = N->getOperand(0); 515 SDValue Op1 = N->getOperand(1); 516 SDLoc dl(N); 517 518 APInt LKZ, LKO, RKZ, RKO; 519 CurDAG->computeKnownBits(Op0, LKZ, LKO); 520 CurDAG->computeKnownBits(Op1, RKZ, RKO); 521 522 unsigned TargetMask = LKZ.getZExtValue(); 523 unsigned InsertMask = RKZ.getZExtValue(); 524 525 if ((TargetMask | InsertMask) == 0xFFFFFFFF) { 526 unsigned Op0Opc = Op0.getOpcode(); 527 unsigned Op1Opc = Op1.getOpcode(); 528 unsigned Value, SH = 0; 529 TargetMask = ~TargetMask; 530 InsertMask = ~InsertMask; 531 532 // If the LHS has a foldable shift and the RHS does not, then swap it to the 533 // RHS so that we can fold the shift into the insert. 534 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) { 535 if (Op0.getOperand(0).getOpcode() == ISD::SHL || 536 Op0.getOperand(0).getOpcode() == ISD::SRL) { 537 if (Op1.getOperand(0).getOpcode() != ISD::SHL && 538 Op1.getOperand(0).getOpcode() != ISD::SRL) { 539 std::swap(Op0, Op1); 540 std::swap(Op0Opc, Op1Opc); 541 std::swap(TargetMask, InsertMask); 542 } 543 } 544 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) { 545 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL && 546 Op1.getOperand(0).getOpcode() != ISD::SRL) { 547 std::swap(Op0, Op1); 548 std::swap(Op0Opc, Op1Opc); 549 std::swap(TargetMask, InsertMask); 550 } 551 } 552 553 unsigned MB, ME; 554 if (isRunOfOnes(InsertMask, MB, ME)) { 555 SDValue Tmp1, Tmp2; 556 557 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) && 558 isInt32Immediate(Op1.getOperand(1), Value)) { 559 Op1 = Op1.getOperand(0); 560 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value; 561 } 562 if (Op1Opc == ISD::AND) { 563 // The AND mask might not be a constant, and we need to make sure that 564 // if we're going to fold the masking with the insert, all bits not 565 // know to be zero in the mask are known to be one. 566 APInt MKZ, MKO; 567 CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO); 568 bool CanFoldMask = InsertMask == MKO.getZExtValue(); 569 570 unsigned SHOpc = Op1.getOperand(0).getOpcode(); 571 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask && 572 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) { 573 // Note that Value must be in range here (less than 32) because 574 // otherwise there would not be any bits set in InsertMask. 575 Op1 = Op1.getOperand(0).getOperand(0); 576 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value; 577 } 578 } 579 580 SH &= 31; 581 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl), 582 getI32Imm(ME, dl) }; 583 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops)); 584 return true; 585 } 586 } 587 return false; 588 } 589 590 // Predict the number of instructions that would be generated by calling 591 // getInt64(N). 592 static unsigned getInt64CountDirect(int64_t Imm) { 593 // Assume no remaining bits. 594 unsigned Remainder = 0; 595 // Assume no shift required. 596 unsigned Shift = 0; 597 598 // If it can't be represented as a 32 bit value. 599 if (!isInt<32>(Imm)) { 600 Shift = countTrailingZeros<uint64_t>(Imm); 601 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift; 602 603 // If the shifted value fits 32 bits. 604 if (isInt<32>(ImmSh)) { 605 // Go with the shifted value. 606 Imm = ImmSh; 607 } else { 608 // Still stuck with a 64 bit value. 609 Remainder = Imm; 610 Shift = 32; 611 Imm >>= 32; 612 } 613 } 614 615 // Intermediate operand. 616 unsigned Result = 0; 617 618 // Handle first 32 bits. 619 unsigned Lo = Imm & 0xFFFF; 620 621 // Simple value. 622 if (isInt<16>(Imm)) { 623 // Just the Lo bits. 624 ++Result; 625 } else if (Lo) { 626 // Handle the Hi bits and Lo bits. 627 Result += 2; 628 } else { 629 // Just the Hi bits. 630 ++Result; 631 } 632 633 // If no shift, we're done. 634 if (!Shift) return Result; 635 636 // Shift for next step if the upper 32-bits were not zero. 637 if (Imm) 638 ++Result; 639 640 // Add in the last bits as required. 641 if ((Remainder >> 16) & 0xFFFF) 642 ++Result; 643 if (Remainder & 0xFFFF) 644 ++Result; 645 646 return Result; 647 } 648 649 static uint64_t Rot64(uint64_t Imm, unsigned R) { 650 return (Imm << R) | (Imm >> (64 - R)); 651 } 652 653 static unsigned getInt64Count(int64_t Imm) { 654 unsigned Count = getInt64CountDirect(Imm); 655 if (Count == 1) 656 return Count; 657 658 for (unsigned r = 1; r < 63; ++r) { 659 uint64_t RImm = Rot64(Imm, r); 660 unsigned RCount = getInt64CountDirect(RImm) + 1; 661 Count = std::min(Count, RCount); 662 663 // See comments in getInt64 for an explanation of the logic below. 664 unsigned LS = findLastSet(RImm); 665 if (LS != r-1) 666 continue; 667 668 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1)); 669 uint64_t RImmWithOnes = RImm | OnesMask; 670 671 RCount = getInt64CountDirect(RImmWithOnes) + 1; 672 Count = std::min(Count, RCount); 673 } 674 675 return Count; 676 } 677 678 // Select a 64-bit constant. For cost-modeling purposes, getInt64Count 679 // (above) needs to be kept in sync with this function. 680 static SDNode *getInt64Direct(SelectionDAG *CurDAG, const SDLoc &dl, 681 int64_t Imm) { 682 // Assume no remaining bits. 683 unsigned Remainder = 0; 684 // Assume no shift required. 685 unsigned Shift = 0; 686 687 // If it can't be represented as a 32 bit value. 688 if (!isInt<32>(Imm)) { 689 Shift = countTrailingZeros<uint64_t>(Imm); 690 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift; 691 692 // If the shifted value fits 32 bits. 693 if (isInt<32>(ImmSh)) { 694 // Go with the shifted value. 695 Imm = ImmSh; 696 } else { 697 // Still stuck with a 64 bit value. 698 Remainder = Imm; 699 Shift = 32; 700 Imm >>= 32; 701 } 702 } 703 704 // Intermediate operand. 705 SDNode *Result; 706 707 // Handle first 32 bits. 708 unsigned Lo = Imm & 0xFFFF; 709 unsigned Hi = (Imm >> 16) & 0xFFFF; 710 711 auto getI32Imm = [CurDAG, dl](unsigned Imm) { 712 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 713 }; 714 715 // Simple value. 716 if (isInt<16>(Imm)) { 717 // Just the Lo bits. 718 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo)); 719 } else if (Lo) { 720 // Handle the Hi bits. 721 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8; 722 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi)); 723 // And Lo bits. 724 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, 725 SDValue(Result, 0), getI32Imm(Lo)); 726 } else { 727 // Just the Hi bits. 728 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi)); 729 } 730 731 // If no shift, we're done. 732 if (!Shift) return Result; 733 734 // Shift for next step if the upper 32-bits were not zero. 735 if (Imm) { 736 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, 737 SDValue(Result, 0), 738 getI32Imm(Shift), 739 getI32Imm(63 - Shift)); 740 } 741 742 // Add in the last bits as required. 743 if ((Hi = (Remainder >> 16) & 0xFFFF)) { 744 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64, 745 SDValue(Result, 0), getI32Imm(Hi)); 746 } 747 if ((Lo = Remainder & 0xFFFF)) { 748 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, 749 SDValue(Result, 0), getI32Imm(Lo)); 750 } 751 752 return Result; 753 } 754 755 static SDNode *getInt64(SelectionDAG *CurDAG, const SDLoc &dl, int64_t Imm) { 756 unsigned Count = getInt64CountDirect(Imm); 757 if (Count == 1) 758 return getInt64Direct(CurDAG, dl, Imm); 759 760 unsigned RMin = 0; 761 762 int64_t MatImm; 763 unsigned MaskEnd; 764 765 for (unsigned r = 1; r < 63; ++r) { 766 uint64_t RImm = Rot64(Imm, r); 767 unsigned RCount = getInt64CountDirect(RImm) + 1; 768 if (RCount < Count) { 769 Count = RCount; 770 RMin = r; 771 MatImm = RImm; 772 MaskEnd = 63; 773 } 774 775 // If the immediate to generate has many trailing zeros, it might be 776 // worthwhile to generate a rotated value with too many leading ones 777 // (because that's free with li/lis's sign-extension semantics), and then 778 // mask them off after rotation. 779 780 unsigned LS = findLastSet(RImm); 781 // We're adding (63-LS) higher-order ones, and we expect to mask them off 782 // after performing the inverse rotation by (64-r). So we need that: 783 // 63-LS == 64-r => LS == r-1 784 if (LS != r-1) 785 continue; 786 787 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1)); 788 uint64_t RImmWithOnes = RImm | OnesMask; 789 790 RCount = getInt64CountDirect(RImmWithOnes) + 1; 791 if (RCount < Count) { 792 Count = RCount; 793 RMin = r; 794 MatImm = RImmWithOnes; 795 MaskEnd = LS; 796 } 797 } 798 799 if (!RMin) 800 return getInt64Direct(CurDAG, dl, Imm); 801 802 auto getI32Imm = [CurDAG, dl](unsigned Imm) { 803 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 804 }; 805 806 SDValue Val = SDValue(getInt64Direct(CurDAG, dl, MatImm), 0); 807 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val, 808 getI32Imm(64 - RMin), getI32Imm(MaskEnd)); 809 } 810 811 // Select a 64-bit constant. 812 static SDNode *getInt64(SelectionDAG *CurDAG, SDNode *N) { 813 SDLoc dl(N); 814 815 // Get 64 bit value. 816 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue(); 817 return getInt64(CurDAG, dl, Imm); 818 } 819 820 namespace { 821 class BitPermutationSelector { 822 struct ValueBit { 823 SDValue V; 824 825 // The bit number in the value, using a convention where bit 0 is the 826 // lowest-order bit. 827 unsigned Idx; 828 829 enum Kind { 830 ConstZero, 831 Variable 832 } K; 833 834 ValueBit(SDValue V, unsigned I, Kind K = Variable) 835 : V(V), Idx(I), K(K) {} 836 ValueBit(Kind K = Variable) 837 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {} 838 839 bool isZero() const { 840 return K == ConstZero; 841 } 842 843 bool hasValue() const { 844 return K == Variable; 845 } 846 847 SDValue getValue() const { 848 assert(hasValue() && "Cannot get the value of a constant bit"); 849 return V; 850 } 851 852 unsigned getValueBitIndex() const { 853 assert(hasValue() && "Cannot get the value bit index of a constant bit"); 854 return Idx; 855 } 856 }; 857 858 // A bit group has the same underlying value and the same rotate factor. 859 struct BitGroup { 860 SDValue V; 861 unsigned RLAmt; 862 unsigned StartIdx, EndIdx; 863 864 // This rotation amount assumes that the lower 32 bits of the quantity are 865 // replicated in the high 32 bits by the rotation operator (which is done 866 // by rlwinm and friends in 64-bit mode). 867 bool Repl32; 868 // Did converting to Repl32 == true change the rotation factor? If it did, 869 // it decreased it by 32. 870 bool Repl32CR; 871 // Was this group coalesced after setting Repl32 to true? 872 bool Repl32Coalesced; 873 874 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E) 875 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false), 876 Repl32Coalesced(false) { 877 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R << 878 " [" << S << ", " << E << "]\n"); 879 } 880 }; 881 882 // Information on each (Value, RLAmt) pair (like the number of groups 883 // associated with each) used to choose the lowering method. 884 struct ValueRotInfo { 885 SDValue V; 886 unsigned RLAmt; 887 unsigned NumGroups; 888 unsigned FirstGroupStartIdx; 889 bool Repl32; 890 891 ValueRotInfo() 892 : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX), 893 Repl32(false) {} 894 895 // For sorting (in reverse order) by NumGroups, and then by 896 // FirstGroupStartIdx. 897 bool operator < (const ValueRotInfo &Other) const { 898 // We need to sort so that the non-Repl32 come first because, when we're 899 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit 900 // masking operation. 901 if (Repl32 < Other.Repl32) 902 return true; 903 else if (Repl32 > Other.Repl32) 904 return false; 905 else if (NumGroups > Other.NumGroups) 906 return true; 907 else if (NumGroups < Other.NumGroups) 908 return false; 909 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx) 910 return true; 911 return false; 912 } 913 }; 914 915 // Return true if something interesting was deduced, return false if we're 916 // providing only a generic representation of V (or something else likewise 917 // uninteresting for instruction selection). 918 bool getValueBits(SDValue V, SmallVector<ValueBit, 64> &Bits) { 919 switch (V.getOpcode()) { 920 default: break; 921 case ISD::ROTL: 922 if (isa<ConstantSDNode>(V.getOperand(1))) { 923 unsigned RotAmt = V.getConstantOperandVal(1); 924 925 SmallVector<ValueBit, 64> LHSBits(Bits.size()); 926 getValueBits(V.getOperand(0), LHSBits); 927 928 for (unsigned i = 0; i < Bits.size(); ++i) 929 Bits[i] = LHSBits[i < RotAmt ? i + (Bits.size() - RotAmt) : i - RotAmt]; 930 931 return true; 932 } 933 break; 934 case ISD::SHL: 935 if (isa<ConstantSDNode>(V.getOperand(1))) { 936 unsigned ShiftAmt = V.getConstantOperandVal(1); 937 938 SmallVector<ValueBit, 64> LHSBits(Bits.size()); 939 getValueBits(V.getOperand(0), LHSBits); 940 941 for (unsigned i = ShiftAmt; i < Bits.size(); ++i) 942 Bits[i] = LHSBits[i - ShiftAmt]; 943 944 for (unsigned i = 0; i < ShiftAmt; ++i) 945 Bits[i] = ValueBit(ValueBit::ConstZero); 946 947 return true; 948 } 949 break; 950 case ISD::SRL: 951 if (isa<ConstantSDNode>(V.getOperand(1))) { 952 unsigned ShiftAmt = V.getConstantOperandVal(1); 953 954 SmallVector<ValueBit, 64> LHSBits(Bits.size()); 955 getValueBits(V.getOperand(0), LHSBits); 956 957 for (unsigned i = 0; i < Bits.size() - ShiftAmt; ++i) 958 Bits[i] = LHSBits[i + ShiftAmt]; 959 960 for (unsigned i = Bits.size() - ShiftAmt; i < Bits.size(); ++i) 961 Bits[i] = ValueBit(ValueBit::ConstZero); 962 963 return true; 964 } 965 break; 966 case ISD::AND: 967 if (isa<ConstantSDNode>(V.getOperand(1))) { 968 uint64_t Mask = V.getConstantOperandVal(1); 969 970 SmallVector<ValueBit, 64> LHSBits(Bits.size()); 971 bool LHSTrivial = getValueBits(V.getOperand(0), LHSBits); 972 973 for (unsigned i = 0; i < Bits.size(); ++i) 974 if (((Mask >> i) & 1) == 1) 975 Bits[i] = LHSBits[i]; 976 else 977 Bits[i] = ValueBit(ValueBit::ConstZero); 978 979 // Mark this as interesting, only if the LHS was also interesting. This 980 // prevents the overall procedure from matching a single immediate 'and' 981 // (which is non-optimal because such an and might be folded with other 982 // things if we don't select it here). 983 return LHSTrivial; 984 } 985 break; 986 case ISD::OR: { 987 SmallVector<ValueBit, 64> LHSBits(Bits.size()), RHSBits(Bits.size()); 988 getValueBits(V.getOperand(0), LHSBits); 989 getValueBits(V.getOperand(1), RHSBits); 990 991 bool AllDisjoint = true; 992 for (unsigned i = 0; i < Bits.size(); ++i) 993 if (LHSBits[i].isZero()) 994 Bits[i] = RHSBits[i]; 995 else if (RHSBits[i].isZero()) 996 Bits[i] = LHSBits[i]; 997 else { 998 AllDisjoint = false; 999 break; 1000 } 1001 1002 if (!AllDisjoint) 1003 break; 1004 1005 return true; 1006 } 1007 } 1008 1009 for (unsigned i = 0; i < Bits.size(); ++i) 1010 Bits[i] = ValueBit(V, i); 1011 1012 return false; 1013 } 1014 1015 // For each value (except the constant ones), compute the left-rotate amount 1016 // to get it from its original to final position. 1017 void computeRotationAmounts() { 1018 HasZeros = false; 1019 RLAmt.resize(Bits.size()); 1020 for (unsigned i = 0; i < Bits.size(); ++i) 1021 if (Bits[i].hasValue()) { 1022 unsigned VBI = Bits[i].getValueBitIndex(); 1023 if (i >= VBI) 1024 RLAmt[i] = i - VBI; 1025 else 1026 RLAmt[i] = Bits.size() - (VBI - i); 1027 } else if (Bits[i].isZero()) { 1028 HasZeros = true; 1029 RLAmt[i] = UINT32_MAX; 1030 } else { 1031 llvm_unreachable("Unknown value bit type"); 1032 } 1033 } 1034 1035 // Collect groups of consecutive bits with the same underlying value and 1036 // rotation factor. If we're doing late masking, we ignore zeros, otherwise 1037 // they break up groups. 1038 void collectBitGroups(bool LateMask) { 1039 BitGroups.clear(); 1040 1041 unsigned LastRLAmt = RLAmt[0]; 1042 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue(); 1043 unsigned LastGroupStartIdx = 0; 1044 for (unsigned i = 1; i < Bits.size(); ++i) { 1045 unsigned ThisRLAmt = RLAmt[i]; 1046 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue(); 1047 if (LateMask && !ThisValue) { 1048 ThisValue = LastValue; 1049 ThisRLAmt = LastRLAmt; 1050 // If we're doing late masking, then the first bit group always starts 1051 // at zero (even if the first bits were zero). 1052 if (BitGroups.empty()) 1053 LastGroupStartIdx = 0; 1054 } 1055 1056 // If this bit has the same underlying value and the same rotate factor as 1057 // the last one, then they're part of the same group. 1058 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue) 1059 continue; 1060 1061 if (LastValue.getNode()) 1062 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx, 1063 i-1)); 1064 LastRLAmt = ThisRLAmt; 1065 LastValue = ThisValue; 1066 LastGroupStartIdx = i; 1067 } 1068 if (LastValue.getNode()) 1069 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx, 1070 Bits.size()-1)); 1071 1072 if (BitGroups.empty()) 1073 return; 1074 1075 // We might be able to combine the first and last groups. 1076 if (BitGroups.size() > 1) { 1077 // If the first and last groups are the same, then remove the first group 1078 // in favor of the last group, making the ending index of the last group 1079 // equal to the ending index of the to-be-removed first group. 1080 if (BitGroups[0].StartIdx == 0 && 1081 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 && 1082 BitGroups[0].V == BitGroups[BitGroups.size()-1].V && 1083 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) { 1084 DEBUG(dbgs() << "\tcombining final bit group with initial one\n"); 1085 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx; 1086 BitGroups.erase(BitGroups.begin()); 1087 } 1088 } 1089 } 1090 1091 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups 1092 // associated with each. If there is a degeneracy, pick the one that occurs 1093 // first (in the final value). 1094 void collectValueRotInfo() { 1095 ValueRots.clear(); 1096 1097 for (auto &BG : BitGroups) { 1098 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0); 1099 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)]; 1100 VRI.V = BG.V; 1101 VRI.RLAmt = BG.RLAmt; 1102 VRI.Repl32 = BG.Repl32; 1103 VRI.NumGroups += 1; 1104 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx); 1105 } 1106 1107 // Now that we've collected the various ValueRotInfo instances, we need to 1108 // sort them. 1109 ValueRotsVec.clear(); 1110 for (auto &I : ValueRots) { 1111 ValueRotsVec.push_back(I.second); 1112 } 1113 std::sort(ValueRotsVec.begin(), ValueRotsVec.end()); 1114 } 1115 1116 // In 64-bit mode, rlwinm and friends have a rotation operator that 1117 // replicates the low-order 32 bits into the high-order 32-bits. The mask 1118 // indices of these instructions can only be in the lower 32 bits, so they 1119 // can only represent some 64-bit bit groups. However, when they can be used, 1120 // the 32-bit replication can be used to represent, as a single bit group, 1121 // otherwise separate bit groups. We'll convert to replicated-32-bit bit 1122 // groups when possible. Returns true if any of the bit groups were 1123 // converted. 1124 void assignRepl32BitGroups() { 1125 // If we have bits like this: 1126 // 1127 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 1128 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24 1129 // Groups: | RLAmt = 8 | RLAmt = 40 | 1130 // 1131 // But, making use of a 32-bit operation that replicates the low-order 32 1132 // bits into the high-order 32 bits, this can be one bit group with a RLAmt 1133 // of 8. 1134 1135 auto IsAllLow32 = [this](BitGroup & BG) { 1136 if (BG.StartIdx <= BG.EndIdx) { 1137 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) { 1138 if (!Bits[i].hasValue()) 1139 continue; 1140 if (Bits[i].getValueBitIndex() >= 32) 1141 return false; 1142 } 1143 } else { 1144 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) { 1145 if (!Bits[i].hasValue()) 1146 continue; 1147 if (Bits[i].getValueBitIndex() >= 32) 1148 return false; 1149 } 1150 for (unsigned i = 0; i <= BG.EndIdx; ++i) { 1151 if (!Bits[i].hasValue()) 1152 continue; 1153 if (Bits[i].getValueBitIndex() >= 32) 1154 return false; 1155 } 1156 } 1157 1158 return true; 1159 }; 1160 1161 for (auto &BG : BitGroups) { 1162 if (BG.StartIdx < 32 && BG.EndIdx < 32) { 1163 if (IsAllLow32(BG)) { 1164 if (BG.RLAmt >= 32) { 1165 BG.RLAmt -= 32; 1166 BG.Repl32CR = true; 1167 } 1168 1169 BG.Repl32 = true; 1170 1171 DEBUG(dbgs() << "\t32-bit replicated bit group for " << 1172 BG.V.getNode() << " RLAmt = " << BG.RLAmt << 1173 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n"); 1174 } 1175 } 1176 } 1177 1178 // Now walk through the bit groups, consolidating where possible. 1179 for (auto I = BitGroups.begin(); I != BitGroups.end();) { 1180 // We might want to remove this bit group by merging it with the previous 1181 // group (which might be the ending group). 1182 auto IP = (I == BitGroups.begin()) ? 1183 std::prev(BitGroups.end()) : std::prev(I); 1184 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt && 1185 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) { 1186 1187 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " << 1188 I->V.getNode() << " RLAmt = " << I->RLAmt << 1189 " [" << I->StartIdx << ", " << I->EndIdx << 1190 "] with group with range [" << 1191 IP->StartIdx << ", " << IP->EndIdx << "]\n"); 1192 1193 IP->EndIdx = I->EndIdx; 1194 IP->Repl32CR = IP->Repl32CR || I->Repl32CR; 1195 IP->Repl32Coalesced = true; 1196 I = BitGroups.erase(I); 1197 continue; 1198 } else { 1199 // There is a special case worth handling: If there is a single group 1200 // covering the entire upper 32 bits, and it can be merged with both 1201 // the next and previous groups (which might be the same group), then 1202 // do so. If it is the same group (so there will be only one group in 1203 // total), then we need to reverse the order of the range so that it 1204 // covers the entire 64 bits. 1205 if (I->StartIdx == 32 && I->EndIdx == 63) { 1206 assert(std::next(I) == BitGroups.end() && 1207 "bit group ends at index 63 but there is another?"); 1208 auto IN = BitGroups.begin(); 1209 1210 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V && 1211 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt && 1212 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP && 1213 IsAllLow32(*I)) { 1214 1215 DEBUG(dbgs() << "\tcombining bit group for " << 1216 I->V.getNode() << " RLAmt = " << I->RLAmt << 1217 " [" << I->StartIdx << ", " << I->EndIdx << 1218 "] with 32-bit replicated groups with ranges [" << 1219 IP->StartIdx << ", " << IP->EndIdx << "] and [" << 1220 IN->StartIdx << ", " << IN->EndIdx << "]\n"); 1221 1222 if (IP == IN) { 1223 // There is only one other group; change it to cover the whole 1224 // range (backward, so that it can still be Repl32 but cover the 1225 // whole 64-bit range). 1226 IP->StartIdx = 31; 1227 IP->EndIdx = 30; 1228 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32; 1229 IP->Repl32Coalesced = true; 1230 I = BitGroups.erase(I); 1231 } else { 1232 // There are two separate groups, one before this group and one 1233 // after us (at the beginning). We're going to remove this group, 1234 // but also the group at the very beginning. 1235 IP->EndIdx = IN->EndIdx; 1236 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32; 1237 IP->Repl32Coalesced = true; 1238 I = BitGroups.erase(I); 1239 BitGroups.erase(BitGroups.begin()); 1240 } 1241 1242 // This must be the last group in the vector (and we might have 1243 // just invalidated the iterator above), so break here. 1244 break; 1245 } 1246 } 1247 } 1248 1249 ++I; 1250 } 1251 } 1252 1253 SDValue getI32Imm(unsigned Imm, const SDLoc &dl) { 1254 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 1255 } 1256 1257 uint64_t getZerosMask() { 1258 uint64_t Mask = 0; 1259 for (unsigned i = 0; i < Bits.size(); ++i) { 1260 if (Bits[i].hasValue()) 1261 continue; 1262 Mask |= (UINT64_C(1) << i); 1263 } 1264 1265 return ~Mask; 1266 } 1267 1268 // Depending on the number of groups for a particular value, it might be 1269 // better to rotate, mask explicitly (using andi/andis), and then or the 1270 // result. Select this part of the result first. 1271 void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) { 1272 if (BPermRewriterNoMasking) 1273 return; 1274 1275 for (ValueRotInfo &VRI : ValueRotsVec) { 1276 unsigned Mask = 0; 1277 for (unsigned i = 0; i < Bits.size(); ++i) { 1278 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V) 1279 continue; 1280 if (RLAmt[i] != VRI.RLAmt) 1281 continue; 1282 Mask |= (1u << i); 1283 } 1284 1285 // Compute the masks for andi/andis that would be necessary. 1286 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16; 1287 assert((ANDIMask != 0 || ANDISMask != 0) && 1288 "No set bits in mask for value bit groups"); 1289 bool NeedsRotate = VRI.RLAmt != 0; 1290 1291 // We're trying to minimize the number of instructions. If we have one 1292 // group, using one of andi/andis can break even. If we have three 1293 // groups, we can use both andi and andis and break even (to use both 1294 // andi and andis we also need to or the results together). We need four 1295 // groups if we also need to rotate. To use andi/andis we need to do more 1296 // than break even because rotate-and-mask instructions tend to be easier 1297 // to schedule. 1298 1299 // FIXME: We've biased here against using andi/andis, which is right for 1300 // POWER cores, but not optimal everywhere. For example, on the A2, 1301 // andi/andis have single-cycle latency whereas the rotate-and-mask 1302 // instructions take two cycles, and it would be better to bias toward 1303 // andi/andis in break-even cases. 1304 1305 unsigned NumAndInsts = (unsigned) NeedsRotate + 1306 (unsigned) (ANDIMask != 0) + 1307 (unsigned) (ANDISMask != 0) + 1308 (unsigned) (ANDIMask != 0 && ANDISMask != 0) + 1309 (unsigned) (bool) Res; 1310 1311 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() << 1312 " RL: " << VRI.RLAmt << ":" << 1313 "\n\t\t\tisel using masking: " << NumAndInsts << 1314 " using rotates: " << VRI.NumGroups << "\n"); 1315 1316 if (NumAndInsts >= VRI.NumGroups) 1317 continue; 1318 1319 DEBUG(dbgs() << "\t\t\t\tusing masking\n"); 1320 1321 if (InstCnt) *InstCnt += NumAndInsts; 1322 1323 SDValue VRot; 1324 if (VRI.RLAmt) { 1325 SDValue Ops[] = 1326 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl), 1327 getI32Imm(31, dl) }; 1328 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, 1329 Ops), 0); 1330 } else { 1331 VRot = VRI.V; 1332 } 1333 1334 SDValue ANDIVal, ANDISVal; 1335 if (ANDIMask != 0) 1336 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32, 1337 VRot, getI32Imm(ANDIMask, dl)), 0); 1338 if (ANDISMask != 0) 1339 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32, 1340 VRot, getI32Imm(ANDISMask, dl)), 0); 1341 1342 SDValue TotalVal; 1343 if (!ANDIVal) 1344 TotalVal = ANDISVal; 1345 else if (!ANDISVal) 1346 TotalVal = ANDIVal; 1347 else 1348 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1349 ANDIVal, ANDISVal), 0); 1350 1351 if (!Res) 1352 Res = TotalVal; 1353 else 1354 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1355 Res, TotalVal), 0); 1356 1357 // Now, remove all groups with this underlying value and rotation 1358 // factor. 1359 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 1360 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt; 1361 }); 1362 } 1363 } 1364 1365 // Instruction selection for the 32-bit case. 1366 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) { 1367 SDLoc dl(N); 1368 SDValue Res; 1369 1370 if (InstCnt) *InstCnt = 0; 1371 1372 // Take care of cases that should use andi/andis first. 1373 SelectAndParts32(dl, Res, InstCnt); 1374 1375 // If we've not yet selected a 'starting' instruction, and we have no zeros 1376 // to fill in, select the (Value, RLAmt) with the highest priority (largest 1377 // number of groups), and start with this rotated value. 1378 if ((!HasZeros || LateMask) && !Res) { 1379 ValueRotInfo &VRI = ValueRotsVec[0]; 1380 if (VRI.RLAmt) { 1381 if (InstCnt) *InstCnt += 1; 1382 SDValue Ops[] = 1383 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl), 1384 getI32Imm(31, dl) }; 1385 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 1386 0); 1387 } else { 1388 Res = VRI.V; 1389 } 1390 1391 // Now, remove all groups with this underlying value and rotation factor. 1392 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 1393 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt; 1394 }); 1395 } 1396 1397 if (InstCnt) *InstCnt += BitGroups.size(); 1398 1399 // Insert the other groups (one at a time). 1400 for (auto &BG : BitGroups) { 1401 if (!Res) { 1402 SDValue Ops[] = 1403 { BG.V, getI32Imm(BG.RLAmt, dl), 1404 getI32Imm(Bits.size() - BG.EndIdx - 1, dl), 1405 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) }; 1406 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 1407 } else { 1408 SDValue Ops[] = 1409 { Res, BG.V, getI32Imm(BG.RLAmt, dl), 1410 getI32Imm(Bits.size() - BG.EndIdx - 1, dl), 1411 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) }; 1412 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0); 1413 } 1414 } 1415 1416 if (LateMask) { 1417 unsigned Mask = (unsigned) getZerosMask(); 1418 1419 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16; 1420 assert((ANDIMask != 0 || ANDISMask != 0) && 1421 "No set bits in zeros mask?"); 1422 1423 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) + 1424 (unsigned) (ANDISMask != 0) + 1425 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 1426 1427 SDValue ANDIVal, ANDISVal; 1428 if (ANDIMask != 0) 1429 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32, 1430 Res, getI32Imm(ANDIMask, dl)), 0); 1431 if (ANDISMask != 0) 1432 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32, 1433 Res, getI32Imm(ANDISMask, dl)), 0); 1434 1435 if (!ANDIVal) 1436 Res = ANDISVal; 1437 else if (!ANDISVal) 1438 Res = ANDIVal; 1439 else 1440 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1441 ANDIVal, ANDISVal), 0); 1442 } 1443 1444 return Res.getNode(); 1445 } 1446 1447 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32, 1448 unsigned MaskStart, unsigned MaskEnd, 1449 bool IsIns) { 1450 // In the notation used by the instructions, 'start' and 'end' are reversed 1451 // because bits are counted from high to low order. 1452 unsigned InstMaskStart = 64 - MaskEnd - 1, 1453 InstMaskEnd = 64 - MaskStart - 1; 1454 1455 if (Repl32) 1456 return 1; 1457 1458 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) || 1459 InstMaskEnd == 63 - RLAmt) 1460 return 1; 1461 1462 return 2; 1463 } 1464 1465 // For 64-bit values, not all combinations of rotates and masks are 1466 // available. Produce one if it is available. 1467 SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt, 1468 bool Repl32, unsigned MaskStart, unsigned MaskEnd, 1469 unsigned *InstCnt = nullptr) { 1470 // In the notation used by the instructions, 'start' and 'end' are reversed 1471 // because bits are counted from high to low order. 1472 unsigned InstMaskStart = 64 - MaskEnd - 1, 1473 InstMaskEnd = 64 - MaskStart - 1; 1474 1475 if (InstCnt) *InstCnt += 1; 1476 1477 if (Repl32) { 1478 // This rotation amount assumes that the lower 32 bits of the quantity 1479 // are replicated in the high 32 bits by the rotation operator (which is 1480 // done by rlwinm and friends). 1481 assert(InstMaskStart >= 32 && "Mask cannot start out of range"); 1482 assert(InstMaskEnd >= 32 && "Mask cannot end out of range"); 1483 SDValue Ops[] = 1484 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl), 1485 getI32Imm(InstMaskEnd - 32, dl) }; 1486 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64, 1487 Ops), 0); 1488 } 1489 1490 if (InstMaskEnd == 63) { 1491 SDValue Ops[] = 1492 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) }; 1493 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0); 1494 } 1495 1496 if (InstMaskStart == 0) { 1497 SDValue Ops[] = 1498 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) }; 1499 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0); 1500 } 1501 1502 if (InstMaskEnd == 63 - RLAmt) { 1503 SDValue Ops[] = 1504 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) }; 1505 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0); 1506 } 1507 1508 // We cannot do this with a single instruction, so we'll use two. The 1509 // problem is that we're not free to choose both a rotation amount and mask 1510 // start and end independently. We can choose an arbitrary mask start and 1511 // end, but then the rotation amount is fixed. Rotation, however, can be 1512 // inverted, and so by applying an "inverse" rotation first, we can get the 1513 // desired result. 1514 if (InstCnt) *InstCnt += 1; 1515 1516 // The rotation mask for the second instruction must be MaskStart. 1517 unsigned RLAmt2 = MaskStart; 1518 // The first instruction must rotate V so that the overall rotation amount 1519 // is RLAmt. 1520 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64; 1521 if (RLAmt1) 1522 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63); 1523 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd); 1524 } 1525 1526 // For 64-bit values, not all combinations of rotates and masks are 1527 // available. Produce a rotate-mask-and-insert if one is available. 1528 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl, 1529 unsigned RLAmt, bool Repl32, unsigned MaskStart, 1530 unsigned MaskEnd, unsigned *InstCnt = nullptr) { 1531 // In the notation used by the instructions, 'start' and 'end' are reversed 1532 // because bits are counted from high to low order. 1533 unsigned InstMaskStart = 64 - MaskEnd - 1, 1534 InstMaskEnd = 64 - MaskStart - 1; 1535 1536 if (InstCnt) *InstCnt += 1; 1537 1538 if (Repl32) { 1539 // This rotation amount assumes that the lower 32 bits of the quantity 1540 // are replicated in the high 32 bits by the rotation operator (which is 1541 // done by rlwinm and friends). 1542 assert(InstMaskStart >= 32 && "Mask cannot start out of range"); 1543 assert(InstMaskEnd >= 32 && "Mask cannot end out of range"); 1544 SDValue Ops[] = 1545 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl), 1546 getI32Imm(InstMaskEnd - 32, dl) }; 1547 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64, 1548 Ops), 0); 1549 } 1550 1551 if (InstMaskEnd == 63 - RLAmt) { 1552 SDValue Ops[] = 1553 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) }; 1554 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0); 1555 } 1556 1557 // We cannot do this with a single instruction, so we'll use two. The 1558 // problem is that we're not free to choose both a rotation amount and mask 1559 // start and end independently. We can choose an arbitrary mask start and 1560 // end, but then the rotation amount is fixed. Rotation, however, can be 1561 // inverted, and so by applying an "inverse" rotation first, we can get the 1562 // desired result. 1563 if (InstCnt) *InstCnt += 1; 1564 1565 // The rotation mask for the second instruction must be MaskStart. 1566 unsigned RLAmt2 = MaskStart; 1567 // The first instruction must rotate V so that the overall rotation amount 1568 // is RLAmt. 1569 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64; 1570 if (RLAmt1) 1571 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63); 1572 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd); 1573 } 1574 1575 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) { 1576 if (BPermRewriterNoMasking) 1577 return; 1578 1579 // The idea here is the same as in the 32-bit version, but with additional 1580 // complications from the fact that Repl32 might be true. Because we 1581 // aggressively convert bit groups to Repl32 form (which, for small 1582 // rotation factors, involves no other change), and then coalesce, it might 1583 // be the case that a single 64-bit masking operation could handle both 1584 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32 1585 // form allowed coalescing, then we must use a 32-bit rotaton in order to 1586 // completely capture the new combined bit group. 1587 1588 for (ValueRotInfo &VRI : ValueRotsVec) { 1589 uint64_t Mask = 0; 1590 1591 // We need to add to the mask all bits from the associated bit groups. 1592 // If Repl32 is false, we need to add bits from bit groups that have 1593 // Repl32 true, but are trivially convertable to Repl32 false. Such a 1594 // group is trivially convertable if it overlaps only with the lower 32 1595 // bits, and the group has not been coalesced. 1596 auto MatchingBG = [VRI](const BitGroup &BG) { 1597 if (VRI.V != BG.V) 1598 return false; 1599 1600 unsigned EffRLAmt = BG.RLAmt; 1601 if (!VRI.Repl32 && BG.Repl32) { 1602 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx && 1603 !BG.Repl32Coalesced) { 1604 if (BG.Repl32CR) 1605 EffRLAmt += 32; 1606 } else { 1607 return false; 1608 } 1609 } else if (VRI.Repl32 != BG.Repl32) { 1610 return false; 1611 } 1612 1613 return VRI.RLAmt == EffRLAmt; 1614 }; 1615 1616 for (auto &BG : BitGroups) { 1617 if (!MatchingBG(BG)) 1618 continue; 1619 1620 if (BG.StartIdx <= BG.EndIdx) { 1621 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) 1622 Mask |= (UINT64_C(1) << i); 1623 } else { 1624 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) 1625 Mask |= (UINT64_C(1) << i); 1626 for (unsigned i = 0; i <= BG.EndIdx; ++i) 1627 Mask |= (UINT64_C(1) << i); 1628 } 1629 } 1630 1631 // We can use the 32-bit andi/andis technique if the mask does not 1632 // require any higher-order bits. This can save an instruction compared 1633 // to always using the general 64-bit technique. 1634 bool Use32BitInsts = isUInt<32>(Mask); 1635 // Compute the masks for andi/andis that would be necessary. 1636 unsigned ANDIMask = (Mask & UINT16_MAX), 1637 ANDISMask = (Mask >> 16) & UINT16_MAX; 1638 1639 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)); 1640 1641 unsigned NumAndInsts = (unsigned) NeedsRotate + 1642 (unsigned) (bool) Res; 1643 if (Use32BitInsts) 1644 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) + 1645 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 1646 else 1647 NumAndInsts += getInt64Count(Mask) + /* and */ 1; 1648 1649 unsigned NumRLInsts = 0; 1650 bool FirstBG = true; 1651 for (auto &BG : BitGroups) { 1652 if (!MatchingBG(BG)) 1653 continue; 1654 NumRLInsts += 1655 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx, 1656 !FirstBG); 1657 FirstBG = false; 1658 } 1659 1660 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() << 1661 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") << 1662 "\n\t\t\tisel using masking: " << NumAndInsts << 1663 " using rotates: " << NumRLInsts << "\n"); 1664 1665 // When we'd use andi/andis, we bias toward using the rotates (andi only 1666 // has a record form, and is cracked on POWER cores). However, when using 1667 // general 64-bit constant formation, bias toward the constant form, 1668 // because that exposes more opportunities for CSE. 1669 if (NumAndInsts > NumRLInsts) 1670 continue; 1671 if (Use32BitInsts && NumAndInsts == NumRLInsts) 1672 continue; 1673 1674 DEBUG(dbgs() << "\t\t\t\tusing masking\n"); 1675 1676 if (InstCnt) *InstCnt += NumAndInsts; 1677 1678 SDValue VRot; 1679 // We actually need to generate a rotation if we have a non-zero rotation 1680 // factor or, in the Repl32 case, if we care about any of the 1681 // higher-order replicated bits. In the latter case, we generate a mask 1682 // backward so that it actually includes the entire 64 bits. 1683 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask))) 1684 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32, 1685 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63); 1686 else 1687 VRot = VRI.V; 1688 1689 SDValue TotalVal; 1690 if (Use32BitInsts) { 1691 assert((ANDIMask != 0 || ANDISMask != 0) && 1692 "No set bits in mask when using 32-bit ands for 64-bit value"); 1693 1694 SDValue ANDIVal, ANDISVal; 1695 if (ANDIMask != 0) 1696 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64, 1697 VRot, getI32Imm(ANDIMask, dl)), 0); 1698 if (ANDISMask != 0) 1699 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64, 1700 VRot, getI32Imm(ANDISMask, dl)), 0); 1701 1702 if (!ANDIVal) 1703 TotalVal = ANDISVal; 1704 else if (!ANDISVal) 1705 TotalVal = ANDIVal; 1706 else 1707 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 1708 ANDIVal, ANDISVal), 0); 1709 } else { 1710 TotalVal = SDValue(getInt64(CurDAG, dl, Mask), 0); 1711 TotalVal = 1712 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64, 1713 VRot, TotalVal), 0); 1714 } 1715 1716 if (!Res) 1717 Res = TotalVal; 1718 else 1719 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 1720 Res, TotalVal), 0); 1721 1722 // Now, remove all groups with this underlying value and rotation 1723 // factor. 1724 eraseMatchingBitGroups(MatchingBG); 1725 } 1726 } 1727 1728 // Instruction selection for the 64-bit case. 1729 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) { 1730 SDLoc dl(N); 1731 SDValue Res; 1732 1733 if (InstCnt) *InstCnt = 0; 1734 1735 // Take care of cases that should use andi/andis first. 1736 SelectAndParts64(dl, Res, InstCnt); 1737 1738 // If we've not yet selected a 'starting' instruction, and we have no zeros 1739 // to fill in, select the (Value, RLAmt) with the highest priority (largest 1740 // number of groups), and start with this rotated value. 1741 if ((!HasZeros || LateMask) && !Res) { 1742 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32 1743 // groups will come first, and so the VRI representing the largest number 1744 // of groups might not be first (it might be the first Repl32 groups). 1745 unsigned MaxGroupsIdx = 0; 1746 if (!ValueRotsVec[0].Repl32) { 1747 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i) 1748 if (ValueRotsVec[i].Repl32) { 1749 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups) 1750 MaxGroupsIdx = i; 1751 break; 1752 } 1753 } 1754 1755 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx]; 1756 bool NeedsRotate = false; 1757 if (VRI.RLAmt) { 1758 NeedsRotate = true; 1759 } else if (VRI.Repl32) { 1760 for (auto &BG : BitGroups) { 1761 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt || 1762 BG.Repl32 != VRI.Repl32) 1763 continue; 1764 1765 // We don't need a rotate if the bit group is confined to the lower 1766 // 32 bits. 1767 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx) 1768 continue; 1769 1770 NeedsRotate = true; 1771 break; 1772 } 1773 } 1774 1775 if (NeedsRotate) 1776 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32, 1777 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63, 1778 InstCnt); 1779 else 1780 Res = VRI.V; 1781 1782 // Now, remove all groups with this underlying value and rotation factor. 1783 if (Res) 1784 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 1785 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt && 1786 BG.Repl32 == VRI.Repl32; 1787 }); 1788 } 1789 1790 // Because 64-bit rotates are more flexible than inserts, we might have a 1791 // preference regarding which one we do first (to save one instruction). 1792 if (!Res) 1793 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) { 1794 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx, 1795 false) < 1796 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx, 1797 true)) { 1798 if (I != BitGroups.begin()) { 1799 BitGroup BG = *I; 1800 BitGroups.erase(I); 1801 BitGroups.insert(BitGroups.begin(), BG); 1802 } 1803 1804 break; 1805 } 1806 } 1807 1808 // Insert the other groups (one at a time). 1809 for (auto &BG : BitGroups) { 1810 if (!Res) 1811 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx, 1812 BG.EndIdx, InstCnt); 1813 else 1814 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32, 1815 BG.StartIdx, BG.EndIdx, InstCnt); 1816 } 1817 1818 if (LateMask) { 1819 uint64_t Mask = getZerosMask(); 1820 1821 // We can use the 32-bit andi/andis technique if the mask does not 1822 // require any higher-order bits. This can save an instruction compared 1823 // to always using the general 64-bit technique. 1824 bool Use32BitInsts = isUInt<32>(Mask); 1825 // Compute the masks for andi/andis that would be necessary. 1826 unsigned ANDIMask = (Mask & UINT16_MAX), 1827 ANDISMask = (Mask >> 16) & UINT16_MAX; 1828 1829 if (Use32BitInsts) { 1830 assert((ANDIMask != 0 || ANDISMask != 0) && 1831 "No set bits in mask when using 32-bit ands for 64-bit value"); 1832 1833 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) + 1834 (unsigned) (ANDISMask != 0) + 1835 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 1836 1837 SDValue ANDIVal, ANDISVal; 1838 if (ANDIMask != 0) 1839 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64, 1840 Res, getI32Imm(ANDIMask, dl)), 0); 1841 if (ANDISMask != 0) 1842 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64, 1843 Res, getI32Imm(ANDISMask, dl)), 0); 1844 1845 if (!ANDIVal) 1846 Res = ANDISVal; 1847 else if (!ANDISVal) 1848 Res = ANDIVal; 1849 else 1850 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 1851 ANDIVal, ANDISVal), 0); 1852 } else { 1853 if (InstCnt) *InstCnt += getInt64Count(Mask) + /* and */ 1; 1854 1855 SDValue MaskVal = SDValue(getInt64(CurDAG, dl, Mask), 0); 1856 Res = 1857 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64, 1858 Res, MaskVal), 0); 1859 } 1860 } 1861 1862 return Res.getNode(); 1863 } 1864 1865 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) { 1866 // Fill in BitGroups. 1867 collectBitGroups(LateMask); 1868 if (BitGroups.empty()) 1869 return nullptr; 1870 1871 // For 64-bit values, figure out when we can use 32-bit instructions. 1872 if (Bits.size() == 64) 1873 assignRepl32BitGroups(); 1874 1875 // Fill in ValueRotsVec. 1876 collectValueRotInfo(); 1877 1878 if (Bits.size() == 32) { 1879 return Select32(N, LateMask, InstCnt); 1880 } else { 1881 assert(Bits.size() == 64 && "Not 64 bits here?"); 1882 return Select64(N, LateMask, InstCnt); 1883 } 1884 1885 return nullptr; 1886 } 1887 1888 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) { 1889 BitGroups.erase(remove_if(BitGroups, F), BitGroups.end()); 1890 } 1891 1892 SmallVector<ValueBit, 64> Bits; 1893 1894 bool HasZeros; 1895 SmallVector<unsigned, 64> RLAmt; 1896 1897 SmallVector<BitGroup, 16> BitGroups; 1898 1899 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots; 1900 SmallVector<ValueRotInfo, 16> ValueRotsVec; 1901 1902 SelectionDAG *CurDAG; 1903 1904 public: 1905 BitPermutationSelector(SelectionDAG *DAG) 1906 : CurDAG(DAG) {} 1907 1908 // Here we try to match complex bit permutations into a set of 1909 // rotate-and-shift/shift/and/or instructions, using a set of heuristics 1910 // known to produce optimial code for common cases (like i32 byte swapping). 1911 SDNode *Select(SDNode *N) { 1912 Bits.resize(N->getValueType(0).getSizeInBits()); 1913 if (!getValueBits(SDValue(N, 0), Bits)) 1914 return nullptr; 1915 1916 DEBUG(dbgs() << "Considering bit-permutation-based instruction" 1917 " selection for: "); 1918 DEBUG(N->dump(CurDAG)); 1919 1920 // Fill it RLAmt and set HasZeros. 1921 computeRotationAmounts(); 1922 1923 if (!HasZeros) 1924 return Select(N, false); 1925 1926 // We currently have two techniques for handling results with zeros: early 1927 // masking (the default) and late masking. Late masking is sometimes more 1928 // efficient, but because the structure of the bit groups is different, it 1929 // is hard to tell without generating both and comparing the results. With 1930 // late masking, we ignore zeros in the resulting value when inserting each 1931 // set of bit groups, and then mask in the zeros at the end. With early 1932 // masking, we only insert the non-zero parts of the result at every step. 1933 1934 unsigned InstCnt, InstCntLateMask; 1935 DEBUG(dbgs() << "\tEarly masking:\n"); 1936 SDNode *RN = Select(N, false, &InstCnt); 1937 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n"); 1938 1939 DEBUG(dbgs() << "\tLate masking:\n"); 1940 SDNode *RNLM = Select(N, true, &InstCntLateMask); 1941 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask << 1942 " instructions\n"); 1943 1944 if (InstCnt <= InstCntLateMask) { 1945 DEBUG(dbgs() << "\tUsing early-masking for isel\n"); 1946 return RN; 1947 } 1948 1949 DEBUG(dbgs() << "\tUsing late-masking for isel\n"); 1950 return RNLM; 1951 } 1952 }; 1953 } // anonymous namespace 1954 1955 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) { 1956 if (N->getValueType(0) != MVT::i32 && 1957 N->getValueType(0) != MVT::i64) 1958 return false; 1959 1960 if (!UseBitPermRewriter) 1961 return false; 1962 1963 switch (N->getOpcode()) { 1964 default: break; 1965 case ISD::ROTL: 1966 case ISD::SHL: 1967 case ISD::SRL: 1968 case ISD::AND: 1969 case ISD::OR: { 1970 BitPermutationSelector BPS(CurDAG); 1971 if (SDNode *New = BPS.Select(N)) { 1972 ReplaceNode(N, New); 1973 return true; 1974 } 1975 return false; 1976 } 1977 } 1978 1979 return false; 1980 } 1981 1982 /// SelectCC - Select a comparison of the specified values with the specified 1983 /// condition code, returning the CR# of the expression. 1984 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1985 const SDLoc &dl) { 1986 // Always select the LHS. 1987 unsigned Opc; 1988 1989 if (LHS.getValueType() == MVT::i32) { 1990 unsigned Imm; 1991 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 1992 if (isInt32Immediate(RHS, Imm)) { 1993 // SETEQ/SETNE comparison with 16-bit immediate, fold it. 1994 if (isUInt<16>(Imm)) 1995 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS, 1996 getI32Imm(Imm & 0xFFFF, dl)), 1997 0); 1998 // If this is a 16-bit signed immediate, fold it. 1999 if (isInt<16>((int)Imm)) 2000 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS, 2001 getI32Imm(Imm & 0xFFFF, dl)), 2002 0); 2003 2004 // For non-equality comparisons, the default code would materialize the 2005 // constant, then compare against it, like this: 2006 // lis r2, 4660 2007 // ori r2, r2, 22136 2008 // cmpw cr0, r3, r2 2009 // Since we are just comparing for equality, we can emit this instead: 2010 // xoris r0,r3,0x1234 2011 // cmplwi cr0,r0,0x5678 2012 // beq cr0,L6 2013 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS, 2014 getI32Imm(Imm >> 16, dl)), 0); 2015 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor, 2016 getI32Imm(Imm & 0xFFFF, dl)), 0); 2017 } 2018 Opc = PPC::CMPLW; 2019 } else if (ISD::isUnsignedIntSetCC(CC)) { 2020 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm)) 2021 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS, 2022 getI32Imm(Imm & 0xFFFF, dl)), 0); 2023 Opc = PPC::CMPLW; 2024 } else { 2025 short SImm; 2026 if (isIntS16Immediate(RHS, SImm)) 2027 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS, 2028 getI32Imm((int)SImm & 0xFFFF, 2029 dl)), 2030 0); 2031 Opc = PPC::CMPW; 2032 } 2033 } else if (LHS.getValueType() == MVT::i64) { 2034 uint64_t Imm; 2035 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2036 if (isInt64Immediate(RHS.getNode(), Imm)) { 2037 // SETEQ/SETNE comparison with 16-bit immediate, fold it. 2038 if (isUInt<16>(Imm)) 2039 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS, 2040 getI32Imm(Imm & 0xFFFF, dl)), 2041 0); 2042 // If this is a 16-bit signed immediate, fold it. 2043 if (isInt<16>(Imm)) 2044 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS, 2045 getI32Imm(Imm & 0xFFFF, dl)), 2046 0); 2047 2048 // For non-equality comparisons, the default code would materialize the 2049 // constant, then compare against it, like this: 2050 // lis r2, 4660 2051 // ori r2, r2, 22136 2052 // cmpd cr0, r3, r2 2053 // Since we are just comparing for equality, we can emit this instead: 2054 // xoris r0,r3,0x1234 2055 // cmpldi cr0,r0,0x5678 2056 // beq cr0,L6 2057 if (isUInt<32>(Imm)) { 2058 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS, 2059 getI64Imm(Imm >> 16, dl)), 0); 2060 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor, 2061 getI64Imm(Imm & 0xFFFF, dl)), 2062 0); 2063 } 2064 } 2065 Opc = PPC::CMPLD; 2066 } else if (ISD::isUnsignedIntSetCC(CC)) { 2067 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm)) 2068 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS, 2069 getI64Imm(Imm & 0xFFFF, dl)), 0); 2070 Opc = PPC::CMPLD; 2071 } else { 2072 short SImm; 2073 if (isIntS16Immediate(RHS, SImm)) 2074 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS, 2075 getI64Imm(SImm & 0xFFFF, dl)), 2076 0); 2077 Opc = PPC::CMPD; 2078 } 2079 } else if (LHS.getValueType() == MVT::f32) { 2080 Opc = PPC::FCMPUS; 2081 } else { 2082 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!"); 2083 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD; 2084 } 2085 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0); 2086 } 2087 2088 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) { 2089 switch (CC) { 2090 case ISD::SETUEQ: 2091 case ISD::SETONE: 2092 case ISD::SETOLE: 2093 case ISD::SETOGE: 2094 llvm_unreachable("Should be lowered by legalize!"); 2095 default: llvm_unreachable("Unknown condition!"); 2096 case ISD::SETOEQ: 2097 case ISD::SETEQ: return PPC::PRED_EQ; 2098 case ISD::SETUNE: 2099 case ISD::SETNE: return PPC::PRED_NE; 2100 case ISD::SETOLT: 2101 case ISD::SETLT: return PPC::PRED_LT; 2102 case ISD::SETULE: 2103 case ISD::SETLE: return PPC::PRED_LE; 2104 case ISD::SETOGT: 2105 case ISD::SETGT: return PPC::PRED_GT; 2106 case ISD::SETUGE: 2107 case ISD::SETGE: return PPC::PRED_GE; 2108 case ISD::SETO: return PPC::PRED_NU; 2109 case ISD::SETUO: return PPC::PRED_UN; 2110 // These two are invalid for floating point. Assume we have int. 2111 case ISD::SETULT: return PPC::PRED_LT; 2112 case ISD::SETUGT: return PPC::PRED_GT; 2113 } 2114 } 2115 2116 /// getCRIdxForSetCC - Return the index of the condition register field 2117 /// associated with the SetCC condition, and whether or not the field is 2118 /// treated as inverted. That is, lt = 0; ge = 0 inverted. 2119 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) { 2120 Invert = false; 2121 switch (CC) { 2122 default: llvm_unreachable("Unknown condition!"); 2123 case ISD::SETOLT: 2124 case ISD::SETLT: return 0; // Bit #0 = SETOLT 2125 case ISD::SETOGT: 2126 case ISD::SETGT: return 1; // Bit #1 = SETOGT 2127 case ISD::SETOEQ: 2128 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ 2129 case ISD::SETUO: return 3; // Bit #3 = SETUO 2130 case ISD::SETUGE: 2131 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE 2132 case ISD::SETULE: 2133 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE 2134 case ISD::SETUNE: 2135 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE 2136 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO 2137 case ISD::SETUEQ: 2138 case ISD::SETOGE: 2139 case ISD::SETOLE: 2140 case ISD::SETONE: 2141 llvm_unreachable("Invalid branch code: should be expanded by legalize"); 2142 // These are invalid for floating point. Assume integer. 2143 case ISD::SETULT: return 0; 2144 case ISD::SETUGT: return 1; 2145 } 2146 } 2147 2148 // getVCmpInst: return the vector compare instruction for the specified 2149 // vector type and condition code. Since this is for altivec specific code, 2150 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32). 2151 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC, 2152 bool HasVSX, bool &Swap, bool &Negate) { 2153 Swap = false; 2154 Negate = false; 2155 2156 if (VecVT.isFloatingPoint()) { 2157 /* Handle some cases by swapping input operands. */ 2158 switch (CC) { 2159 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break; 2160 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break; 2161 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break; 2162 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break; 2163 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break; 2164 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break; 2165 default: break; 2166 } 2167 /* Handle some cases by negating the result. */ 2168 switch (CC) { 2169 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break; 2170 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break; 2171 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break; 2172 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break; 2173 default: break; 2174 } 2175 /* We have instructions implementing the remaining cases. */ 2176 switch (CC) { 2177 case ISD::SETEQ: 2178 case ISD::SETOEQ: 2179 if (VecVT == MVT::v4f32) 2180 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP; 2181 else if (VecVT == MVT::v2f64) 2182 return PPC::XVCMPEQDP; 2183 break; 2184 case ISD::SETGT: 2185 case ISD::SETOGT: 2186 if (VecVT == MVT::v4f32) 2187 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP; 2188 else if (VecVT == MVT::v2f64) 2189 return PPC::XVCMPGTDP; 2190 break; 2191 case ISD::SETGE: 2192 case ISD::SETOGE: 2193 if (VecVT == MVT::v4f32) 2194 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP; 2195 else if (VecVT == MVT::v2f64) 2196 return PPC::XVCMPGEDP; 2197 break; 2198 default: 2199 break; 2200 } 2201 llvm_unreachable("Invalid floating-point vector compare condition"); 2202 } else { 2203 /* Handle some cases by swapping input operands. */ 2204 switch (CC) { 2205 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break; 2206 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break; 2207 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break; 2208 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break; 2209 default: break; 2210 } 2211 /* Handle some cases by negating the result. */ 2212 switch (CC) { 2213 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break; 2214 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break; 2215 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break; 2216 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break; 2217 default: break; 2218 } 2219 /* We have instructions implementing the remaining cases. */ 2220 switch (CC) { 2221 case ISD::SETEQ: 2222 case ISD::SETUEQ: 2223 if (VecVT == MVT::v16i8) 2224 return PPC::VCMPEQUB; 2225 else if (VecVT == MVT::v8i16) 2226 return PPC::VCMPEQUH; 2227 else if (VecVT == MVT::v4i32) 2228 return PPC::VCMPEQUW; 2229 else if (VecVT == MVT::v2i64) 2230 return PPC::VCMPEQUD; 2231 break; 2232 case ISD::SETGT: 2233 if (VecVT == MVT::v16i8) 2234 return PPC::VCMPGTSB; 2235 else if (VecVT == MVT::v8i16) 2236 return PPC::VCMPGTSH; 2237 else if (VecVT == MVT::v4i32) 2238 return PPC::VCMPGTSW; 2239 else if (VecVT == MVT::v2i64) 2240 return PPC::VCMPGTSD; 2241 break; 2242 case ISD::SETUGT: 2243 if (VecVT == MVT::v16i8) 2244 return PPC::VCMPGTUB; 2245 else if (VecVT == MVT::v8i16) 2246 return PPC::VCMPGTUH; 2247 else if (VecVT == MVT::v4i32) 2248 return PPC::VCMPGTUW; 2249 else if (VecVT == MVT::v2i64) 2250 return PPC::VCMPGTUD; 2251 break; 2252 default: 2253 break; 2254 } 2255 llvm_unreachable("Invalid integer vector compare condition"); 2256 } 2257 } 2258 2259 bool PPCDAGToDAGISel::trySETCC(SDNode *N) { 2260 SDLoc dl(N); 2261 unsigned Imm; 2262 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 2263 EVT PtrVT = 2264 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout()); 2265 bool isPPC64 = (PtrVT == MVT::i64); 2266 2267 if (!PPCSubTarget->useCRBits() && 2268 isInt32Immediate(N->getOperand(1), Imm)) { 2269 // We can codegen setcc op, imm very efficiently compared to a brcond. 2270 // Check for those cases here. 2271 // setcc op, 0 2272 if (Imm == 0) { 2273 SDValue Op = N->getOperand(0); 2274 switch (CC) { 2275 default: break; 2276 case ISD::SETEQ: { 2277 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0); 2278 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl), 2279 getI32Imm(31, dl) }; 2280 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2281 return true; 2282 } 2283 case ISD::SETNE: { 2284 if (isPPC64) break; 2285 SDValue AD = 2286 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 2287 Op, getI32Imm(~0U, dl)), 0); 2288 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1)); 2289 return true; 2290 } 2291 case ISD::SETLT: { 2292 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl), 2293 getI32Imm(31, dl) }; 2294 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2295 return true; 2296 } 2297 case ISD::SETGT: { 2298 SDValue T = 2299 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0); 2300 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0); 2301 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl), 2302 getI32Imm(31, dl) }; 2303 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2304 return true; 2305 } 2306 } 2307 } else if (Imm == ~0U) { // setcc op, -1 2308 SDValue Op = N->getOperand(0); 2309 switch (CC) { 2310 default: break; 2311 case ISD::SETEQ: 2312 if (isPPC64) break; 2313 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 2314 Op, getI32Imm(1, dl)), 0); 2315 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 2316 SDValue(CurDAG->getMachineNode(PPC::LI, dl, 2317 MVT::i32, 2318 getI32Imm(0, dl)), 2319 0), Op.getValue(1)); 2320 return true; 2321 case ISD::SETNE: { 2322 if (isPPC64) break; 2323 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0); 2324 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 2325 Op, getI32Imm(~0U, dl)); 2326 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op, 2327 SDValue(AD, 1)); 2328 return true; 2329 } 2330 case ISD::SETLT: { 2331 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op, 2332 getI32Imm(1, dl)), 0); 2333 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD, 2334 Op), 0); 2335 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl), 2336 getI32Imm(31, dl) }; 2337 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2338 return true; 2339 } 2340 case ISD::SETGT: { 2341 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl), 2342 getI32Imm(31, dl) }; 2343 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 2344 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl)); 2345 return true; 2346 } 2347 } 2348 } 2349 } 2350 2351 SDValue LHS = N->getOperand(0); 2352 SDValue RHS = N->getOperand(1); 2353 2354 // Altivec Vector compare instructions do not set any CR register by default and 2355 // vector compare operations return the same type as the operands. 2356 if (LHS.getValueType().isVector()) { 2357 if (PPCSubTarget->hasQPX()) 2358 return false; 2359 2360 EVT VecVT = LHS.getValueType(); 2361 bool Swap, Negate; 2362 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC, 2363 PPCSubTarget->hasVSX(), Swap, Negate); 2364 if (Swap) 2365 std::swap(LHS, RHS); 2366 2367 EVT ResVT = VecVT.changeVectorElementTypeToInteger(); 2368 if (Negate) { 2369 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0); 2370 CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR, 2371 ResVT, VCmp, VCmp); 2372 return true; 2373 } 2374 2375 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS); 2376 return true; 2377 } 2378 2379 if (PPCSubTarget->useCRBits()) 2380 return false; 2381 2382 bool Inv; 2383 unsigned Idx = getCRIdxForSetCC(CC, Inv); 2384 SDValue CCReg = SelectCC(LHS, RHS, CC, dl); 2385 SDValue IntCR; 2386 2387 // Force the ccreg into CR7. 2388 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32); 2389 2390 SDValue InFlag(nullptr, 0); // Null incoming flag value. 2391 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg, 2392 InFlag).getValue(1); 2393 2394 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg, 2395 CCReg), 0); 2396 2397 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl), 2398 getI32Imm(31, dl), getI32Imm(31, dl) }; 2399 if (!Inv) { 2400 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2401 return true; 2402 } 2403 2404 // Get the specified bit. 2405 SDValue Tmp = 2406 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 2407 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl)); 2408 return true; 2409 } 2410 2411 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) { 2412 // Transfer memoperands. 2413 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1); 2414 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 2415 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1); 2416 } 2417 2418 2419 // Select - Convert the specified operand from a target-independent to a 2420 // target-specific node if it hasn't already been changed. 2421 void PPCDAGToDAGISel::Select(SDNode *N) { 2422 SDLoc dl(N); 2423 if (N->isMachineOpcode()) { 2424 N->setNodeId(-1); 2425 return; // Already selected. 2426 } 2427 2428 // In case any misguided DAG-level optimizations form an ADD with a 2429 // TargetConstant operand, crash here instead of miscompiling (by selecting 2430 // an r+r add instead of some kind of r+i add). 2431 if (N->getOpcode() == ISD::ADD && 2432 N->getOperand(1).getOpcode() == ISD::TargetConstant) 2433 llvm_unreachable("Invalid ADD with TargetConstant operand"); 2434 2435 // Try matching complex bit permutations before doing anything else. 2436 if (tryBitPermutation(N)) 2437 return; 2438 2439 switch (N->getOpcode()) { 2440 default: break; 2441 2442 case ISD::Constant: { 2443 if (N->getValueType(0) == MVT::i64) { 2444 ReplaceNode(N, getInt64(CurDAG, N)); 2445 return; 2446 } 2447 break; 2448 } 2449 2450 case ISD::SETCC: { 2451 if (trySETCC(N)) 2452 return; 2453 break; 2454 } 2455 case PPCISD::GlobalBaseReg: 2456 ReplaceNode(N, getGlobalBaseReg()); 2457 return; 2458 2459 case ISD::FrameIndex: 2460 selectFrameIndex(N, N); 2461 return; 2462 2463 case PPCISD::MFOCRF: { 2464 SDValue InFlag = N->getOperand(1); 2465 ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, 2466 N->getOperand(0), InFlag)); 2467 return; 2468 } 2469 2470 case PPCISD::READ_TIME_BASE: { 2471 ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32, 2472 MVT::Other, N->getOperand(0))); 2473 return; 2474 } 2475 2476 case PPCISD::SRA_ADDZE: { 2477 SDValue N0 = N->getOperand(0); 2478 SDValue ShiftAmt = 2479 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))-> 2480 getConstantIntValue(), dl, 2481 N->getValueType(0)); 2482 if (N->getValueType(0) == MVT::i64) { 2483 SDNode *Op = 2484 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue, 2485 N0, ShiftAmt); 2486 CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0), 2487 SDValue(Op, 1)); 2488 return; 2489 } else { 2490 assert(N->getValueType(0) == MVT::i32 && 2491 "Expecting i64 or i32 in PPCISD::SRA_ADDZE"); 2492 SDNode *Op = 2493 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue, 2494 N0, ShiftAmt); 2495 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0), 2496 SDValue(Op, 1)); 2497 return; 2498 } 2499 } 2500 2501 case ISD::LOAD: { 2502 // Handle preincrement loads. 2503 LoadSDNode *LD = cast<LoadSDNode>(N); 2504 EVT LoadedVT = LD->getMemoryVT(); 2505 2506 // Normal loads are handled by code generated from the .td file. 2507 if (LD->getAddressingMode() != ISD::PRE_INC) 2508 break; 2509 2510 SDValue Offset = LD->getOffset(); 2511 if (Offset.getOpcode() == ISD::TargetConstant || 2512 Offset.getOpcode() == ISD::TargetGlobalAddress) { 2513 2514 unsigned Opcode; 2515 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD; 2516 if (LD->getValueType(0) != MVT::i64) { 2517 // Handle PPC32 integer and normal FP loads. 2518 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 2519 switch (LoadedVT.getSimpleVT().SimpleTy) { 2520 default: llvm_unreachable("Invalid PPC load type!"); 2521 case MVT::f64: Opcode = PPC::LFDU; break; 2522 case MVT::f32: Opcode = PPC::LFSU; break; 2523 case MVT::i32: Opcode = PPC::LWZU; break; 2524 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break; 2525 case MVT::i1: 2526 case MVT::i8: Opcode = PPC::LBZU; break; 2527 } 2528 } else { 2529 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!"); 2530 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 2531 switch (LoadedVT.getSimpleVT().SimpleTy) { 2532 default: llvm_unreachable("Invalid PPC load type!"); 2533 case MVT::i64: Opcode = PPC::LDU; break; 2534 case MVT::i32: Opcode = PPC::LWZU8; break; 2535 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break; 2536 case MVT::i1: 2537 case MVT::i8: Opcode = PPC::LBZU8; break; 2538 } 2539 } 2540 2541 SDValue Chain = LD->getChain(); 2542 SDValue Base = LD->getBasePtr(); 2543 SDValue Ops[] = { Offset, Base, Chain }; 2544 SDNode *MN = CurDAG->getMachineNode( 2545 Opcode, dl, LD->getValueType(0), 2546 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops); 2547 transferMemOperands(N, MN); 2548 ReplaceNode(N, MN); 2549 return; 2550 } else { 2551 unsigned Opcode; 2552 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD; 2553 if (LD->getValueType(0) != MVT::i64) { 2554 // Handle PPC32 integer and normal FP loads. 2555 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 2556 switch (LoadedVT.getSimpleVT().SimpleTy) { 2557 default: llvm_unreachable("Invalid PPC load type!"); 2558 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX 2559 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX 2560 case MVT::f64: Opcode = PPC::LFDUX; break; 2561 case MVT::f32: Opcode = PPC::LFSUX; break; 2562 case MVT::i32: Opcode = PPC::LWZUX; break; 2563 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break; 2564 case MVT::i1: 2565 case MVT::i8: Opcode = PPC::LBZUX; break; 2566 } 2567 } else { 2568 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!"); 2569 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) && 2570 "Invalid sext update load"); 2571 switch (LoadedVT.getSimpleVT().SimpleTy) { 2572 default: llvm_unreachable("Invalid PPC load type!"); 2573 case MVT::i64: Opcode = PPC::LDUX; break; 2574 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break; 2575 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break; 2576 case MVT::i1: 2577 case MVT::i8: Opcode = PPC::LBZUX8; break; 2578 } 2579 } 2580 2581 SDValue Chain = LD->getChain(); 2582 SDValue Base = LD->getBasePtr(); 2583 SDValue Ops[] = { Base, Offset, Chain }; 2584 SDNode *MN = CurDAG->getMachineNode( 2585 Opcode, dl, LD->getValueType(0), 2586 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops); 2587 transferMemOperands(N, MN); 2588 ReplaceNode(N, MN); 2589 return; 2590 } 2591 } 2592 2593 case ISD::AND: { 2594 unsigned Imm, Imm2, SH, MB, ME; 2595 uint64_t Imm64; 2596 2597 // If this is an and of a value rotated between 0 and 31 bits and then and'd 2598 // with a mask, emit rlwinm 2599 if (isInt32Immediate(N->getOperand(1), Imm) && 2600 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) { 2601 SDValue Val = N->getOperand(0).getOperand(0); 2602 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl), 2603 getI32Imm(ME, dl) }; 2604 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2605 return; 2606 } 2607 // If this is just a masked value where the input is not handled above, and 2608 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm 2609 if (isInt32Immediate(N->getOperand(1), Imm) && 2610 isRunOfOnes(Imm, MB, ME) && 2611 N->getOperand(0).getOpcode() != ISD::ROTL) { 2612 SDValue Val = N->getOperand(0); 2613 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl), 2614 getI32Imm(ME, dl) }; 2615 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2616 return; 2617 } 2618 // If this is a 64-bit zero-extension mask, emit rldicl. 2619 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) && 2620 isMask_64(Imm64)) { 2621 SDValue Val = N->getOperand(0); 2622 MB = 64 - countTrailingOnes(Imm64); 2623 SH = 0; 2624 2625 // If the operand is a logical right shift, we can fold it into this 2626 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb) 2627 // for n <= mb. The right shift is really a left rotate followed by a 2628 // mask, and this mask is a more-restrictive sub-mask of the mask implied 2629 // by the shift. 2630 if (Val.getOpcode() == ISD::SRL && 2631 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) { 2632 assert(Imm < 64 && "Illegal shift amount"); 2633 Val = Val.getOperand(0); 2634 SH = 64 - Imm; 2635 } 2636 2637 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) }; 2638 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops); 2639 return; 2640 } 2641 // AND X, 0 -> 0, not "rlwinm 32". 2642 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) { 2643 ReplaceUses(SDValue(N, 0), N->getOperand(1)); 2644 return; 2645 } 2646 // ISD::OR doesn't get all the bitfield insertion fun. 2647 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a 2648 // bitfield insert. 2649 if (isInt32Immediate(N->getOperand(1), Imm) && 2650 N->getOperand(0).getOpcode() == ISD::OR && 2651 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) { 2652 // The idea here is to check whether this is equivalent to: 2653 // (c1 & m) | (x & ~m) 2654 // where m is a run-of-ones mask. The logic here is that, for each bit in 2655 // c1 and c2: 2656 // - if both are 1, then the output will be 1. 2657 // - if both are 0, then the output will be 0. 2658 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will 2659 // come from x. 2660 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will 2661 // be 0. 2662 // If that last condition is never the case, then we can form m from the 2663 // bits that are the same between c1 and c2. 2664 unsigned MB, ME; 2665 if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) { 2666 SDValue Ops[] = { N->getOperand(0).getOperand(0), 2667 N->getOperand(0).getOperand(1), 2668 getI32Imm(0, dl), getI32Imm(MB, dl), 2669 getI32Imm(ME, dl) }; 2670 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops)); 2671 return; 2672 } 2673 } 2674 2675 // Other cases are autogenerated. 2676 break; 2677 } 2678 case ISD::OR: { 2679 if (N->getValueType(0) == MVT::i32) 2680 if (tryBitfieldInsert(N)) 2681 return; 2682 2683 short Imm; 2684 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex && 2685 isIntS16Immediate(N->getOperand(1), Imm)) { 2686 APInt LHSKnownZero, LHSKnownOne; 2687 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne); 2688 2689 // If this is equivalent to an add, then we can fold it with the 2690 // FrameIndex calculation. 2691 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) { 2692 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm); 2693 return; 2694 } 2695 } 2696 2697 // Other cases are autogenerated. 2698 break; 2699 } 2700 case ISD::ADD: { 2701 short Imm; 2702 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex && 2703 isIntS16Immediate(N->getOperand(1), Imm)) { 2704 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm); 2705 return; 2706 } 2707 2708 break; 2709 } 2710 case ISD::SHL: { 2711 unsigned Imm, SH, MB, ME; 2712 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) && 2713 isRotateAndMask(N, Imm, true, SH, MB, ME)) { 2714 SDValue Ops[] = { N->getOperand(0).getOperand(0), 2715 getI32Imm(SH, dl), getI32Imm(MB, dl), 2716 getI32Imm(ME, dl) }; 2717 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2718 return; 2719 } 2720 2721 // Other cases are autogenerated. 2722 break; 2723 } 2724 case ISD::SRL: { 2725 unsigned Imm, SH, MB, ME; 2726 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) && 2727 isRotateAndMask(N, Imm, true, SH, MB, ME)) { 2728 SDValue Ops[] = { N->getOperand(0).getOperand(0), 2729 getI32Imm(SH, dl), getI32Imm(MB, dl), 2730 getI32Imm(ME, dl) }; 2731 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2732 return; 2733 } 2734 2735 // Other cases are autogenerated. 2736 break; 2737 } 2738 // FIXME: Remove this once the ANDI glue bug is fixed: 2739 case PPCISD::ANDIo_1_EQ_BIT: 2740 case PPCISD::ANDIo_1_GT_BIT: { 2741 if (!ANDIGlueBug) 2742 break; 2743 2744 EVT InVT = N->getOperand(0).getValueType(); 2745 assert((InVT == MVT::i64 || InVT == MVT::i32) && 2746 "Invalid input type for ANDIo_1_EQ_BIT"); 2747 2748 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo; 2749 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue, 2750 N->getOperand(0), 2751 CurDAG->getTargetConstant(1, dl, InVT)), 2752 0); 2753 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32); 2754 SDValue SRIdxVal = 2755 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ? 2756 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32); 2757 2758 CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg, 2759 SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */); 2760 return; 2761 } 2762 case ISD::SELECT_CC: { 2763 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 2764 EVT PtrVT = 2765 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout()); 2766 bool isPPC64 = (PtrVT == MVT::i64); 2767 2768 // If this is a select of i1 operands, we'll pattern match it. 2769 if (PPCSubTarget->useCRBits() && 2770 N->getOperand(0).getValueType() == MVT::i1) 2771 break; 2772 2773 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc 2774 if (!isPPC64) 2775 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2776 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2))) 2777 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3))) 2778 if (N1C->isNullValue() && N3C->isNullValue() && 2779 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE && 2780 // FIXME: Implement this optzn for PPC64. 2781 N->getValueType(0) == MVT::i32) { 2782 SDNode *Tmp = 2783 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 2784 N->getOperand(0), getI32Imm(~0U, dl)); 2785 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0), 2786 N->getOperand(0), SDValue(Tmp, 1)); 2787 return; 2788 } 2789 2790 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl); 2791 2792 if (N->getValueType(0) == MVT::i1) { 2793 // An i1 select is: (c & t) | (!c & f). 2794 bool Inv; 2795 unsigned Idx = getCRIdxForSetCC(CC, Inv); 2796 2797 unsigned SRI; 2798 switch (Idx) { 2799 default: llvm_unreachable("Invalid CC index"); 2800 case 0: SRI = PPC::sub_lt; break; 2801 case 1: SRI = PPC::sub_gt; break; 2802 case 2: SRI = PPC::sub_eq; break; 2803 case 3: SRI = PPC::sub_un; break; 2804 } 2805 2806 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg); 2807 2808 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1, 2809 CCBit, CCBit), 0); 2810 SDValue C = Inv ? NotCCBit : CCBit, 2811 NotC = Inv ? CCBit : NotCCBit; 2812 2813 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1, 2814 C, N->getOperand(2)), 0); 2815 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1, 2816 NotC, N->getOperand(3)), 0); 2817 2818 CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF); 2819 return; 2820 } 2821 2822 unsigned BROpc = getPredicateForSetCC(CC); 2823 2824 unsigned SelectCCOp; 2825 if (N->getValueType(0) == MVT::i32) 2826 SelectCCOp = PPC::SELECT_CC_I4; 2827 else if (N->getValueType(0) == MVT::i64) 2828 SelectCCOp = PPC::SELECT_CC_I8; 2829 else if (N->getValueType(0) == MVT::f32) 2830 if (PPCSubTarget->hasP8Vector()) 2831 SelectCCOp = PPC::SELECT_CC_VSSRC; 2832 else 2833 SelectCCOp = PPC::SELECT_CC_F4; 2834 else if (N->getValueType(0) == MVT::f64) 2835 if (PPCSubTarget->hasVSX()) 2836 SelectCCOp = PPC::SELECT_CC_VSFRC; 2837 else 2838 SelectCCOp = PPC::SELECT_CC_F8; 2839 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64) 2840 SelectCCOp = PPC::SELECT_CC_QFRC; 2841 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32) 2842 SelectCCOp = PPC::SELECT_CC_QSRC; 2843 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1) 2844 SelectCCOp = PPC::SELECT_CC_QBRC; 2845 else if (N->getValueType(0) == MVT::v2f64 || 2846 N->getValueType(0) == MVT::v2i64) 2847 SelectCCOp = PPC::SELECT_CC_VSRC; 2848 else 2849 SelectCCOp = PPC::SELECT_CC_VRRC; 2850 2851 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3), 2852 getI32Imm(BROpc, dl) }; 2853 CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops); 2854 return; 2855 } 2856 case ISD::VSELECT: 2857 if (PPCSubTarget->hasVSX()) { 2858 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) }; 2859 CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops); 2860 return; 2861 } 2862 2863 break; 2864 case ISD::VECTOR_SHUFFLE: 2865 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 || 2866 N->getValueType(0) == MVT::v2i64)) { 2867 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 2868 2869 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1), 2870 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1); 2871 unsigned DM[2]; 2872 2873 for (int i = 0; i < 2; ++i) 2874 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2) 2875 DM[i] = 0; 2876 else 2877 DM[i] = 1; 2878 2879 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 && 2880 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR && 2881 isa<LoadSDNode>(Op1.getOperand(0))) { 2882 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0)); 2883 SDValue Base, Offset; 2884 2885 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() && 2886 (LD->getMemoryVT() == MVT::f64 || 2887 LD->getMemoryVT() == MVT::i64) && 2888 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) { 2889 SDValue Chain = LD->getChain(); 2890 SDValue Ops[] = { Base, Offset, Chain }; 2891 CurDAG->SelectNodeTo(N, PPC::LXVDSX, N->getValueType(0), Ops); 2892 return; 2893 } 2894 } 2895 2896 // For little endian, we must swap the input operands and adjust 2897 // the mask elements (reverse and invert them). 2898 if (PPCSubTarget->isLittleEndian()) { 2899 std::swap(Op1, Op2); 2900 unsigned tmp = DM[0]; 2901 DM[0] = 1 - DM[1]; 2902 DM[1] = 1 - tmp; 2903 } 2904 2905 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl, 2906 MVT::i32); 2907 SDValue Ops[] = { Op1, Op2, DMV }; 2908 CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops); 2909 return; 2910 } 2911 2912 break; 2913 case PPCISD::BDNZ: 2914 case PPCISD::BDZ: { 2915 bool IsPPC64 = PPCSubTarget->isPPC64(); 2916 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) }; 2917 CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ 2918 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) 2919 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ), 2920 MVT::Other, Ops); 2921 return; 2922 } 2923 case PPCISD::COND_BRANCH: { 2924 // Op #0 is the Chain. 2925 // Op #1 is the PPC::PRED_* number. 2926 // Op #2 is the CR# 2927 // Op #3 is the Dest MBB 2928 // Op #4 is the Flag. 2929 // Prevent PPC::PRED_* from being selected into LI. 2930 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 2931 if (EnableBranchHint) 2932 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3)); 2933 2934 SDValue Pred = getI32Imm(PCC, dl); 2935 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3), 2936 N->getOperand(0), N->getOperand(4) }; 2937 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops); 2938 return; 2939 } 2940 case ISD::BR_CC: { 2941 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 2942 unsigned PCC = getPredicateForSetCC(CC); 2943 2944 if (N->getOperand(2).getValueType() == MVT::i1) { 2945 unsigned Opc; 2946 bool Swap; 2947 switch (PCC) { 2948 default: llvm_unreachable("Unexpected Boolean-operand predicate"); 2949 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break; 2950 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break; 2951 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break; 2952 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break; 2953 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break; 2954 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break; 2955 } 2956 2957 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1, 2958 N->getOperand(Swap ? 3 : 2), 2959 N->getOperand(Swap ? 2 : 3)), 0); 2960 CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4), 2961 N->getOperand(0)); 2962 return; 2963 } 2964 2965 if (EnableBranchHint) 2966 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4)); 2967 2968 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl); 2969 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode, 2970 N->getOperand(4), N->getOperand(0) }; 2971 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops); 2972 return; 2973 } 2974 case ISD::BRIND: { 2975 // FIXME: Should custom lower this. 2976 SDValue Chain = N->getOperand(0); 2977 SDValue Target = N->getOperand(1); 2978 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8; 2979 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8; 2980 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target, 2981 Chain), 0); 2982 CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain); 2983 return; 2984 } 2985 case PPCISD::TOC_ENTRY: { 2986 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) && 2987 "Only supported for 64-bit ABI and 32-bit SVR4"); 2988 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) { 2989 SDValue GA = N->getOperand(0); 2990 SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA, 2991 N->getOperand(1)); 2992 transferMemOperands(N, MN); 2993 ReplaceNode(N, MN); 2994 return; 2995 } 2996 2997 // For medium and large code model, we generate two instructions as 2998 // described below. Otherwise we allow SelectCodeCommon to handle this, 2999 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA. 3000 CodeModel::Model CModel = TM.getCodeModel(); 3001 if (CModel != CodeModel::Medium && CModel != CodeModel::Large) 3002 break; 3003 3004 // The first source operand is a TargetGlobalAddress or a TargetJumpTable. 3005 // If it must be toc-referenced according to PPCSubTarget, we generate: 3006 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>)) 3007 // Otherwise we generate: 3008 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>) 3009 SDValue GA = N->getOperand(0); 3010 SDValue TOCbase = N->getOperand(1); 3011 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64, 3012 TOCbase, GA); 3013 3014 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) || 3015 CModel == CodeModel::Large) { 3016 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA, 3017 SDValue(Tmp, 0)); 3018 transferMemOperands(N, MN); 3019 ReplaceNode(N, MN); 3020 return; 3021 } 3022 3023 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 3024 const GlobalValue *GV = G->getGlobal(); 3025 unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV); 3026 if (GVFlags & PPCII::MO_NLP_FLAG) { 3027 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA, 3028 SDValue(Tmp, 0)); 3029 transferMemOperands(N, MN); 3030 ReplaceNode(N, MN); 3031 return; 3032 } 3033 } 3034 3035 ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64, 3036 SDValue(Tmp, 0), GA)); 3037 return; 3038 } 3039 case PPCISD::PPC32_PICGOT: { 3040 // Generate a PIC-safe GOT reference. 3041 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() && 3042 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4"); 3043 CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, 3044 PPCLowering->getPointerTy(CurDAG->getDataLayout()), 3045 MVT::i32); 3046 return; 3047 } 3048 case PPCISD::VADD_SPLAT: { 3049 // This expands into one of three sequences, depending on whether 3050 // the first operand is odd or even, positive or negative. 3051 assert(isa<ConstantSDNode>(N->getOperand(0)) && 3052 isa<ConstantSDNode>(N->getOperand(1)) && 3053 "Invalid operand on VADD_SPLAT!"); 3054 3055 int Elt = N->getConstantOperandVal(0); 3056 int EltSize = N->getConstantOperandVal(1); 3057 unsigned Opc1, Opc2, Opc3; 3058 EVT VT; 3059 3060 if (EltSize == 1) { 3061 Opc1 = PPC::VSPLTISB; 3062 Opc2 = PPC::VADDUBM; 3063 Opc3 = PPC::VSUBUBM; 3064 VT = MVT::v16i8; 3065 } else if (EltSize == 2) { 3066 Opc1 = PPC::VSPLTISH; 3067 Opc2 = PPC::VADDUHM; 3068 Opc3 = PPC::VSUBUHM; 3069 VT = MVT::v8i16; 3070 } else { 3071 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!"); 3072 Opc1 = PPC::VSPLTISW; 3073 Opc2 = PPC::VADDUWM; 3074 Opc3 = PPC::VSUBUWM; 3075 VT = MVT::v4i32; 3076 } 3077 3078 if ((Elt & 1) == 0) { 3079 // Elt is even, in the range [-32,-18] + [16,30]. 3080 // 3081 // Convert: VADD_SPLAT elt, size 3082 // Into: tmp = VSPLTIS[BHW] elt 3083 // VADDU[BHW]M tmp, tmp 3084 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4 3085 SDValue EltVal = getI32Imm(Elt >> 1, dl); 3086 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 3087 SDValue TmpVal = SDValue(Tmp, 0); 3088 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal)); 3089 return; 3090 3091 } else if (Elt > 0) { 3092 // Elt is odd and positive, in the range [17,31]. 3093 // 3094 // Convert: VADD_SPLAT elt, size 3095 // Into: tmp1 = VSPLTIS[BHW] elt-16 3096 // tmp2 = VSPLTIS[BHW] -16 3097 // VSUBU[BHW]M tmp1, tmp2 3098 SDValue EltVal = getI32Imm(Elt - 16, dl); 3099 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 3100 EltVal = getI32Imm(-16, dl); 3101 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 3102 ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0), 3103 SDValue(Tmp2, 0))); 3104 return; 3105 3106 } else { 3107 // Elt is odd and negative, in the range [-31,-17]. 3108 // 3109 // Convert: VADD_SPLAT elt, size 3110 // Into: tmp1 = VSPLTIS[BHW] elt+16 3111 // tmp2 = VSPLTIS[BHW] -16 3112 // VADDU[BHW]M tmp1, tmp2 3113 SDValue EltVal = getI32Imm(Elt + 16, dl); 3114 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 3115 EltVal = getI32Imm(-16, dl); 3116 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 3117 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0), 3118 SDValue(Tmp2, 0))); 3119 return; 3120 } 3121 } 3122 } 3123 3124 SelectCode(N); 3125 } 3126 3127 // If the target supports the cmpb instruction, do the idiom recognition here. 3128 // We don't do this as a DAG combine because we don't want to do it as nodes 3129 // are being combined (because we might miss part of the eventual idiom). We 3130 // don't want to do it during instruction selection because we want to reuse 3131 // the logic for lowering the masking operations already part of the 3132 // instruction selector. 3133 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) { 3134 SDLoc dl(N); 3135 3136 assert(N->getOpcode() == ISD::OR && 3137 "Only OR nodes are supported for CMPB"); 3138 3139 SDValue Res; 3140 if (!PPCSubTarget->hasCMPB()) 3141 return Res; 3142 3143 if (N->getValueType(0) != MVT::i32 && 3144 N->getValueType(0) != MVT::i64) 3145 return Res; 3146 3147 EVT VT = N->getValueType(0); 3148 3149 SDValue RHS, LHS; 3150 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; 3151 uint64_t Mask = 0, Alt = 0; 3152 3153 auto IsByteSelectCC = [this](SDValue O, unsigned &b, 3154 uint64_t &Mask, uint64_t &Alt, 3155 SDValue &LHS, SDValue &RHS) { 3156 if (O.getOpcode() != ISD::SELECT_CC) 3157 return false; 3158 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get(); 3159 3160 if (!isa<ConstantSDNode>(O.getOperand(2)) || 3161 !isa<ConstantSDNode>(O.getOperand(3))) 3162 return false; 3163 3164 uint64_t PM = O.getConstantOperandVal(2); 3165 uint64_t PAlt = O.getConstantOperandVal(3); 3166 for (b = 0; b < 8; ++b) { 3167 uint64_t Mask = UINT64_C(0xFF) << (8*b); 3168 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt) 3169 break; 3170 } 3171 3172 if (b == 8) 3173 return false; 3174 Mask |= PM; 3175 Alt |= PAlt; 3176 3177 if (!isa<ConstantSDNode>(O.getOperand(1)) || 3178 O.getConstantOperandVal(1) != 0) { 3179 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1); 3180 if (Op0.getOpcode() == ISD::TRUNCATE) 3181 Op0 = Op0.getOperand(0); 3182 if (Op1.getOpcode() == ISD::TRUNCATE) 3183 Op1 = Op1.getOperand(0); 3184 3185 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL && 3186 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ && 3187 isa<ConstantSDNode>(Op0.getOperand(1))) { 3188 3189 unsigned Bits = Op0.getValueType().getSizeInBits(); 3190 if (b != Bits/8-1) 3191 return false; 3192 if (Op0.getConstantOperandVal(1) != Bits-8) 3193 return false; 3194 3195 LHS = Op0.getOperand(0); 3196 RHS = Op1.getOperand(0); 3197 return true; 3198 } 3199 3200 // When we have small integers (i16 to be specific), the form present 3201 // post-legalization uses SETULT in the SELECT_CC for the 3202 // higher-order byte, depending on the fact that the 3203 // even-higher-order bytes are known to all be zero, for example: 3204 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult 3205 // (so when the second byte is the same, because all higher-order 3206 // bits from bytes 3 and 4 are known to be zero, the result of the 3207 // xor can be at most 255) 3208 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT && 3209 isa<ConstantSDNode>(O.getOperand(1))) { 3210 3211 uint64_t ULim = O.getConstantOperandVal(1); 3212 if (ULim != (UINT64_C(1) << b*8)) 3213 return false; 3214 3215 // Now we need to make sure that the upper bytes are known to be 3216 // zero. 3217 unsigned Bits = Op0.getValueType().getSizeInBits(); 3218 if (!CurDAG->MaskedValueIsZero(Op0, 3219 APInt::getHighBitsSet(Bits, Bits - (b+1)*8))) 3220 return false; 3221 3222 LHS = Op0.getOperand(0); 3223 RHS = Op0.getOperand(1); 3224 return true; 3225 } 3226 3227 return false; 3228 } 3229 3230 if (CC != ISD::SETEQ) 3231 return false; 3232 3233 SDValue Op = O.getOperand(0); 3234 if (Op.getOpcode() == ISD::AND) { 3235 if (!isa<ConstantSDNode>(Op.getOperand(1))) 3236 return false; 3237 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b))) 3238 return false; 3239 3240 SDValue XOR = Op.getOperand(0); 3241 if (XOR.getOpcode() == ISD::TRUNCATE) 3242 XOR = XOR.getOperand(0); 3243 if (XOR.getOpcode() != ISD::XOR) 3244 return false; 3245 3246 LHS = XOR.getOperand(0); 3247 RHS = XOR.getOperand(1); 3248 return true; 3249 } else if (Op.getOpcode() == ISD::SRL) { 3250 if (!isa<ConstantSDNode>(Op.getOperand(1))) 3251 return false; 3252 unsigned Bits = Op.getValueType().getSizeInBits(); 3253 if (b != Bits/8-1) 3254 return false; 3255 if (Op.getConstantOperandVal(1) != Bits-8) 3256 return false; 3257 3258 SDValue XOR = Op.getOperand(0); 3259 if (XOR.getOpcode() == ISD::TRUNCATE) 3260 XOR = XOR.getOperand(0); 3261 if (XOR.getOpcode() != ISD::XOR) 3262 return false; 3263 3264 LHS = XOR.getOperand(0); 3265 RHS = XOR.getOperand(1); 3266 return true; 3267 } 3268 3269 return false; 3270 }; 3271 3272 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0)); 3273 while (!Queue.empty()) { 3274 SDValue V = Queue.pop_back_val(); 3275 3276 for (const SDValue &O : V.getNode()->ops()) { 3277 unsigned b; 3278 uint64_t M = 0, A = 0; 3279 SDValue OLHS, ORHS; 3280 if (O.getOpcode() == ISD::OR) { 3281 Queue.push_back(O); 3282 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) { 3283 if (!LHS) { 3284 LHS = OLHS; 3285 RHS = ORHS; 3286 BytesFound[b] = true; 3287 Mask |= M; 3288 Alt |= A; 3289 } else if ((LHS == ORHS && RHS == OLHS) || 3290 (RHS == ORHS && LHS == OLHS)) { 3291 BytesFound[b] = true; 3292 Mask |= M; 3293 Alt |= A; 3294 } else { 3295 return Res; 3296 } 3297 } else { 3298 return Res; 3299 } 3300 } 3301 } 3302 3303 unsigned LastB = 0, BCnt = 0; 3304 for (unsigned i = 0; i < 8; ++i) 3305 if (BytesFound[LastB]) { 3306 ++BCnt; 3307 LastB = i; 3308 } 3309 3310 if (!LastB || BCnt < 2) 3311 return Res; 3312 3313 // Because we'll be zero-extending the output anyway if don't have a specific 3314 // value for each input byte (via the Mask), we can 'anyext' the inputs. 3315 if (LHS.getValueType() != VT) { 3316 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT); 3317 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT); 3318 } 3319 3320 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS); 3321 3322 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1); 3323 if (NonTrivialMask && !Alt) { 3324 // Res = Mask & CMPB 3325 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, 3326 CurDAG->getConstant(Mask, dl, VT)); 3327 } else if (Alt) { 3328 // Res = (CMPB & Mask) | (~CMPB & Alt) 3329 // Which, as suggested here: 3330 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge 3331 // can be written as: 3332 // Res = Alt ^ ((Alt ^ Mask) & CMPB) 3333 // useful because the (Alt ^ Mask) can be pre-computed. 3334 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, 3335 CurDAG->getConstant(Mask ^ Alt, dl, VT)); 3336 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res, 3337 CurDAG->getConstant(Alt, dl, VT)); 3338 } 3339 3340 return Res; 3341 } 3342 3343 // When CR bit registers are enabled, an extension of an i1 variable to a i32 3344 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus 3345 // involves constant materialization of a 0 or a 1 or both. If the result of 3346 // the extension is then operated upon by some operator that can be constant 3347 // folded with a constant 0 or 1, and that constant can be materialized using 3348 // only one instruction (like a zero or one), then we should fold in those 3349 // operations with the select. 3350 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) { 3351 if (!PPCSubTarget->useCRBits()) 3352 return; 3353 3354 if (N->getOpcode() != ISD::ZERO_EXTEND && 3355 N->getOpcode() != ISD::SIGN_EXTEND && 3356 N->getOpcode() != ISD::ANY_EXTEND) 3357 return; 3358 3359 if (N->getOperand(0).getValueType() != MVT::i1) 3360 return; 3361 3362 if (!N->hasOneUse()) 3363 return; 3364 3365 SDLoc dl(N); 3366 EVT VT = N->getValueType(0); 3367 SDValue Cond = N->getOperand(0); 3368 SDValue ConstTrue = 3369 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT); 3370 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT); 3371 3372 do { 3373 SDNode *User = *N->use_begin(); 3374 if (User->getNumOperands() != 2) 3375 break; 3376 3377 auto TryFold = [this, N, User, dl](SDValue Val) { 3378 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1); 3379 SDValue O0 = UserO0.getNode() == N ? Val : UserO0; 3380 SDValue O1 = UserO1.getNode() == N ? Val : UserO1; 3381 3382 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl, 3383 User->getValueType(0), 3384 O0.getNode(), O1.getNode()); 3385 }; 3386 3387 SDValue TrueRes = TryFold(ConstTrue); 3388 if (!TrueRes) 3389 break; 3390 SDValue FalseRes = TryFold(ConstFalse); 3391 if (!FalseRes) 3392 break; 3393 3394 // For us to materialize these using one instruction, we must be able to 3395 // represent them as signed 16-bit integers. 3396 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(), 3397 False = cast<ConstantSDNode>(FalseRes)->getZExtValue(); 3398 if (!isInt<16>(True) || !isInt<16>(False)) 3399 break; 3400 3401 // We can replace User with a new SELECT node, and try again to see if we 3402 // can fold the select with its user. 3403 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes); 3404 N = User; 3405 ConstTrue = TrueRes; 3406 ConstFalse = FalseRes; 3407 } while (N->hasOneUse()); 3408 } 3409 3410 void PPCDAGToDAGISel::PreprocessISelDAG() { 3411 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode()); 3412 ++Position; 3413 3414 bool MadeChange = false; 3415 while (Position != CurDAG->allnodes_begin()) { 3416 SDNode *N = &*--Position; 3417 if (N->use_empty()) 3418 continue; 3419 3420 SDValue Res; 3421 switch (N->getOpcode()) { 3422 default: break; 3423 case ISD::OR: 3424 Res = combineToCMPB(N); 3425 break; 3426 } 3427 3428 if (!Res) 3429 foldBoolExts(Res, N); 3430 3431 if (Res) { 3432 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: "); 3433 DEBUG(N->dump(CurDAG)); 3434 DEBUG(dbgs() << "\nNew: "); 3435 DEBUG(Res.getNode()->dump(CurDAG)); 3436 DEBUG(dbgs() << "\n"); 3437 3438 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); 3439 MadeChange = true; 3440 } 3441 } 3442 3443 if (MadeChange) 3444 CurDAG->RemoveDeadNodes(); 3445 } 3446 3447 /// PostprocessISelDAG - Perform some late peephole optimizations 3448 /// on the DAG representation. 3449 void PPCDAGToDAGISel::PostprocessISelDAG() { 3450 3451 // Skip peepholes at -O0. 3452 if (TM.getOptLevel() == CodeGenOpt::None) 3453 return; 3454 3455 PeepholePPC64(); 3456 PeepholeCROps(); 3457 PeepholePPC64ZExt(); 3458 } 3459 3460 // Check if all users of this node will become isel where the second operand 3461 // is the constant zero. If this is so, and if we can negate the condition, 3462 // then we can flip the true and false operands. This will allow the zero to 3463 // be folded with the isel so that we don't need to materialize a register 3464 // containing zero. 3465 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) { 3466 // If we're not using isel, then this does not matter. 3467 if (!PPCSubTarget->hasISEL()) 3468 return false; 3469 3470 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 3471 UI != UE; ++UI) { 3472 SDNode *User = *UI; 3473 if (!User->isMachineOpcode()) 3474 return false; 3475 if (User->getMachineOpcode() != PPC::SELECT_I4 && 3476 User->getMachineOpcode() != PPC::SELECT_I8) 3477 return false; 3478 3479 SDNode *Op2 = User->getOperand(2).getNode(); 3480 if (!Op2->isMachineOpcode()) 3481 return false; 3482 3483 if (Op2->getMachineOpcode() != PPC::LI && 3484 Op2->getMachineOpcode() != PPC::LI8) 3485 return false; 3486 3487 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0)); 3488 if (!C) 3489 return false; 3490 3491 if (!C->isNullValue()) 3492 return false; 3493 } 3494 3495 return true; 3496 } 3497 3498 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) { 3499 SmallVector<SDNode *, 4> ToReplace; 3500 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 3501 UI != UE; ++UI) { 3502 SDNode *User = *UI; 3503 assert((User->getMachineOpcode() == PPC::SELECT_I4 || 3504 User->getMachineOpcode() == PPC::SELECT_I8) && 3505 "Must have all select users"); 3506 ToReplace.push_back(User); 3507 } 3508 3509 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(), 3510 UE = ToReplace.end(); UI != UE; ++UI) { 3511 SDNode *User = *UI; 3512 SDNode *ResNode = 3513 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User), 3514 User->getValueType(0), User->getOperand(0), 3515 User->getOperand(2), 3516 User->getOperand(1)); 3517 3518 DEBUG(dbgs() << "CR Peephole replacing:\nOld: "); 3519 DEBUG(User->dump(CurDAG)); 3520 DEBUG(dbgs() << "\nNew: "); 3521 DEBUG(ResNode->dump(CurDAG)); 3522 DEBUG(dbgs() << "\n"); 3523 3524 ReplaceUses(User, ResNode); 3525 } 3526 } 3527 3528 void PPCDAGToDAGISel::PeepholeCROps() { 3529 bool IsModified; 3530 do { 3531 IsModified = false; 3532 for (SDNode &Node : CurDAG->allnodes()) { 3533 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node); 3534 if (!MachineNode || MachineNode->use_empty()) 3535 continue; 3536 SDNode *ResNode = MachineNode; 3537 3538 bool Op1Set = false, Op1Unset = false, 3539 Op1Not = false, 3540 Op2Set = false, Op2Unset = false, 3541 Op2Not = false; 3542 3543 unsigned Opcode = MachineNode->getMachineOpcode(); 3544 switch (Opcode) { 3545 default: break; 3546 case PPC::CRAND: 3547 case PPC::CRNAND: 3548 case PPC::CROR: 3549 case PPC::CRXOR: 3550 case PPC::CRNOR: 3551 case PPC::CREQV: 3552 case PPC::CRANDC: 3553 case PPC::CRORC: { 3554 SDValue Op = MachineNode->getOperand(1); 3555 if (Op.isMachineOpcode()) { 3556 if (Op.getMachineOpcode() == PPC::CRSET) 3557 Op2Set = true; 3558 else if (Op.getMachineOpcode() == PPC::CRUNSET) 3559 Op2Unset = true; 3560 else if (Op.getMachineOpcode() == PPC::CRNOR && 3561 Op.getOperand(0) == Op.getOperand(1)) 3562 Op2Not = true; 3563 } 3564 } // fallthrough 3565 case PPC::BC: 3566 case PPC::BCn: 3567 case PPC::SELECT_I4: 3568 case PPC::SELECT_I8: 3569 case PPC::SELECT_F4: 3570 case PPC::SELECT_F8: 3571 case PPC::SELECT_QFRC: 3572 case PPC::SELECT_QSRC: 3573 case PPC::SELECT_QBRC: 3574 case PPC::SELECT_VRRC: 3575 case PPC::SELECT_VSFRC: 3576 case PPC::SELECT_VSSRC: 3577 case PPC::SELECT_VSRC: { 3578 SDValue Op = MachineNode->getOperand(0); 3579 if (Op.isMachineOpcode()) { 3580 if (Op.getMachineOpcode() == PPC::CRSET) 3581 Op1Set = true; 3582 else if (Op.getMachineOpcode() == PPC::CRUNSET) 3583 Op1Unset = true; 3584 else if (Op.getMachineOpcode() == PPC::CRNOR && 3585 Op.getOperand(0) == Op.getOperand(1)) 3586 Op1Not = true; 3587 } 3588 } 3589 break; 3590 } 3591 3592 bool SelectSwap = false; 3593 switch (Opcode) { 3594 default: break; 3595 case PPC::CRAND: 3596 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3597 // x & x = x 3598 ResNode = MachineNode->getOperand(0).getNode(); 3599 else if (Op1Set) 3600 // 1 & y = y 3601 ResNode = MachineNode->getOperand(1).getNode(); 3602 else if (Op2Set) 3603 // x & 1 = x 3604 ResNode = MachineNode->getOperand(0).getNode(); 3605 else if (Op1Unset || Op2Unset) 3606 // x & 0 = 0 & y = 0 3607 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 3608 MVT::i1); 3609 else if (Op1Not) 3610 // ~x & y = andc(y, x) 3611 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 3612 MVT::i1, MachineNode->getOperand(1), 3613 MachineNode->getOperand(0). 3614 getOperand(0)); 3615 else if (Op2Not) 3616 // x & ~y = andc(x, y) 3617 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 3618 MVT::i1, MachineNode->getOperand(0), 3619 MachineNode->getOperand(1). 3620 getOperand(0)); 3621 else if (AllUsersSelectZero(MachineNode)) { 3622 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode), 3623 MVT::i1, MachineNode->getOperand(0), 3624 MachineNode->getOperand(1)); 3625 SelectSwap = true; 3626 } 3627 break; 3628 case PPC::CRNAND: 3629 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3630 // nand(x, x) -> nor(x, x) 3631 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3632 MVT::i1, MachineNode->getOperand(0), 3633 MachineNode->getOperand(0)); 3634 else if (Op1Set) 3635 // nand(1, y) -> nor(y, y) 3636 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3637 MVT::i1, MachineNode->getOperand(1), 3638 MachineNode->getOperand(1)); 3639 else if (Op2Set) 3640 // nand(x, 1) -> nor(x, x) 3641 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3642 MVT::i1, MachineNode->getOperand(0), 3643 MachineNode->getOperand(0)); 3644 else if (Op1Unset || Op2Unset) 3645 // nand(x, 0) = nand(0, y) = 1 3646 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 3647 MVT::i1); 3648 else if (Op1Not) 3649 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y) 3650 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 3651 MVT::i1, MachineNode->getOperand(0). 3652 getOperand(0), 3653 MachineNode->getOperand(1)); 3654 else if (Op2Not) 3655 // nand(x, ~y) = ~x | y = orc(y, x) 3656 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 3657 MVT::i1, MachineNode->getOperand(1). 3658 getOperand(0), 3659 MachineNode->getOperand(0)); 3660 else if (AllUsersSelectZero(MachineNode)) { 3661 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode), 3662 MVT::i1, MachineNode->getOperand(0), 3663 MachineNode->getOperand(1)); 3664 SelectSwap = true; 3665 } 3666 break; 3667 case PPC::CROR: 3668 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3669 // x | x = x 3670 ResNode = MachineNode->getOperand(0).getNode(); 3671 else if (Op1Set || Op2Set) 3672 // x | 1 = 1 | y = 1 3673 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 3674 MVT::i1); 3675 else if (Op1Unset) 3676 // 0 | y = y 3677 ResNode = MachineNode->getOperand(1).getNode(); 3678 else if (Op2Unset) 3679 // x | 0 = x 3680 ResNode = MachineNode->getOperand(0).getNode(); 3681 else if (Op1Not) 3682 // ~x | y = orc(y, x) 3683 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 3684 MVT::i1, MachineNode->getOperand(1), 3685 MachineNode->getOperand(0). 3686 getOperand(0)); 3687 else if (Op2Not) 3688 // x | ~y = orc(x, y) 3689 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 3690 MVT::i1, MachineNode->getOperand(0), 3691 MachineNode->getOperand(1). 3692 getOperand(0)); 3693 else if (AllUsersSelectZero(MachineNode)) { 3694 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3695 MVT::i1, MachineNode->getOperand(0), 3696 MachineNode->getOperand(1)); 3697 SelectSwap = true; 3698 } 3699 break; 3700 case PPC::CRXOR: 3701 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3702 // xor(x, x) = 0 3703 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 3704 MVT::i1); 3705 else if (Op1Set) 3706 // xor(1, y) -> nor(y, y) 3707 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3708 MVT::i1, MachineNode->getOperand(1), 3709 MachineNode->getOperand(1)); 3710 else if (Op2Set) 3711 // xor(x, 1) -> nor(x, x) 3712 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3713 MVT::i1, MachineNode->getOperand(0), 3714 MachineNode->getOperand(0)); 3715 else if (Op1Unset) 3716 // xor(0, y) = y 3717 ResNode = MachineNode->getOperand(1).getNode(); 3718 else if (Op2Unset) 3719 // xor(x, 0) = x 3720 ResNode = MachineNode->getOperand(0).getNode(); 3721 else if (Op1Not) 3722 // xor(~x, y) = eqv(x, y) 3723 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 3724 MVT::i1, MachineNode->getOperand(0). 3725 getOperand(0), 3726 MachineNode->getOperand(1)); 3727 else if (Op2Not) 3728 // xor(x, ~y) = eqv(x, y) 3729 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 3730 MVT::i1, MachineNode->getOperand(0), 3731 MachineNode->getOperand(1). 3732 getOperand(0)); 3733 else if (AllUsersSelectZero(MachineNode)) { 3734 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 3735 MVT::i1, MachineNode->getOperand(0), 3736 MachineNode->getOperand(1)); 3737 SelectSwap = true; 3738 } 3739 break; 3740 case PPC::CRNOR: 3741 if (Op1Set || Op2Set) 3742 // nor(1, y) -> 0 3743 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 3744 MVT::i1); 3745 else if (Op1Unset) 3746 // nor(0, y) = ~y -> nor(y, y) 3747 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3748 MVT::i1, MachineNode->getOperand(1), 3749 MachineNode->getOperand(1)); 3750 else if (Op2Unset) 3751 // nor(x, 0) = ~x 3752 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3753 MVT::i1, MachineNode->getOperand(0), 3754 MachineNode->getOperand(0)); 3755 else if (Op1Not) 3756 // nor(~x, y) = andc(x, y) 3757 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 3758 MVT::i1, MachineNode->getOperand(0). 3759 getOperand(0), 3760 MachineNode->getOperand(1)); 3761 else if (Op2Not) 3762 // nor(x, ~y) = andc(y, x) 3763 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 3764 MVT::i1, MachineNode->getOperand(1). 3765 getOperand(0), 3766 MachineNode->getOperand(0)); 3767 else if (AllUsersSelectZero(MachineNode)) { 3768 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode), 3769 MVT::i1, MachineNode->getOperand(0), 3770 MachineNode->getOperand(1)); 3771 SelectSwap = true; 3772 } 3773 break; 3774 case PPC::CREQV: 3775 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3776 // eqv(x, x) = 1 3777 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 3778 MVT::i1); 3779 else if (Op1Set) 3780 // eqv(1, y) = y 3781 ResNode = MachineNode->getOperand(1).getNode(); 3782 else if (Op2Set) 3783 // eqv(x, 1) = x 3784 ResNode = MachineNode->getOperand(0).getNode(); 3785 else if (Op1Unset) 3786 // eqv(0, y) = ~y -> nor(y, y) 3787 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3788 MVT::i1, MachineNode->getOperand(1), 3789 MachineNode->getOperand(1)); 3790 else if (Op2Unset) 3791 // eqv(x, 0) = ~x 3792 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3793 MVT::i1, MachineNode->getOperand(0), 3794 MachineNode->getOperand(0)); 3795 else if (Op1Not) 3796 // eqv(~x, y) = xor(x, y) 3797 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 3798 MVT::i1, MachineNode->getOperand(0). 3799 getOperand(0), 3800 MachineNode->getOperand(1)); 3801 else if (Op2Not) 3802 // eqv(x, ~y) = xor(x, y) 3803 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 3804 MVT::i1, MachineNode->getOperand(0), 3805 MachineNode->getOperand(1). 3806 getOperand(0)); 3807 else if (AllUsersSelectZero(MachineNode)) { 3808 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 3809 MVT::i1, MachineNode->getOperand(0), 3810 MachineNode->getOperand(1)); 3811 SelectSwap = true; 3812 } 3813 break; 3814 case PPC::CRANDC: 3815 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3816 // andc(x, x) = 0 3817 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 3818 MVT::i1); 3819 else if (Op1Set) 3820 // andc(1, y) = ~y 3821 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3822 MVT::i1, MachineNode->getOperand(1), 3823 MachineNode->getOperand(1)); 3824 else if (Op1Unset || Op2Set) 3825 // andc(0, y) = andc(x, 1) = 0 3826 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 3827 MVT::i1); 3828 else if (Op2Unset) 3829 // andc(x, 0) = x 3830 ResNode = MachineNode->getOperand(0).getNode(); 3831 else if (Op1Not) 3832 // andc(~x, y) = ~(x | y) = nor(x, y) 3833 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3834 MVT::i1, MachineNode->getOperand(0). 3835 getOperand(0), 3836 MachineNode->getOperand(1)); 3837 else if (Op2Not) 3838 // andc(x, ~y) = x & y 3839 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode), 3840 MVT::i1, MachineNode->getOperand(0), 3841 MachineNode->getOperand(1). 3842 getOperand(0)); 3843 else if (AllUsersSelectZero(MachineNode)) { 3844 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 3845 MVT::i1, MachineNode->getOperand(1), 3846 MachineNode->getOperand(0)); 3847 SelectSwap = true; 3848 } 3849 break; 3850 case PPC::CRORC: 3851 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3852 // orc(x, x) = 1 3853 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 3854 MVT::i1); 3855 else if (Op1Set || Op2Unset) 3856 // orc(1, y) = orc(x, 0) = 1 3857 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 3858 MVT::i1); 3859 else if (Op2Set) 3860 // orc(x, 1) = x 3861 ResNode = MachineNode->getOperand(0).getNode(); 3862 else if (Op1Unset) 3863 // orc(0, y) = ~y 3864 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3865 MVT::i1, MachineNode->getOperand(1), 3866 MachineNode->getOperand(1)); 3867 else if (Op1Not) 3868 // orc(~x, y) = ~(x & y) = nand(x, y) 3869 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode), 3870 MVT::i1, MachineNode->getOperand(0). 3871 getOperand(0), 3872 MachineNode->getOperand(1)); 3873 else if (Op2Not) 3874 // orc(x, ~y) = x | y 3875 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode), 3876 MVT::i1, MachineNode->getOperand(0), 3877 MachineNode->getOperand(1). 3878 getOperand(0)); 3879 else if (AllUsersSelectZero(MachineNode)) { 3880 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 3881 MVT::i1, MachineNode->getOperand(1), 3882 MachineNode->getOperand(0)); 3883 SelectSwap = true; 3884 } 3885 break; 3886 case PPC::SELECT_I4: 3887 case PPC::SELECT_I8: 3888 case PPC::SELECT_F4: 3889 case PPC::SELECT_F8: 3890 case PPC::SELECT_QFRC: 3891 case PPC::SELECT_QSRC: 3892 case PPC::SELECT_QBRC: 3893 case PPC::SELECT_VRRC: 3894 case PPC::SELECT_VSFRC: 3895 case PPC::SELECT_VSSRC: 3896 case PPC::SELECT_VSRC: 3897 if (Op1Set) 3898 ResNode = MachineNode->getOperand(1).getNode(); 3899 else if (Op1Unset) 3900 ResNode = MachineNode->getOperand(2).getNode(); 3901 else if (Op1Not) 3902 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(), 3903 SDLoc(MachineNode), 3904 MachineNode->getValueType(0), 3905 MachineNode->getOperand(0). 3906 getOperand(0), 3907 MachineNode->getOperand(2), 3908 MachineNode->getOperand(1)); 3909 break; 3910 case PPC::BC: 3911 case PPC::BCn: 3912 if (Op1Not) 3913 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn : 3914 PPC::BC, 3915 SDLoc(MachineNode), 3916 MVT::Other, 3917 MachineNode->getOperand(0). 3918 getOperand(0), 3919 MachineNode->getOperand(1), 3920 MachineNode->getOperand(2)); 3921 // FIXME: Handle Op1Set, Op1Unset here too. 3922 break; 3923 } 3924 3925 // If we're inverting this node because it is used only by selects that 3926 // we'd like to swap, then swap the selects before the node replacement. 3927 if (SelectSwap) 3928 SwapAllSelectUsers(MachineNode); 3929 3930 if (ResNode != MachineNode) { 3931 DEBUG(dbgs() << "CR Peephole replacing:\nOld: "); 3932 DEBUG(MachineNode->dump(CurDAG)); 3933 DEBUG(dbgs() << "\nNew: "); 3934 DEBUG(ResNode->dump(CurDAG)); 3935 DEBUG(dbgs() << "\n"); 3936 3937 ReplaceUses(MachineNode, ResNode); 3938 IsModified = true; 3939 } 3940 } 3941 if (IsModified) 3942 CurDAG->RemoveDeadNodes(); 3943 } while (IsModified); 3944 } 3945 3946 // Gather the set of 32-bit operations that are known to have their 3947 // higher-order 32 bits zero, where ToPromote contains all such operations. 3948 static bool PeepholePPC64ZExtGather(SDValue Op32, 3949 SmallPtrSetImpl<SDNode *> &ToPromote) { 3950 if (!Op32.isMachineOpcode()) 3951 return false; 3952 3953 // First, check for the "frontier" instructions (those that will clear the 3954 // higher-order 32 bits. 3955 3956 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap 3957 // around. If it does not, then these instructions will clear the 3958 // higher-order bits. 3959 if ((Op32.getMachineOpcode() == PPC::RLWINM || 3960 Op32.getMachineOpcode() == PPC::RLWNM) && 3961 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) { 3962 ToPromote.insert(Op32.getNode()); 3963 return true; 3964 } 3965 3966 // SLW and SRW always clear the higher-order bits. 3967 if (Op32.getMachineOpcode() == PPC::SLW || 3968 Op32.getMachineOpcode() == PPC::SRW) { 3969 ToPromote.insert(Op32.getNode()); 3970 return true; 3971 } 3972 3973 // For LI and LIS, we need the immediate to be positive (so that it is not 3974 // sign extended). 3975 if (Op32.getMachineOpcode() == PPC::LI || 3976 Op32.getMachineOpcode() == PPC::LIS) { 3977 if (!isUInt<15>(Op32.getConstantOperandVal(0))) 3978 return false; 3979 3980 ToPromote.insert(Op32.getNode()); 3981 return true; 3982 } 3983 3984 // LHBRX and LWBRX always clear the higher-order bits. 3985 if (Op32.getMachineOpcode() == PPC::LHBRX || 3986 Op32.getMachineOpcode() == PPC::LWBRX) { 3987 ToPromote.insert(Op32.getNode()); 3988 return true; 3989 } 3990 3991 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended. 3992 if (Op32.getMachineOpcode() == PPC::CNTLZW) { 3993 ToPromote.insert(Op32.getNode()); 3994 return true; 3995 } 3996 3997 // Next, check for those instructions we can look through. 3998 3999 // Assuming the mask does not wrap around, then the higher-order bits are 4000 // taken directly from the first operand. 4001 if (Op32.getMachineOpcode() == PPC::RLWIMI && 4002 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) { 4003 SmallPtrSet<SDNode *, 16> ToPromote1; 4004 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1)) 4005 return false; 4006 4007 ToPromote.insert(Op32.getNode()); 4008 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 4009 return true; 4010 } 4011 4012 // For OR, the higher-order bits are zero if that is true for both operands. 4013 // For SELECT_I4, the same is true (but the relevant operand numbers are 4014 // shifted by 1). 4015 if (Op32.getMachineOpcode() == PPC::OR || 4016 Op32.getMachineOpcode() == PPC::SELECT_I4) { 4017 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0; 4018 SmallPtrSet<SDNode *, 16> ToPromote1; 4019 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1)) 4020 return false; 4021 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1)) 4022 return false; 4023 4024 ToPromote.insert(Op32.getNode()); 4025 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 4026 return true; 4027 } 4028 4029 // For ORI and ORIS, we need the higher-order bits of the first operand to be 4030 // zero, and also for the constant to be positive (so that it is not sign 4031 // extended). 4032 if (Op32.getMachineOpcode() == PPC::ORI || 4033 Op32.getMachineOpcode() == PPC::ORIS) { 4034 SmallPtrSet<SDNode *, 16> ToPromote1; 4035 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1)) 4036 return false; 4037 if (!isUInt<15>(Op32.getConstantOperandVal(1))) 4038 return false; 4039 4040 ToPromote.insert(Op32.getNode()); 4041 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 4042 return true; 4043 } 4044 4045 // The higher-order bits of AND are zero if that is true for at least one of 4046 // the operands. 4047 if (Op32.getMachineOpcode() == PPC::AND) { 4048 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2; 4049 bool Op0OK = 4050 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1); 4051 bool Op1OK = 4052 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2); 4053 if (!Op0OK && !Op1OK) 4054 return false; 4055 4056 ToPromote.insert(Op32.getNode()); 4057 4058 if (Op0OK) 4059 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 4060 4061 if (Op1OK) 4062 ToPromote.insert(ToPromote2.begin(), ToPromote2.end()); 4063 4064 return true; 4065 } 4066 4067 // For ANDI and ANDIS, the higher-order bits are zero if either that is true 4068 // of the first operand, or if the second operand is positive (so that it is 4069 // not sign extended). 4070 if (Op32.getMachineOpcode() == PPC::ANDIo || 4071 Op32.getMachineOpcode() == PPC::ANDISo) { 4072 SmallPtrSet<SDNode *, 16> ToPromote1; 4073 bool Op0OK = 4074 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1); 4075 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1)); 4076 if (!Op0OK && !Op1OK) 4077 return false; 4078 4079 ToPromote.insert(Op32.getNode()); 4080 4081 if (Op0OK) 4082 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 4083 4084 return true; 4085 } 4086 4087 return false; 4088 } 4089 4090 void PPCDAGToDAGISel::PeepholePPC64ZExt() { 4091 if (!PPCSubTarget->isPPC64()) 4092 return; 4093 4094 // When we zero-extend from i32 to i64, we use a pattern like this: 4095 // def : Pat<(i64 (zext i32:$in)), 4096 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32), 4097 // 0, 32)>; 4098 // There are several 32-bit shift/rotate instructions, however, that will 4099 // clear the higher-order bits of their output, rendering the RLDICL 4100 // unnecessary. When that happens, we remove it here, and redefine the 4101 // relevant 32-bit operation to be a 64-bit operation. 4102 4103 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode()); 4104 ++Position; 4105 4106 bool MadeChange = false; 4107 while (Position != CurDAG->allnodes_begin()) { 4108 SDNode *N = &*--Position; 4109 // Skip dead nodes and any non-machine opcodes. 4110 if (N->use_empty() || !N->isMachineOpcode()) 4111 continue; 4112 4113 if (N->getMachineOpcode() != PPC::RLDICL) 4114 continue; 4115 4116 if (N->getConstantOperandVal(1) != 0 || 4117 N->getConstantOperandVal(2) != 32) 4118 continue; 4119 4120 SDValue ISR = N->getOperand(0); 4121 if (!ISR.isMachineOpcode() || 4122 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG) 4123 continue; 4124 4125 if (!ISR.hasOneUse()) 4126 continue; 4127 4128 if (ISR.getConstantOperandVal(2) != PPC::sub_32) 4129 continue; 4130 4131 SDValue IDef = ISR.getOperand(0); 4132 if (!IDef.isMachineOpcode() || 4133 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF) 4134 continue; 4135 4136 // We now know that we're looking at a canonical i32 -> i64 zext. See if we 4137 // can get rid of it. 4138 4139 SDValue Op32 = ISR->getOperand(1); 4140 if (!Op32.isMachineOpcode()) 4141 continue; 4142 4143 // There are some 32-bit instructions that always clear the high-order 32 4144 // bits, there are also some instructions (like AND) that we can look 4145 // through. 4146 SmallPtrSet<SDNode *, 16> ToPromote; 4147 if (!PeepholePPC64ZExtGather(Op32, ToPromote)) 4148 continue; 4149 4150 // If the ToPromote set contains nodes that have uses outside of the set 4151 // (except for the original INSERT_SUBREG), then abort the transformation. 4152 bool OutsideUse = false; 4153 for (SDNode *PN : ToPromote) { 4154 for (SDNode *UN : PN->uses()) { 4155 if (!ToPromote.count(UN) && UN != ISR.getNode()) { 4156 OutsideUse = true; 4157 break; 4158 } 4159 } 4160 4161 if (OutsideUse) 4162 break; 4163 } 4164 if (OutsideUse) 4165 continue; 4166 4167 MadeChange = true; 4168 4169 // We now know that this zero extension can be removed by promoting to 4170 // nodes in ToPromote to 64-bit operations, where for operations in the 4171 // frontier of the set, we need to insert INSERT_SUBREGs for their 4172 // operands. 4173 for (SDNode *PN : ToPromote) { 4174 unsigned NewOpcode; 4175 switch (PN->getMachineOpcode()) { 4176 default: 4177 llvm_unreachable("Don't know the 64-bit variant of this instruction"); 4178 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break; 4179 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break; 4180 case PPC::SLW: NewOpcode = PPC::SLW8; break; 4181 case PPC::SRW: NewOpcode = PPC::SRW8; break; 4182 case PPC::LI: NewOpcode = PPC::LI8; break; 4183 case PPC::LIS: NewOpcode = PPC::LIS8; break; 4184 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break; 4185 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break; 4186 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break; 4187 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break; 4188 case PPC::OR: NewOpcode = PPC::OR8; break; 4189 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break; 4190 case PPC::ORI: NewOpcode = PPC::ORI8; break; 4191 case PPC::ORIS: NewOpcode = PPC::ORIS8; break; 4192 case PPC::AND: NewOpcode = PPC::AND8; break; 4193 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break; 4194 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break; 4195 } 4196 4197 // Note: During the replacement process, the nodes will be in an 4198 // inconsistent state (some instructions will have operands with values 4199 // of the wrong type). Once done, however, everything should be right 4200 // again. 4201 4202 SmallVector<SDValue, 4> Ops; 4203 for (const SDValue &V : PN->ops()) { 4204 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 && 4205 !isa<ConstantSDNode>(V)) { 4206 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) }; 4207 SDNode *ReplOp = 4208 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V), 4209 ISR.getNode()->getVTList(), ReplOpOps); 4210 Ops.push_back(SDValue(ReplOp, 0)); 4211 } else { 4212 Ops.push_back(V); 4213 } 4214 } 4215 4216 // Because all to-be-promoted nodes only have users that are other 4217 // promoted nodes (or the original INSERT_SUBREG), we can safely replace 4218 // the i32 result value type with i64. 4219 4220 SmallVector<EVT, 2> NewVTs; 4221 SDVTList VTs = PN->getVTList(); 4222 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i) 4223 if (VTs.VTs[i] == MVT::i32) 4224 NewVTs.push_back(MVT::i64); 4225 else 4226 NewVTs.push_back(VTs.VTs[i]); 4227 4228 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: "); 4229 DEBUG(PN->dump(CurDAG)); 4230 4231 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops); 4232 4233 DEBUG(dbgs() << "\nNew: "); 4234 DEBUG(PN->dump(CurDAG)); 4235 DEBUG(dbgs() << "\n"); 4236 } 4237 4238 // Now we replace the original zero extend and its associated INSERT_SUBREG 4239 // with the value feeding the INSERT_SUBREG (which has now been promoted to 4240 // return an i64). 4241 4242 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: "); 4243 DEBUG(N->dump(CurDAG)); 4244 DEBUG(dbgs() << "\nNew: "); 4245 DEBUG(Op32.getNode()->dump(CurDAG)); 4246 DEBUG(dbgs() << "\n"); 4247 4248 ReplaceUses(N, Op32.getNode()); 4249 } 4250 4251 if (MadeChange) 4252 CurDAG->RemoveDeadNodes(); 4253 } 4254 4255 void PPCDAGToDAGISel::PeepholePPC64() { 4256 // These optimizations are currently supported only for 64-bit SVR4. 4257 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64()) 4258 return; 4259 4260 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode()); 4261 ++Position; 4262 4263 while (Position != CurDAG->allnodes_begin()) { 4264 SDNode *N = &*--Position; 4265 // Skip dead nodes and any non-machine opcodes. 4266 if (N->use_empty() || !N->isMachineOpcode()) 4267 continue; 4268 4269 unsigned FirstOp; 4270 unsigned StorageOpcode = N->getMachineOpcode(); 4271 4272 switch (StorageOpcode) { 4273 default: continue; 4274 4275 case PPC::LBZ: 4276 case PPC::LBZ8: 4277 case PPC::LD: 4278 case PPC::LFD: 4279 case PPC::LFS: 4280 case PPC::LHA: 4281 case PPC::LHA8: 4282 case PPC::LHZ: 4283 case PPC::LHZ8: 4284 case PPC::LWA: 4285 case PPC::LWZ: 4286 case PPC::LWZ8: 4287 FirstOp = 0; 4288 break; 4289 4290 case PPC::STB: 4291 case PPC::STB8: 4292 case PPC::STD: 4293 case PPC::STFD: 4294 case PPC::STFS: 4295 case PPC::STH: 4296 case PPC::STH8: 4297 case PPC::STW: 4298 case PPC::STW8: 4299 FirstOp = 1; 4300 break; 4301 } 4302 4303 // If this is a load or store with a zero offset, or within the alignment, 4304 // we may be able to fold an add-immediate into the memory operation. 4305 // The check against alignment is below, as it can't occur until we check 4306 // the arguments to N 4307 if (!isa<ConstantSDNode>(N->getOperand(FirstOp))) 4308 continue; 4309 4310 SDValue Base = N->getOperand(FirstOp + 1); 4311 if (!Base.isMachineOpcode()) 4312 continue; 4313 4314 // On targets with fusion, we don't want this to fire and remove a fusion 4315 // opportunity, unless a) it results in another fusion opportunity or 4316 // b) optimizing for size. 4317 if (PPCSubTarget->hasFusion() && 4318 (!MF->getFunction()->optForSize() && !Base.hasOneUse())) 4319 continue; 4320 4321 unsigned Flags = 0; 4322 bool ReplaceFlags = true; 4323 4324 // When the feeding operation is an add-immediate of some sort, 4325 // determine whether we need to add relocation information to the 4326 // target flags on the immediate operand when we fold it into the 4327 // load instruction. 4328 // 4329 // For something like ADDItocL, the relocation information is 4330 // inferred from the opcode; when we process it in the AsmPrinter, 4331 // we add the necessary relocation there. A load, though, can receive 4332 // relocation from various flavors of ADDIxxx, so we need to carry 4333 // the relocation information in the target flags. 4334 switch (Base.getMachineOpcode()) { 4335 default: continue; 4336 4337 case PPC::ADDI8: 4338 case PPC::ADDI: 4339 // In some cases (such as TLS) the relocation information 4340 // is already in place on the operand, so copying the operand 4341 // is sufficient. 4342 ReplaceFlags = false; 4343 // For these cases, the immediate may not be divisible by 4, in 4344 // which case the fold is illegal for DS-form instructions. (The 4345 // other cases provide aligned addresses and are always safe.) 4346 if ((StorageOpcode == PPC::LWA || 4347 StorageOpcode == PPC::LD || 4348 StorageOpcode == PPC::STD) && 4349 (!isa<ConstantSDNode>(Base.getOperand(1)) || 4350 Base.getConstantOperandVal(1) % 4 != 0)) 4351 continue; 4352 break; 4353 case PPC::ADDIdtprelL: 4354 Flags = PPCII::MO_DTPREL_LO; 4355 break; 4356 case PPC::ADDItlsldL: 4357 Flags = PPCII::MO_TLSLD_LO; 4358 break; 4359 case PPC::ADDItocL: 4360 Flags = PPCII::MO_TOC_LO; 4361 break; 4362 } 4363 4364 SDValue ImmOpnd = Base.getOperand(1); 4365 int MaxDisplacement = 0; 4366 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) { 4367 const GlobalValue *GV = GA->getGlobal(); 4368 MaxDisplacement = GV->getAlignment() - 1; 4369 } 4370 4371 int Offset = N->getConstantOperandVal(FirstOp); 4372 if (Offset < 0 || Offset > MaxDisplacement) 4373 continue; 4374 4375 // We found an opportunity. Reverse the operands from the add 4376 // immediate and substitute them into the load or store. If 4377 // needed, update the target flags for the immediate operand to 4378 // reflect the necessary relocation information. 4379 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: "); 4380 DEBUG(Base->dump(CurDAG)); 4381 DEBUG(dbgs() << "\nN: "); 4382 DEBUG(N->dump(CurDAG)); 4383 DEBUG(dbgs() << "\n"); 4384 4385 // If the relocation information isn't already present on the 4386 // immediate operand, add it now. 4387 if (ReplaceFlags) { 4388 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) { 4389 SDLoc dl(GA); 4390 const GlobalValue *GV = GA->getGlobal(); 4391 // We can't perform this optimization for data whose alignment 4392 // is insufficient for the instruction encoding. 4393 if (GV->getAlignment() < 4 && 4394 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD || 4395 StorageOpcode == PPC::LWA || (Offset % 4) != 0)) { 4396 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n"); 4397 continue; 4398 } 4399 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags); 4400 } else if (ConstantPoolSDNode *CP = 4401 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) { 4402 const Constant *C = CP->getConstVal(); 4403 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64, 4404 CP->getAlignment(), 4405 Offset, Flags); 4406 } 4407 } 4408 4409 if (FirstOp == 1) // Store 4410 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd, 4411 Base.getOperand(0), N->getOperand(3)); 4412 else // Load 4413 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0), 4414 N->getOperand(2)); 4415 4416 // The add-immediate may now be dead, in which case remove it. 4417 if (Base.getNode()->use_empty()) 4418 CurDAG->RemoveDeadNode(Base.getNode()); 4419 } 4420 } 4421 4422 4423 /// createPPCISelDag - This pass converts a legalized DAG into a 4424 /// PowerPC-specific DAG, ready for instruction scheduling. 4425 /// 4426 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) { 4427 return new PPCDAGToDAGISel(TM); 4428 } 4429