LLVM 18.0.0git
PPCISelDAGToDAG.cpp
Go to the documentation of this file.
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
16#include "PPC.h"
17#include "PPCISelLowering.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"
27#include "llvm/ADT/Statistic.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"
55#include "llvm/Support/Debug.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
70using namespace llvm;
71
72#define DEBUG_TYPE "ppc-isel"
73#define PASS_NAME "PowerPC DAG->DAG Pattern Instruction Selection"
74
75STATISTIC(NumSextSetcc,
76 "Number of (sext(setcc)) nodes expanded into GPR sequence.");
77STATISTIC(NumZextSetcc,
78 "Number of (zext(setcc)) nodes expanded into GPR sequence.");
79STATISTIC(SignExtensionsAdded,
80 "Number of sign extensions for compare inputs added.");
81STATISTIC(ZeroExtensionsAdded,
82 "Number of zero extensions for compare inputs added.");
83STATISTIC(NumLogicOpsOnComparison,
84 "Number of logical ops on i1 values calculated in GPR.");
85STATISTIC(OmittedForNonExtendUses,
86 "Number of compares not eliminated as they have non-extending uses.");
87STATISTIC(NumP9Setb,
88 "Number of compares lowered to setb.");
89
90// FIXME: Remove this once the bug has been fixed!
91cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
92cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
93
94static cl::opt<bool>
95 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
96 cl::desc("use aggressive ppc isel for bit permutations"),
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
105 "ppc-use-branch-hint", cl::init(true),
106 cl::desc("Enable static hinting of branches on ppc"),
107 cl::Hidden);
108
110 "ppc-tls-opt", cl::init(true),
111 cl::desc("Enable tls optimization peephole"),
112 cl::Hidden);
113
117
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.")));
137namespace {
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();
168 const int Result = MFI.CreateStackObject(8, Align(8), false);
170 }
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) ==
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) ==
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.
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");
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
423private:
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
452char PPCDAGToDAGISel::ID = 0;
453
454INITIALIZE_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///
459SDNode *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();
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 {
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.
513static 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.
566static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
567 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
568 Imm = cast<ConstantSDNode>(N)->getZExtValue();
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.
576static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
577 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
578 Imm = cast<ConstantSDNode>(N)->getZExtValue();
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.
586static 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.
592static bool isInt64Immediate(SDValue N, uint64_t &Imm) {
593 return isInt64Immediate(N.getNode(), Imm);
594}
595
596static 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.
650static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
651 return N->getOpcode() == Opc
652 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
653}
654
655void 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
668bool 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.
713 assert(
714 Base.getOpcode() == PPCISD::ADD_TLS &&
715 "Only expecting the ADD_TLS instruction to acquire the thread pointer!");
716 const PPCSubtarget &Subtarget =
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.
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
789bool 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
837bool 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.
892bool 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) &&
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 &&
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
965static 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.
1023static 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.
1032static 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.
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
1393static 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 =
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.
1500 SDLoc dl(N);
1501
1502 // Get 64 bit value.
1503 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
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
1513namespace {
1514
1515class 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 =
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 unsigned RotAmt = V.getConstantOperandVal(1);
1639
1640 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1641
1642 for (unsigned i = 0; i < NumBits; ++i)
1643 Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];
1644
1645 return std::make_pair(Interesting = true, &Bits);
1646 }
1647 break;
1648 case ISD::SHL:
1649 case PPCISD::SHL:
1650 if (isa<ConstantSDNode>(V.getOperand(1))) {
1651 unsigned ShiftAmt = V.getConstantOperandVal(1);
1652
1653 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1654
1655 for (unsigned i = ShiftAmt; i < NumBits; ++i)
1656 Bits[i] = LHSBits[i - ShiftAmt];
1657
1658 for (unsigned i = 0; i < ShiftAmt; ++i)
1659 Bits[i] = ValueBit(ValueBit::ConstZero);
1660
1661 return std::make_pair(Interesting = true, &Bits);
1662 }
1663 break;
1664 case ISD::SRL:
1665 case PPCISD::SRL:
1666 if (isa<ConstantSDNode>(V.getOperand(1))) {
1667 unsigned ShiftAmt = V.getConstantOperandVal(1);
1668
1669 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1670
1671 for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)
1672 Bits[i] = LHSBits[i + ShiftAmt];
1673
1674 for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)
1675 Bits[i] = ValueBit(ValueBit::ConstZero);
1676
1677 return std::make_pair(Interesting = true, &Bits);
1678 }
1679 break;
1680 case ISD::AND:
1681 if (isa<ConstantSDNode>(V.getOperand(1))) {
1682 uint64_t Mask = V.getConstantOperandVal(1);
1683
1684 const SmallVector<ValueBit, 64> *LHSBits;
1685 // Mark this as interesting, only if the LHS was also interesting. This
1686 // prevents the overall procedure from matching a single immediate 'and'
1687 // (which is non-optimal because such an and might be folded with other
1688 // things if we don't select it here).
1689 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits);
1690
1691 for (unsigned i = 0; i < NumBits; ++i)
1692 if (((Mask >> i) & 1) == 1)
1693 Bits[i] = (*LHSBits)[i];
1694 else {
1695 // AND instruction masks this bit. If the input is already zero,
1696 // we have nothing to do here. Otherwise, make the bit ConstZero.
1697 if ((*LHSBits)[i].isZero())
1698 Bits[i] = (*LHSBits)[i];
1699 else
1700 Bits[i] = ValueBit(ValueBit::ConstZero);
1701 }
1702
1703 return std::make_pair(Interesting, &Bits);
1704 }
1705 break;
1706 case ISD::OR: {
1707 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1708 const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second;
1709
1710 bool AllDisjoint = true;
1711 SDValue LastVal = SDValue();
1712 unsigned LastIdx = 0;
1713 for (unsigned i = 0; i < NumBits; ++i) {
1714 if (LHSBits[i].isZero() && RHSBits[i].isZero()) {
1715 // If both inputs are known to be zero and one is ConstZero and
1716 // another is VariableKnownToBeZero, we can select whichever
1717 // we like. To minimize the number of bit groups, we select
1718 // VariableKnownToBeZero if this bit is the next bit of the same
1719 // input variable from the previous bit. Otherwise, we select
1720 // ConstZero.
1721 if (LHSBits[i].hasValue() && LHSBits[i].getValue() == LastVal &&
1722 LHSBits[i].getValueBitIndex() == LastIdx + 1)
1723 Bits[i] = LHSBits[i];
1724 else if (RHSBits[i].hasValue() && RHSBits[i].getValue() == LastVal &&
1725 RHSBits[i].getValueBitIndex() == LastIdx + 1)
1726 Bits[i] = RHSBits[i];
1727 else
1728 Bits[i] = ValueBit(ValueBit::ConstZero);
1729 }
1730 else if (LHSBits[i].isZero())
1731 Bits[i] = RHSBits[i];
1732 else if (RHSBits[i].isZero())
1733 Bits[i] = LHSBits[i];
1734 else {
1735 AllDisjoint = false;
1736 break;
1737 }
1738 // We remember the value and bit index of this bit.
1739 if (Bits[i].hasValue()) {
1740 LastVal = Bits[i].getValue();
1741 LastIdx = Bits[i].getValueBitIndex();
1742 }
1743 else {
1744 if (LastVal) LastVal = SDValue();
1745 LastIdx = 0;
1746 }
1747 }
1748
1749 if (!AllDisjoint)
1750 break;
1751
1752 return std::make_pair(Interesting = true, &Bits);
1753 }
1754 case ISD::ZERO_EXTEND: {
1755 // We support only the case with zero extension from i32 to i64 so far.
1756 if (V.getValueType() != MVT::i64 ||
1757 V.getOperand(0).getValueType() != MVT::i32)
1758 break;
1759
1760 const SmallVector<ValueBit, 64> *LHSBits;
1761 const unsigned NumOperandBits = 32;
1762 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0),
1763 NumOperandBits);
1764
1765 for (unsigned i = 0; i < NumOperandBits; ++i)
1766 Bits[i] = (*LHSBits)[i];
1767
1768 for (unsigned i = NumOperandBits; i < NumBits; ++i)
1769 Bits[i] = ValueBit(ValueBit::ConstZero);
1770
1771 return std::make_pair(Interesting, &Bits);
1772 }
1773 case ISD::TRUNCATE: {
1774 EVT FromType = V.getOperand(0).getValueType();
1775 EVT ToType = V.getValueType();
1776 // We support only the case with truncate from i64 to i32.
1777 if (FromType != MVT::i64 || ToType != MVT::i32)
1778 break;
1779 const unsigned NumAllBits = FromType.getSizeInBits();
1781 std::tie(Interesting, InBits) = getValueBits(V.getOperand(0),
1782 NumAllBits);
1783 const unsigned NumValidBits = ToType.getSizeInBits();
1784
1785 // A 32-bit instruction cannot touch upper 32-bit part of 64-bit value.
1786 // So, we cannot include this truncate.
1787 bool UseUpper32bit = false;
1788 for (unsigned i = 0; i < NumValidBits; ++i)
1789 if ((*InBits)[i].hasValue() && (*InBits)[i].getValueBitIndex() >= 32) {
1790 UseUpper32bit = true;
1791 break;
1792 }
1793 if (UseUpper32bit)
1794 break;
1795
1796 for (unsigned i = 0; i < NumValidBits; ++i)
1797 Bits[i] = (*InBits)[i];
1798
1799 return std::make_pair(Interesting, &Bits);
1800 }
1801 case ISD::AssertZext: {
1802 // For AssertZext, we look through the operand and
1803 // mark the bits known to be zero.
1804 const SmallVector<ValueBit, 64> *LHSBits;
1805 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0),
1806 NumBits);
1807
1808 EVT FromType = cast<VTSDNode>(V.getOperand(1))->getVT();
1809 const unsigned NumValidBits = FromType.getSizeInBits();
1810 for (unsigned i = 0; i < NumValidBits; ++i)
1811 Bits[i] = (*LHSBits)[i];
1812
1813 // These bits are known to be zero but the AssertZext may be from a value
1814 // that already has some constant zero bits (i.e. from a masking and).
1815 for (unsigned i = NumValidBits; i < NumBits; ++i)
1816 Bits[i] = (*LHSBits)[i].hasValue()
1817 ? ValueBit((*LHSBits)[i].getValue(),
1818 (*LHSBits)[i].getValueBitIndex(),
1819 ValueBit::VariableKnownToBeZero)
1820 : ValueBit(ValueBit::ConstZero);
1821
1822 return std::make_pair(Interesting, &Bits);
1823 }
1824 case ISD::LOAD:
1825 LoadSDNode *LD = cast<LoadSDNode>(V);
1826 if (ISD::isZEXTLoad(V.getNode()) && V.getResNo() == 0) {
1827 EVT VT = LD->getMemoryVT();
1828 const unsigned NumValidBits = VT.getSizeInBits();
1829
1830 for (unsigned i = 0; i < NumValidBits; ++i)
1831 Bits[i] = ValueBit(V, i);
1832
1833 // These bits are known to be zero.
1834 for (unsigned i = NumValidBits; i < NumBits; ++i)
1835 Bits[i] = ValueBit(V, i, ValueBit::VariableKnownToBeZero);
1836
1837 // Zero-extending load itself cannot be optimized. So, it is not
1838 // interesting by itself though it gives useful information.
1839 return std::make_pair(Interesting = false, &Bits);
1840 }
1841 break;
1842 }
1843
1844 for (unsigned i = 0; i < NumBits; ++i)
1845 Bits[i] = ValueBit(V, i);
1846
1847 return std::make_pair(Interesting = false, &Bits);
1848 }
1849
1850 // For each value (except the constant ones), compute the left-rotate amount
1851 // to get it from its original to final position.
1852 void computeRotationAmounts() {
1853 NeedMask = false;
1854 RLAmt.resize(Bits.size());
1855 for (unsigned i = 0; i < Bits.size(); ++i)
1856 if (Bits[i].hasValue()) {
1857 unsigned VBI = Bits[i].getValueBitIndex();
1858 if (i >= VBI)
1859 RLAmt[i] = i - VBI;
1860 else
1861 RLAmt[i] = Bits.size() - (VBI - i);
1862 } else if (Bits[i].isZero()) {
1863 NeedMask = true;
1864 RLAmt[i] = UINT32_MAX;
1865 } else {
1866 llvm_unreachable("Unknown value bit type");
1867 }
1868 }
1869
1870 // Collect groups of consecutive bits with the same underlying value and
1871 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1872 // they break up groups.
1873 void collectBitGroups(bool LateMask) {
1874 BitGroups.clear();
1875
1876 unsigned LastRLAmt = RLAmt[0];
1877 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1878 unsigned LastGroupStartIdx = 0;
1879 bool IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue();
1880 for (unsigned i = 1; i < Bits.size(); ++i) {
1881 unsigned ThisRLAmt = RLAmt[i];
1882 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1883 if (LateMask && !ThisValue) {
1884 ThisValue = LastValue;
1885 ThisRLAmt = LastRLAmt;
1886 // If we're doing late masking, then the first bit group always starts
1887 // at zero (even if the first bits were zero).
1888 if (BitGroups.empty())
1889 LastGroupStartIdx = 0;
1890 }
1891
1892 // If this bit is known to be zero and the current group is a bit group
1893 // of zeros, we do not need to terminate the current bit group even the
1894 // Value or RLAmt does not match here. Instead, we terminate this group
1895 // when the first non-zero bit appears later.
1896 if (IsGroupOfZeros && Bits[i].isZero())
1897 continue;
1898
1899 // If this bit has the same underlying value and the same rotate factor as
1900 // the last one, then they're part of the same group.
1901 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1902 // We cannot continue the current group if this bits is not known to
1903 // be zero in a bit group of zeros.
1904 if (!(IsGroupOfZeros && ThisValue && !Bits[i].isZero()))
1905 continue;
1906
1907 if (LastValue.getNode())
1908 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1909 i-1));
1910 LastRLAmt = ThisRLAmt;
1911 LastValue = ThisValue;
1912 LastGroupStartIdx = i;
1913 IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue();
1914 }
1915 if (LastValue.getNode())
1916 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1917 Bits.size()-1));
1918
1919 if (BitGroups.empty())
1920 return;
1921
1922 // We might be able to combine the first and last groups.
1923 if (BitGroups.size() > 1) {
1924 // If the first and last groups are the same, then remove the first group
1925 // in favor of the last group, making the ending index of the last group
1926 // equal to the ending index of the to-be-removed first group.
1927 if (BitGroups[0].StartIdx == 0 &&
1928 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1929 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1930 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1931 LLVM_DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1932 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1933 BitGroups.erase(BitGroups.begin());
1934 }
1935 }
1936 }
1937
1938 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1939 // associated with each. If the number of groups are same, we prefer a group
1940 // which does not require rotate, i.e. RLAmt is 0, to avoid the first rotate
1941 // instruction. If there is a degeneracy, pick the one that occurs
1942 // first (in the final value).
1943 void collectValueRotInfo() {
1944 ValueRots.clear();
1945
1946 for (auto &BG : BitGroups) {
1947 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1948 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1949 VRI.V = BG.V;
1950 VRI.RLAmt = BG.RLAmt;
1951 VRI.Repl32 = BG.Repl32;
1952 VRI.NumGroups += 1;
1953 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1954 }
1955
1956 // Now that we've collected the various ValueRotInfo instances, we need to
1957 // sort them.
1958 ValueRotsVec.clear();
1959 for (auto &I : ValueRots) {
1960 ValueRotsVec.push_back(I.second);
1961 }
1962 llvm::sort(ValueRotsVec);
1963 }
1964
1965 // In 64-bit mode, rlwinm and friends have a rotation operator that
1966 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1967 // indices of these instructions can only be in the lower 32 bits, so they
1968 // can only represent some 64-bit bit groups. However, when they can be used,
1969 // the 32-bit replication can be used to represent, as a single bit group,
1970 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1971 // groups when possible. Returns true if any of the bit groups were
1972 // converted.
1973 void assignRepl32BitGroups() {
1974 // If we have bits like this:
1975 //
1976 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1977 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1978 // Groups: | RLAmt = 8 | RLAmt = 40 |
1979 //
1980 // But, making use of a 32-bit operation that replicates the low-order 32
1981 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1982 // of 8.
1983
1984 auto IsAllLow32 = [this](BitGroup & BG) {
1985 if (BG.StartIdx <= BG.EndIdx) {
1986 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1987 if (!Bits[i].hasValue())
1988 continue;
1989 if (Bits[i].getValueBitIndex() >= 32)
1990 return false;
1991 }
1992 } else {
1993 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1994 if (!Bits[i].hasValue())
1995 continue;
1996 if (Bits[i].getValueBitIndex() >= 32)
1997 return false;
1998 }
1999 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
2000 if (!Bits[i].hasValue())
2001 continue;
2002 if (Bits[i].getValueBitIndex() >= 32)
2003 return false;
2004 }
2005 }
2006
2007 return true;
2008 };
2009
2010 for (auto &BG : BitGroups) {
2011 // If this bit group has RLAmt of 0 and will not be merged with
2012 // another bit group, we don't benefit from Repl32. We don't mark
2013 // such group to give more freedom for later instruction selection.
2014 if (BG.RLAmt == 0) {
2015 auto PotentiallyMerged = [this](BitGroup & BG) {
2016 for (auto &BG2 : BitGroups)
2017 if (&BG != &BG2 && BG.V == BG2.V &&
2018 (BG2.RLAmt == 0 || BG2.RLAmt == 32))
2019 return true;
2020 return false;
2021 };
2022 if (!PotentiallyMerged(BG))
2023 continue;
2024 }
2025 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
2026 if (IsAllLow32(BG)) {
2027 if (BG.RLAmt >= 32) {
2028 BG.RLAmt -= 32;
2029 BG.Repl32CR = true;
2030 }
2031
2032 BG.Repl32 = true;
2033
2034 LLVM_DEBUG(dbgs() << "\t32-bit replicated bit group for "
2035 << BG.V.getNode() << " RLAmt = " << BG.RLAmt << " ["
2036 << BG.StartIdx << ", " << BG.EndIdx << "]\n");
2037 }
2038 }
2039 }
2040
2041 // Now walk through the bit groups, consolidating where possible.
2042 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
2043 // We might want to remove this bit group by merging it with the previous
2044 // group (which might be the ending group).
2045 auto IP = (I == BitGroups.begin()) ?
2046 std::prev(BitGroups.end()) : std::prev(I);
2047 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
2048 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
2049
2050 LLVM_DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for "
2051 << I->V.getNode() << " RLAmt = " << I->RLAmt << " ["
2052 << I->StartIdx << ", " << I->EndIdx
2053 << "] with group with range [" << IP->StartIdx << ", "
2054 << IP->EndIdx << "]\n");
2055
2056 IP->EndIdx = I->EndIdx;
2057 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
2058 IP->Repl32Coalesced = true;
2059 I = BitGroups.erase(I);
2060 continue;
2061 } else {
2062 // There is a special case worth handling: If there is a single group
2063 // covering the entire upper 32 bits, and it can be merged with both
2064 // the next and previous groups (which might be the same group), then
2065 // do so. If it is the same group (so there will be only one group in
2066 // total), then we need to reverse the order of the range so that it
2067 // covers the entire 64 bits.
2068 if (I->StartIdx == 32 && I->EndIdx == 63) {
2069 assert(std::next(I) == BitGroups.end() &&
2070 "bit group ends at index 63 but there is another?");
2071 auto IN = BitGroups.begin();
2072
2073 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
2074 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
2075 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
2076 IsAllLow32(*I)) {
2077
2078 LLVM_DEBUG(dbgs() << "\tcombining bit group for " << I->V.getNode()
2079 << " RLAmt = " << I->RLAmt << " [" << I->StartIdx
2080 << ", " << I->EndIdx
2081 << "] with 32-bit replicated groups with ranges ["
2082 << IP->StartIdx << ", " << IP->EndIdx << "] and ["
2083 << IN->StartIdx << ", " << IN->EndIdx << "]\n");
2084
2085 if (IP == IN) {
2086 // There is only one other group; change it to cover the whole
2087 // range (backward, so that it can still be Repl32 but cover the
2088 // whole 64-bit range).
2089 IP->StartIdx = 31;
2090 IP->EndIdx = 30;
2091 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
2092 IP->Repl32Coalesced = true;
2093 I = BitGroups.erase(I);
2094 } else {
2095 // There are two separate groups, one before this group and one
2096 // after us (at the beginning). We're going to remove this group,
2097 // but also the group at the very beginning.
2098 IP->EndIdx = IN->EndIdx;
2099 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
2100 IP->Repl32Coalesced = true;
2101 I = BitGroups.erase(I);
2102 BitGroups.erase(BitGroups.begin());
2103 }
2104
2105 // This must be the last group in the vector (and we might have
2106 // just invalidated the iterator above), so break here.
2107 break;
2108 }
2109 }
2110 }
2111
2112 ++I;
2113 }
2114 }
2115
2116 SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
2117 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
2118 }
2119
2120 uint64_t getZerosMask() {
2121 uint64_t Mask = 0;
2122 for (unsigned i = 0; i < Bits.size(); ++i) {
2123 if (Bits[i].hasValue())
2124 continue;
2125 Mask |= (UINT64_C(1) << i);
2126 }
2127
2128 return ~Mask;
2129 }
2130
2131 // This method extends an input value to 64 bit if input is 32-bit integer.
2132 // While selecting instructions in BitPermutationSelector in 64-bit mode,
2133 // an input value can be a 32-bit integer if a ZERO_EXTEND node is included.
2134 // In such case, we extend it to 64 bit to be consistent with other values.
2135 SDValue ExtendToInt64(SDValue V, const SDLoc &dl) {
2136 if (V.getValueSizeInBits() == 64)
2137 return V;
2138
2139 assert(V.getValueSizeInBits() == 32);
2140 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2141 SDValue ImDef = SDValue(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,
2142 MVT::i64), 0);
2143 SDValue ExtVal = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,
2144 MVT::i64, ImDef, V,
2145 SubRegIdx), 0);
2146 return ExtVal;
2147 }
2148
2149 SDValue TruncateToInt32(SDValue V, const SDLoc &dl) {
2150 if (V.getValueSizeInBits() == 32)
2151 return V;
2152
2153 assert(V.getValueSizeInBits() == 64);
2154 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2155 SDValue SubVal = SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl,
2156 MVT::i32, V, SubRegIdx), 0);
2157 return SubVal;
2158 }
2159
2160 // Depending on the number of groups for a particular value, it might be
2161 // better to rotate, mask explicitly (using andi/andis), and then or the
2162 // result. Select this part of the result first.
2163 void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
2165 return;
2166
2167 for (ValueRotInfo &VRI : ValueRotsVec) {
2168 unsigned Mask = 0;
2169 for (unsigned i = 0; i < Bits.size(); ++i) {
2170 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
2171 continue;
2172 if (RLAmt[i] != VRI.RLAmt)
2173 continue;
2174 Mask |= (1u << i);
2175 }
2176
2177 // Compute the masks for andi/andis that would be necessary.
2178 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
2179 assert((ANDIMask != 0 || ANDISMask != 0) &&
2180 "No set bits in mask for value bit groups");
2181 bool NeedsRotate = VRI.RLAmt != 0;
2182
2183 // We're trying to minimize the number of instructions. If we have one
2184 // group, using one of andi/andis can break even. If we have three
2185 // groups, we can use both andi and andis and break even (to use both
2186 // andi and andis we also need to or the results together). We need four
2187 // groups if we also need to rotate. To use andi/andis we need to do more
2188 // than break even because rotate-and-mask instructions tend to be easier
2189 // to schedule.
2190
2191 // FIXME: We've biased here against using andi/andis, which is right for
2192 // POWER cores, but not optimal everywhere. For example, on the A2,
2193 // andi/andis have single-cycle latency whereas the rotate-and-mask
2194 // instructions take two cycles, and it would be better to bias toward
2195 // andi/andis in break-even cases.
2196
2197 unsigned NumAndInsts = (unsigned) NeedsRotate +
2198 (unsigned) (ANDIMask != 0) +
2199 (unsigned) (ANDISMask != 0) +
2200 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
2201 (unsigned) (bool) Res;
2202
2203 LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode()
2204 << " RL: " << VRI.RLAmt << ":"
2205 << "\n\t\t\tisel using masking: " << NumAndInsts
2206 << " using rotates: " << VRI.NumGroups << "\n");
2207
2208 if (NumAndInsts >= VRI.NumGroups)
2209 continue;
2210
2211 LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n");
2212
2213 if (InstCnt) *InstCnt += NumAndInsts;
2214
2215 SDValue VRot;
2216 if (VRI.RLAmt) {
2217 SDValue Ops[] =
2218 { TruncateToInt32(VRI.V, dl), getI32Imm(VRI.RLAmt, dl),
2219 getI32Imm(0, dl), getI32Imm(31, dl) };
2220 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2221 Ops), 0);
2222 } else {
2223 VRot = TruncateToInt32(VRI.V, dl);
2224 }
2225
2226 SDValue ANDIVal, ANDISVal;
2227 if (ANDIMask != 0)
2228 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32,
2229 VRot, getI32Imm(ANDIMask, dl)),
2230 0);
2231 if (ANDISMask != 0)
2232 ANDISVal =
2233 SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, VRot,
2234 getI32Imm(ANDISMask, dl)),
2235 0);
2236
2237 SDValue TotalVal;
2238 if (!ANDIVal)
2239 TotalVal = ANDISVal;
2240 else if (!ANDISVal)
2241 TotalVal = ANDIVal;
2242 else
2243 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
2244 ANDIVal, ANDISVal), 0);
2245
2246 if (!Res)
2247 Res = TotalVal;
2248 else
2249 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
2250 Res, TotalVal), 0);
2251
2252 // Now, remove all groups with this underlying value and rotation
2253 // factor.
2254 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
2255 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
2256 });
2257 }
2258 }
2259
2260 // Instruction selection for the 32-bit case.
2261 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
2262 SDLoc dl(N);
2263 SDValue Res;
2264
2265 if (InstCnt) *InstCnt = 0;
2266
2267 // Take care of cases that should use andi/andis first.
2268 SelectAndParts32(dl, Res, InstCnt);
2269
2270 // If we've not yet selected a 'starting' instruction, and we have no zeros
2271 // to fill in, select the (Value, RLAmt) with the highest priority (largest
2272 // number of groups), and start with this rotated value.
2273 if ((!NeedMask || LateMask) && !Res) {
2274 ValueRotInfo &VRI = ValueRotsVec[0];
2275 if (VRI.RLAmt) {
2276 if (InstCnt) *InstCnt += 1;
2277 SDValue Ops[] =
2278 { TruncateToInt32(VRI.V, dl), getI32Imm(VRI.RLAmt, dl),
2279 getI32Imm(0, dl), getI32Imm(31, dl) };
2280 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
2281 0);
2282 } else {
2283 Res = TruncateToInt32(VRI.V, dl);
2284 }
2285
2286 // Now, remove all groups with this underlying value and rotation factor.
2287 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
2288 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
2289 });
2290 }
2291
2292 if (InstCnt) *InstCnt += BitGroups.size();
2293
2294 // Insert the other groups (one at a time).
2295 for (auto &BG : BitGroups) {
2296 if (!Res) {
2297 SDValue Ops[] =
2298 { TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl),
2299 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
2300 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
2301 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2302 } else {
2303 SDValue Ops[] =
2304 { Res, TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl),
2305 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
2306 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
2307 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
2308 }
2309 }
2310
2311 if (LateMask) {
2312 unsigned Mask = (unsigned) getZerosMask();
2313
2314 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
2315 assert((ANDIMask != 0 || ANDISMask != 0) &&
2316 "No set bits in zeros mask?");
2317
2318 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
2319 (unsigned) (ANDISMask != 0) +
2320 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2321
2322 SDValue ANDIVal, ANDISVal;
2323 if (ANDIMask != 0)
2324 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32,
2325 Res, getI32Imm(ANDIMask, dl)),
2326 0);
2327 if (ANDISMask != 0)
2328 ANDISVal =
2329 SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, Res,
2330 getI32Imm(ANDISMask, dl)),
2331 0);
2332
2333 if (!ANDIVal)
2334 Res = ANDISVal;
2335 else if (!ANDISVal)
2336 Res = ANDIVal;
2337 else
2338 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
2339 ANDIVal, ANDISVal), 0);
2340 }
2341
2342 return Res.getNode();
2343 }
2344
2345 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
2346 unsigned MaskStart, unsigned MaskEnd,
2347 bool IsIns) {
2348 // In the notation used by the instructions, 'start' and 'end' are reversed
2349 // because bits are counted from high to low order.
2350 unsigned InstMaskStart = 64 - MaskEnd - 1,
2351 InstMaskEnd = 64 - MaskStart - 1;
2352
2353 if (Repl32)
2354 return 1;
2355
2356 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
2357 InstMaskEnd == 63 - RLAmt)
2358 return 1;
2359
2360 return 2;
2361 }
2362
2363 // For 64-bit values, not all combinations of rotates and masks are
2364 // available. Produce one if it is available.
2365 SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,
2366 bool Repl32, unsigned MaskStart, unsigned MaskEnd,
2367 unsigned *InstCnt = nullptr) {
2368 // In the notation used by the instructions, 'start' and 'end' are reversed
2369 // because bits are counted from high to low order.
2370 unsigned InstMaskStart = 64 - MaskEnd - 1,
2371 InstMaskEnd = 64 - MaskStart - 1;
2372
2373 if (InstCnt) *InstCnt += 1;
2374
2375 if (Repl32) {
2376 // This rotation amount assumes that the lower 32 bits of the quantity
2377 // are replicated in the high 32 bits by the rotation operator (which is
2378 // done by rlwinm and friends).
2379 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
2380 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
2381 SDValue Ops[] =
2382 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2383 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };
2384 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
2385 Ops), 0);
2386 }
2387
2388 if (InstMaskEnd == 63) {
2389 SDValue Ops[] =
2390 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2391 getI32Imm(InstMaskStart, dl) };
2392 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
2393 }
2394
2395 if (InstMaskStart == 0) {
2396 SDValue Ops[] =
2397 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2398 getI32Imm(InstMaskEnd, dl) };
2399 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
2400 }
2401
2402 if (InstMaskEnd == 63 - RLAmt) {
2403 SDValue Ops[] =
2404 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2405 getI32Imm(InstMaskStart, dl) };
2406 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
2407 }
2408
2409 // We cannot do this with a single instruction, so we'll use two. The
2410 // problem is that we're not free to choose both a rotation amount and mask
2411 // start and end independently. We can choose an arbitrary mask start and
2412 // end, but then the rotation amount is fixed. Rotation, however, can be
2413 // inverted, and so by applying an "inverse" rotation first, we can get the
2414 // desired result.
2415 if (InstCnt) *InstCnt += 1;
2416
2417 // The rotation mask for the second instruction must be MaskStart.
2418 unsigned RLAmt2 = MaskStart;
2419 // The first instruction must rotate V so that the overall rotation amount
2420 // is RLAmt.
2421 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
2422 if (RLAmt1)
2423 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
2424 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
2425 }
2426
2427 // For 64-bit values, not all combinations of rotates and masks are
2428 // available. Produce a rotate-mask-and-insert if one is available.
2429 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,
2430 unsigned RLAmt, bool Repl32, unsigned MaskStart,
2431 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
2432 // In the notation used by the instructions, 'start' and 'end' are reversed
2433 // because bits are counted from high to low order.
2434 unsigned InstMaskStart = 64 - MaskEnd - 1,
2435 InstMaskEnd = 64 - MaskStart - 1;
2436
2437 if (InstCnt) *InstCnt += 1;
2438
2439 if (Repl32) {
2440 // This rotation amount assumes that the lower 32 bits of the quantity
2441 // are replicated in the high 32 bits by the rotation operator (which is
2442 // done by rlwinm and friends).
2443 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
2444 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
2445 SDValue Ops[] =
2446 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2447 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };
2448 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
2449 Ops), 0);
2450 }
2451
2452 if (InstMaskEnd == 63 - RLAmt) {
2453 SDValue Ops[] =
2454 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2455 getI32Imm(InstMaskStart, dl) };
2456 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
2457 }
2458
2459 // We cannot do this with a single instruction, so we'll use two. The
2460 // problem is that we're not free to choose both a rotation amount and mask
2461 // start and end independently. We can choose an arbitrary mask start and
2462 // end, but then the rotation amount is fixed. Rotation, however, can be
2463 // inverted, and so by applying an "inverse" rotation first, we can get the
2464 // desired result.
2465 if (InstCnt) *InstCnt += 1;
2466
2467 // The rotation mask for the second instruction must be MaskStart.
2468 unsigned RLAmt2 = MaskStart;
2469 // The first instruction must rotate V so that the overall rotation amount
2470 // is RLAmt.
2471 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
2472 if (RLAmt1)
2473 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
2474 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
2475 }
2476
2477 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
2479 return;
2480
2481 // The idea here is the same as in the 32-bit version, but with additional
2482 // complications from the fact that Repl32 might be true. Because we
2483 // aggressively convert bit groups to Repl32 form (which, for small
2484 // rotation factors, involves no other change), and then coalesce, it might
2485 // be the case that a single 64-bit masking operation could handle both
2486 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
2487 // form allowed coalescing, then we must use a 32-bit rotaton in order to
2488 // completely capture the new combined bit group.
2489
2490 for (ValueRotInfo &VRI : ValueRotsVec) {
2491 uint64_t Mask = 0;
2492
2493 // We need to add to the mask all bits from the associated bit groups.
2494 // If Repl32 is false, we need to add bits from bit groups that have
2495 // Repl32 true, but are trivially convertable to Repl32 false. Such a
2496 // group is trivially convertable if it overlaps only with the lower 32
2497 // bits, and the group has not been coalesced.
2498 auto MatchingBG = [VRI](const BitGroup &BG) {
2499 if (VRI.V != BG.V)
2500 return false;
2501
2502 unsigned EffRLAmt = BG.RLAmt;
2503 if (!VRI.Repl32 && BG.Repl32) {
2504 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
2505 !BG.Repl32Coalesced) {
2506 if (BG.Repl32CR)
2507 EffRLAmt += 32;
2508 } else {
2509 return false;
2510 }
2511 } else if (VRI.Repl32 != BG.Repl32) {
2512 return false;
2513 }
2514
2515 return VRI.RLAmt == EffRLAmt;
2516 };
2517
2518 for (auto &BG : BitGroups) {
2519 if (!MatchingBG(BG))
2520 continue;
2521
2522 if (BG.StartIdx <= BG.EndIdx) {
2523 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
2524 Mask |= (UINT64_C(1) << i);
2525 } else {
2526 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
2527 Mask |= (UINT64_C(1) << i);
2528 for (unsigned i = 0; i <= BG.EndIdx; ++i)
2529 Mask |= (UINT64_C(1) << i);
2530 }
2531 }
2532
2533 // We can use the 32-bit andi/andis technique if the mask does not
2534 // require any higher-order bits. This can save an instruction compared
2535 // to always using the general 64-bit technique.
2536 bool Use32BitInsts = isUInt<32>(Mask);
2537 // Compute the masks for andi/andis that would be necessary.
2538 unsigned ANDIMask = (Mask & UINT16_MAX),
2539 ANDISMask = (Mask >> 16) & UINT16_MAX;
2540
2541 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
2542
2543 unsigned NumAndInsts = (unsigned) NeedsRotate +
2544 (unsigned) (bool) Res;
2545 unsigned NumOfSelectInsts = 0;
2546 selectI64Imm(CurDAG, dl, Mask, &NumOfSelectInsts);
2547 assert(NumOfSelectInsts > 0 && "Failed to select an i64 constant.");
2548 if (Use32BitInsts)
2549 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
2550 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2551 else
2552 NumAndInsts += NumOfSelectInsts + /* and */ 1;
2553
2554 unsigned NumRLInsts = 0;
2555 bool FirstBG = true;
2556 bool MoreBG = false;
2557 for (auto &BG : BitGroups) {
2558 if (!MatchingBG(BG)) {
2559 MoreBG = true;
2560 continue;
2561 }
2562 NumRLInsts +=
2563 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
2564 !FirstBG);
2565 FirstBG = false;
2566 }
2567
2568 LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode()
2569 << " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":")
2570 << "\n\t\t\tisel using masking: " << NumAndInsts
2571 << " using rotates: " << NumRLInsts << "\n");
2572
2573 // When we'd use andi/andis, we bias toward using the rotates (andi only
2574 // has a record form, and is cracked on POWER cores). However, when using
2575 // general 64-bit constant formation, bias toward the constant form,
2576 // because that exposes more opportunities for CSE.
2577 if (NumAndInsts > NumRLInsts)
2578 continue;
2579 // When merging multiple bit groups, instruction or is used.
2580 // But when rotate is used, rldimi can inert the rotated value into any
2581 // register, so instruction or can be avoided.
2582 if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)
2583 continue;
2584
2585 LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n");
2586
2587 if (InstCnt) *InstCnt += NumAndInsts;
2588
2589 SDValue VRot;
2590 // We actually need to generate a rotation if we have a non-zero rotation
2591 // factor or, in the Repl32 case, if we care about any of the
2592 // higher-order replicated bits. In the latter case, we generate a mask
2593 // backward so that it actually includes the entire 64 bits.
2594 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
2595 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
2596 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
2597 else
2598 VRot = VRI.V;
2599
2600 SDValue TotalVal;
2601 if (Use32BitInsts) {
2602 assert((ANDIMask != 0 || ANDISMask != 0) &&
2603 "No set bits in mask when using 32-bit ands for 64-bit value");
2604
2605 SDValue ANDIVal, ANDISVal;
2606 if (ANDIMask != 0)
2607 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI8_rec, dl, MVT::i64,
2608 ExtendToInt64(VRot, dl),
2609 getI32Imm(ANDIMask, dl)),
2610 0);
2611 if (ANDISMask != 0)
2612 ANDISVal =
2613 SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64,
2614 ExtendToInt64(VRot, dl),
2615 getI32Imm(ANDISMask, dl)),
2616 0);
2617
2618 if (!ANDIVal)
2619 TotalVal = ANDISVal;
2620 else if (!ANDISVal)
2621 TotalVal = ANDIVal;
2622 else
2623 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2624 ExtendToInt64(ANDIVal, dl), ANDISVal), 0);
2625 } else {
2626 TotalVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0);
2627 TotalVal =
2628 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
2629 ExtendToInt64(VRot, dl), TotalVal),
2630 0);
2631 }
2632
2633 if (!Res)
2634 Res = TotalVal;
2635 else
2636 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2637 ExtendToInt64(Res, dl), TotalVal),
2638 0);
2639
2640 // Now, remove all groups with this underlying value and rotation
2641 // factor.
2642 eraseMatchingBitGroups(MatchingBG);
2643 }
2644 }
2645
2646 // Instruction selection for the 64-bit case.
2647 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
2648 SDLoc dl(N);
2649 SDValue Res;
2650
2651 if (InstCnt) *InstCnt = 0;
2652
2653 // Take care of cases that should use andi/andis first.
2654 SelectAndParts64(dl, Res, InstCnt);
2655
2656 // If we've not yet selected a 'starting' instruction, and we have no zeros
2657 // to fill in, select the (Value, RLAmt) with the highest priority (largest
2658 // number of groups), and start with this rotated value.
2659 if ((!NeedMask || LateMask) && !Res) {
2660 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
2661 // groups will come first, and so the VRI representing the largest number
2662 // of groups might not be first (it might be the first Repl32 groups).
2663 unsigned MaxGroupsIdx = 0;
2664 if (!ValueRotsVec[0].Repl32) {
2665 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
2666 if (ValueRotsVec[i].Repl32) {
2667 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
2668 MaxGroupsIdx = i;
2669 break;
2670 }
2671 }
2672
2673 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
2674 bool NeedsRotate = false;
2675 if (VRI.RLAmt) {
2676 NeedsRotate = true;
2677 } else if (VRI.Repl32) {
2678 for (auto &BG : BitGroups) {
2679 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
2680 BG.Repl32 != VRI.Repl32)
2681 continue;
2682
2683 // We don't need a rotate if the bit group is confined to the lower
2684 // 32 bits.
2685 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
2686 continue;
2687
2688 NeedsRotate = true;
2689 break;
2690 }
2691 }
2692
2693 if (NeedsRotate)
2694 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
2695 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
2696 InstCnt);
2697 else
2698 Res = VRI.V;
2699
2700 // Now, remove all groups with this underlying value and rotation factor.
2701 if (Res)
2702 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
2703 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
2704 BG.Repl32 == VRI.Repl32;
2705 });
2706 }
2707
2708 // Because 64-bit rotates are more flexible than inserts, we might have a
2709 // preference regarding which one we do first (to save one instruction).
2710 if (!Res)
2711 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
2712 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
2713 false) <
2714 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
2715 true)) {
2716 if (I != BitGroups.begin()) {
2717 BitGroup BG = *I;
2718 BitGroups.erase(I);
2719 BitGroups.insert(BitGroups.begin(), BG);
2720 }
2721
2722 break;
2723 }
2724 }
2725
2726 // Insert the other groups (one at a time).
2727 for (auto &BG : BitGroups) {
2728 if (!Res)
2729 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
2730 BG.EndIdx, InstCnt);
2731 else
2732 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
2733 BG.StartIdx, BG.EndIdx, InstCnt);
2734 }
2735
2736 if (LateMask) {
2737 uint64_t Mask = getZerosMask();
2738
2739 // We can use the 32-bit andi/andis technique if the mask does not
2740 // require any higher-order bits. This can save an instruction compared
2741 // to always using the general 64-bit technique.
2742 bool Use32BitInsts = isUInt<32>(Mask);
2743 // Compute the masks for andi/andis that would be necessary.
2744 unsigned ANDIMask = (Mask & UINT16_MAX),
2745 ANDISMask = (Mask >> 16) & UINT16_MAX;
2746
2747 if (Use32BitInsts) {
2748 assert((ANDIMask != 0 || ANDISMask != 0) &&
2749 "No set bits in mask when using 32-bit ands for 64-bit value");
2750
2751 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
2752 (unsigned) (ANDISMask != 0) +
2753 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2754
2755 SDValue ANDIVal, ANDISVal;
2756 if (ANDIMask != 0)
2757 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI8_rec, dl, MVT::i64,
2758 ExtendToInt64(Res, dl),
2759 getI32Imm(ANDIMask, dl)),
2760 0);
2761 if (ANDISMask != 0)
2762 ANDISVal =
2763 SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64,
2764 ExtendToInt64(Res, dl),
2765 getI32Imm(ANDISMask, dl)),
2766 0);
2767
2768 if (!ANDIVal)
2769 Res = ANDISVal;
2770 else if (!ANDISVal)
2771 Res = ANDIVal;
2772 else
2773 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2774 ExtendToInt64(ANDIVal, dl), ANDISVal), 0);
2775 } else {
2776 unsigned NumOfSelectInsts = 0;
2777 SDValue MaskVal =
2778 SDValue(selectI64Imm(CurDAG, dl, Mask, &NumOfSelectInsts), 0);
2779 Res = SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
2780 ExtendToInt64(Res, dl), MaskVal),
2781 0);
2782 if (InstCnt)
2783 *InstCnt += NumOfSelectInsts + /* and */ 1;
2784 }
2785 }
2786
2787 return Res.getNode();
2788 }
2789
2790 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
2791 // Fill in BitGroups.
2792 collectBitGroups(LateMask);
2793 if (BitGroups.empty())
2794 return nullptr;
2795
2796 // For 64-bit values, figure out when we can use 32-bit instructions.
2797 if (Bits.size() == 64)
2798 assignRepl32BitGroups();
2799
2800 // Fill in ValueRotsVec.
2801 collectValueRotInfo();
2802
2803 if (Bits.size() == 32) {
2804 return Select32(N, LateMask, InstCnt);
2805 } else {
2806 assert(Bits.size() == 64 && "Not 64 bits here?");
2807 return Select64(N, LateMask, InstCnt);
2808 }
2809
2810 return nullptr;
2811 }
2812
2813 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
2814 erase_if(BitGroups, F);
2815 }
2816
2818
2819 bool NeedMask = false;
2821
2822 SmallVector<BitGroup, 16> BitGroups;
2823
2824 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
2825 SmallVector<ValueRotInfo, 16> ValueRotsVec;
2826
2827 SelectionDAG *CurDAG = nullptr;
2828
2829public:
2830 BitPermutationSelector(SelectionDAG *DAG)
2831 : CurDAG(DAG) {}
2832
2833 // Here we try to match complex bit permutations into a set of
2834 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
2835 // known to produce optimal code for common cases (like i32 byte swapping).
2836 SDNode *Select(SDNode *N) {
2837 Memoizer.clear();
2838 auto Result =
2839 getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits());
2840 if (!Result.first)
2841 return nullptr;
2842 Bits = std::move(*Result.second);
2843
2844 LLVM_DEBUG(dbgs() << "Considering bit-permutation-based instruction"
2845 " selection for: ");
2846 LLVM_DEBUG(N->dump(CurDAG));
2847
2848 // Fill it RLAmt and set NeedMask.
2849 computeRotationAmounts();
2850
2851 if (!NeedMask)
2852 return Select(N, false);
2853
2854 // We currently have two techniques for handling results with zeros: early
2855 // masking (the default) and late masking. Late masking is sometimes more
2856 // efficient, but because the structure of the bit groups is different, it
2857 // is hard to tell without generating both and comparing the results. With
2858 // late masking, we ignore zeros in the resulting value when inserting each
2859 // set of bit groups, and then mask in the zeros at the end. With early
2860 // masking, we only insert the non-zero parts of the result at every step.
2861
2862 unsigned InstCnt = 0, InstCntLateMask = 0;
2863 LLVM_DEBUG(dbgs() << "\tEarly masking:\n");
2864 SDNode *RN = Select(N, false, &InstCnt);
2865 LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
2866
2867 LLVM_DEBUG(dbgs() << "\tLate masking:\n");
2868 SDNode *RNLM = Select(N, true, &InstCntLateMask);
2869 LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask
2870 << " instructions\n");
2871
2872 if (InstCnt <= InstCntLateMask) {
2873 LLVM_DEBUG(dbgs() << "\tUsing early-masking for isel\n");
2874 return RN;
2875 }
2876
2877 LLVM_DEBUG(dbgs() << "\tUsing late-masking for isel\n");
2878 return RNLM;
2879 }
2880};
2881
2882class IntegerCompareEliminator {
2883 SelectionDAG *CurDAG;
2884 PPCDAGToDAGISel *S;
2885 // Conversion type for interpreting results of a 32-bit instruction as
2886 // a 64-bit value or vice versa.
2887 enum ExtOrTruncConversion { Ext, Trunc };
2888
2889 // Modifiers to guide how an ISD::SETCC node's result is to be computed
2890 // in a GPR.
2891 // ZExtOrig - use the original condition code, zero-extend value
2892 // ZExtInvert - invert the condition code, zero-extend value
2893 // SExtOrig - use the original condition code, sign-extend value
2894 // SExtInvert - invert the condition code, sign-extend value
2895 enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert };
2896
2897 // Comparisons against zero to emit GPR code sequences for. Each of these
2898 // sequences may need to be emitted for two or more equivalent patterns.
2899 // For example (a >= 0) == (a > -1). The direction of the comparison (</>)
2900 // matters as well as the extension type: sext (-1/0), zext (1/0).
2901 // GEZExt - (zext (LHS >= 0))
2902 // GESExt - (sext (LHS >= 0))
2903 // LEZExt - (zext (LHS <= 0))
2904 // LESExt - (sext (LHS <= 0))
2905 enum ZeroCompare { GEZExt, GESExt, LEZExt, LESExt };
2906
2907 SDNode *tryEXTEND(SDNode *N);
2908 SDNode *tryLogicOpOfCompares(SDNode *N);
2909 SDValue computeLogicOpInGPR(SDValue LogicOp);
2910 SDValue signExtendInputIfNeeded(SDValue Input);
2911 SDValue zeroExtendInputIfNeeded(SDValue Input);
2912 SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv);
2913 SDValue getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
2914 ZeroCompare CmpTy);
2915 SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2916 int64_t RHSValue, SDLoc dl);
2917 SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2918 int64_t RHSValue, SDLoc dl);
2919 SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2920 int64_t RHSValue, SDLoc dl);
2921 SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2922 int64_t RHSValue, SDLoc dl);
2923 SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts);
2924
2925public:
2926 IntegerCompareEliminator(SelectionDAG *DAG,
2927 PPCDAGToDAGISel *Sel) : CurDAG(DAG), S(Sel) {
2929 .getPointerTy(CurDAG->getDataLayout()).getSizeInBits() == 64 &&
2930 "Only expecting to use this on 64 bit targets.");
2931 }
2932 SDNode *Select(SDNode *N) {
2933 if (CmpInGPR == ICGPR_None)
2934 return nullptr;
2935 switch (N->getOpcode()) {
2936 default: break;
2937 case ISD::ZERO_EXTEND:
2940 return nullptr;
2941 [[fallthrough]];
2942 case ISD::SIGN_EXTEND:
2945 return nullptr;
2946 return tryEXTEND(N);
2947 case ISD::AND:
2948 case ISD::OR:
2949 case ISD::XOR:
2950 return tryLogicOpOfCompares(N);
2951 }
2952 return nullptr;
2953 }
2954};
2955
2956// The obvious case for wanting to keep the value in a GPR. Namely, the
2957// result of the comparison is actually needed in a GPR.
2958SDNode *IntegerCompareEliminator::tryEXTEND(SDNode *N) {
2959 assert((N->getOpcode() == ISD::ZERO_EXTEND ||
2960 N->getOpcode() == ISD::SIGN_EXTEND) &&
2961 "Expecting a zero/sign extend node!");
2962 SDValue WideRes;
2963 // If we are zero-extending the result of a logical operation on i1
2964 // values, we can keep the values in GPRs.
2965 if (ISD::isBitwiseLogicOp(N->getOperand(0).getOpcode()) &&
2966 N->getOperand(0).getValueType() == MVT::i1 &&
2967 N->getOpcode() == ISD::ZERO_EXTEND)
2968 WideRes = computeLogicOpInGPR(N->getOperand(0));
2969 else if (N->getOperand(0).getOpcode() != ISD::SETCC)
2970 return nullptr;
2971 else
2972 WideRes =
2973 getSETCCInGPR(N->getOperand(0),
2974 N->getOpcode() == ISD::SIGN_EXTEND ?
2975 SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig);
2976
2977 if (!WideRes)
2978 return nullptr;
2979
2980 SDLoc dl(N);
2981 bool Input32Bit = WideRes.getValueType() == MVT::i32;
2982 bool Output32Bit = N->getValueType(0) == MVT::i32;
2983
2984 NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0;
2985 NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1;
2986
2987 SDValue ConvOp = WideRes;
2988 if (Input32Bit != Output32Bit)
2989 ConvOp = addExtOrTrunc(WideRes, Input32Bit ? ExtOrTruncConversion::Ext :
2990 ExtOrTruncConversion::Trunc);
2991 return ConvOp.getNode();
2992}
2993
2994// Attempt to perform logical operations on the results of comparisons while
2995// keeping the values in GPRs. Without doing so, these would end up being
2996// lowered to CR-logical operations which suffer from significant latency and
2997// low ILP.
2998SDNode *IntegerCompareEliminator::tryLogicOpOfCompares(SDNode *N) {
2999 if (N->getValueType(0) != MVT::i1)
3000 return nullptr;
3001 assert(ISD::isBitwiseLogicOp(N->getOpcode()) &&
3002 "Expected a logic operation on setcc results.");
3003 SDValue LoweredLogical = computeLogicOpInGPR(SDValue(N, 0));
3004 if (!LoweredLogical)
3005 return nullptr;
3006
3007 SDLoc dl(N);
3008 bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8;
3009 unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt;
3010 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
3011 SDValue LHS = LoweredLogical.getOperand(0);
3012 SDValue RHS = LoweredLogical.getOperand(1);
3013 SDValue WideOp;
3014 SDValue OpToConvToRecForm;
3015
3016 // Look through any 32-bit to 64-bit implicit extend nodes to find the
3017 // opcode that is input to the XORI.
3018 if (IsBitwiseNegate &&
3019 LoweredLogical.getOperand(0).getMachineOpcode() == PPC::INSERT_SUBREG)
3020 OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(1);
3021 else if (IsBitwiseNegate)
3022 // If the input to the XORI isn't an extension, that's what we're after.
3023 OpToConvToRecForm = LoweredLogical.getOperand(0);
3024 else
3025 // If this is not an XORI, it is a reg-reg logical op and we can convert
3026 // it to record-form.
3027 OpToConvToRecForm = LoweredLogical;
3028
3029 // Get the record-form version of the node we're looking to use to get the
3030 // CR result from.
3031 uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode();
3032 int NewOpc = PPCInstrInfo::getRecordFormOpcode(NonRecOpc);
3033
3034 // Convert the right node to record-form. This is either the logical we're
3035 // looking at or it is the input node to the negation (if we're looking at
3036 // a bitwise negation).
3037 if (NewOpc != -1 && IsBitwiseNegate) {
3038 // The input to the XORI has a record-form. Use it.
3039 assert(LoweredLogical.getConstantOperandVal(1) == 1 &&
3040 "Expected a PPC::XORI8 only for bitwise negation.");
3041 // Emit the record-form instruction.
3042 std::vector<SDValue> Ops;
3043 for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++)
3044 Ops.push_back(OpToConvToRecForm.getOperand(i));
3045
3046 WideOp =
3047 SDValue(CurDAG->getMachineNode(NewOpc, dl,
3048 OpToConvToRecForm.getValueType(),
3049 MVT::Glue, Ops), 0);
3050 } else {
3051 assert((NewOpc != -1 || !IsBitwiseNegate) &&
3052 "No record form available for AND8/OR8/XOR8?");
3053 WideOp =
3054 SDValue(CurDAG->getMachineNode(NewOpc == -1 ? PPC::ANDI8_rec : NewOpc,
3055 dl, MVT::i64, MVT::Glue, LHS, RHS),
3056 0);
3057 }
3058
3059 // Select this node to a single bit from CR0 set by the record-form node
3060 // just created. For bitwise negation, use the EQ bit which is the equivalent
3061 // of negating the result (i.e. it is a bit set when the result of the
3062 // operation is zero).
3063 SDValue SRIdxVal =
3064 CurDAG->getTargetConstant(SubRegToExtract, dl, MVT::i32);
3065 SDValue CRBit =
3066 SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
3067 MVT::i1, CR0Reg, SRIdxVal,
3068 WideOp.getValue(1)), 0);
3069 return CRBit.getNode();
3070}
3071
3072// Lower a logical operation on i1 values into a GPR sequence if possible.
3073// The result can be kept in a GPR if requested.
3074// Three types of inputs can be handled:
3075// - SETCC
3076// - TRUNCATE
3077// - Logical operation (AND/OR/XOR)
3078// There is also a special case that is handled (namely a complement operation
3079// achieved with xor %a, -1).
3080SDValue IntegerCompareEliminator::computeLogicOpInGPR(SDValue LogicOp) {
3082 "Can only handle logic operations here.");
3083 assert(LogicOp.getValueType() == MVT::i1 &&
3084 "Can only handle logic operations on i1 values here.");
3085 SDLoc dl(LogicOp);
3086 SDValue LHS, RHS;
3087
3088 // Special case: xor %a, -1
3089 bool IsBitwiseNegation = isBitwiseNot(LogicOp);
3090
3091 // Produces a GPR sequence for each operand of the binary logic operation.
3092 // For SETCC, it produces the respective comparison, for TRUNCATE it truncates
3093 // the value in a GPR and for logic operations, it will recursively produce
3094 // a GPR sequence for the operation.
3095 auto getLogicOperand = [&] (SDValue Operand) -> SDValue {
3096 unsigned OperandOpcode = Operand.getOpcode();
3097 if (OperandOpcode == ISD::SETCC)
3098 return getSETCCInGPR(Operand, SetccInGPROpts::ZExtOrig);
3099 else if (OperandOpcode == ISD::TRUNCATE) {
3100 SDValue InputOp = Operand.getOperand(0);
3101 EVT InVT = InputOp.getValueType();
3102 return SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 :
3103 PPC::RLDICL, dl, InVT, InputOp,
3104 S->getI64Imm(0, dl),
3105 S->getI64Imm(63, dl)), 0);
3106 } else if (ISD::isBitwiseLogicOp(OperandOpcode))
3107 return computeLogicOpInGPR(Operand);
3108 return SDValue();
3109 };
3110 LHS = getLogicOperand(LogicOp.getOperand(0));
3111 RHS = getLogicOperand(LogicOp.getOperand(1));
3112
3113 // If a GPR sequence can't be produced for the LHS we can't proceed.
3114 // Not producing a GPR sequence for the RHS is only a problem if this isn't
3115 // a bitwise negation operation.
3116 if (!LHS || (!RHS && !IsBitwiseNegation))
3117 return SDValue();
3118
3119 NumLogicOpsOnComparison++;
3120
3121 // We will use the inputs as 64-bit values.
3122 if (LHS.getValueType() == MVT::i32)
3123 LHS = addExtOrTrunc(LHS, ExtOrTruncConversion::Ext);
3124 if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32)
3125 RHS = addExtOrTrunc(RHS, ExtOrTruncConversion::Ext);
3126
3127 unsigned NewOpc;
3128 switch (LogicOp.getOpcode()) {
3129 default: llvm_unreachable("Unknown logic operation.");
3130 case ISD::AND: NewOpc = PPC::AND8; break;
3131 case ISD::OR: NewOpc = PPC::OR8; break;
3132 case ISD::XOR: NewOpc = PPC::XOR8; break;
3133 }
3134
3135 if (IsBitwiseNegation) {
3136 RHS = S->getI64Imm(1, dl);
3137 NewOpc = PPC::XORI8;
3138 }
3139
3140 return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, RHS), 0);
3141
3142}
3143
3144/// If the value isn't guaranteed to be sign-extended to 64-bits, extend it.
3145/// Otherwise just reinterpret it as a 64-bit value.
3146/// Useful when emitting comparison code for 32-bit values without using
3147/// the compare instruction (which only considers the lower 32-bits).
3148SDValue IntegerCompareEliminator::signExtendInputIfNeeded(SDValue Input) {
3149 assert(Input.getValueType() == MVT::i32 &&
3150 "Can only sign-extend 32-bit values here.");
3151 unsigned Opc = Input.getOpcode();
3152
3153 // The value was sign extended and then truncated to 32-bits. No need to
3154 // sign extend it again.
3155 if (Opc == ISD::TRUNCATE &&
3156 (Input.getOperand(0).getOpcode() == ISD::AssertSext ||
3157 Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND))
3158 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3159
3160 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
3161 // The input is a sign-extending load. All ppc sign-extending loads
3162 // sign-extend to the full 64-bits.
3163 if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD)
3164 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3165
3166 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
3167 // We don't sign-extend constants.
3168 if (InputConst)
3169 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3170
3171 SDLoc dl(Input);
3172 SignExtensionsAdded++;
3173 return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32_64, dl,
3174 MVT::i64, Input), 0);
3175}
3176
3177/// If the value isn't guaranteed to be zero-extended to 64-bits, extend it.
3178/// Otherwise just reinterpret it as a 64-bit value.
3179/// Useful when emitting comparison code for 32-bit values without using
3180/// the compare instruction (which only considers the lower 32-bits).
3181SDValue IntegerCompareEliminator::zeroExtendInputIfNeeded(SDValue Input) {
3182 assert(Input.getValueType() == MVT::i32 &&
3183 "Can only zero-extend 32-bit values here.");
3184 unsigned Opc = Input.getOpcode();
3185
3186 // The only condition under which we can omit the actual extend instruction:
3187 // - The value is a positive constant
3188 // - The value comes from a load that isn't a sign-extending load
3189 // An ISD::TRUNCATE needs to be zero-extended unless it is fed by a zext.
3190 bool IsTruncateOfZExt = Opc == ISD::TRUNCATE &&
3191 (Input.getOperand(0).getOpcode() == ISD::AssertZext ||
3192 Input.getOperand(0).getOpcode() == ISD::ZERO_EXTEND);
3193 if (IsTruncateOfZExt)
3194 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3195
3196 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
3197 if (InputConst && InputConst->getSExtValue() >= 0)
3198 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3199
3200 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
3201 // The input is a load that doesn't sign-extend (it will be zero-extended).
3202 if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD)
3203 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3204
3205 // None of the above, need to zero-extend.
3206 SDLoc dl(Input);
3207 ZeroExtensionsAdded++;
3208 return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32_64, dl, MVT::i64, Input,
3209 S->getI64Imm(0, dl),
3210 S->getI64Imm(32, dl)), 0);
3211}
3212
3213// Handle a 32-bit value in a 64-bit register and vice-versa. These are of
3214// course not actual zero/sign extensions that will generate machine code,
3215// they're just a way to reinterpret a 32 bit value in a register as a
3216// 64 bit value and vice-versa.
3217SDValue IntegerCompareEliminator::addExtOrTrunc(SDValue NatWidthRes,
3218 ExtOrTruncConversion Conv) {
3219 SDLoc dl(NatWidthRes);
3220
3221 // For reinterpreting 32-bit values as 64 bit values, we generate
3222 // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1>
3223 if (Conv == ExtOrTruncConversion::Ext) {
3224 SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0);
3225 SDValue SubRegIdx =
3226 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
3227 return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64,
3228 ImDef, NatWidthRes, SubRegIdx), 0);
3229 }
3230
3231 assert(Conv == ExtOrTruncConversion::Trunc &&
3232 "Unknown convertion between 32 and 64 bit values.");
3233 // For reinterpreting 64-bit values as 32-bit values, we just need to
3234 // EXTRACT_SUBREG (i.e. extract the low word).
3235 SDValue SubRegIdx =
3236 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
3237 return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32,
3238 NatWidthRes, SubRegIdx), 0);
3239}
3240
3241// Produce a GPR sequence for compound comparisons (<=, >=) against zero.
3242// Handle both zero-extensions and sign-extensions.
3243SDValue
3244IntegerCompareEliminator::getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
3245 ZeroCompare CmpTy) {
3246 EVT InVT = LHS.getValueType();
3247 bool Is32Bit = InVT == MVT::i32;
3248 SDValue ToExtend;
3249
3250 // Produce the value that needs to be either zero or sign extended.
3251 switch (CmpTy) {
3252 case ZeroCompare::GEZExt:
3253 case ZeroCompare::GESExt:
3254 ToExtend = SDValue(CurDAG->getMachineNode(Is32Bit ? PPC::NOR : PPC::NOR8,
3255 dl, InVT, LHS, LHS), 0);
3256 break;
3257 case ZeroCompare::LEZExt:
3258 case ZeroCompare::LESExt: {
3259 if (Is32Bit) {
3260 // Upper 32 bits cannot be undefined for this sequence.
3261 LHS = signExtendInputIfNeeded(LHS);
3262 SDValue Neg =
3263 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3264 ToExtend =
3265 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3266 Neg, S->getI64Imm(1, dl),
3267 S->getI64Imm(63, dl)), 0);
3268 } else {
3269 SDValue Addi =
3270 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3271 S->getI64Imm(~0ULL, dl)), 0);
3272 ToExtend = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
3273 Addi, LHS), 0);
3274 }
3275 break;
3276 }
3277 }
3278
3279 // For 64-bit sequences, the extensions are the same for the GE/LE cases.
3280 if (!Is32Bit &&
3281 (CmpTy == ZeroCompare::GEZExt || CmpTy == ZeroCompare::LEZExt))
3282 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3283 ToExtend, S->getI64Imm(1, dl),
3284 S->getI64Imm(63, dl)), 0);
3285 if (!Is32Bit &&
3286 (CmpTy == ZeroCompare::GESExt || CmpTy == ZeroCompare::LESExt))
3287 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, ToExtend,
3288 S->getI64Imm(63, dl)), 0);
3289
3290 assert(Is32Bit && "Should have handled the 32-bit sequences above.");
3291 // For 32-bit sequences, the extensions differ between GE/LE cases.
3292 switch (CmpTy) {
3293 case ZeroCompare::GEZExt: {
3294 SDValue ShiftOps[] = { ToExtend, S->getI32Imm(1, dl), S->getI32Imm(31, dl),
3295 S->getI32Imm(31, dl) };
3296 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
3297 ShiftOps), 0);
3298 }
3299 case ZeroCompare::GESExt:
3300 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, ToExtend,
3301 S->getI32Imm(31, dl)), 0);
3302 case ZeroCompare::LEZExt:
3303 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, ToExtend,
3304 S->getI32Imm(1, dl)), 0);
3305 case ZeroCompare::LESExt:
3306 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, ToExtend,
3307 S->getI32Imm(-1, dl)), 0);
3308 }
3309
3310 // The above case covers all the enumerators so it can't have a default clause
3311 // to avoid compiler warnings.
3312 llvm_unreachable("Unknown zero-comparison type.");
3313}
3314
3315/// Produces a zero-extended result of comparing two 32-bit values according to
3316/// the passed condition code.
3317SDValue
3318IntegerCompareEliminator::get32BitZExtCompare(SDValue LHS, SDValue RHS,
3320 int64_t RHSValue, SDLoc dl) {
3323 return SDValue();
3324 bool IsRHSZero = RHSValue == 0;
3325 bool IsRHSOne = RHSValue == 1;
3326 bool IsRHSNegOne = RHSValue == -1LL;
3327 switch (CC) {
3328 default: return SDValue();
3329 case ISD::SETEQ: {
3330 // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5)
3331 // (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5)
3332 SDValue Xor = IsRHSZero ? LHS :
3333 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3334 SDValue Clz =
3335 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
3336 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),
3337 S->getI32Imm(31, dl) };
3338 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
3339 ShiftOps), 0);
3340 }
3341 case ISD::SETNE: {
3342 // (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1)
3343 // (zext (setcc %a, 0, setne)) -> (xor (lshr (cntlzw %a), 5), 1)
3344 SDValue Xor = IsRHSZero ? LHS :
3345 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3346 SDValue Clz =
3347 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
3348 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),
3349 S->getI32Imm(31, dl) };
3350 SDValue Shift =
3351 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
3352 return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
3353 S->getI32Imm(1, dl)), 0);
3354 }
3355 case ISD::SETGE: {
3356 // (zext (setcc %a, %b, setge)) -> (xor (lshr (sub %a, %b), 63), 1)
3357 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 31)
3358 if(IsRHSZero)
3359 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3360
3361 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
3362 // by swapping inputs and falling through.
3363 std::swap(LHS, RHS);
3364 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3365 IsRHSZero = RHSConst && RHSConst->isZero();
3366 [[fallthrough]];
3367 }
3368 case ISD::SETLE: {
3369 if (CmpInGPR == ICGPR_NonExtIn)
3370 return SDValue();
3371 // (zext (setcc %a, %b, setle)) -> (xor (lshr (sub %b, %a), 63), 1)
3372 // (zext (setcc %a, 0, setle)) -> (xor (lshr (- %a), 63), 1)
3373 if(IsRHSZero) {
3374 if (CmpInGPR == ICGPR_NonExtIn)
3375 return SDValue();
3376 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3377 }
3378
3379 // The upper 32-bits of the register can't be undefined for this sequence.
3380 LHS = signExtendInputIfNeeded(LHS);
3381 RHS = signExtendInputIfNeeded(RHS);
3382 SDValue Sub =
3383 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3384 SDValue Shift =
3385 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Sub,
3386 S->getI64Imm(1, dl), S->getI64Imm(63, dl)),
3387 0);
3388 return
3389 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl,
3390 MVT::i64, Shift, S->getI32Imm(1, dl)), 0);
3391 }
3392 case ISD::SETGT: {
3393 // (zext (setcc %a, %b, setgt)) -> (lshr (sub %b, %a), 63)
3394 // (zext (setcc %a, -1, setgt)) -> (lshr (~ %a), 31)
3395 // (zext (setcc %a, 0, setgt)) -> (lshr (- %a), 63)
3396 // Handle SETLT -1 (which is equivalent to SETGE 0).
3397 if (IsRHSNegOne)
3398 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3399
3400 if (IsRHSZero) {
3401 if (CmpInGPR == ICGPR_NonExtIn)
3402 return SDValue();
3403 // The upper 32-bits of the register can't be undefined for this sequence.
3404 LHS = signExtendInputIfNeeded(LHS);
3405 RHS = signExtendInputIfNeeded(RHS);
3406 SDValue Neg =
3407 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3408 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3409 Neg, S->getI32Imm(1, dl), S->getI32Imm(63, dl)), 0);
3410 }
3411 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as
3412 // (%b < %a) by swapping inputs and falling through.
3413 std::swap(LHS, RHS);
3414 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3415 IsRHSZero = RHSConst && RHSConst->isZero();
3416 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3417 [[fallthrough]];
3418 }
3419 case ISD::SETLT: {
3420 // (zext (setcc %a, %b, setlt)) -> (lshr (sub %a, %b), 63)
3421 // (zext (setcc %a, 1, setlt)) -> (xor (lshr (- %a), 63), 1)
3422 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 31)
3423 // Handle SETLT 1 (which is equivalent to SETLE 0).
3424 if (IsRHSOne) {
3425 if (CmpInGPR == ICGPR_NonExtIn)
3426 return SDValue();
3427 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3428 }
3429
3430 if (IsRHSZero) {
3431 SDValue ShiftOps[] = { LHS, S->getI32Imm(1, dl), S->getI32Imm(31, dl),
3432 S->getI32Imm(31, dl) };
3433 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
3434 ShiftOps), 0);
3435 }
3436
3437 if (CmpInGPR == ICGPR_NonExtIn)
3438 return SDValue();
3439 // The upper 32-bits of the register can't be undefined for this sequence.
3440 LHS = signExtendInputIfNeeded(LHS);
3441 RHS = signExtendInputIfNeeded(RHS);
3442 SDValue SUBFNode =
3443 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3444 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3445 SUBFNode, S->getI64Imm(1, dl),
3446 S->getI64Imm(63, dl)), 0);
3447 }
3448 case ISD::SETUGE:
3449 // (zext (setcc %a, %b, setuge)) -> (xor (lshr (sub %b, %a), 63), 1)
3450 // (zext (setcc %a, %b, setule)) -> (xor (lshr (sub %a, %b), 63), 1)
3451 std::swap(LHS, RHS);
3452 [[fallthrough]];
3453 case ISD::SETULE: {
3454 if (CmpInGPR == ICGPR_NonExtIn)
3455 return SDValue();
3456 // The upper 32-bits of the register can't be undefined for this sequence.
3457 LHS = zeroExtendInputIfNeeded(LHS);
3458 RHS = zeroExtendInputIfNeeded(RHS);
3459 SDValue Subtract =
3460 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3461 SDValue SrdiNode =
3462 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3463 Subtract, S->getI64Imm(1, dl),
3464 S->getI64Imm(63, dl)), 0);
3465 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, SrdiNode,
3466 S->getI32Imm(1, dl)), 0);
3467 }
3468 case ISD::SETUGT:
3469 // (zext (setcc %a, %b, setugt)) -> (lshr (sub %b, %a), 63)
3470 // (zext (setcc %a, %b, setult)) -> (lshr (sub %a, %b), 63)
3471 std::swap(LHS, RHS);
3472 [[fallthrough]];
3473 case ISD::SETULT: {
3474 if (CmpInGPR == ICGPR_NonExtIn)
3475 return SDValue();
3476 // The upper 32-bits of the register can't be undefined for this sequence.
3477 LHS = zeroExtendInputIfNeeded(LHS);
3478 RHS = zeroExtendInputIfNeeded(RHS);
3479 SDValue Subtract =
3480 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3481 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3482 Subtract, S->getI64Imm(1, dl),
3483 S->getI64Imm(63, dl)), 0);
3484 }
3485 }
3486}
3487
3488/// Produces a sign-extended result of comparing two 32-bit values according to
3489/// the passed condition code.
3490SDValue
3491IntegerCompareEliminator::get32BitSExtCompare(SDValue LHS, SDValue RHS,
3493 int64_t RHSValue, SDLoc dl) {
3496 return SDValue();
3497 bool IsRHSZero = RHSValue == 0;
3498 bool IsRHSOne = RHSValue == 1;
3499 bool IsRHSNegOne = RHSValue == -1LL;
3500
3501 switch (CC) {
3502 default: return SDValue();
3503 case ISD::SETEQ: {
3504 // (sext (setcc %a, %b, seteq)) ->
3505 // (ashr (shl (ctlz (xor %a, %b)), 58), 63)
3506 // (sext (setcc %a, 0, seteq)) ->
3507 // (ashr (shl (ctlz %a), 58), 63)
3508 SDValue CountInput = IsRHSZero ? LHS :
3509 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3510 SDValue Cntlzw =
3511 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0);
3512 SDValue SHLOps[] = { Cntlzw, S->getI32Imm(27, dl),
3513 S->getI32Imm(5, dl), S->getI32Imm(31, dl) };
3514 SDValue Slwi =
3515 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, SHLOps), 0);
3516 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Slwi), 0);
3517 }
3518 case ISD::SETNE: {
3519 // Bitwise xor the operands, count leading zeros, shift right by 5 bits and
3520 // flip the bit, finally take 2's complement.
3521 // (sext (setcc %a, %b, setne)) ->
3522 // (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1))
3523 // Same as above, but the first xor is not needed.
3524 // (sext (setcc %a, 0, setne)) ->
3525 // (neg (xor (lshr (ctlz %a), 5), 1))
3526 SDValue Xor = IsRHSZero ? LHS :
3527 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3528 SDValue Clz =
3529 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
3530 SDValue ShiftOps[] =
3531 { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), S->getI32Imm(31, dl) };
3532 SDValue Shift =
3533 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
3534 SDValue Xori =
3535 SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
3536 S->getI32Imm(1, dl)), 0);
3537 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Xori), 0);
3538 }
3539 case ISD::SETGE: {
3540 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %a, %b), 63), -1)
3541 // (sext (setcc %a, 0, setge)) -> (ashr (~ %a), 31)
3542 if (IsRHSZero)
3543 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3544
3545 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
3546 // by swapping inputs and falling through.
3547 std::swap(LHS, RHS);
3548 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3549 IsRHSZero = RHSConst && RHSConst->isZero();
3550 [[fallthrough]];
3551 }
3552 case ISD::SETLE: {
3553 if (CmpInGPR == ICGPR_NonExtIn)
3554 return SDValue();
3555 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %b, %a), 63), -1)
3556 // (sext (setcc %a, 0, setle)) -> (add (lshr (- %a), 63), -1)
3557 if (IsRHSZero)
3558 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3559
3560 // The upper 32-bits of the register can't be undefined for this sequence.
3561 LHS = signExtendInputIfNeeded(LHS);
3562 RHS = signExtendInputIfNeeded(RHS);
3563 SDValue SUBFNode =
3564 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, MVT::Glue,
3565 LHS, RHS), 0);
3566 SDValue Srdi =
3567 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3568 SUBFNode, S->getI64Imm(1, dl),
3569 S->getI64Imm(63, dl)), 0);
3570 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Srdi,
3571 S->getI32Imm(-1, dl)), 0);
3572 }
3573 case ISD::SETGT: {
3574 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %b, %a), 63)
3575 // (sext (setcc %a, -1, setgt)) -> (ashr (~ %a), 31)
3576 // (sext (setcc %a, 0, setgt)) -> (ashr (- %a), 63)
3577 if (IsRHSNegOne)
3578 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3579 if (IsRHSZero) {
3580 if (CmpInGPR == ICGPR_NonExtIn)
3581 return SDValue();
3582 // The upper 32-bits of the register can't be undefined for this sequence.
3583 LHS = signExtendInputIfNeeded(LHS);
3584 RHS = signExtendInputIfNeeded(RHS);
3585 SDValue Neg =
3586 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3587 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Neg,
3588 S->getI64Imm(63, dl)), 0);
3589 }
3590 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as
3591 // (%b < %a) by swapping inputs and falling through.
3592 std::swap(LHS, RHS);
3593 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3594 IsRHSZero = RHSConst && RHSConst->isZero();
3595 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3596 [[fallthrough]];
3597 }
3598 case ISD::SETLT: {
3599 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %a, %b), 63)
3600 // (sext (setcc %a, 1, setgt)) -> (add (lshr (- %a), 63), -1)
3601 // (sext (setcc %a, 0, setgt)) -> (ashr %a, 31)
3602 if (IsRHSOne) {
3603 if (CmpInGPR == ICGPR_NonExtIn)
3604 return SDValue();
3605 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3606 }
3607 if (IsRHSZero)
3608 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, LHS,
3609 S->getI32Imm(31, dl)), 0);
3610
3611 if (CmpInGPR == ICGPR_NonExtIn)
3612 return SDValue();
3613 // The upper 32-bits of the register can't be undefined for this sequence.
3614 LHS = signExtendInputIfNeeded(LHS);
3615 RHS = signExtendInputIfNeeded(RHS);
3616 SDValue SUBFNode =
3617 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3618 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3619 SUBFNode, S->getI64Imm(63, dl)), 0);
3620 }
3621 case ISD::SETUGE:
3622 // (sext (setcc %a, %b, setuge)) -> (add (lshr (sub %a, %b), 63), -1)
3623 // (sext (setcc %a, %b, setule)) -> (add (lshr (sub %b, %a), 63), -1)
3624 std::swap(LHS, RHS);
3625 [[fallthrough]];
3626 case ISD::SETULE: {
3627 if (CmpInGPR == ICGPR_NonExtIn)
3628 return SDValue();
3629 // The upper 32-bits of the register can't be undefined for this sequence.
3630 LHS = zeroExtendInputIfNeeded(LHS);
3631 RHS = zeroExtendInputIfNeeded(RHS);
3632 SDValue Subtract =
3633 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3634 SDValue Shift =
3635 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Subtract,
3636 S->getI32Imm(1, dl), S->getI32Imm(63,dl)),
3637 0);
3638 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Shift,
3639 S->getI32Imm(-1, dl)), 0);
3640 }
3641 case ISD::SETUGT:
3642 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %b, %a), 63)
3643 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %a, %b), 63)
3644 std::swap(LHS, RHS);
3645 [[fallthrough]];
3646 case ISD::SETULT: {
3647 if (CmpInGPR == ICGPR_NonExtIn)
3648 return SDValue();
3649 // The upper 32-bits of the register can't be undefined for this sequence.
3650 LHS = zeroExtendInputIfNeeded(LHS);
3651 RHS = zeroExtendInputIfNeeded(RHS);
3652 SDValue Subtract =
3653 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3654 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3655 Subtract, S->getI64Imm(63, dl)), 0);
3656 }
3657 }
3658}
3659
3660/// Produces a zero-extended result of comparing two 64-bit values according to
3661/// the passed condition code.
3662SDValue
3663IntegerCompareEliminator::get64BitZExtCompare(SDValue LHS, SDValue RHS,
3665 int64_t RHSValue, SDLoc dl) {
3668 return SDValue();
3669 bool IsRHSZero = RHSValue == 0;
3670 bool IsRHSOne = RHSValue == 1;
3671 bool IsRHSNegOne = RHSValue == -1LL;
3672 switch (CC) {
3673 default: return SDValue();
3674 case ISD::SETEQ: {
3675 // (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6)
3676 // (zext (setcc %a, 0, seteq)) -> (lshr (ctlz %a), 6)
3677 SDValue Xor = IsRHSZero ? LHS :
3678 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3679 SDValue Clz =
3680 SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0);
3681 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz,
3682 S->getI64Imm(58, dl),
3683 S->getI64Imm(63, dl)), 0);
3684 }
3685 case ISD::SETNE: {
3686 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3687 // (zext (setcc %a, %b, setne)) -> (sube addc.reg, addc.reg, addc.CA)
3688 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3689 // (zext (setcc %a, 0, setne)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3690 SDValue Xor = IsRHSZero ? LHS :
3691 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3692 SDValue AC =
3693 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3694 Xor, S->getI32Imm(~0U, dl)), 0);
3695 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, AC,
3696 Xor, AC.getValue(1)), 0);
3697 }
3698 case ISD::SETGE: {
3699 // {subc.reg, subc.CA} = (subcarry %a, %b)
3700 // (zext (setcc %a, %b, setge)) ->
3701 // (adde (lshr %b, 63), (ashr %a, 63), subc.CA)
3702 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 63)
3703 if (IsRHSZero)
3704 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3705 std::swap(LHS, RHS);
3706 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3707 IsRHSZero = RHSConst && RHSConst->isZero();
3708 [[fallthrough]];
3709 }
3710 case ISD::SETLE: {
3711 // {subc.reg, subc.CA} = (subcarry %b, %a)
3712 // (zext (setcc %a, %b, setge)) ->
3713 // (adde (lshr %a, 63), (ashr %b, 63), subc.CA)
3714 // (zext (setcc %a, 0, setge)) -> (lshr (or %a, (add %a, -1)), 63)
3715 if (IsRHSZero)
3716 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3717 SDValue ShiftL =
3718 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3719 S->getI64Imm(1, dl),
3720 S->getI64Imm(63, dl)), 0);
3721 SDValue ShiftR =
3722 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,
3723 S->getI64Imm(63, dl)), 0);
3724 SDValue SubtractCarry =
3725 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3726 LHS, RHS), 1);
3727 return SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3728 ShiftR, ShiftL, SubtractCarry), 0);
3729 }
3730 case ISD::SETGT: {
3731 // {subc.reg, subc.CA} = (subcarry %b, %a)
3732 // (zext (setcc %a, %b, setgt)) ->
3733 // (xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)
3734 // (zext (setcc %a, 0, setgt)) -> (lshr (nor (add %a, -1), %a), 63)
3735 if (IsRHSNegOne)
3736 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3737 if (IsRHSZero) {
3738 SDValue Addi =
3739 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3740 S->getI64Imm(~0ULL, dl)), 0);
3741 SDValue Nor =
3742 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Addi, LHS), 0);
3743 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Nor,
3744 S->getI64Imm(1, dl),
3745 S->getI64Imm(63, dl)), 0);
3746 }
3747 std::swap(LHS, RHS);
3748 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3749 IsRHSZero = RHSConst && RHSConst->isZero();
3750 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3751 [[fallthrough]];
3752 }
3753 case ISD::SETLT: {
3754 // {subc.reg, subc.CA} = (subcarry %a, %b)
3755 // (zext (setcc %a, %b, setlt)) ->
3756 // (xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)
3757 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 63)
3758 if (IsRHSOne)
3759 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3760 if (IsRHSZero)
3761 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3762 S->getI64Imm(1, dl),
3763 S->getI64Imm(63, dl)), 0);
3764 SDValue SRADINode =
3765 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3766 LHS, S->getI64Imm(63, dl)), 0);
3767 SDValue SRDINode =
3768 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3769 RHS, S->getI64Imm(1, dl),
3770 S->getI64Imm(63, dl)), 0);
3771 SDValue SUBFC8Carry =
3772 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3773 RHS, LHS), 1);
3774 SDValue ADDE8Node =
3775 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3776 SRDINode, SRADINode, SUBFC8Carry), 0);
3777 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
3778 ADDE8Node, S->getI64Imm(1, dl)), 0);
3779 }
3780 case ISD::SETUGE:
3781 // {subc.reg, subc.CA} = (subcarry %a, %b)
3782 // (zext (setcc %a, %b, setuge)) -> (add (sube %b, %b, subc.CA), 1)
3783 std::swap(LHS, RHS);
3784 [[fallthrough]];
3785 case ISD::SETULE: {
3786 // {subc.reg, subc.CA} = (subcarry %b, %a)
3787 // (zext (setcc %a, %b, setule)) -> (add (sube %a, %a, subc.CA), 1)
3788 SDValue SUBFC8Carry =
3789 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3790 LHS, RHS), 1);
3791 SDValue SUBFE8Node =
3792 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue,
3793 LHS, LHS, SUBFC8Carry), 0);
3794 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64,
3795 SUBFE8Node, S->getI64Imm(1, dl)), 0);
3796 }
3797 case ISD::SETUGT:
3798 // {subc.reg, subc.CA} = (subcarry %b, %a)
3799 // (zext (setcc %a, %b, setugt)) -> -(sube %b, %b, subc.CA)
3800 std::swap(LHS, RHS);
3801 [[fallthrough]];
3802 case ISD::SETULT: {
3803 // {subc.reg, subc.CA} = (subcarry %a, %b)
3804 // (zext (setcc %a, %b, setult)) -> -(sube %a, %a, subc.CA)
3805 SDValue SubtractCarry =
3806 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3807 RHS, LHS), 1);
3808 SDValue ExtSub =
3809 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,
3810 LHS, LHS, SubtractCarry), 0);
3811 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,
3812 ExtSub), 0);
3813 }
3814 }
3815}
3816
3817/// Produces a sign-extended result of comparing two 64-bit values according to
3818/// the passed condition code.
3819SDValue
3820IntegerCompareEliminator::get64BitSExtCompare(SDValue LHS, SDValue RHS,
3822 int64_t RHSValue, SDLoc dl) {
3825 return SDValue();
3826 bool IsRHSZero = RHSValue == 0;
3827 bool IsRHSOne = RHSValue == 1;
3828 bool IsRHSNegOne = RHSValue == -1LL;
3829 switch (CC) {
3830 default: return SDValue();
3831 case ISD::SETEQ: {
3832 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3833 // (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA)
3834 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3835 // (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3836 SDValue AddInput = IsRHSZero ? LHS :
3837 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3838 SDValue Addic =
3839 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3840 AddInput, S->getI32Imm(~0U, dl)), 0);
3841 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic,
3842 Addic, Addic.getValue(1)), 0);
3843 }
3844 case ISD::SETNE: {
3845 // {subfc.reg, subfc.CA} = (subcarry 0, (xor %a, %b))
3846 // (sext (setcc %a, %b, setne)) -> (sube subfc.reg, subfc.reg, subfc.CA)
3847 // {subfcz.reg, subfcz.CA} = (subcarry 0, %a)
3848 // (sext (setcc %a, 0, setne)) -> (sube subfcz.reg, subfcz.reg, subfcz.CA)
3849 SDValue Xor = IsRHSZero ? LHS :
3850 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3851 SDValue SC =
3852 SDValue(CurDAG->getMachineNode(PPC::SUBFIC8, dl, MVT::i64, MVT::Glue,
3853 Xor, S->getI32Imm(0, dl)), 0);
3854 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, SC,
3855 SC, SC.getValue(1)), 0);
3856 }
3857 case ISD::SETGE: {
3858 // {subc.reg, subc.CA} = (subcarry %a, %b)
3859 // (zext (setcc %a, %b, setge)) ->
3860 // (- (adde (lshr %b, 63), (ashr %a, 63), subc.CA))
3861 // (zext (setcc %a, 0, setge)) -> (~ (ashr %a, 63))
3862 if (IsRHSZero)
3863 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3864 std::swap(LHS, RHS);
3865 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3866 IsRHSZero = RHSConst && RHSConst->isZero();
3867 [[fallthrough]];
3868 }
3869 case ISD::SETLE: {
3870 // {subc.reg, subc.CA} = (subcarry %b, %a)
3871 // (zext (setcc %a, %b, setge)) ->
3872 // (- (adde (lshr %a, 63), (ashr %b, 63), subc.CA))
3873 // (zext (setcc %a, 0, setge)) -> (ashr (or %a, (add %a, -1)), 63)
3874 if (IsRHSZero)
3875 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3876 SDValue ShiftR =
3877 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,
3878 S->getI64Imm(63, dl)), 0);
3879 SDValue ShiftL =
3880 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3881 S->getI64Imm(1, dl),
3882 S->getI64Imm(63, dl)), 0);
3883 SDValue SubtractCarry =
3884 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3885 LHS, RHS), 1);
3886 SDValue Adde =
3887 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3888 ShiftR, ShiftL, SubtractCarry), 0);
3889 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, Adde), 0);
3890 }
3891 case ISD::SETGT: {
3892 // {subc.reg, subc.CA} = (subcarry %b, %a)
3893 // (zext (setcc %a, %b, setgt)) ->
3894 // -(xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)
3895 // (zext (setcc %a, 0, setgt)) -> (ashr (nor (add %a, -1), %a), 63)
3896 if (IsRHSNegOne)
3897 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3898 if (IsRHSZero) {
3899 SDValue Add =
3900 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3901 S->getI64Imm(-1, dl)), 0);
3902 SDValue Nor =
3903 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Add, LHS), 0);
3904 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Nor,
3905 S->getI64Imm(63, dl)), 0);
3906 }
3907 std::swap(LHS, RHS);
3908 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3909 IsRHSZero = RHSConst && RHSConst->isZero();
3910 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3911 [[fallthrough]];
3912 }
3913 case ISD::SETLT: {
3914 // {subc.reg, subc.CA} = (subcarry %a, %b)
3915 // (zext (setcc %a, %b, setlt)) ->
3916 // -(xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)
3917 // (zext (setcc %a, 0, setlt)) -> (ashr %a, 63)
3918 if (IsRHSOne)
3919 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3920 if (IsRHSZero) {
3921 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, LHS,
3922 S->getI64Imm(63, dl)), 0);
3923 }
3924 SDValue SRADINode =
3925 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3926 LHS, S->getI64Imm(63, dl)), 0);
3927 SDValue SRDINode =
3928 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3929 RHS, S->getI64Imm(1, dl),
3930 S->getI64Imm(63, dl)), 0);
3931 SDValue SUBFC8Carry =
3932 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3933 RHS, LHS), 1);
3934 SDValue ADDE8Node =
3935 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64,
3936 SRDINode, SRADINode, SUBFC8Carry), 0);
3937 SDValue XORI8Node =
3938 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
3939 ADDE8Node, S->getI64Imm(1, dl)), 0);
3940 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,
3941 XORI8Node), 0);
3942 }
3943 case ISD::SETUGE:
3944 // {subc.reg, subc.CA} = (subcarry %a, %b)
3945 // (sext (setcc %a, %b, setuge)) -> ~(sube %b, %b, subc.CA)
3946 std::swap(LHS, RHS);
3947 [[fallthrough]];
3948 case ISD::SETULE: {
3949 // {subc.reg, subc.CA} = (subcarry %b, %a)
3950 // (sext (setcc %a, %b, setule)) -> ~(sube %a, %a, subc.CA)
3951 SDValue SubtractCarry =
3952 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3953 LHS, RHS), 1);
3954 SDValue ExtSub =
3955 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue, LHS,
3956 LHS, SubtractCarry), 0);
3957 return SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64,
3958 ExtSub, ExtSub), 0);
3959 }
3960 case ISD::SETUGT:
3961 // {subc.reg, subc.CA} = (subcarry %b, %a)
3962 // (sext (setcc %a, %b, setugt)) -> (sube %b, %b, subc.CA)
3963 std::swap(LHS, RHS);
3964 [[fallthrough]];
3965 case ISD::SETULT: {
3966 // {subc.reg, subc.CA} = (subcarry %a, %b)
3967 // (sext (setcc %a, %b, setult)) -> (sube %a, %a, subc.CA)
3968 SDValue SubCarry =
3969 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3970 RHS, LHS), 1);
3971 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,
3972 LHS, LHS, SubCarry), 0);
3973 }
3974 }
3975}
3976
3977/// Do all uses of this SDValue need the result in a GPR?
3978/// This is meant to be used on values that have type i1 since
3979/// it is somewhat meaningless to ask if values of other types
3980/// should be kept in GPR's.
3981static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG) {
3982 assert(Compare.getOpcode() == ISD::SETCC &&
3983 "An ISD::SETCC node required here.");
3984
3985 // For values that have a single use, the caller should obviously already have
3986 // checked if that use is an extending use. We check the other uses here.
3987 if (Compare.hasOneUse())
3988 return true;
3989 // We want the value in a GPR if it is being extended, used for a select, or
3990 // used in logical operations.
3991 for (auto *CompareUse : Compare.getNode()->uses())
3992 if (CompareUse->getOpcode() != ISD::SIGN_EXTEND &&
3993 CompareUse->getOpcode() != ISD::ZERO_EXTEND &&
3994 CompareUse->getOpcode() != ISD::SELECT &&
3995 !ISD::isBitwiseLogicOp(CompareUse->getOpcode())) {
3996 OmittedForNonExtendUses++;
3997 return false;
3998 }
3999 return true;
4000}
4001
4002/// Returns an equivalent of a SETCC node but with the result the same width as
4003/// the inputs. This can also be used for SELECT_CC if either the true or false
4004/// values is a power of two while the other is zero.
4005SDValue IntegerCompareEliminator::getSETCCInGPR(SDValue Compare,
4006 SetccInGPROpts ConvOpts) {
4007 assert((Compare.getOpcode() == ISD::SETCC ||
4008 Compare.getOpcode() == ISD::SELECT_CC) &&
4009 "An ISD::SETCC node required here.");
4010
4011 // Don't convert this comparison to a GPR sequence because there are uses
4012 // of the i1 result (i.e. uses that require the result in the CR).
4013 if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG))
4014 return SDValue();
4015
4016 SDValue LHS = Compare.getOperand(0);
4017 SDValue RHS = Compare.getOperand(1);
4018
4019 // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC.
4020 int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2;
4022 cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get();
4023 EVT InputVT = LHS.getValueType();
4024 if (InputVT != MVT::i32 && InputVT != MVT::i64)
4025 return SDValue();
4026
4027 if (ConvOpts == SetccInGPROpts::ZExtInvert ||
4028 ConvOpts == SetccInGPROpts::SExtInvert)
4029 CC = ISD::getSetCCInverse(CC, InputVT);
4030
4031 bool Inputs32Bit = InputVT == MVT::i32;
4032
4033 SDLoc dl(Compare);
4034 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
4035 int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX;
4036 bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig ||
4037 ConvOpts == SetccInGPROpts::SExtInvert;
4038
4039 if (IsSext && Inputs32Bit)
4040 return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
4041 else if (Inputs32Bit)
4042 return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
4043 else if (IsSext)
4044 return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
4045 return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
4046}
4047
4048} // end anonymous namespace
4049
4050bool PPCDAGToDAGISel::tryIntCompareInGPR(SDNode *N) {
4051 if (N->getValueType(0) != MVT::i32 &&
4052 N->getValueType(0) != MVT::i64)
4053 return false;
4054
4055 // This optimization will emit code that assumes 64-bit registers
4056 // so we don't want to run it in 32-bit mode. Also don't run it
4057 // on functions that are not to be optimized.
4058 if (TM.getOptLevel() == CodeGenOptLevel::None || !TM.isPPC64())
4059 return false;
4060
4061 // For POWER10, it is more profitable to use the set boolean extension
4062 // instructions rather than the integer compare elimination codegen.
4063 // Users can override this via the command line option, `--ppc-gpr-icmps`.
4064 if (!(CmpInGPR.getNumOccurrences() > 0) && Subtarget->isISA3_1())
4065 return false;
4066
4067 switch (N->getOpcode()) {
4068 default: break;
4069 case ISD::ZERO_EXTEND:
4070 case ISD::SIGN_EXTEND:
4071 case ISD::AND:
4072 case ISD::OR:
4073 case ISD::XOR: {
4074 IntegerCompareEliminator ICmpElim(CurDAG, this);
4075 if (SDNode *New = ICmpElim.Select(N)) {
4076 ReplaceNode(N, New);
4077 return true;
4078 }
4079 }
4080 }
4081 return false;
4082}
4083
4084bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
4085 if (N->getValueType(0) != MVT::i32 &&
4086 N->getValueType(0) != MVT::i64)
4087 return false;
4088
4089 if (!UseBitPermRewriter)
4090 return false;
4091
4092 switch (N->getOpcode()) {
4093 default: break;
4094 case ISD::SRL:
4095 // If we are on P10, we have a pattern for 32-bit (srl (bswap r), 16) that
4096 // uses the BRH instruction.
4097 if (Subtarget->isISA3_1() && N->getValueType(0) == MVT::i32 &&
4098 N->getOperand(0).getOpcode() == ISD::BSWAP) {
4099 auto &OpRight = N->getOperand(1);
4100 ConstantSDNode *SRLConst = dyn_cast<ConstantSDNode>(OpRight);
4101 if (SRLConst && SRLConst->getSExtValue() == 16)
4102 return false;
4103 }
4104 [[fallthrough]];
4105 case ISD::ROTL:
4106 case ISD::SHL:
4107 case ISD::AND:
4108 case ISD::OR: {
4109 BitPermutationSelector BPS(CurDAG);
4110 if (SDNode *New = BPS.Select(N)) {
4111 ReplaceNode(N, New);
4112 return true;
4113 }
4114 return false;
4115 }
4116 }
4117
4118 return false;
4119}
4120
4121/// SelectCC - Select a comparison of the specified values with the specified
4122/// condition code, returning the CR# of the expression.
4123SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4124 const SDLoc &dl, SDValue Chain) {
4125 // Always select the LHS.
4126 unsigned Opc;
4127
4128 if (LHS.getValueType() == MVT::i32) {
4129 unsigned Imm;
4130 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
4131 if (isInt32Immediate(RHS, Imm)) {
4132 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
4133 if (isUInt<16>(Imm))
4134 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
4135 getI32Imm(Imm & 0xFFFF, dl)),
4136 0);
4137 // If this is a 16-bit signed immediate, fold it.
4138 if (isInt<16>((int)Imm))
4139 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
4140 getI32Imm(Imm & 0xFFFF, dl)),
4141 0);
4142
4143 // For non-equality comparisons, the default code would materialize the
4144 // constant, then compare against it, like this:
4145 // lis r2, 4660
4146 // ori r2, r2, 22136
4147 // cmpw cr0, r3, r2
4148 // Since we are just comparing for equality, we can emit this instead:
4149 // xoris r0,r3,0x1234
4150 // cmplwi cr0,r0,0x5678
4151 // beq cr0,L6
4152 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
4153 getI32Imm(Imm >> 16, dl)), 0);
4154 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
4155 getI32Imm(Imm & 0xFFFF, dl)), 0);
4156 }
4157 Opc = PPC::CMPLW;
4158 } else if (ISD::isUnsignedIntSetCC(CC)) {
4159 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
4160 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
4161 getI32Imm(Imm & 0xFFFF, dl)), 0);
4162 Opc = PPC::CMPLW;
4163 } else {
4164 int16_t SImm;
4165 if (isIntS16Immediate(RHS, SImm))
4166 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
4167 getI32Imm((int)SImm & 0xFFFF,
4168 dl)),
4169 0);
4170 Opc = PPC::CMPW;
4171 }
4172 } else if (LHS.getValueType() == MVT::i64) {
4173 uint64_t Imm;
4174 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
4175 if (isInt64Immediate(RHS.getNode(), Imm)) {
4176 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
4177 if (isUInt<16>(Imm))
4178 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
4179 getI32Imm(Imm & 0xFFFF, dl)),
4180 0);
4181 // If this is a 16-bit signed immediate, fold it.
4182 if (isInt<16>(Imm))
4183 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
4184 getI32Imm(Imm & 0xFFFF, dl)),
4185 0);
4186
4187 // For non-equality comparisons, the default code would materialize the
4188 // constant, then compare against it, like this:
4189 // lis r2, 4660
4190 // ori r2, r2, 22136
4191 // cmpd cr0, r3, r2
4192 // Since we are just comparing for equality, we can emit this instead:
4193 // xoris r0,r3,0x1234
4194 // cmpldi cr0,r0,0x5678
4195 // beq cr0,L6
4196 if (isUInt<32>(Imm)) {
4197 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
4198 getI64Imm(Imm >> 16, dl)), 0);
4199 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
4200 getI64Imm(Imm & 0xFFFF, dl)),
4201 0);
4202 }
4203 }
4204 Opc = PPC::CMPLD;
4205 } else if (ISD::isUnsignedIntSetCC(CC)) {
4206 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
4207 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
4208 getI64Imm(Imm & 0xFFFF, dl)), 0);
4209 Opc = PPC::CMPLD;
4210 } else {
4211 int16_t SImm;
4212 if (isIntS16Immediate(RHS, SImm))
4213 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
4214 getI64Imm(SImm & 0xFFFF, dl)),
4215 0);
4216 Opc = PPC::CMPD;
4217 }
4218 } else if (LHS.getValueType() == MVT::f32) {
4219 if (Subtarget->hasSPE()) {
4220 switch (CC) {
4221 default:
4222 case ISD::SETEQ:
4223 case ISD::SETNE:
4224 Opc = PPC::EFSCMPEQ;
4225 break;
4226 case ISD::SETLT:
4227 case ISD::SETGE:
4228 case ISD::SETOLT:
4229 case ISD::SETOGE:
4230 case ISD::SETULT:
4231 case ISD::SETUGE:
4232 Opc = PPC::EFSCMPLT;
4233 break;
4234 case ISD::SETGT:
4235 case ISD::SETLE:
4236 case ISD::SETOGT:
4237 case ISD::SETOLE:
4238 case ISD::SETUGT:
4239 case ISD::SETULE:
4240 Opc = PPC::EFSCMPGT;
4241 break;
4242 }
4243 } else
4244 Opc = PPC::FCMPUS;
4245 } else if (LHS.getValueType() == MVT::f64) {
4246 if (Subtarget->hasSPE()) {
4247 switch (CC) {
4248 default:
4249 case ISD::SETEQ:
4250 case ISD::SETNE:
4251 Opc = PPC::EFDCMPEQ;
4252 break;
4253 case ISD::SETLT:
4254 case ISD::SETGE:
4255 case ISD::SETOLT:
4256 case ISD::SETOGE:
4257 case ISD::SETULT:
4258 case ISD::SETUGE:
4259 Opc = PPC::EFDCMPLT;
4260 break;
4261 case ISD::SETGT:
4262 case ISD::SETLE:
4263 case ISD::SETOGT:
4264 case ISD::SETOLE:
4265 case ISD::SETUGT:
4266 case ISD::SETULE:
4267 Opc = PPC::EFDCMPGT;
4268 break;
4269 }
4270 } else
4271 Opc = Subtarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
4272 } else {
4273 assert(LHS.getValueType() == MVT::f128 && "Unknown vt!");
4274 assert(Subtarget->hasP9Vector() && "XSCMPUQP requires Power9 Vector");
4275 Opc = PPC::XSCMPUQP;
4276 }
4277 if (Chain)
4278 return SDValue(
4279 CurDAG->getMachineNode(Opc, dl, MVT::i32, MVT::Other, LHS, RHS, Chain),
4280 0);
4281 else
4282 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
4283}
4284
4286 const PPCSubtarget *Subtarget) {
4287 // For SPE instructions, the result is in GT bit of the CR
4288 bool UseSPE = Subtarget->hasSPE() && VT.isFloatingPoint();
4289
4290 switch (CC) {
4291 case ISD::SETUEQ:
4292 case ISD::SETONE:
4293 case ISD::SETOLE:
4294 case ISD::SETOGE:
4295 llvm_unreachable("Should be lowered by legalize!");
4296 default: llvm_unreachable("Unknown condition!");
4297 case ISD::SETOEQ:
4298 case ISD::SETEQ:
4299 return UseSPE ? PPC::PRED_GT : PPC::PRED_EQ;
4300 case ISD::SETUNE:
4301 case ISD::SETNE:
4302 return UseSPE ? PPC::PRED_LE : PPC::PRED_NE;
4303 case ISD::SETOLT:
4304 case ISD::SETLT:
4305 return UseSPE ? PPC::PRED_GT : PPC::PRED_LT;
4306 case ISD::SETULE:
4307 case ISD::SETLE:
4308 return PPC::PRED_LE;
4309 case ISD::SETOGT:
4310 case ISD::SETGT:
4311 return PPC::PRED_GT;
4312 case ISD::SETUGE:
4313 case ISD::SETGE:
4314 return UseSPE ? PPC::PRED_LE : PPC::PRED_GE;
4315 case ISD::SETO: return PPC::PRED_NU;
4316 case ISD::SETUO: return PPC::PRED_UN;
4317 // These two are invalid for floating point. Assume we have int.
4318 case ISD::SETULT: return PPC::PRED_LT;
4319 case ISD::SETUGT: return PPC::PRED_GT;
4320 }
4321}
4322
4323/// getCRIdxForSetCC - Return the index of the condition register field
4324/// associated with the SetCC condition, and whether or not the field is
4325/// treated as inverted. That is, lt = 0; ge = 0 inverted.
4326static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
4327 Invert = false;
4328 switch (CC) {
4329 default: llvm_unreachable("Unknown condition!");
4330 case ISD::SETOLT:
4331 case ISD::SETLT: return 0; // Bit #0 = SETOLT
4332 case ISD::SETOGT:
4333 case ISD::SETGT: return 1; // Bit #1 = SETOGT
4334 case ISD::SETOEQ:
4335 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
4336 case ISD::SETUO: return 3; // Bit #3 = SETUO
4337 case ISD::SETUGE:
4338 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
4339 case ISD::SETULE:
4340 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
4341 case ISD::SETUNE:
4342 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
4343 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
4344 case ISD::SETUEQ:
4345 case ISD::SETOGE:
4346 case ISD::SETOLE:
4347 case ISD::SETONE:
4348 llvm_unreachable("Invalid branch code: should be expanded by legalize");
4349 // These are invalid for floating point. Assume integer.
4350 case ISD::SETULT: return 0;
4351 case ISD::SETUGT: return 1;
4352 }
4353}
4354
4355// getVCmpInst: return the vector compare instruction for the specified
4356// vector type and condition code. Since this is for altivec specific code,
4357// only support the altivec types (v16i8, v8i16, v4i32, v2i64, v1i128,
4358// and v4f32).
4359static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
4360 bool HasVSX, bool &Swap, bool &Negate) {
4361 Swap = false;
4362 Negate = false;
4363
4364 if (VecVT.isFloatingPoint()) {
4365 /* Handle some cases by swapping input operands. */
4366 switch (CC) {
4367 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
4368 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
4369 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
4370 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
4371 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
4372 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
4373 default: break;
4374 }
4375 /* Handle some cases by negating the result. */
4376 switch (CC) {
4377 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
4378 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
4379 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
4380 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
4381 default: break;
4382 }
4383 /* We have instructions implementing the remaining cases. */
4384 switch (CC) {
4385 case ISD::SETEQ:
4386 case ISD::SETOEQ:
4387 if (VecVT == MVT::v4f32)
4388 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
4389 else if (VecVT == MVT::v2f64)
4390 return PPC::XVCMPEQDP;
4391 break;
4392 case ISD::SETGT:
4393 case ISD::SETOGT:
4394 if (VecVT == MVT::v4f32)
4395 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
4396 else if (VecVT == MVT::v2f64)
4397 return PPC::XVCMPGTDP;
4398 break;
4399 case ISD::SETGE:
4400 case ISD::SETOGE:
4401 if (VecVT == MVT::v4f32)
4402 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
4403 else if (VecVT == MVT::v2f64)
4404 return PPC::XVCMPGEDP;
4405 break;
4406 default:
4407 break;
4408 }
4409 llvm_unreachable("Invalid floating-point vector compare condition");
4410 } else {
4411 /* Handle some cases by swapping input operands. */
4412 switch (CC) {
4413 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
4414 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
4415 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
4416 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
4417 default: break;
4418 }
4419 /* Handle some cases by negating the result. */
4420 switch (CC) {
4421 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
4422 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
4423 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
4424 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
4425 default: break;
4426 }
4427 /* We have instructions implementing the remaining cases. */
4428 switch (CC) {
4429 case ISD::SETEQ:
4430 case ISD::SETUEQ:
4431 if (VecVT == MVT::v16i8)
4432 return PPC::VCMPEQUB;
4433 else if (VecVT == MVT::v8i16)
4434 return PPC::VCMPEQUH;
4435 else if (VecVT == MVT::v4i32)
4436 return PPC::VCMPEQUW;
4437 else if (VecVT == MVT::v2i64)
4438 return PPC::VCMPEQUD;
4439 else if (VecVT == MVT::v1i128)
4440 return PPC::VCMPEQUQ;
4441 break;
4442 case ISD::SETGT:
4443 if (VecVT == MVT::v16i8)
4444 return PPC::VCMPGTSB;
4445 else if (VecVT == MVT::v8i16)
4446 return PPC::VCMPGTSH;
4447 else if (VecVT == MVT::v4i32)
4448 return PPC::VCMPGTSW;
4449 else if (VecVT == MVT::v2i64)
4450 return PPC::VCMPGTSD;
4451 else if (VecVT == MVT::v1i128)
4452 return PPC::VCMPGTSQ;
4453 break;
4454 case ISD::SETUGT:
4455 if (VecVT == MVT::v16i8)
4456 return PPC::VCMPGTUB;
4457 else if (VecVT == MVT::v8i16)
4458 return PPC::VCMPGTUH;
4459 else if (VecVT == MVT::v4i32)
4460 return PPC::VCMPGTUW;
4461 else if (VecVT == MVT::v2i64)
4462 return PPC::VCMPGTUD;
4463 else if (VecVT == MVT::v1i128)
4464 return PPC::VCMPGTUQ;
4465 break;
4466 default:
4467 break;
4468 }
4469 llvm_unreachable("Invalid integer vector compare condition");
4470 }
4471}
4472
4473bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
4474 SDLoc dl(N);
4475 unsigned Imm;
4476 bool IsStrict = N->isStrictFPOpcode();
4478 cast<CondCodeSDNode>(N->getOperand(IsStrict ? 3 : 2))->get();
4479 EVT PtrVT =
4481 bool isPPC64 = (PtrVT == MVT::i64);
4482 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
4483
4484 SDValue LHS = N->getOperand(IsStrict ? 1 : 0);
4485 SDValue RHS = N->getOperand(IsStrict ? 2 : 1);
4486
4487 if (!IsStrict && !Subtarget->useCRBits() && isInt32Immediate(RHS, Imm)) {
4488 // We can codegen setcc op, imm very efficiently compared to a brcond.
4489 // Check for those cases here.
4490 // setcc op, 0
4491 if (Imm == 0) {
4492 SDValue Op = LHS;
4493 switch (CC) {
4494 default: break;
4495 case ISD::SETEQ: {
4496 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
4497 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
4498 getI32Imm(31, dl) };
4499 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4500 return true;
4501 }
4502 case ISD::SETNE: {
4503 if (isPPC64) break;
4504 SDValue AD =
4505 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4506 Op, getI32Imm(~0U, dl)), 0);
4507 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
4508 return true;
4509 }
4510 case ISD::SETLT: {
4511 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
4512 getI32Imm(31, dl) };
4513 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4514 return true;
4515 }
4516 case ISD::SETGT: {
4517 SDValue T =
4518 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
4519 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
4520 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
4521 getI32Imm(31, dl) };
4522 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4523 return true;
4524 }
4525 }
4526 } else if (Imm == ~0U) { // setcc op, -1
4527 SDValue Op = LHS;
4528 switch (CC) {
4529 default: break;
4530 case ISD::SETEQ:
4531 if (isPPC64) break;
4532 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4533 Op, getI32Imm(1, dl)), 0);
4534 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
4535 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
4536 MVT::i32,
4537 getI32Imm(0, dl)),
4538 0), Op.getValue(1));
4539 return true;
4540 case ISD::SETNE: {
4541 if (isPPC64) break;
4542 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
4543 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4544 Op, getI32Imm(~0U, dl));
4545 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
4546 SDValue(AD, 1));
4547 return true;
4548 }
4549 case ISD::SETLT: {
4550 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
4551 getI32Imm(1, dl)), 0);
4552 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
4553 Op), 0);
4554 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
4555 getI32Imm(31, dl) };
4556 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4557 return true;
4558 }
4559 case ISD::SETGT: {
4560 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
4561 getI32Imm(31, dl) };
4562 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
4563 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
4564 return true;
4565 }
4566 }
4567 }
4568 }
4569
4570 // Altivec Vector compare instructions do not set any CR register by default and
4571 // vector compare operations return the same type as the operands.
4572 if (!IsStrict && LHS.getValueType().isVector()) {
4573 if (Subtarget->hasSPE())
4574 return false;
4575
4576 EVT VecVT = LHS.getValueType();
4577 bool Swap, Negate;
4578 unsigned int VCmpInst =
4579 getVCmpInst(VecVT.getSimpleVT(), CC, Subtarget->hasVSX(), Swap, Negate);
4580 if (Swap)
4581 std::swap(LHS, RHS);
4582
4583 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
4584 if (Negate) {
4585 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
4586 CurDAG->SelectNodeTo(N, Subtarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
4587 ResVT, VCmp, VCmp);
4588 return true;
4589 }
4590
4591 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
4592 return true;
4593 }
4594
4595 if (Subtarget->useCRBits())
4596 return false;
4597
4598 bool Inv;
4599 unsigned Idx = getCRIdxForSetCC(CC, Inv);
4600 SDValue CCReg = SelectCC(LHS, RHS, CC, dl, Chain);
4601 if (IsStrict)
4602 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), CCReg.getValue(1));
4603 SDValue IntCR;
4604
4605 // SPE e*cmp* instructions only set the 'gt' bit, so hard-code that
4606 // The correct compare instruction is already set by SelectCC()
4607 if (Subtarget->hasSPE() && LHS.getValueType().isFloatingPoint()) {
4608 Idx = 1;
4609 }
4610
4611 // Force the ccreg into CR7.
4612 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
4613
4614 SDValue InGlue; // Null incoming flag value.
4615 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
4616 InGlue).getValue(1);
4617
4618 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
4619 CCReg), 0);
4620
4621 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
4622 getI32Imm(31, dl), getI32Imm(31, dl) };
4623 if (!Inv) {
4624 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4625 return true;
4626 }
4627
4628 // Get the specified bit.
4629 SDValue Tmp =
4630 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
4631 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
4632 return true;
4633}
4634
4635/// Does this node represent a load/store node whose address can be represented
4636/// with a register plus an immediate that's a multiple of \p Val:
4637bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {
4638 LoadSDNode *LDN = dyn_cast<LoadSDNode>(N);
4639 StoreSDNode *STN = dyn_cast<StoreSDNode>(N);
4640 MemIntrinsicSDNode *MIN = dyn_cast<MemIntrinsicSDNode>(N);
4641 SDValue AddrOp;
4642 if (LDN || (MIN && MIN->getOpcode() == PPCISD::LD_SPLAT))
4643 AddrOp = N->getOperand(1);
4644 else if (STN)
4645 AddrOp = STN->getOperand(2);
4646
4647 // If the address points a frame object or a frame object with an offset,
4648 // we need to check the object alignment.
4649 short Imm = 0;
4650 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(
4651 AddrOp.getOpcode() == ISD::ADD ? AddrOp.getOperand(0) :
4652 AddrOp)) {
4653 // If op0 is a frame index that is under aligned, we can't do it either,
4654 // because it is translated to r31 or r1 + slot + offset. We won't know the
4655 // slot number until the stack frame is finalized.
4656 const MachineFrameInfo &MFI = CurDAG->getMachineFunction().getFrameInfo();
4657 unsigned SlotAlign = MFI.getObjectAlign(FI->getIndex()).value();
4658 if ((SlotAlign % Val) != 0)
4659 return false;
4660
4661 // If we have an offset, we need further check on the offset.
4662 if (AddrOp.getOpcode() != ISD::ADD)
4663 return true;
4664 }
4665
4666 if (AddrOp.getOpcode() == ISD::ADD)
4667 return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val);
4668
4669 // If the address comes from the outside, the offset will be zero.
4670 return AddrOp.getOpcode() == ISD::CopyFromReg;
4671}
4672
4673void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
4674 // Transfer memoperands.
4675 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
4676 CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});
4677}
4678
4680 bool &NeedSwapOps, bool &IsUnCmp) {
4681
4682 assert(N->getOpcode() == ISD::SELECT_CC && "Expecting a SELECT_CC here.");
4683
4684 SDValue LHS = N->getOperand(0);
4685 SDValue RHS = N->getOperand(1);
4686 SDValue TrueRes = N->getOperand(2);
4687 SDValue FalseRes = N->getOperand(3);
4688 ConstantSDNode *TrueConst = dyn_cast<ConstantSDNode>(TrueRes);
4689 if (!TrueConst || (N->getSimpleValueType(0) != MVT::i64 &&
4690 N->getSimpleValueType(0) != MVT::i32))
4691 return false;
4692
4693 // We are looking for any of:
4694 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4695 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4696 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, 1, -1, cc2), seteq)
4697 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, -1, 1, cc2), seteq)
4698 int64_t TrueResVal = TrueConst->getSExtValue();
4699 if ((TrueResVal < -1 || TrueResVal > 1) ||
4700 (TrueResVal == -1 && FalseRes.getOpcode() != ISD::ZERO_EXTEND) ||
4701 (TrueResVal == 1 && FalseRes.getOpcode() != ISD::SIGN_EXTEND) ||
4702 (TrueResVal == 0 &&
4703 (FalseRes.getOpcode() != ISD::SELECT_CC || CC != ISD::SETEQ)))
4704 return false;
4705
4706 SDValue SetOrSelCC = FalseRes.getOpcode() == ISD::SELECT_CC
4707 ? FalseRes
4708 : FalseRes.getOperand(0);
4709 bool InnerIsSel = SetOrSelCC.getOpcode() == ISD::SELECT_CC;
4710 if (SetOrSelCC.getOpcode() != ISD::SETCC &&
4711 SetOrSelCC.getOpcode() != ISD::SELECT_CC)
4712 return false;
4713
4714 // Without this setb optimization, the outer SELECT_CC will be manually
4715 // selected to SELECT_CC_I4/SELECT_CC_I8 Pseudo, then expand-isel-pseudos pass
4716 // transforms pseudo instruction to isel instruction. When there are more than
4717 // one use for result like zext/sext, with current optimization we only see
4718 // isel is replaced by setb but can't see any significant gain. Since
4719 // setb has longer latency than original isel, we should avoid this. Another
4720 // point is that setb requires comparison always kept, it can break the
4721 // opportunity to get the comparison away if we have in future.
4722 if (!SetOrSelCC.hasOneUse() || (!InnerIsSel && !FalseRes.hasOneUse()))
4723 return false;
4724
4725 SDValue InnerLHS = SetOrSelCC.getOperand(0);
4726 SDValue InnerRHS = SetOrSelCC.getOperand(1);
4727 ISD::CondCode InnerCC =
4728 cast<CondCodeSDNode>(SetOrSelCC.getOperand(InnerIsSel ? 4 : 2))->get();
4729 // If the inner comparison is a select_cc, make sure the true/false values are
4730 // 1/-1 and canonicalize it if needed.
4731 if (InnerIsSel) {
4732 ConstantSDNode *SelCCTrueConst =
4733 dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(2));
4734 ConstantSDNode *SelCCFalseConst =
4735 dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(3));
4736 if (!SelCCTrueConst || !SelCCFalseConst)
4737 return false;
4738 int64_t SelCCTVal = SelCCTrueConst->getSExtValue();
4739 int64_t SelCCFVal = SelCCFalseConst->getSExtValue();
4740 // The values must be -1/1 (requiring a swap) or 1/-1.
4741 if (SelCCTVal == -1 && SelCCFVal == 1) {
4742 std::swap(InnerLHS, InnerRHS);
4743 } else if (SelCCTVal != 1 || SelCCFVal != -1)
4744 return false;
4745 }
4746
4747 // Canonicalize unsigned case
4748 if (InnerCC == ISD::SETULT || InnerCC == ISD::SETUGT) {
4749 IsUnCmp = true;
4750 InnerCC = (InnerCC == ISD::SETULT) ? ISD::SETLT : ISD::SETGT;
4751 }
4752
4753 bool InnerSwapped = false;
4754 if (LHS == InnerRHS && RHS == InnerLHS)
4755 InnerSwapped = true;
4756 else if (LHS != InnerLHS || RHS != InnerRHS)
4757 return false;
4758
4759 switch (CC) {
4760 // (select_cc lhs, rhs, 0, \
4761 // (select_cc [lr]hs, [lr]hs, 1, -1, setlt/setgt), seteq)
4762 case ISD::SETEQ:
4763 if (!InnerIsSel)
4764 return false;
4765 if (InnerCC != ISD::SETLT && InnerCC != ISD::SETGT)
4766 return false;
4767 NeedSwapOps = (InnerCC == ISD::SETGT) ? InnerSwapped : !InnerSwapped;
4768 break;
4769
4770 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4771 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setgt)), setu?lt)
4772 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setlt)), setu?lt)
4773 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4774 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setgt)), setu?lt)
4775 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setlt)), setu?lt)
4776 case ISD::SETULT:
4777 if (!IsUnCmp && InnerCC != ISD::SETNE)
4778 return false;
4779 IsUnCmp = true;
4780 [[fallthrough]];
4781 case ISD::SETLT:
4782 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETGT && !InnerSwapped) ||
4783 (InnerCC == ISD::SETLT && InnerSwapped))
4784 NeedSwapOps = (TrueResVal == 1);
4785 else
4786 return false;
4787 break;
4788
4789 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4790 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setlt)), setu?gt)
4791 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setgt)), setu?gt)
4792 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4793 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setlt)), setu?gt)
4794 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setgt)), setu?gt)
4795 case ISD::SETUGT:
4796 if (!IsUnCmp && InnerCC != ISD::SETNE)
4797 return false;
4798 IsUnCmp = true;
4799 [[fallthrough]];
4800 case ISD::SETGT:
4801 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETLT && !InnerSwapped) ||
4802 (InnerCC == ISD::SETGT && InnerSwapped))
4803 NeedSwapOps = (TrueResVal == -1);
4804 else
4805 return false;
4806 break;
4807
4808 default:
4809 return false;
4810 }
4811
4812 LLVM_DEBUG(dbgs() << "Found a node that can be lowered to a SETB: ");
4813 LLVM_DEBUG(N->dump());
4814
4815 return true;
4816}
4817
4818// Return true if it's a software square-root/divide operand.
4819static bool isSWTestOp(SDValue N) {
4820 if (N.getOpcode() == PPCISD::FTSQRT)
4821 return true;
4822 if (N.getNumOperands() < 1 || !isa<ConstantSDNode>(N.getOperand(0)) ||
4823 N.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
4824 return false;
4825 switch (N.getConstantOperandVal(0)) {
4826 case Intrinsic::ppc_vsx_xvtdivdp:
4827 case Intrinsic::ppc_vsx_xvtdivsp:
4828 case Intrinsic::ppc_vsx_xvtsqrtdp:
4829 case Intrinsic::ppc_vsx_xvtsqrtsp:
4830 return true;
4831 }
4832 return false;
4833}
4834
4835bool PPCDAGToDAGISel::tryFoldSWTestBRCC(SDNode *N) {
4836 assert(N->getOpcode() == ISD::BR_CC && "ISD::BR_CC is expected.");
4837 // We are looking for following patterns, where `truncate to i1` actually has
4838 // the same semantic with `and 1`.
4839 // (br_cc seteq, (truncateToi1 SWTestOp), 0) -> (BCC PRED_NU, SWTestOp)
4840 // (br_cc seteq, (and SWTestOp, 2), 0) -> (BCC PRED_NE, SWTestOp)
4841 // (br_cc seteq, (and SWTestOp, 4), 0) -> (BCC PRED_LE, SWTestOp)
4842 // (br_cc seteq, (and SWTestOp, 8), 0) -> (BCC PRED_GE, SWTestOp)
4843 // (br_cc setne, (truncateToi1 SWTestOp), 0) -> (BCC PRED_UN, SWTestOp)
4844 // (br_cc setne, (and SWTestOp, 2), 0) -> (BCC PRED_EQ, SWTestOp)
4845 // (br_cc setne, (and SWTestOp, 4), 0) -> (BCC PRED_GT, SWTestOp)
4846 // (br_cc setne, (and SWTestOp, 8), 0) -> (BCC PRED_LT, SWTestOp)
4847 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
4848 if (CC != ISD::SETEQ && CC != ISD::SETNE)
4849 return false;
4850
4851 SDValue CmpRHS = N->getOperand(3);
4852 if (!isNullConstant(CmpRHS))
4853 return false;
4854
4855 SDValue CmpLHS = N->getOperand(2);
4856 if (CmpLHS.getNumOperands() < 1 || !isSWTestOp(CmpLHS.getOperand(0)))
4857 return false;
4858
4859 unsigned PCC = 0;
4860 bool IsCCNE = CC == ISD::SETNE;
4861 if (CmpLHS.getOpcode() == ISD::AND &&
4862 isa<ConstantSDNode>(CmpLHS.getOperand(1)))
4863 switch (CmpLHS.getConstantOperandVal(1)) {
4864 case 1:
4865 PCC = IsCCNE ? PPC::PRED_UN : PPC::PRED_NU;
4866 break;
4867 case 2:
4868 PCC = IsCCNE ? PPC::PRED_EQ : PPC::PRED_NE;
4869 break;
4870 case 4:
4871 PCC = IsCCNE ? PPC::PRED_GT : PPC::PRED_LE;
4872 break;
4873 case 8:
4874 PCC = IsCCNE ? PPC::PRED_LT : PPC::PRED_GE;
4875 break;
4876 default:
4877 return false;
4878 }
4879 else if (CmpLHS.getOpcode() == ISD::TRUNCATE &&
4880 CmpLHS.getValueType() == MVT::i1)
4881 PCC = IsCCNE ? PPC::PRED_UN : PPC::PRED_NU;
4882
4883 if (PCC) {
4884 SDLoc dl(N);
4885 SDValue Ops[] = {getI32Imm(PCC, dl), CmpLHS.getOperand(0), N->getOperand(4),
4886 N->getOperand(0)};
4887 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
4888 return true;
4889 }
4890 return false;
4891}
4892
4893bool PPCDAGToDAGISel::trySelectLoopCountIntrinsic(SDNode *N) {
4894 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
4895 // value, for example when crbits is disabled. If so, select the
4896 // loop_decrement intrinsics now.
4897 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
4898 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
4899
4900 if (LHS.getOpcode() != ISD::AND || !isa<ConstantSDNode>(LHS.getOperand(1)) ||
4901 isNullConstant(LHS.getOperand(1)))
4902 return false;
4903
4904 if (LHS.getOperand(0).getOpcode() != ISD::INTRINSIC_W_CHAIN ||
4905 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() !=
4906 Intrinsic::loop_decrement)
4907 return false;
4908
4909 if (!isa<ConstantSDNode>(RHS))
4910 return false;
4911
4912 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
4913 "Counter decrement comparison is not EQ or NE");
4914
4915 SDValue OldDecrement = LHS.getOperand(0);
4916 assert(OldDecrement.hasOneUse() && "loop decrement has more than one use!");
4917
4918 SDLoc DecrementLoc(OldDecrement);
4919 SDValue ChainInput = OldDecrement.getOperand(0);
4920 SDValue DecrementOps[] = {Subtarget->isPPC64() ? getI64Imm(1, DecrementLoc)
4921 : getI32Imm(1, DecrementLoc)};
4922 unsigned DecrementOpcode =
4923 Subtarget->isPPC64() ? PPC::DecreaseCTR8loop : PPC::DecreaseCTRloop;
4924 SDNode *NewDecrement = CurDAG->getMachineNode(DecrementOpcode, DecrementLoc,
4925 MVT::i1, DecrementOps);
4926
4927 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
4928 bool IsBranchOnTrue = (CC == ISD::SETEQ && Val) || (CC == ISD::SETNE && !Val);
4929 unsigned Opcode = IsBranchOnTrue ? PPC::BC : PPC::BCn;
4930
4931 ReplaceUses(LHS.getValue(0), LHS.getOperand(1));
4932 CurDAG->RemoveDeadNode(LHS.getNode());
4933
4934 // Mark the old loop_decrement intrinsic as dead.
4935 ReplaceUses(OldDecrement.getValue(1), ChainInput);
4936 CurDAG->RemoveDeadNode(OldDecrement.getNode());
4937
4938 SDValue Chain = CurDAG->getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
4939 ChainInput, N->getOperand(0));
4940
4941 CurDAG->SelectNodeTo(N, Opcode, MVT::Other, SDValue(NewDecrement, 0),
4942 N->getOperand(4), Chain);
4943 return true;
4944}
4945
4946bool PPCDAGToDAGISel::tryAsSingleRLWINM(SDNode *N) {
4947 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4948 unsigned Imm;
4949 if (!isInt32Immediate(N->getOperand(1), Imm))
4950 return false;
4951
4952 SDLoc dl(N);
4953 SDValue Val = N->getOperand(0);
4954 unsigned SH, MB, ME;
4955 // If this is an and of a value rotated between 0 and 31 bits and then and'd
4956 // with a mask, emit rlwinm
4957 if (isRotateAndMask(Val.getNode(), Imm, false, SH, MB, ME)) {
4958 Val = Val.getOperand(0);
4959 SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
4960 getI32Imm(ME, dl)};
4961 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4962 return true;
4963 }
4964
4965 // If this is just a masked value where the input is not handled, and
4966 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
4967 if (isRunOfOnes(Imm, MB, ME) && Val.getOpcode() != ISD::ROTL) {
4968 SDValue Ops[] = {Val, getI32Imm(0, dl), getI32Imm(MB, dl),
4969 getI32Imm(ME, dl)};
4970 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4971 return true;
4972 }
4973
4974 // AND X, 0 -> 0, not "rlwinm 32".
4975 if (Imm == 0) {
4976 ReplaceUses(SDValue(N, 0), N->getOperand(1));
4977 return true;
4978 }
4979
4980 return false;
4981}
4982
4983b