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