Bug Summary

File:lib/Target/PowerPC/PPCISelDAGToDAG.cpp
Warning:line 1623, column 15
Value stored to 'I' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

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