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