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