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