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