Bug Summary

File:llvm/lib/Target/SystemZ/SystemZISelLowering.cpp
Warning:line 767, column 36
The result of the left shift is undefined due to shifting by '18446744073709551615', which is greater or equal to the width of type 'uint64_t'

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 SystemZISelLowering.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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Target/SystemZ -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/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/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Target/SystemZ -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp

1//===-- SystemZISelLowering.cpp - SystemZ DAG lowering implementation -----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the SystemZTargetLowering class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "SystemZISelLowering.h"
14#include "SystemZCallingConv.h"
15#include "SystemZConstantPoolValue.h"
16#include "SystemZMachineFunctionInfo.h"
17#include "SystemZTargetMachine.h"
18#include "llvm/CodeGen/CallingConvLower.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
21#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
22#include "llvm/IR/IntrinsicInst.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/IntrinsicsS390.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/KnownBits.h"
27#include <cctype>
28
29using namespace llvm;
30
31#define DEBUG_TYPE"systemz-lower" "systemz-lower"
32
33namespace {
34// Represents information about a comparison.
35struct Comparison {
36 Comparison(SDValue Op0In, SDValue Op1In, SDValue ChainIn)
37 : Op0(Op0In), Op1(Op1In), Chain(ChainIn),
38 Opcode(0), ICmpType(0), CCValid(0), CCMask(0) {}
39
40 // The operands to the comparison.
41 SDValue Op0, Op1;
42
43 // Chain if this is a strict floating-point comparison.
44 SDValue Chain;
45
46 // The opcode that should be used to compare Op0 and Op1.
47 unsigned Opcode;
48
49 // A SystemZICMP value. Only used for integer comparisons.
50 unsigned ICmpType;
51
52 // The mask of CC values that Opcode can produce.
53 unsigned CCValid;
54
55 // The mask of CC values for which the original condition is true.
56 unsigned CCMask;
57};
58} // end anonymous namespace
59
60// Classify VT as either 32 or 64 bit.
61static bool is32Bit(EVT VT) {
62 switch (VT.getSimpleVT().SimpleTy) {
63 case MVT::i32:
64 return true;
65 case MVT::i64:
66 return false;
67 default:
68 llvm_unreachable("Unsupported type")::llvm::llvm_unreachable_internal("Unsupported type", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 68)
;
69 }
70}
71
72// Return a version of MachineOperand that can be safely used before the
73// final use.
74static MachineOperand earlyUseOperand(MachineOperand Op) {
75 if (Op.isReg())
76 Op.setIsKill(false);
77 return Op;
78}
79
80SystemZTargetLowering::SystemZTargetLowering(const TargetMachine &TM,
81 const SystemZSubtarget &STI)
82 : TargetLowering(TM), Subtarget(STI) {
83 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize(0));
84
85 // Set up the register classes.
86 if (Subtarget.hasHighWord())
87 addRegisterClass(MVT::i32, &SystemZ::GRX32BitRegClass);
88 else
89 addRegisterClass(MVT::i32, &SystemZ::GR32BitRegClass);
90 addRegisterClass(MVT::i64, &SystemZ::GR64BitRegClass);
91 if (!useSoftFloat()) {
92 if (Subtarget.hasVector()) {
93 addRegisterClass(MVT::f32, &SystemZ::VR32BitRegClass);
94 addRegisterClass(MVT::f64, &SystemZ::VR64BitRegClass);
95 } else {
96 addRegisterClass(MVT::f32, &SystemZ::FP32BitRegClass);
97 addRegisterClass(MVT::f64, &SystemZ::FP64BitRegClass);
98 }
99 if (Subtarget.hasVectorEnhancements1())
100 addRegisterClass(MVT::f128, &SystemZ::VR128BitRegClass);
101 else
102 addRegisterClass(MVT::f128, &SystemZ::FP128BitRegClass);
103
104 if (Subtarget.hasVector()) {
105 addRegisterClass(MVT::v16i8, &SystemZ::VR128BitRegClass);
106 addRegisterClass(MVT::v8i16, &SystemZ::VR128BitRegClass);
107 addRegisterClass(MVT::v4i32, &SystemZ::VR128BitRegClass);
108 addRegisterClass(MVT::v2i64, &SystemZ::VR128BitRegClass);
109 addRegisterClass(MVT::v4f32, &SystemZ::VR128BitRegClass);
110 addRegisterClass(MVT::v2f64, &SystemZ::VR128BitRegClass);
111 }
112 }
113
114 // Compute derived properties from the register classes
115 computeRegisterProperties(Subtarget.getRegisterInfo());
116
117 // Set up special registers.
118 setStackPointerRegisterToSaveRestore(SystemZ::R15D);
119
120 // TODO: It may be better to default to latency-oriented scheduling, however
121 // LLVM's current latency-oriented scheduler can't handle physreg definitions
122 // such as SystemZ has with CC, so set this to the register-pressure
123 // scheduler, because it can.
124 setSchedulingPreference(Sched::RegPressure);
125
126 setBooleanContents(ZeroOrOneBooleanContent);
127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128
129 // Instructions are strings of 2-byte aligned 2-byte values.
130 setMinFunctionAlignment(Align(2));
131 // For performance reasons we prefer 16-byte alignment.
132 setPrefFunctionAlignment(Align(16));
133
134 // Handle operations that are handled in a similar way for all types.
135 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
136 I <= MVT::LAST_FP_VALUETYPE;
137 ++I) {
138 MVT VT = MVT::SimpleValueType(I);
139 if (isTypeLegal(VT)) {
140 // Lower SET_CC into an IPM-based sequence.
141 setOperationAction(ISD::SETCC, VT, Custom);
142 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
143 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
144
145 // Expand SELECT(C, A, B) into SELECT_CC(X, 0, A, B, NE).
146 setOperationAction(ISD::SELECT, VT, Expand);
147
148 // Lower SELECT_CC and BR_CC into separate comparisons and branches.
149 setOperationAction(ISD::SELECT_CC, VT, Custom);
150 setOperationAction(ISD::BR_CC, VT, Custom);
151 }
152 }
153
154 // Expand jump table branches as address arithmetic followed by an
155 // indirect jump.
156 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
157
158 // Expand BRCOND into a BR_CC (see above).
159 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
160
161 // Handle integer types.
162 for (unsigned I = MVT::FIRST_INTEGER_VALUETYPE;
163 I <= MVT::LAST_INTEGER_VALUETYPE;
164 ++I) {
165 MVT VT = MVT::SimpleValueType(I);
166 if (isTypeLegal(VT)) {
167 // Expand individual DIV and REMs into DIVREMs.
168 setOperationAction(ISD::SDIV, VT, Expand);
169 setOperationAction(ISD::UDIV, VT, Expand);
170 setOperationAction(ISD::SREM, VT, Expand);
171 setOperationAction(ISD::UREM, VT, Expand);
172 setOperationAction(ISD::SDIVREM, VT, Custom);
173 setOperationAction(ISD::UDIVREM, VT, Custom);
174
175 // Support addition/subtraction with overflow.
176 setOperationAction(ISD::SADDO, VT, Custom);
177 setOperationAction(ISD::SSUBO, VT, Custom);
178
179 // Support addition/subtraction with carry.
180 setOperationAction(ISD::UADDO, VT, Custom);
181 setOperationAction(ISD::USUBO, VT, Custom);
182
183 // Support carry in as value rather than glue.
184 setOperationAction(ISD::ADDCARRY, VT, Custom);
185 setOperationAction(ISD::SUBCARRY, VT, Custom);
186
187 // Lower ATOMIC_LOAD and ATOMIC_STORE into normal volatile loads and
188 // stores, putting a serialization instruction after the stores.
189 setOperationAction(ISD::ATOMIC_LOAD, VT, Custom);
190 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
191
192 // Lower ATOMIC_LOAD_SUB into ATOMIC_LOAD_ADD if LAA and LAAG are
193 // available, or if the operand is constant.
194 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
195
196 // Use POPCNT on z196 and above.
197 if (Subtarget.hasPopulationCount())
198 setOperationAction(ISD::CTPOP, VT, Custom);
199 else
200 setOperationAction(ISD::CTPOP, VT, Expand);
201
202 // No special instructions for these.
203 setOperationAction(ISD::CTTZ, VT, Expand);
204 setOperationAction(ISD::ROTR, VT, Expand);
205
206 // Use *MUL_LOHI where possible instead of MULH*.
207 setOperationAction(ISD::MULHS, VT, Expand);
208 setOperationAction(ISD::MULHU, VT, Expand);
209 setOperationAction(ISD::SMUL_LOHI, VT, Custom);
210 setOperationAction(ISD::UMUL_LOHI, VT, Custom);
211
212 // Only z196 and above have native support for conversions to unsigned.
213 // On z10, promoting to i64 doesn't generate an inexact condition for
214 // values that are outside the i32 range but in the i64 range, so use
215 // the default expansion.
216 if (!Subtarget.hasFPExtension())
217 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
218
219 // Mirror those settings for STRICT_FP_TO_[SU]INT. Note that these all
220 // default to Expand, so need to be modified to Legal where appropriate.
221 setOperationAction(ISD::STRICT_FP_TO_SINT, VT, Legal);
222 if (Subtarget.hasFPExtension())
223 setOperationAction(ISD::STRICT_FP_TO_UINT, VT, Legal);
224
225 // And similarly for STRICT_[SU]INT_TO_FP.
226 setOperationAction(ISD::STRICT_SINT_TO_FP, VT, Legal);
227 if (Subtarget.hasFPExtension())
228 setOperationAction(ISD::STRICT_UINT_TO_FP, VT, Legal);
229 }
230 }
231
232 // Type legalization will convert 8- and 16-bit atomic operations into
233 // forms that operate on i32s (but still keeping the original memory VT).
234 // Lower them into full i32 operations.
235 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Custom);
236 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Custom);
237 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
238 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
239 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Custom);
240 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Custom);
241 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Custom);
242 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Custom);
243 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Custom);
244 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Custom);
245 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Custom);
246
247 // Even though i128 is not a legal type, we still need to custom lower
248 // the atomic operations in order to exploit SystemZ instructions.
249 setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
250 setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
251
252 // We can use the CC result of compare-and-swap to implement
253 // the "success" result of ATOMIC_CMP_SWAP_WITH_SUCCESS.
254 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Custom);
255 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Custom);
256 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
257
258 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
259
260 // Traps are legal, as we will convert them to "j .+2".
261 setOperationAction(ISD::TRAP, MVT::Other, Legal);
262
263 // z10 has instructions for signed but not unsigned FP conversion.
264 // Handle unsigned 32-bit types as signed 64-bit types.
265 if (!Subtarget.hasFPExtension()) {
266 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Promote);
267 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
268 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Promote);
269 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
270 }
271
272 // We have native support for a 64-bit CTLZ, via FLOGR.
273 setOperationAction(ISD::CTLZ, MVT::i32, Promote);
274 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Promote);
275 setOperationAction(ISD::CTLZ, MVT::i64, Legal);
276
277 // On z15 we have native support for a 64-bit CTPOP.
278 if (Subtarget.hasMiscellaneousExtensions3()) {
279 setOperationAction(ISD::CTPOP, MVT::i32, Promote);
280 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
281 }
282
283 // Give LowerOperation the chance to replace 64-bit ORs with subregs.
284 setOperationAction(ISD::OR, MVT::i64, Custom);
285
286 // FIXME: Can we support these natively?
287 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
288 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
289 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
290
291 // We have native instructions for i8, i16 and i32 extensions, but not i1.
292 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
293 for (MVT VT : MVT::integer_valuetypes()) {
294 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
295 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
296 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
297 }
298
299 // Handle the various types of symbolic address.
300 setOperationAction(ISD::ConstantPool, PtrVT, Custom);
301 setOperationAction(ISD::GlobalAddress, PtrVT, Custom);
302 setOperationAction(ISD::GlobalTLSAddress, PtrVT, Custom);
303 setOperationAction(ISD::BlockAddress, PtrVT, Custom);
304 setOperationAction(ISD::JumpTable, PtrVT, Custom);
305
306 // We need to handle dynamic allocations specially because of the
307 // 160-byte area at the bottom of the stack.
308 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
309 setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, PtrVT, Custom);
310
311 // Use custom expanders so that we can force the function to use
312 // a frame pointer.
313 setOperationAction(ISD::STACKSAVE, MVT::Other, Custom);
314 setOperationAction(ISD::STACKRESTORE, MVT::Other, Custom);
315
316 // Handle prefetches with PFD or PFDRL.
317 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
318
319 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
320 // Assume by default that all vector operations need to be expanded.
321 for (unsigned Opcode = 0; Opcode < ISD::BUILTIN_OP_END; ++Opcode)
322 if (getOperationAction(Opcode, VT) == Legal)
323 setOperationAction(Opcode, VT, Expand);
324
325 // Likewise all truncating stores and extending loads.
326 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
327 setTruncStoreAction(VT, InnerVT, Expand);
328 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
329 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
330 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
331 }
332
333 if (isTypeLegal(VT)) {
334 // These operations are legal for anything that can be stored in a
335 // vector register, even if there is no native support for the format
336 // as such. In particular, we can do these for v4f32 even though there
337 // are no specific instructions for that format.
338 setOperationAction(ISD::LOAD, VT, Legal);
339 setOperationAction(ISD::STORE, VT, Legal);
340 setOperationAction(ISD::VSELECT, VT, Legal);
341 setOperationAction(ISD::BITCAST, VT, Legal);
342 setOperationAction(ISD::UNDEF, VT, Legal);
343
344 // Likewise, except that we need to replace the nodes with something
345 // more specific.
346 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
347 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
348 }
349 }
350
351 // Handle integer vector types.
352 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
353 if (isTypeLegal(VT)) {
354 // These operations have direct equivalents.
355 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Legal);
356 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Legal);
357 setOperationAction(ISD::ADD, VT, Legal);
358 setOperationAction(ISD::SUB, VT, Legal);
359 if (VT != MVT::v2i64)
360 setOperationAction(ISD::MUL, VT, Legal);
361 setOperationAction(ISD::AND, VT, Legal);
362 setOperationAction(ISD::OR, VT, Legal);
363 setOperationAction(ISD::XOR, VT, Legal);
364 if (Subtarget.hasVectorEnhancements1())
365 setOperationAction(ISD::CTPOP, VT, Legal);
366 else
367 setOperationAction(ISD::CTPOP, VT, Custom);
368 setOperationAction(ISD::CTTZ, VT, Legal);
369 setOperationAction(ISD::CTLZ, VT, Legal);
370
371 // Convert a GPR scalar to a vector by inserting it into element 0.
372 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
373
374 // Use a series of unpacks for extensions.
375 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
376 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
377
378 // Detect shifts by a scalar amount and convert them into
379 // V*_BY_SCALAR.
380 setOperationAction(ISD::SHL, VT, Custom);
381 setOperationAction(ISD::SRA, VT, Custom);
382 setOperationAction(ISD::SRL, VT, Custom);
383
384 // At present ROTL isn't matched by DAGCombiner. ROTR should be
385 // converted into ROTL.
386 setOperationAction(ISD::ROTL, VT, Expand);
387 setOperationAction(ISD::ROTR, VT, Expand);
388
389 // Map SETCCs onto one of VCE, VCH or VCHL, swapping the operands
390 // and inverting the result as necessary.
391 setOperationAction(ISD::SETCC, VT, Custom);
392 setOperationAction(ISD::STRICT_FSETCC, VT, Custom);
393 if (Subtarget.hasVectorEnhancements1())
394 setOperationAction(ISD::STRICT_FSETCCS, VT, Custom);
395 }
396 }
397
398 if (Subtarget.hasVector()) {
399 // There should be no need to check for float types other than v2f64
400 // since <2 x f32> isn't a legal type.
401 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
402 setOperationAction(ISD::FP_TO_SINT, MVT::v2f64, Legal);
403 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
404 setOperationAction(ISD::FP_TO_UINT, MVT::v2f64, Legal);
405 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
406 setOperationAction(ISD::SINT_TO_FP, MVT::v2f64, Legal);
407 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
408 setOperationAction(ISD::UINT_TO_FP, MVT::v2f64, Legal);
409
410 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
411 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2f64, Legal);
412 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
413 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2f64, Legal);
414 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
415 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2f64, Legal);
416 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
417 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2f64, Legal);
418 }
419
420 if (Subtarget.hasVectorEnhancements2()) {
421 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
422 setOperationAction(ISD::FP_TO_SINT, MVT::v4f32, Legal);
423 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
424 setOperationAction(ISD::FP_TO_UINT, MVT::v4f32, Legal);
425 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
426 setOperationAction(ISD::SINT_TO_FP, MVT::v4f32, Legal);
427 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
428 setOperationAction(ISD::UINT_TO_FP, MVT::v4f32, Legal);
429
430 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
431 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4f32, Legal);
432 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
433 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4f32, Legal);
434 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
435 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4f32, Legal);
436 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
437 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4f32, Legal);
438 }
439
440 // Handle floating-point types.
441 for (unsigned I = MVT::FIRST_FP_VALUETYPE;
442 I <= MVT::LAST_FP_VALUETYPE;
443 ++I) {
444 MVT VT = MVT::SimpleValueType(I);
445 if (isTypeLegal(VT)) {
446 // We can use FI for FRINT.
447 setOperationAction(ISD::FRINT, VT, Legal);
448
449 // We can use the extended form of FI for other rounding operations.
450 if (Subtarget.hasFPExtension()) {
451 setOperationAction(ISD::FNEARBYINT, VT, Legal);
452 setOperationAction(ISD::FFLOOR, VT, Legal);
453 setOperationAction(ISD::FCEIL, VT, Legal);
454 setOperationAction(ISD::FTRUNC, VT, Legal);
455 setOperationAction(ISD::FROUND, VT, Legal);
456 }
457
458 // No special instructions for these.
459 setOperationAction(ISD::FSIN, VT, Expand);
460 setOperationAction(ISD::FCOS, VT, Expand);
461 setOperationAction(ISD::FSINCOS, VT, Expand);
462 setOperationAction(ISD::FREM, VT, Expand);
463 setOperationAction(ISD::FPOW, VT, Expand);
464
465 // Handle constrained floating-point operations.
466 setOperationAction(ISD::STRICT_FADD, VT, Legal);
467 setOperationAction(ISD::STRICT_FSUB, VT, Legal);
468 setOperationAction(ISD::STRICT_FMUL, VT, Legal);
469 setOperationAction(ISD::STRICT_FDIV, VT, Legal);
470 setOperationAction(ISD::STRICT_FMA, VT, Legal);
471 setOperationAction(ISD::STRICT_FSQRT, VT, Legal);
472 setOperationAction(ISD::STRICT_FRINT, VT, Legal);
473 setOperationAction(ISD::STRICT_FP_ROUND, VT, Legal);
474 setOperationAction(ISD::STRICT_FP_EXTEND, VT, Legal);
475 if (Subtarget.hasFPExtension()) {
476 setOperationAction(ISD::STRICT_FNEARBYINT, VT, Legal);
477 setOperationAction(ISD::STRICT_FFLOOR, VT, Legal);
478 setOperationAction(ISD::STRICT_FCEIL, VT, Legal);
479 setOperationAction(ISD::STRICT_FROUND, VT, Legal);
480 setOperationAction(ISD::STRICT_FTRUNC, VT, Legal);
481 }
482 }
483 }
484
485 // Handle floating-point vector types.
486 if (Subtarget.hasVector()) {
487 // Scalar-to-vector conversion is just a subreg.
488 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
489 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
490
491 // Some insertions and extractions can be done directly but others
492 // need to go via integers.
493 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
494 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
495 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
496 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
497
498 // These operations have direct equivalents.
499 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
500 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
501 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
502 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
503 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
504 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
505 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
506 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
507 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
508 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
509 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
510 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
511 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
512 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
513
514 // Handle constrained floating-point operations.
515 setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
516 setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
517 setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
518 setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
519 setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
520 setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
521 setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
522 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
523 setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
524 setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal);
525 setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
526 setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
527 }
528
529 // The vector enhancements facility 1 has instructions for these.
530 if (Subtarget.hasVectorEnhancements1()) {
531 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
532 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
533 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
534 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
535 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
536 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
537 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
538 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
539 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
540 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
541 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
542 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
543 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
544 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
545
546 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
547 setOperationAction(ISD::FMAXIMUM, MVT::f64, Legal);
548 setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
549 setOperationAction(ISD::FMINIMUM, MVT::f64, Legal);
550
551 setOperationAction(ISD::FMAXNUM, MVT::v2f64, Legal);
552 setOperationAction(ISD::FMAXIMUM, MVT::v2f64, Legal);
553 setOperationAction(ISD::FMINNUM, MVT::v2f64, Legal);
554 setOperationAction(ISD::FMINIMUM, MVT::v2f64, Legal);
555
556 setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
557 setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
558 setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
559 setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
560
561 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
562 setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
563 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
564 setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
565
566 setOperationAction(ISD::FMAXNUM, MVT::f128, Legal);
567 setOperationAction(ISD::FMAXIMUM, MVT::f128, Legal);
568 setOperationAction(ISD::FMINNUM, MVT::f128, Legal);
569 setOperationAction(ISD::FMINIMUM, MVT::f128, Legal);
570
571 // Handle constrained floating-point operations.
572 setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
573 setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
574 setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
575 setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
576 setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
577 setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
578 setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
579 setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
580 setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
581 setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal);
582 setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
583 setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
584 for (auto VT : { MVT::f32, MVT::f64, MVT::f128,
585 MVT::v4f32, MVT::v2f64 }) {
586 setOperationAction(ISD::STRICT_FMAXNUM, VT, Legal);
587 setOperationAction(ISD::STRICT_FMINNUM, VT, Legal);
588 setOperationAction(ISD::STRICT_FMAXIMUM, VT, Legal);
589 setOperationAction(ISD::STRICT_FMINIMUM, VT, Legal);
590 }
591 }
592
593 // We only have fused f128 multiply-addition on vector registers.
594 if (!Subtarget.hasVectorEnhancements1()) {
595 setOperationAction(ISD::FMA, MVT::f128, Expand);
596 setOperationAction(ISD::STRICT_FMA, MVT::f128, Expand);
597 }
598
599 // We don't have a copysign instruction on vector registers.
600 if (Subtarget.hasVectorEnhancements1())
601 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
602
603 // Needed so that we don't try to implement f128 constant loads using
604 // a load-and-extend of a f80 constant (in cases where the constant
605 // would fit in an f80).
606 for (MVT VT : MVT::fp_valuetypes())
607 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
608
609 // We don't have extending load instruction on vector registers.
610 if (Subtarget.hasVectorEnhancements1()) {
611 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
612 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
613 }
614
615 // Floating-point truncation and stores need to be done separately.
616 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
617 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
618 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
619
620 // We have 64-bit FPR<->GPR moves, but need special handling for
621 // 32-bit forms.
622 if (!Subtarget.hasVector()) {
623 setOperationAction(ISD::BITCAST, MVT::i32, Custom);
624 setOperationAction(ISD::BITCAST, MVT::f32, Custom);
625 }
626
627 // VASTART and VACOPY need to deal with the SystemZ-specific varargs
628 // structure, but VAEND is a no-op.
629 setOperationAction(ISD::VASTART, MVT::Other, Custom);
630 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
631 setOperationAction(ISD::VAEND, MVT::Other, Expand);
632
633 // Codes for which we want to perform some z-specific combinations.
634 setTargetDAGCombine(ISD::ZERO_EXTEND);
635 setTargetDAGCombine(ISD::SIGN_EXTEND);
636 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
637 setTargetDAGCombine(ISD::LOAD);
638 setTargetDAGCombine(ISD::STORE);
639 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
640 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
641 setTargetDAGCombine(ISD::FP_ROUND);
642 setTargetDAGCombine(ISD::STRICT_FP_ROUND);
643 setTargetDAGCombine(ISD::FP_EXTEND);
644 setTargetDAGCombine(ISD::STRICT_FP_EXTEND);
645 setTargetDAGCombine(ISD::BSWAP);
646 setTargetDAGCombine(ISD::SDIV);
647 setTargetDAGCombine(ISD::UDIV);
648 setTargetDAGCombine(ISD::SREM);
649 setTargetDAGCombine(ISD::UREM);
650
651 // Handle intrinsics.
652 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
653 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
654
655 // We want to use MVC in preference to even a single load/store pair.
656 MaxStoresPerMemcpy = 0;
657 MaxStoresPerMemcpyOptSize = 0;
658
659 // The main memset sequence is a byte store followed by an MVC.
660 // Two STC or MV..I stores win over that, but the kind of fused stores
661 // generated by target-independent code don't when the byte value is
662 // variable. E.g. "STC <reg>;MHI <reg>,257;STH <reg>" is not better
663 // than "STC;MVC". Handle the choice in target-specific code instead.
664 MaxStoresPerMemset = 0;
665 MaxStoresPerMemsetOptSize = 0;
666
667 // Default to having -disable-strictnode-mutation on
668 IsStrictFPEnabled = true;
669}
670
671bool SystemZTargetLowering::useSoftFloat() const {
672 return Subtarget.hasSoftFloat();
673}
674
675EVT SystemZTargetLowering::getSetCCResultType(const DataLayout &DL,
676 LLVMContext &, EVT VT) const {
677 if (!VT.isVector())
678 return MVT::i32;
679 return VT.changeVectorElementTypeToInteger();
680}
681
682bool SystemZTargetLowering::isFMAFasterThanFMulAndFAdd(
683 const MachineFunction &MF, EVT VT) const {
684 VT = VT.getScalarType();
685
686 if (!VT.isSimple())
687 return false;
688
689 switch (VT.getSimpleVT().SimpleTy) {
690 case MVT::f32:
691 case MVT::f64:
692 return true;
693 case MVT::f128:
694 return Subtarget.hasVectorEnhancements1();
695 default:
696 break;
697 }
698
699 return false;
700}
701
702// Return true if the constant can be generated with a vector instruction,
703// such as VGM, VGMB or VREPI.
704bool SystemZVectorConstantInfo::isVectorConstantLegal(
705 const SystemZSubtarget &Subtarget) {
706 const SystemZInstrInfo *TII =
707 static_cast<const SystemZInstrInfo *>(Subtarget.getInstrInfo());
708 if (!Subtarget.hasVector() ||
3
Assuming the condition is false
709 (isFP128
3.1
Field 'isFP128' is false
3.1
Field 'isFP128' is false
3.1
Field 'isFP128' is false
&& !Subtarget.hasVectorEnhancements1()))
710 return false;
711
712 // Try using VECTOR GENERATE BYTE MASK. This is the architecturally-
713 // preferred way of creating all-zero and all-one vectors so give it
714 // priority over other methods below.
715 unsigned Mask = 0;
716 unsigned I = 0;
717 for (; I < SystemZ::VectorBytes; ++I) {
4
Loop condition is true. Entering loop body
718 uint64_t Byte = IntBits.lshr(I * 8).trunc(8).getZExtValue();
719 if (Byte == 0xff)
5
Assuming 'Byte' is not equal to 255
6
Taking false branch
720 Mask |= 1ULL << I;
721 else if (Byte != 0)
7
Assuming 'Byte' is not equal to 0
8
Taking true branch
722 break;
9
Execution continues on line 724
723 }
724 if (I
9.1
'I' is not equal to 'VectorBytes'
9.1
'I' is not equal to 'VectorBytes'
9.1
'I' is not equal to 'VectorBytes'
== SystemZ::VectorBytes) {
10
Taking false branch
725 Opcode = SystemZISD::BYTE_MASK;
726 OpVals.push_back(Mask);
727 VecVT = MVT::getVectorVT(MVT::getIntegerVT(8), 16);
728 return true;
729 }
730
731 if (SplatBitSize
10.1
Field 'SplatBitSize' is <= 64
10.1
Field 'SplatBitSize' is <= 64
10.1
Field 'SplatBitSize' is <= 64
> 64)
11
Taking false branch
732 return false;
733
734 auto tryValue = [&](uint64_t Value) -> bool {
735 // Try VECTOR REPLICATE IMMEDIATE
736 int64_t SignedValue = SignExtend64(Value, SplatBitSize);
737 if (isInt<16>(SignedValue)) {
738 OpVals.push_back(((unsigned) SignedValue));
739 Opcode = SystemZISD::REPLICATE;
740 VecVT = MVT::getVectorVT(MVT::getIntegerVT(SplatBitSize),
741 SystemZ::VectorBits / SplatBitSize);
742 return true;
743 }
744 // Try VECTOR GENERATE MASK
745 unsigned Start, End;
746 if (TII->isRxSBGMask(Value, SplatBitSize, Start, End)) {
747 // isRxSBGMask returns the bit numbers for a full 64-bit value, with 0
748 // denoting 1 << 63 and 63 denoting 1. Convert them to bit numbers for
749 // an SplatBitSize value, so that 0 denotes 1 << (SplatBitSize-1).
750 OpVals.push_back(Start - (64 - SplatBitSize));
751 OpVals.push_back(End - (64 - SplatBitSize));
752 Opcode = SystemZISD::ROTATE_MASK;
753 VecVT = MVT::getVectorVT(MVT::getIntegerVT(SplatBitSize),
754 SystemZ::VectorBits / SplatBitSize);
755 return true;
756 }
757 return false;
758 };
759
760 // First try assuming that any undefined bits above the highest set bit
761 // and below the lowest set bit are 1s. This increases the likelihood of
762 // being able to use a sign-extended element value in VECTOR REPLICATE
763 // IMMEDIATE or a wraparound mask in VECTOR GENERATE MASK.
764 uint64_t SplatBitsZ = SplatBits.getZExtValue();
765 uint64_t SplatUndefZ = SplatUndef.getZExtValue();
766 uint64_t Lower =
767 (SplatUndefZ & ((uint64_t(1) << findFirstSet(SplatBitsZ)) - 1));
12
Calling 'findFirstSet<unsigned long>'
19
Returning from 'findFirstSet<unsigned long>'
20
The result of the left shift is undefined due to shifting by '18446744073709551615', which is greater or equal to the width of type 'uint64_t'
768 uint64_t Upper =
769 (SplatUndefZ & ~((uint64_t(1) << findLastSet(SplatBitsZ)) - 1));
770 if (tryValue(SplatBitsZ | Upper | Lower))
771 return true;
772
773 // Now try assuming that any undefined bits between the first and
774 // last defined set bits are set. This increases the chances of
775 // using a non-wraparound mask.
776 uint64_t Middle = SplatUndefZ & ~Upper & ~Lower;
777 return tryValue(SplatBitsZ | Middle);
778}
779
780SystemZVectorConstantInfo::SystemZVectorConstantInfo(APFloat FPImm) {
781 IntBits = FPImm.bitcastToAPInt().zextOrSelf(128);
782 isFP128 = (&FPImm.getSemantics() == &APFloat::IEEEquad());
783
784 // Find the smallest splat.
785 SplatBits = FPImm.bitcastToAPInt();
786 unsigned Width = SplatBits.getBitWidth();
787 while (Width > 8) {
788 unsigned HalfSize = Width / 2;
789 APInt HighValue = SplatBits.lshr(HalfSize).trunc(HalfSize);
790 APInt LowValue = SplatBits.trunc(HalfSize);
791
792 // If the two halves do not match, stop here.
793 if (HighValue != LowValue || 8 > HalfSize)
794 break;
795
796 SplatBits = HighValue;
797 Width = HalfSize;
798 }
799 SplatUndef = 0;
800 SplatBitSize = Width;
801}
802
803SystemZVectorConstantInfo::SystemZVectorConstantInfo(BuildVectorSDNode *BVN) {
804 assert(BVN->isConstant() && "Expected a constant BUILD_VECTOR")((BVN->isConstant() && "Expected a constant BUILD_VECTOR"
) ? static_cast<void> (0) : __assert_fail ("BVN->isConstant() && \"Expected a constant BUILD_VECTOR\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 804, __PRETTY_FUNCTION__))
;
805 bool HasAnyUndefs;
806
807 // Get IntBits by finding the 128 bit splat.
808 BVN->isConstantSplat(IntBits, SplatUndef, SplatBitSize, HasAnyUndefs, 128,
809 true);
810
811 // Get SplatBits by finding the 8 bit or greater splat.
812 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs, 8,
813 true);
814}
815
816bool SystemZTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
817 bool ForCodeSize) const {
818 // We can load zero using LZ?R and negative zero using LZ?R;LC?BR.
819 if (Imm.isZero() || Imm.isNegZero())
1
Taking false branch
820 return true;
821
822 return SystemZVectorConstantInfo(Imm).isVectorConstantLegal(Subtarget);
2
Calling 'SystemZVectorConstantInfo::isVectorConstantLegal'
823}
824
825bool SystemZTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
826 // We can use CGFI or CLGFI.
827 return isInt<32>(Imm) || isUInt<32>(Imm);
828}
829
830bool SystemZTargetLowering::isLegalAddImmediate(int64_t Imm) const {
831 // We can use ALGFI or SLGFI.
832 return isUInt<32>(Imm) || isUInt<32>(-Imm);
833}
834
835bool SystemZTargetLowering::allowsMisalignedMemoryAccesses(
836 EVT VT, unsigned, unsigned, MachineMemOperand::Flags, bool *Fast) const {
837 // Unaligned accesses should never be slower than the expanded version.
838 // We check specifically for aligned accesses in the few cases where
839 // they are required.
840 if (Fast)
841 *Fast = true;
842 return true;
843}
844
845// Information about the addressing mode for a memory access.
846struct AddressingMode {
847 // True if a long displacement is supported.
848 bool LongDisplacement;
849
850 // True if use of index register is supported.
851 bool IndexReg;
852
853 AddressingMode(bool LongDispl, bool IdxReg) :
854 LongDisplacement(LongDispl), IndexReg(IdxReg) {}
855};
856
857// Return the desired addressing mode for a Load which has only one use (in
858// the same block) which is a Store.
859static AddressingMode getLoadStoreAddrMode(bool HasVector,
860 Type *Ty) {
861 // With vector support a Load->Store combination may be combined to either
862 // an MVC or vector operations and it seems to work best to allow the
863 // vector addressing mode.
864 if (HasVector)
865 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
866
867 // Otherwise only the MVC case is special.
868 bool MVC = Ty->isIntegerTy(8);
869 return AddressingMode(!MVC/*LongDispl*/, !MVC/*IdxReg*/);
870}
871
872// Return the addressing mode which seems most desirable given an LLVM
873// Instruction pointer.
874static AddressingMode
875supportedAddressingMode(Instruction *I, bool HasVector) {
876 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
877 switch (II->getIntrinsicID()) {
878 default: break;
879 case Intrinsic::memset:
880 case Intrinsic::memmove:
881 case Intrinsic::memcpy:
882 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
883 }
884 }
885
886 if (isa<LoadInst>(I) && I->hasOneUse()) {
887 auto *SingleUser = cast<Instruction>(*I->user_begin());
888 if (SingleUser->getParent() == I->getParent()) {
889 if (isa<ICmpInst>(SingleUser)) {
890 if (auto *C = dyn_cast<ConstantInt>(SingleUser->getOperand(1)))
891 if (C->getBitWidth() <= 64 &&
892 (isInt<16>(C->getSExtValue()) || isUInt<16>(C->getZExtValue())))
893 // Comparison of memory with 16 bit signed / unsigned immediate
894 return AddressingMode(false/*LongDispl*/, false/*IdxReg*/);
895 } else if (isa<StoreInst>(SingleUser))
896 // Load->Store
897 return getLoadStoreAddrMode(HasVector, I->getType());
898 }
899 } else if (auto *StoreI = dyn_cast<StoreInst>(I)) {
900 if (auto *LoadI = dyn_cast<LoadInst>(StoreI->getValueOperand()))
901 if (LoadI->hasOneUse() && LoadI->getParent() == I->getParent())
902 // Load->Store
903 return getLoadStoreAddrMode(HasVector, LoadI->getType());
904 }
905
906 if (HasVector && (isa<LoadInst>(I) || isa<StoreInst>(I))) {
907
908 // * Use LDE instead of LE/LEY for z13 to avoid partial register
909 // dependencies (LDE only supports small offsets).
910 // * Utilize the vector registers to hold floating point
911 // values (vector load / store instructions only support small
912 // offsets).
913
914 Type *MemAccessTy = (isa<LoadInst>(I) ? I->getType() :
915 I->getOperand(0)->getType());
916 bool IsFPAccess = MemAccessTy->isFloatingPointTy();
917 bool IsVectorAccess = MemAccessTy->isVectorTy();
918
919 // A store of an extracted vector element will be combined into a VSTE type
920 // instruction.
921 if (!IsVectorAccess && isa<StoreInst>(I)) {
922 Value *DataOp = I->getOperand(0);
923 if (isa<ExtractElementInst>(DataOp))
924 IsVectorAccess = true;
925 }
926
927 // A load which gets inserted into a vector element will be combined into a
928 // VLE type instruction.
929 if (!IsVectorAccess && isa<LoadInst>(I) && I->hasOneUse()) {
930 User *LoadUser = *I->user_begin();
931 if (isa<InsertElementInst>(LoadUser))
932 IsVectorAccess = true;
933 }
934
935 if (IsFPAccess || IsVectorAccess)
936 return AddressingMode(false/*LongDispl*/, true/*IdxReg*/);
937 }
938
939 return AddressingMode(true/*LongDispl*/, true/*IdxReg*/);
940}
941
942bool SystemZTargetLowering::isLegalAddressingMode(const DataLayout &DL,
943 const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I) const {
944 // Punt on globals for now, although they can be used in limited
945 // RELATIVE LONG cases.
946 if (AM.BaseGV)
947 return false;
948
949 // Require a 20-bit signed offset.
950 if (!isInt<20>(AM.BaseOffs))
951 return false;
952
953 AddressingMode SupportedAM(true, true);
954 if (I != nullptr)
955 SupportedAM = supportedAddressingMode(I, Subtarget.hasVector());
956
957 if (!SupportedAM.LongDisplacement && !isUInt<12>(AM.BaseOffs))
958 return false;
959
960 if (!SupportedAM.IndexReg)
961 // No indexing allowed.
962 return AM.Scale == 0;
963 else
964 // Indexing is OK but no scale factor can be applied.
965 return AM.Scale == 0 || AM.Scale == 1;
966}
967
968bool SystemZTargetLowering::isTruncateFree(Type *FromType, Type *ToType) const {
969 if (!FromType->isIntegerTy() || !ToType->isIntegerTy())
970 return false;
971 unsigned FromBits = FromType->getPrimitiveSizeInBits();
972 unsigned ToBits = ToType->getPrimitiveSizeInBits();
973 return FromBits > ToBits;
974}
975
976bool SystemZTargetLowering::isTruncateFree(EVT FromVT, EVT ToVT) const {
977 if (!FromVT.isInteger() || !ToVT.isInteger())
978 return false;
979 unsigned FromBits = FromVT.getSizeInBits();
980 unsigned ToBits = ToVT.getSizeInBits();
981 return FromBits > ToBits;
982}
983
984//===----------------------------------------------------------------------===//
985// Inline asm support
986//===----------------------------------------------------------------------===//
987
988TargetLowering::ConstraintType
989SystemZTargetLowering::getConstraintType(StringRef Constraint) const {
990 if (Constraint.size() == 1) {
991 switch (Constraint[0]) {
992 case 'a': // Address register
993 case 'd': // Data register (equivalent to 'r')
994 case 'f': // Floating-point register
995 case 'h': // High-part register
996 case 'r': // General-purpose register
997 case 'v': // Vector register
998 return C_RegisterClass;
999
1000 case 'Q': // Memory with base and unsigned 12-bit displacement
1001 case 'R': // Likewise, plus an index
1002 case 'S': // Memory with base and signed 20-bit displacement
1003 case 'T': // Likewise, plus an index
1004 case 'm': // Equivalent to 'T'.
1005 return C_Memory;
1006
1007 case 'I': // Unsigned 8-bit constant
1008 case 'J': // Unsigned 12-bit constant
1009 case 'K': // Signed 16-bit constant
1010 case 'L': // Signed 20-bit displacement (on all targets we support)
1011 case 'M': // 0x7fffffff
1012 return C_Immediate;
1013
1014 default:
1015 break;
1016 }
1017 }
1018 return TargetLowering::getConstraintType(Constraint);
1019}
1020
1021TargetLowering::ConstraintWeight SystemZTargetLowering::
1022getSingleConstraintMatchWeight(AsmOperandInfo &info,
1023 const char *constraint) const {
1024 ConstraintWeight weight = CW_Invalid;
1025 Value *CallOperandVal = info.CallOperandVal;
1026 // If we don't have a value, we can't do a match,
1027 // but allow it at the lowest weight.
1028 if (!CallOperandVal)
1029 return CW_Default;
1030 Type *type = CallOperandVal->getType();
1031 // Look at the constraint type.
1032 switch (*constraint) {
1033 default:
1034 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
1035 break;
1036
1037 case 'a': // Address register
1038 case 'd': // Data register (equivalent to 'r')
1039 case 'h': // High-part register
1040 case 'r': // General-purpose register
1041 if (CallOperandVal->getType()->isIntegerTy())
1042 weight = CW_Register;
1043 break;
1044
1045 case 'f': // Floating-point register
1046 if (type->isFloatingPointTy())
1047 weight = CW_Register;
1048 break;
1049
1050 case 'v': // Vector register
1051 if ((type->isVectorTy() || type->isFloatingPointTy()) &&
1052 Subtarget.hasVector())
1053 weight = CW_Register;
1054 break;
1055
1056 case 'I': // Unsigned 8-bit constant
1057 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1058 if (isUInt<8>(C->getZExtValue()))
1059 weight = CW_Constant;
1060 break;
1061
1062 case 'J': // Unsigned 12-bit constant
1063 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1064 if (isUInt<12>(C->getZExtValue()))
1065 weight = CW_Constant;
1066 break;
1067
1068 case 'K': // Signed 16-bit constant
1069 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1070 if (isInt<16>(C->getSExtValue()))
1071 weight = CW_Constant;
1072 break;
1073
1074 case 'L': // Signed 20-bit displacement (on all targets we support)
1075 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1076 if (isInt<20>(C->getSExtValue()))
1077 weight = CW_Constant;
1078 break;
1079
1080 case 'M': // 0x7fffffff
1081 if (auto *C = dyn_cast<ConstantInt>(CallOperandVal))
1082 if (C->getZExtValue() == 0x7fffffff)
1083 weight = CW_Constant;
1084 break;
1085 }
1086 return weight;
1087}
1088
1089// Parse a "{tNNN}" register constraint for which the register type "t"
1090// has already been verified. MC is the class associated with "t" and
1091// Map maps 0-based register numbers to LLVM register numbers.
1092static std::pair<unsigned, const TargetRegisterClass *>
1093parseRegisterNumber(StringRef Constraint, const TargetRegisterClass *RC,
1094 const unsigned *Map, unsigned Size) {
1095 assert(*(Constraint.end()-1) == '}' && "Missing '}'")((*(Constraint.end()-1) == '}' && "Missing '}'") ? static_cast
<void> (0) : __assert_fail ("*(Constraint.end()-1) == '}' && \"Missing '}'\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1095, __PRETTY_FUNCTION__))
;
1096 if (isdigit(Constraint[2])) {
1097 unsigned Index;
1098 bool Failed =
1099 Constraint.slice(2, Constraint.size() - 1).getAsInteger(10, Index);
1100 if (!Failed && Index < Size && Map[Index])
1101 return std::make_pair(Map[Index], RC);
1102 }
1103 return std::make_pair(0U, nullptr);
1104}
1105
1106std::pair<unsigned, const TargetRegisterClass *>
1107SystemZTargetLowering::getRegForInlineAsmConstraint(
1108 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
1109 if (Constraint.size() == 1) {
1110 // GCC Constraint Letters
1111 switch (Constraint[0]) {
1112 default: break;
1113 case 'd': // Data register (equivalent to 'r')
1114 case 'r': // General-purpose register
1115 if (VT == MVT::i64)
1116 return std::make_pair(0U, &SystemZ::GR64BitRegClass);
1117 else if (VT == MVT::i128)
1118 return std::make_pair(0U, &SystemZ::GR128BitRegClass);
1119 return std::make_pair(0U, &SystemZ::GR32BitRegClass);
1120
1121 case 'a': // Address register
1122 if (VT == MVT::i64)
1123 return std::make_pair(0U, &SystemZ::ADDR64BitRegClass);
1124 else if (VT == MVT::i128)
1125 return std::make_pair(0U, &SystemZ::ADDR128BitRegClass);
1126 return std::make_pair(0U, &SystemZ::ADDR32BitRegClass);
1127
1128 case 'h': // High-part register (an LLVM extension)
1129 return std::make_pair(0U, &SystemZ::GRH32BitRegClass);
1130
1131 case 'f': // Floating-point register
1132 if (!useSoftFloat()) {
1133 if (VT == MVT::f64)
1134 return std::make_pair(0U, &SystemZ::FP64BitRegClass);
1135 else if (VT == MVT::f128)
1136 return std::make_pair(0U, &SystemZ::FP128BitRegClass);
1137 return std::make_pair(0U, &SystemZ::FP32BitRegClass);
1138 }
1139 break;
1140 case 'v': // Vector register
1141 if (Subtarget.hasVector()) {
1142 if (VT == MVT::f32)
1143 return std::make_pair(0U, &SystemZ::VR32BitRegClass);
1144 if (VT == MVT::f64)
1145 return std::make_pair(0U, &SystemZ::VR64BitRegClass);
1146 return std::make_pair(0U, &SystemZ::VR128BitRegClass);
1147 }
1148 break;
1149 }
1150 }
1151 if (Constraint.size() > 0 && Constraint[0] == '{') {
1152 // We need to override the default register parsing for GPRs and FPRs
1153 // because the interpretation depends on VT. The internal names of
1154 // the registers are also different from the external names
1155 // (F0D and F0S instead of F0, etc.).
1156 if (Constraint[1] == 'r') {
1157 if (VT == MVT::i32)
1158 return parseRegisterNumber(Constraint, &SystemZ::GR32BitRegClass,
1159 SystemZMC::GR32Regs, 16);
1160 if (VT == MVT::i128)
1161 return parseRegisterNumber(Constraint, &SystemZ::GR128BitRegClass,
1162 SystemZMC::GR128Regs, 16);
1163 return parseRegisterNumber(Constraint, &SystemZ::GR64BitRegClass,
1164 SystemZMC::GR64Regs, 16);
1165 }
1166 if (Constraint[1] == 'f') {
1167 if (useSoftFloat())
1168 return std::make_pair(
1169 0u, static_cast<const TargetRegisterClass *>(nullptr));
1170 if (VT == MVT::f32)
1171 return parseRegisterNumber(Constraint, &SystemZ::FP32BitRegClass,
1172 SystemZMC::FP32Regs, 16);
1173 if (VT == MVT::f128)
1174 return parseRegisterNumber(Constraint, &SystemZ::FP128BitRegClass,
1175 SystemZMC::FP128Regs, 16);
1176 return parseRegisterNumber(Constraint, &SystemZ::FP64BitRegClass,
1177 SystemZMC::FP64Regs, 16);
1178 }
1179 if (Constraint[1] == 'v') {
1180 if (!Subtarget.hasVector())
1181 return std::make_pair(
1182 0u, static_cast<const TargetRegisterClass *>(nullptr));
1183 if (VT == MVT::f32)
1184 return parseRegisterNumber(Constraint, &SystemZ::VR32BitRegClass,
1185 SystemZMC::VR32Regs, 32);
1186 if (VT == MVT::f64)
1187 return parseRegisterNumber(Constraint, &SystemZ::VR64BitRegClass,
1188 SystemZMC::VR64Regs, 32);
1189 return parseRegisterNumber(Constraint, &SystemZ::VR128BitRegClass,
1190 SystemZMC::VR128Regs, 32);
1191 }
1192 }
1193 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
1194}
1195
1196// FIXME? Maybe this could be a TableGen attribute on some registers and
1197// this table could be generated automatically from RegInfo.
1198Register SystemZTargetLowering::getRegisterByName(const char *RegName, LLT VT,
1199 const MachineFunction &MF) const {
1200
1201 Register Reg = StringSwitch<Register>(RegName)
1202 .Case("r15", SystemZ::R15D)
1203 .Default(0);
1204 if (Reg)
1205 return Reg;
1206 report_fatal_error("Invalid register name global variable");
1207}
1208
1209void SystemZTargetLowering::
1210LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
1211 std::vector<SDValue> &Ops,
1212 SelectionDAG &DAG) const {
1213 // Only support length 1 constraints for now.
1214 if (Constraint.length() == 1) {
1215 switch (Constraint[0]) {
1216 case 'I': // Unsigned 8-bit constant
1217 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1218 if (isUInt<8>(C->getZExtValue()))
1219 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1220 Op.getValueType()));
1221 return;
1222
1223 case 'J': // Unsigned 12-bit constant
1224 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1225 if (isUInt<12>(C->getZExtValue()))
1226 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1227 Op.getValueType()));
1228 return;
1229
1230 case 'K': // Signed 16-bit constant
1231 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1232 if (isInt<16>(C->getSExtValue()))
1233 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
1234 Op.getValueType()));
1235 return;
1236
1237 case 'L': // Signed 20-bit displacement (on all targets we support)
1238 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1239 if (isInt<20>(C->getSExtValue()))
1240 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
1241 Op.getValueType()));
1242 return;
1243
1244 case 'M': // 0x7fffffff
1245 if (auto *C = dyn_cast<ConstantSDNode>(Op))
1246 if (C->getZExtValue() == 0x7fffffff)
1247 Ops.push_back(DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
1248 Op.getValueType()));
1249 return;
1250 }
1251 }
1252 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
1253}
1254
1255//===----------------------------------------------------------------------===//
1256// Calling conventions
1257//===----------------------------------------------------------------------===//
1258
1259#include "SystemZGenCallingConv.inc"
1260
1261const MCPhysReg *SystemZTargetLowering::getScratchRegisters(
1262 CallingConv::ID) const {
1263 static const MCPhysReg ScratchRegs[] = { SystemZ::R0D, SystemZ::R1D,
1264 SystemZ::R14D, 0 };
1265 return ScratchRegs;
1266}
1267
1268bool SystemZTargetLowering::allowTruncateForTailCall(Type *FromType,
1269 Type *ToType) const {
1270 return isTruncateFree(FromType, ToType);
1271}
1272
1273bool SystemZTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
1274 return CI->isTailCall();
1275}
1276
1277// We do not yet support 128-bit single-element vector types. If the user
1278// attempts to use such types as function argument or return type, prefer
1279// to error out instead of emitting code violating the ABI.
1280static void VerifyVectorType(MVT VT, EVT ArgVT) {
1281 if (ArgVT.isVector() && !VT.isVector())
1282 report_fatal_error("Unsupported vector argument or return type");
1283}
1284
1285static void VerifyVectorTypes(const SmallVectorImpl<ISD::InputArg> &Ins) {
1286 for (unsigned i = 0; i < Ins.size(); ++i)
1287 VerifyVectorType(Ins[i].VT, Ins[i].ArgVT);
1288}
1289
1290static void VerifyVectorTypes(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1291 for (unsigned i = 0; i < Outs.size(); ++i)
1292 VerifyVectorType(Outs[i].VT, Outs[i].ArgVT);
1293}
1294
1295// Value is a value that has been passed to us in the location described by VA
1296// (and so has type VA.getLocVT()). Convert Value to VA.getValVT(), chaining
1297// any loads onto Chain.
1298static SDValue convertLocVTToValVT(SelectionDAG &DAG, const SDLoc &DL,
1299 CCValAssign &VA, SDValue Chain,
1300 SDValue Value) {
1301 // If the argument has been promoted from a smaller type, insert an
1302 // assertion to capture this.
1303 if (VA.getLocInfo() == CCValAssign::SExt)
1304 Value = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Value,
1305 DAG.getValueType(VA.getValVT()));
1306 else if (VA.getLocInfo() == CCValAssign::ZExt)
1307 Value = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Value,
1308 DAG.getValueType(VA.getValVT()));
1309
1310 if (VA.isExtInLoc())
1311 Value = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Value);
1312 else if (VA.getLocInfo() == CCValAssign::BCvt) {
1313 // If this is a short vector argument loaded from the stack,
1314 // extend from i64 to full vector size and then bitcast.
1315 assert(VA.getLocVT() == MVT::i64)((VA.getLocVT() == MVT::i64) ? static_cast<void> (0) : __assert_fail
("VA.getLocVT() == MVT::i64", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1315, __PRETTY_FUNCTION__))
;
1316 assert(VA.getValVT().isVector())((VA.getValVT().isVector()) ? static_cast<void> (0) : __assert_fail
("VA.getValVT().isVector()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1316, __PRETTY_FUNCTION__))
;
1317 Value = DAG.getBuildVector(MVT::v2i64, DL, {Value, DAG.getUNDEF(MVT::i64)});
1318 Value = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Value);
1319 } else
1320 assert(VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo")((VA.getLocInfo() == CCValAssign::Full && "Unsupported getLocInfo"
) ? static_cast<void> (0) : __assert_fail ("VA.getLocInfo() == CCValAssign::Full && \"Unsupported getLocInfo\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1320, __PRETTY_FUNCTION__))
;
1321 return Value;
1322}
1323
1324// Value is a value of type VA.getValVT() that we need to copy into
1325// the location described by VA. Return a copy of Value converted to
1326// VA.getValVT(). The caller is responsible for handling indirect values.
1327static SDValue convertValVTToLocVT(SelectionDAG &DAG, const SDLoc &DL,
1328 CCValAssign &VA, SDValue Value) {
1329 switch (VA.getLocInfo()) {
1330 case CCValAssign::SExt:
1331 return DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Value);
1332 case CCValAssign::ZExt:
1333 return DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Value);
1334 case CCValAssign::AExt:
1335 return DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Value);
1336 case CCValAssign::BCvt:
1337 // If this is a short vector argument to be stored to the stack,
1338 // bitcast to v2i64 and then extract first element.
1339 assert(VA.getLocVT() == MVT::i64)((VA.getLocVT() == MVT::i64) ? static_cast<void> (0) : __assert_fail
("VA.getLocVT() == MVT::i64", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1339, __PRETTY_FUNCTION__))
;
1340 assert(VA.getValVT().isVector())((VA.getValVT().isVector()) ? static_cast<void> (0) : __assert_fail
("VA.getValVT().isVector()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1340, __PRETTY_FUNCTION__))
;
1341 Value = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Value);
1342 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VA.getLocVT(), Value,
1343 DAG.getConstant(0, DL, MVT::i32));
1344 case CCValAssign::Full:
1345 return Value;
1346 default:
1347 llvm_unreachable("Unhandled getLocInfo()")::llvm::llvm_unreachable_internal("Unhandled getLocInfo()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1347)
;
1348 }
1349}
1350
1351SDValue SystemZTargetLowering::LowerFormalArguments(
1352 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
1353 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1354 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1355 MachineFunction &MF = DAG.getMachineFunction();
1356 MachineFrameInfo &MFI = MF.getFrameInfo();
1357 MachineRegisterInfo &MRI = MF.getRegInfo();
1358 SystemZMachineFunctionInfo *FuncInfo =
1359 MF.getInfo<SystemZMachineFunctionInfo>();
1360 auto *TFL =
1361 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
1362 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1363
1364 // Detect unsupported vector argument types.
1365 if (Subtarget.hasVector())
1366 VerifyVectorTypes(Ins);
1367
1368 // Assign locations to all of the incoming arguments.
1369 SmallVector<CCValAssign, 16> ArgLocs;
1370 SystemZCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1371 CCInfo.AnalyzeFormalArguments(Ins, CC_SystemZ);
1372
1373 unsigned NumFixedGPRs = 0;
1374 unsigned NumFixedFPRs = 0;
1375 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1376 SDValue ArgValue;
1377 CCValAssign &VA = ArgLocs[I];
1378 EVT LocVT = VA.getLocVT();
1379 if (VA.isRegLoc()) {
1380 // Arguments passed in registers
1381 const TargetRegisterClass *RC;
1382 switch (LocVT.getSimpleVT().SimpleTy) {
1383 default:
1384 // Integers smaller than i64 should be promoted to i64.
1385 llvm_unreachable("Unexpected argument type")::llvm::llvm_unreachable_internal("Unexpected argument type",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1385)
;
1386 case MVT::i32:
1387 NumFixedGPRs += 1;
1388 RC = &SystemZ::GR32BitRegClass;
1389 break;
1390 case MVT::i64:
1391 NumFixedGPRs += 1;
1392 RC = &SystemZ::GR64BitRegClass;
1393 break;
1394 case MVT::f32:
1395 NumFixedFPRs += 1;
1396 RC = &SystemZ::FP32BitRegClass;
1397 break;
1398 case MVT::f64:
1399 NumFixedFPRs += 1;
1400 RC = &SystemZ::FP64BitRegClass;
1401 break;
1402 case MVT::v16i8:
1403 case MVT::v8i16:
1404 case MVT::v4i32:
1405 case MVT::v2i64:
1406 case MVT::v4f32:
1407 case MVT::v2f64:
1408 RC = &SystemZ::VR128BitRegClass;
1409 break;
1410 }
1411
1412 Register VReg = MRI.createVirtualRegister(RC);
1413 MRI.addLiveIn(VA.getLocReg(), VReg);
1414 ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
1415 } else {
1416 assert(VA.isMemLoc() && "Argument not register or memory")((VA.isMemLoc() && "Argument not register or memory")
? static_cast<void> (0) : __assert_fail ("VA.isMemLoc() && \"Argument not register or memory\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1416, __PRETTY_FUNCTION__))
;
1417
1418 // Create the frame index object for this incoming parameter.
1419 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
1420 VA.getLocMemOffset(), true);
1421
1422 // Create the SelectionDAG nodes corresponding to a load
1423 // from this parameter. Unpromoted ints and floats are
1424 // passed as right-justified 8-byte values.
1425 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1426 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1427 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
1428 DAG.getIntPtrConstant(4, DL));
1429 ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
1430 MachinePointerInfo::getFixedStack(MF, FI));
1431 }
1432
1433 // Convert the value of the argument register into the value that's
1434 // being passed.
1435 if (VA.getLocInfo() == CCValAssign::Indirect) {
1436 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
1437 MachinePointerInfo()));
1438 // If the original argument was split (e.g. i128), we need
1439 // to load all parts of it here (using the same address).
1440 unsigned ArgIndex = Ins[I].OrigArgIndex;
1441 assert (Ins[I].PartOffset == 0)((Ins[I].PartOffset == 0) ? static_cast<void> (0) : __assert_fail
("Ins[I].PartOffset == 0", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1441, __PRETTY_FUNCTION__))
;
1442 while (I + 1 != E && Ins[I + 1].OrigArgIndex == ArgIndex) {
1443 CCValAssign &PartVA = ArgLocs[I + 1];
1444 unsigned PartOffset = Ins[I + 1].PartOffset;
1445 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue,
1446 DAG.getIntPtrConstant(PartOffset, DL));
1447 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
1448 MachinePointerInfo()));
1449 ++I;
1450 }
1451 } else
1452 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, ArgValue));
1453 }
1454
1455 if (IsVarArg) {
1456 // Save the number of non-varargs registers for later use by va_start, etc.
1457 FuncInfo->setVarArgsFirstGPR(NumFixedGPRs);
1458 FuncInfo->setVarArgsFirstFPR(NumFixedFPRs);
1459
1460 // Likewise the address (in the form of a frame index) of where the
1461 // first stack vararg would be. The 1-byte size here is arbitrary.
1462 int64_t StackSize = CCInfo.getNextStackOffset();
1463 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
1464
1465 // ...and a similar frame index for the caller-allocated save area
1466 // that will be used to store the incoming registers.
1467 int64_t RegSaveOffset =
1468 -SystemZMC::CallFrameSize + TFL->getRegSpillOffset(MF, SystemZ::R2D) - 16;
1469 unsigned RegSaveIndex = MFI.CreateFixedObject(1, RegSaveOffset, true);
1470 FuncInfo->setRegSaveFrameIndex(RegSaveIndex);
1471
1472 // Store the FPR varargs in the reserved frame slots. (We store the
1473 // GPRs as part of the prologue.)
1474 if (NumFixedFPRs < SystemZ::NumArgFPRs && !useSoftFloat()) {
1475 SDValue MemOps[SystemZ::NumArgFPRs];
1476 for (unsigned I = NumFixedFPRs; I < SystemZ::NumArgFPRs; ++I) {
1477 unsigned Offset = TFL->getRegSpillOffset(MF, SystemZ::ArgFPRs[I]);
1478 int FI =
1479 MFI.CreateFixedObject(8, -SystemZMC::CallFrameSize + Offset, true);
1480 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
1481 unsigned VReg = MF.addLiveIn(SystemZ::ArgFPRs[I],
1482 &SystemZ::FP64BitRegClass);
1483 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f64);
1484 MemOps[I] = DAG.getStore(ArgValue.getValue(1), DL, ArgValue, FIN,
1485 MachinePointerInfo::getFixedStack(MF, FI));
1486 }
1487 // Join the stores, which are independent of one another.
1488 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1489 makeArrayRef(&MemOps[NumFixedFPRs],
1490 SystemZ::NumArgFPRs-NumFixedFPRs));
1491 }
1492 }
1493
1494 return Chain;
1495}
1496
1497static bool canUseSiblingCall(const CCState &ArgCCInfo,
1498 SmallVectorImpl<CCValAssign> &ArgLocs,
1499 SmallVectorImpl<ISD::OutputArg> &Outs) {
1500 // Punt if there are any indirect or stack arguments, or if the call
1501 // needs the callee-saved argument register R6, or if the call uses
1502 // the callee-saved register arguments SwiftSelf and SwiftError.
1503 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1504 CCValAssign &VA = ArgLocs[I];
1505 if (VA.getLocInfo() == CCValAssign::Indirect)
1506 return false;
1507 if (!VA.isRegLoc())
1508 return false;
1509 Register Reg = VA.getLocReg();
1510 if (Reg == SystemZ::R6H || Reg == SystemZ::R6L || Reg == SystemZ::R6D)
1511 return false;
1512 if (Outs[I].Flags.isSwiftSelf() || Outs[I].Flags.isSwiftError())
1513 return false;
1514 }
1515 return true;
1516}
1517
1518SDValue
1519SystemZTargetLowering::LowerCall(CallLoweringInfo &CLI,
1520 SmallVectorImpl<SDValue> &InVals) const {
1521 SelectionDAG &DAG = CLI.DAG;
1522 SDLoc &DL = CLI.DL;
1523 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1524 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1525 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1526 SDValue Chain = CLI.Chain;
1527 SDValue Callee = CLI.Callee;
1528 bool &IsTailCall = CLI.IsTailCall;
1529 CallingConv::ID CallConv = CLI.CallConv;
1530 bool IsVarArg = CLI.IsVarArg;
1531 MachineFunction &MF = DAG.getMachineFunction();
1532 EVT PtrVT = getPointerTy(MF.getDataLayout());
1533
1534 // Detect unsupported vector argument and return types.
1535 if (Subtarget.hasVector()) {
1536 VerifyVectorTypes(Outs);
1537 VerifyVectorTypes(Ins);
1538 }
1539
1540 // Analyze the operands of the call, assigning locations to each operand.
1541 SmallVector<CCValAssign, 16> ArgLocs;
1542 SystemZCCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
1543 ArgCCInfo.AnalyzeCallOperands(Outs, CC_SystemZ);
1544
1545 // We don't support GuaranteedTailCallOpt, only automatically-detected
1546 // sibling calls.
1547 if (IsTailCall && !canUseSiblingCall(ArgCCInfo, ArgLocs, Outs))
1548 IsTailCall = false;
1549
1550 // Get a count of how many bytes are to be pushed on the stack.
1551 unsigned NumBytes = ArgCCInfo.getNextStackOffset();
1552
1553 // Mark the start of the call.
1554 if (!IsTailCall)
1555 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
1556
1557 // Copy argument values to their designated locations.
1558 SmallVector<std::pair<unsigned, SDValue>, 9> RegsToPass;
1559 SmallVector<SDValue, 8> MemOpChains;
1560 SDValue StackPtr;
1561 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
1562 CCValAssign &VA = ArgLocs[I];
1563 SDValue ArgValue = OutVals[I];
1564
1565 if (VA.getLocInfo() == CCValAssign::Indirect) {
1566 // Store the argument in a stack slot and pass its address.
1567 SDValue SpillSlot = DAG.CreateStackTemporary(Outs[I].ArgVT);
1568 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1569 MemOpChains.push_back(
1570 DAG.getStore(Chain, DL, ArgValue, SpillSlot,
1571 MachinePointerInfo::getFixedStack(MF, FI)));
1572 // If the original argument was split (e.g. i128), we need
1573 // to store all parts of it here (and pass just one address).
1574 unsigned ArgIndex = Outs[I].OrigArgIndex;
1575 assert (Outs[I].PartOffset == 0)((Outs[I].PartOffset == 0) ? static_cast<void> (0) : __assert_fail
("Outs[I].PartOffset == 0", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1575, __PRETTY_FUNCTION__))
;
1576 while (I + 1 != E && Outs[I + 1].OrigArgIndex == ArgIndex) {
1577 SDValue PartValue = OutVals[I + 1];
1578 unsigned PartOffset = Outs[I + 1].PartOffset;
1579 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot,
1580 DAG.getIntPtrConstant(PartOffset, DL));
1581 MemOpChains.push_back(
1582 DAG.getStore(Chain, DL, PartValue, Address,
1583 MachinePointerInfo::getFixedStack(MF, FI)));
1584 ++I;
1585 }
1586 ArgValue = SpillSlot;
1587 } else
1588 ArgValue = convertValVTToLocVT(DAG, DL, VA, ArgValue);
1589
1590 if (VA.isRegLoc())
1591 // Queue up the argument copies and emit them at the end.
1592 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
1593 else {
1594 assert(VA.isMemLoc() && "Argument not register or memory")((VA.isMemLoc() && "Argument not register or memory")
? static_cast<void> (0) : __assert_fail ("VA.isMemLoc() && \"Argument not register or memory\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1594, __PRETTY_FUNCTION__))
;
1595
1596 // Work out the address of the stack slot. Unpromoted ints and
1597 // floats are passed as right-justified 8-byte values.
1598 if (!StackPtr.getNode())
1599 StackPtr = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, PtrVT);
1600 unsigned Offset = SystemZMC::CallFrameSize + VA.getLocMemOffset();
1601 if (VA.getLocVT() == MVT::i32 || VA.getLocVT() == MVT::f32)
1602 Offset += 4;
1603 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
1604 DAG.getIntPtrConstant(Offset, DL));
1605
1606 // Emit the store.
1607 MemOpChains.push_back(
1608 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
1609 }
1610 }
1611
1612 // Join the stores, which are independent of one another.
1613 if (!MemOpChains.empty())
1614 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
1615
1616 // Accept direct calls by converting symbolic call addresses to the
1617 // associated Target* opcodes. Force %r1 to be used for indirect
1618 // tail calls.
1619 SDValue Glue;
1620 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1621 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, PtrVT);
1622 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1623 } else if (auto *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1624 Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT);
1625 Callee = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Callee);
1626 } else if (IsTailCall) {
1627 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R1D, Callee, Glue);
1628 Glue = Chain.getValue(1);
1629 Callee = DAG.getRegister(SystemZ::R1D, Callee.getValueType());
1630 }
1631
1632 // Build a sequence of copy-to-reg nodes, chained and glued together.
1633 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I) {
1634 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[I].first,
1635 RegsToPass[I].second, Glue);
1636 Glue = Chain.getValue(1);
1637 }
1638
1639 // The first call operand is the chain and the second is the target address.
1640 SmallVector<SDValue, 8> Ops;
1641 Ops.push_back(Chain);
1642 Ops.push_back(Callee);
1643
1644 // Add argument registers to the end of the list so that they are
1645 // known live into the call.
1646 for (unsigned I = 0, E = RegsToPass.size(); I != E; ++I)
1647 Ops.push_back(DAG.getRegister(RegsToPass[I].first,
1648 RegsToPass[I].second.getValueType()));
1649
1650 // Add a register mask operand representing the call-preserved registers.
1651 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1652 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
1653 assert(Mask && "Missing call preserved mask for calling convention")((Mask && "Missing call preserved mask for calling convention"
) ? static_cast<void> (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1653, __PRETTY_FUNCTION__))
;
1654 Ops.push_back(DAG.getRegisterMask(Mask));
1655
1656 // Glue the call to the argument copies, if any.
1657 if (Glue.getNode())
1658 Ops.push_back(Glue);
1659
1660 // Emit the call.
1661 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1662 if (IsTailCall)
1663 return DAG.getNode(SystemZISD::SIBCALL, DL, NodeTys, Ops);
1664 Chain = DAG.getNode(SystemZISD::CALL, DL, NodeTys, Ops);
1665 Glue = Chain.getValue(1);
1666
1667 // Mark the end of the call, which is glued to the call itself.
1668 Chain = DAG.getCALLSEQ_END(Chain,
1669 DAG.getConstant(NumBytes, DL, PtrVT, true),
1670 DAG.getConstant(0, DL, PtrVT, true),
1671 Glue, DL);
1672 Glue = Chain.getValue(1);
1673
1674 // Assign locations to each value returned by this call.
1675 SmallVector<CCValAssign, 16> RetLocs;
1676 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1677 RetCCInfo.AnalyzeCallResult(Ins, RetCC_SystemZ);
1678
1679 // Copy all of the result registers out of their specified physreg.
1680 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1681 CCValAssign &VA = RetLocs[I];
1682
1683 // Copy the value out, gluing the copy to the end of the call sequence.
1684 SDValue RetValue = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(),
1685 VA.getLocVT(), Glue);
1686 Chain = RetValue.getValue(1);
1687 Glue = RetValue.getValue(2);
1688
1689 // Convert the value of the return register into the value that's
1690 // being returned.
1691 InVals.push_back(convertLocVTToValVT(DAG, DL, VA, Chain, RetValue));
1692 }
1693
1694 return Chain;
1695}
1696
1697bool SystemZTargetLowering::
1698CanLowerReturn(CallingConv::ID CallConv,
1699 MachineFunction &MF, bool isVarArg,
1700 const SmallVectorImpl<ISD::OutputArg> &Outs,
1701 LLVMContext &Context) const {
1702 // Detect unsupported vector return types.
1703 if (Subtarget.hasVector())
1704 VerifyVectorTypes(Outs);
1705
1706 // Special case that we cannot easily detect in RetCC_SystemZ since
1707 // i128 is not a legal type.
1708 for (auto &Out : Outs)
1709 if (Out.ArgVT == MVT::i128)
1710 return false;
1711
1712 SmallVector<CCValAssign, 16> RetLocs;
1713 CCState RetCCInfo(CallConv, isVarArg, MF, RetLocs, Context);
1714 return RetCCInfo.CheckReturn(Outs, RetCC_SystemZ);
1715}
1716
1717SDValue
1718SystemZTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1719 bool IsVarArg,
1720 const SmallVectorImpl<ISD::OutputArg> &Outs,
1721 const SmallVectorImpl<SDValue> &OutVals,
1722 const SDLoc &DL, SelectionDAG &DAG) const {
1723 MachineFunction &MF = DAG.getMachineFunction();
1724
1725 // Detect unsupported vector return types.
1726 if (Subtarget.hasVector())
1727 VerifyVectorTypes(Outs);
1728
1729 // Assign locations to each returned value.
1730 SmallVector<CCValAssign, 16> RetLocs;
1731 CCState RetCCInfo(CallConv, IsVarArg, MF, RetLocs, *DAG.getContext());
1732 RetCCInfo.AnalyzeReturn(Outs, RetCC_SystemZ);
1733
1734 // Quick exit for void returns
1735 if (RetLocs.empty())
1736 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, Chain);
1737
1738 if (CallConv == CallingConv::GHC)
1739 report_fatal_error("GHC functions return void only");
1740
1741 // Copy the result values into the output registers.
1742 SDValue Glue;
1743 SmallVector<SDValue, 4> RetOps;
1744 RetOps.push_back(Chain);
1745 for (unsigned I = 0, E = RetLocs.size(); I != E; ++I) {
1746 CCValAssign &VA = RetLocs[I];
1747 SDValue RetValue = OutVals[I];
1748
1749 // Make the return register live on exit.
1750 assert(VA.isRegLoc() && "Can only return in registers!")((VA.isRegLoc() && "Can only return in registers!") ?
static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1750, __PRETTY_FUNCTION__))
;
1751
1752 // Promote the value as required.
1753 RetValue = convertValVTToLocVT(DAG, DL, VA, RetValue);
1754
1755 // Chain and glue the copies together.
1756 Register Reg = VA.getLocReg();
1757 Chain = DAG.getCopyToReg(Chain, DL, Reg, RetValue, Glue);
1758 Glue = Chain.getValue(1);
1759 RetOps.push_back(DAG.getRegister(Reg, VA.getLocVT()));
1760 }
1761
1762 // Update chain and glue.
1763 RetOps[0] = Chain;
1764 if (Glue.getNode())
1765 RetOps.push_back(Glue);
1766
1767 return DAG.getNode(SystemZISD::RET_FLAG, DL, MVT::Other, RetOps);
1768}
1769
1770// Return true if Op is an intrinsic node with chain that returns the CC value
1771// as its only (other) argument. Provide the associated SystemZISD opcode and
1772// the mask of valid CC values if so.
1773static bool isIntrinsicWithCCAndChain(SDValue Op, unsigned &Opcode,
1774 unsigned &CCValid) {
1775 unsigned Id = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1776 switch (Id) {
1777 case Intrinsic::s390_tbegin:
1778 Opcode = SystemZISD::TBEGIN;
1779 CCValid = SystemZ::CCMASK_TBEGIN;
1780 return true;
1781
1782 case Intrinsic::s390_tbegin_nofloat:
1783 Opcode = SystemZISD::TBEGIN_NOFLOAT;
1784 CCValid = SystemZ::CCMASK_TBEGIN;
1785 return true;
1786
1787 case Intrinsic::s390_tend:
1788 Opcode = SystemZISD::TEND;
1789 CCValid = SystemZ::CCMASK_TEND;
1790 return true;
1791
1792 default:
1793 return false;
1794 }
1795}
1796
1797// Return true if Op is an intrinsic node without chain that returns the
1798// CC value as its final argument. Provide the associated SystemZISD
1799// opcode and the mask of valid CC values if so.
1800static bool isIntrinsicWithCC(SDValue Op, unsigned &Opcode, unsigned &CCValid) {
1801 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1802 switch (Id) {
1803 case Intrinsic::s390_vpkshs:
1804 case Intrinsic::s390_vpksfs:
1805 case Intrinsic::s390_vpksgs:
1806 Opcode = SystemZISD::PACKS_CC;
1807 CCValid = SystemZ::CCMASK_VCMP;
1808 return true;
1809
1810 case Intrinsic::s390_vpklshs:
1811 case Intrinsic::s390_vpklsfs:
1812 case Intrinsic::s390_vpklsgs:
1813 Opcode = SystemZISD::PACKLS_CC;
1814 CCValid = SystemZ::CCMASK_VCMP;
1815 return true;
1816
1817 case Intrinsic::s390_vceqbs:
1818 case Intrinsic::s390_vceqhs:
1819 case Intrinsic::s390_vceqfs:
1820 case Intrinsic::s390_vceqgs:
1821 Opcode = SystemZISD::VICMPES;
1822 CCValid = SystemZ::CCMASK_VCMP;
1823 return true;
1824
1825 case Intrinsic::s390_vchbs:
1826 case Intrinsic::s390_vchhs:
1827 case Intrinsic::s390_vchfs:
1828 case Intrinsic::s390_vchgs:
1829 Opcode = SystemZISD::VICMPHS;
1830 CCValid = SystemZ::CCMASK_VCMP;
1831 return true;
1832
1833 case Intrinsic::s390_vchlbs:
1834 case Intrinsic::s390_vchlhs:
1835 case Intrinsic::s390_vchlfs:
1836 case Intrinsic::s390_vchlgs:
1837 Opcode = SystemZISD::VICMPHLS;
1838 CCValid = SystemZ::CCMASK_VCMP;
1839 return true;
1840
1841 case Intrinsic::s390_vtm:
1842 Opcode = SystemZISD::VTM;
1843 CCValid = SystemZ::CCMASK_VCMP;
1844 return true;
1845
1846 case Intrinsic::s390_vfaebs:
1847 case Intrinsic::s390_vfaehs:
1848 case Intrinsic::s390_vfaefs:
1849 Opcode = SystemZISD::VFAE_CC;
1850 CCValid = SystemZ::CCMASK_ANY;
1851 return true;
1852
1853 case Intrinsic::s390_vfaezbs:
1854 case Intrinsic::s390_vfaezhs:
1855 case Intrinsic::s390_vfaezfs:
1856 Opcode = SystemZISD::VFAEZ_CC;
1857 CCValid = SystemZ::CCMASK_ANY;
1858 return true;
1859
1860 case Intrinsic::s390_vfeebs:
1861 case Intrinsic::s390_vfeehs:
1862 case Intrinsic::s390_vfeefs:
1863 Opcode = SystemZISD::VFEE_CC;
1864 CCValid = SystemZ::CCMASK_ANY;
1865 return true;
1866
1867 case Intrinsic::s390_vfeezbs:
1868 case Intrinsic::s390_vfeezhs:
1869 case Intrinsic::s390_vfeezfs:
1870 Opcode = SystemZISD::VFEEZ_CC;
1871 CCValid = SystemZ::CCMASK_ANY;
1872 return true;
1873
1874 case Intrinsic::s390_vfenebs:
1875 case Intrinsic::s390_vfenehs:
1876 case Intrinsic::s390_vfenefs:
1877 Opcode = SystemZISD::VFENE_CC;
1878 CCValid = SystemZ::CCMASK_ANY;
1879 return true;
1880
1881 case Intrinsic::s390_vfenezbs:
1882 case Intrinsic::s390_vfenezhs:
1883 case Intrinsic::s390_vfenezfs:
1884 Opcode = SystemZISD::VFENEZ_CC;
1885 CCValid = SystemZ::CCMASK_ANY;
1886 return true;
1887
1888 case Intrinsic::s390_vistrbs:
1889 case Intrinsic::s390_vistrhs:
1890 case Intrinsic::s390_vistrfs:
1891 Opcode = SystemZISD::VISTR_CC;
1892 CCValid = SystemZ::CCMASK_0 | SystemZ::CCMASK_3;
1893 return true;
1894
1895 case Intrinsic::s390_vstrcbs:
1896 case Intrinsic::s390_vstrchs:
1897 case Intrinsic::s390_vstrcfs:
1898 Opcode = SystemZISD::VSTRC_CC;
1899 CCValid = SystemZ::CCMASK_ANY;
1900 return true;
1901
1902 case Intrinsic::s390_vstrczbs:
1903 case Intrinsic::s390_vstrczhs:
1904 case Intrinsic::s390_vstrczfs:
1905 Opcode = SystemZISD::VSTRCZ_CC;
1906 CCValid = SystemZ::CCMASK_ANY;
1907 return true;
1908
1909 case Intrinsic::s390_vstrsb:
1910 case Intrinsic::s390_vstrsh:
1911 case Intrinsic::s390_vstrsf:
1912 Opcode = SystemZISD::VSTRS_CC;
1913 CCValid = SystemZ::CCMASK_ANY;
1914 return true;
1915
1916 case Intrinsic::s390_vstrszb:
1917 case Intrinsic::s390_vstrszh:
1918 case Intrinsic::s390_vstrszf:
1919 Opcode = SystemZISD::VSTRSZ_CC;
1920 CCValid = SystemZ::CCMASK_ANY;
1921 return true;
1922
1923 case Intrinsic::s390_vfcedbs:
1924 case Intrinsic::s390_vfcesbs:
1925 Opcode = SystemZISD::VFCMPES;
1926 CCValid = SystemZ::CCMASK_VCMP;
1927 return true;
1928
1929 case Intrinsic::s390_vfchdbs:
1930 case Intrinsic::s390_vfchsbs:
1931 Opcode = SystemZISD::VFCMPHS;
1932 CCValid = SystemZ::CCMASK_VCMP;
1933 return true;
1934
1935 case Intrinsic::s390_vfchedbs:
1936 case Intrinsic::s390_vfchesbs:
1937 Opcode = SystemZISD::VFCMPHES;
1938 CCValid = SystemZ::CCMASK_VCMP;
1939 return true;
1940
1941 case Intrinsic::s390_vftcidb:
1942 case Intrinsic::s390_vftcisb:
1943 Opcode = SystemZISD::VFTCI;
1944 CCValid = SystemZ::CCMASK_VCMP;
1945 return true;
1946
1947 case Intrinsic::s390_tdc:
1948 Opcode = SystemZISD::TDC;
1949 CCValid = SystemZ::CCMASK_TDC;
1950 return true;
1951
1952 default:
1953 return false;
1954 }
1955}
1956
1957// Emit an intrinsic with chain and an explicit CC register result.
1958static SDNode *emitIntrinsicWithCCAndChain(SelectionDAG &DAG, SDValue Op,
1959 unsigned Opcode) {
1960 // Copy all operands except the intrinsic ID.
1961 unsigned NumOps = Op.getNumOperands();
1962 SmallVector<SDValue, 6> Ops;
1963 Ops.reserve(NumOps - 1);
1964 Ops.push_back(Op.getOperand(0));
1965 for (unsigned I = 2; I < NumOps; ++I)
1966 Ops.push_back(Op.getOperand(I));
1967
1968 assert(Op->getNumValues() == 2 && "Expected only CC result and chain")((Op->getNumValues() == 2 && "Expected only CC result and chain"
) ? static_cast<void> (0) : __assert_fail ("Op->getNumValues() == 2 && \"Expected only CC result and chain\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 1968, __PRETTY_FUNCTION__))
;
1969 SDVTList RawVTs = DAG.getVTList(MVT::i32, MVT::Other);
1970 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), RawVTs, Ops);
1971 SDValue OldChain = SDValue(Op.getNode(), 1);
1972 SDValue NewChain = SDValue(Intr.getNode(), 1);
1973 DAG.ReplaceAllUsesOfValueWith(OldChain, NewChain);
1974 return Intr.getNode();
1975}
1976
1977// Emit an intrinsic with an explicit CC register result.
1978static SDNode *emitIntrinsicWithCC(SelectionDAG &DAG, SDValue Op,
1979 unsigned Opcode) {
1980 // Copy all operands except the intrinsic ID.
1981 unsigned NumOps = Op.getNumOperands();
1982 SmallVector<SDValue, 6> Ops;
1983 Ops.reserve(NumOps - 1);
1984 for (unsigned I = 1; I < NumOps; ++I)
1985 Ops.push_back(Op.getOperand(I));
1986
1987 SDValue Intr = DAG.getNode(Opcode, SDLoc(Op), Op->getVTList(), Ops);
1988 return Intr.getNode();
1989}
1990
1991// CC is a comparison that will be implemented using an integer or
1992// floating-point comparison. Return the condition code mask for
1993// a branch on true. In the integer case, CCMASK_CMP_UO is set for
1994// unsigned comparisons and clear for signed ones. In the floating-point
1995// case, CCMASK_CMP_UO has its normal mask meaning (unordered).
1996static unsigned CCMaskForCondCode(ISD::CondCode CC) {
1997#define CONV(X) \
1998 case ISD::SET##X: return SystemZ::CCMASK_CMP_##X; \
1999 case ISD::SETO##X: return SystemZ::CCMASK_CMP_##X; \
2000 case ISD::SETU##X: return SystemZ::CCMASK_CMP_UO | SystemZ::CCMASK_CMP_##X
2001
2002 switch (CC) {
2003 default:
2004 llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2004)
;
2005
2006 CONV(EQ);
2007 CONV(NE);
2008 CONV(GT);
2009 CONV(GE);
2010 CONV(LT);
2011 CONV(LE);
2012
2013 case ISD::SETO: return SystemZ::CCMASK_CMP_O;
2014 case ISD::SETUO: return SystemZ::CCMASK_CMP_UO;
2015 }
2016#undef CONV
2017}
2018
2019// If C can be converted to a comparison against zero, adjust the operands
2020// as necessary.
2021static void adjustZeroCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2022 if (C.ICmpType == SystemZICMP::UnsignedOnly)
2023 return;
2024
2025 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1.getNode());
2026 if (!ConstOp1)
2027 return;
2028
2029 int64_t Value = ConstOp1->getSExtValue();
2030 if ((Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_GT) ||
2031 (Value == -1 && C.CCMask == SystemZ::CCMASK_CMP_LE) ||
2032 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_LT) ||
2033 (Value == 1 && C.CCMask == SystemZ::CCMASK_CMP_GE)) {
2034 C.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2035 C.Op1 = DAG.getConstant(0, DL, C.Op1.getValueType());
2036 }
2037}
2038
2039// If a comparison described by C is suitable for CLI(Y), CHHSI or CLHHSI,
2040// adjust the operands as necessary.
2041static void adjustSubwordCmp(SelectionDAG &DAG, const SDLoc &DL,
2042 Comparison &C) {
2043 // For us to make any changes, it must a comparison between a single-use
2044 // load and a constant.
2045 if (!C.Op0.hasOneUse() ||
2046 C.Op0.getOpcode() != ISD::LOAD ||
2047 C.Op1.getOpcode() != ISD::Constant)
2048 return;
2049
2050 // We must have an 8- or 16-bit load.
2051 auto *Load = cast<LoadSDNode>(C.Op0);
2052 unsigned NumBits = Load->getMemoryVT().getStoreSizeInBits();
2053 if (NumBits != 8 && NumBits != 16)
2054 return;
2055
2056 // The load must be an extending one and the constant must be within the
2057 // range of the unextended value.
2058 auto *ConstOp1 = cast<ConstantSDNode>(C.Op1);
2059 uint64_t Value = ConstOp1->getZExtValue();
2060 uint64_t Mask = (1 << NumBits) - 1;
2061 if (Load->getExtensionType() == ISD::SEXTLOAD) {
2062 // Make sure that ConstOp1 is in range of C.Op0.
2063 int64_t SignedValue = ConstOp1->getSExtValue();
2064 if (uint64_t(SignedValue) + (uint64_t(1) << (NumBits - 1)) > Mask)
2065 return;
2066 if (C.ICmpType != SystemZICMP::SignedOnly) {
2067 // Unsigned comparison between two sign-extended values is equivalent
2068 // to unsigned comparison between two zero-extended values.
2069 Value &= Mask;
2070 } else if (NumBits == 8) {
2071 // Try to treat the comparison as unsigned, so that we can use CLI.
2072 // Adjust CCMask and Value as necessary.
2073 if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_LT)
2074 // Test whether the high bit of the byte is set.
2075 Value = 127, C.CCMask = SystemZ::CCMASK_CMP_GT;
2076 else if (Value == 0 && C.CCMask == SystemZ::CCMASK_CMP_GE)
2077 // Test whether the high bit of the byte is clear.
2078 Value = 128, C.CCMask = SystemZ::CCMASK_CMP_LT;
2079 else
2080 // No instruction exists for this combination.
2081 return;
2082 C.ICmpType = SystemZICMP::UnsignedOnly;
2083 }
2084 } else if (Load->getExtensionType() == ISD::ZEXTLOAD) {
2085 if (Value > Mask)
2086 return;
2087 // If the constant is in range, we can use any comparison.
2088 C.ICmpType = SystemZICMP::Any;
2089 } else
2090 return;
2091
2092 // Make sure that the first operand is an i32 of the right extension type.
2093 ISD::LoadExtType ExtType = (C.ICmpType == SystemZICMP::SignedOnly ?
2094 ISD::SEXTLOAD :
2095 ISD::ZEXTLOAD);
2096 if (C.Op0.getValueType() != MVT::i32 ||
2097 Load->getExtensionType() != ExtType) {
2098 C.Op0 = DAG.getExtLoad(ExtType, SDLoc(Load), MVT::i32, Load->getChain(),
2099 Load->getBasePtr(), Load->getPointerInfo(),
2100 Load->getMemoryVT(), Load->getAlignment(),
2101 Load->getMemOperand()->getFlags());
2102 // Update the chain uses.
2103 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), C.Op0.getValue(1));
2104 }
2105
2106 // Make sure that the second operand is an i32 with the right value.
2107 if (C.Op1.getValueType() != MVT::i32 ||
2108 Value != ConstOp1->getZExtValue())
2109 C.Op1 = DAG.getConstant(Value, DL, MVT::i32);
2110}
2111
2112// Return true if Op is either an unextended load, or a load suitable
2113// for integer register-memory comparisons of type ICmpType.
2114static bool isNaturalMemoryOperand(SDValue Op, unsigned ICmpType) {
2115 auto *Load = dyn_cast<LoadSDNode>(Op.getNode());
2116 if (Load) {
2117 // There are no instructions to compare a register with a memory byte.
2118 if (Load->getMemoryVT() == MVT::i8)
2119 return false;
2120 // Otherwise decide on extension type.
2121 switch (Load->getExtensionType()) {
2122 case ISD::NON_EXTLOAD:
2123 return true;
2124 case ISD::SEXTLOAD:
2125 return ICmpType != SystemZICMP::UnsignedOnly;
2126 case ISD::ZEXTLOAD:
2127 return ICmpType != SystemZICMP::SignedOnly;
2128 default:
2129 break;
2130 }
2131 }
2132 return false;
2133}
2134
2135// Return true if it is better to swap the operands of C.
2136static bool shouldSwapCmpOperands(const Comparison &C) {
2137 // Leave f128 comparisons alone, since they have no memory forms.
2138 if (C.Op0.getValueType() == MVT::f128)
2139 return false;
2140
2141 // Always keep a floating-point constant second, since comparisons with
2142 // zero can use LOAD TEST and comparisons with other constants make a
2143 // natural memory operand.
2144 if (isa<ConstantFPSDNode>(C.Op1))
2145 return false;
2146
2147 // Never swap comparisons with zero since there are many ways to optimize
2148 // those later.
2149 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2150 if (ConstOp1 && ConstOp1->getZExtValue() == 0)
2151 return false;
2152
2153 // Also keep natural memory operands second if the loaded value is
2154 // only used here. Several comparisons have memory forms.
2155 if (isNaturalMemoryOperand(C.Op1, C.ICmpType) && C.Op1.hasOneUse())
2156 return false;
2157
2158 // Look for cases where Cmp0 is a single-use load and Cmp1 isn't.
2159 // In that case we generally prefer the memory to be second.
2160 if (isNaturalMemoryOperand(C.Op0, C.ICmpType) && C.Op0.hasOneUse()) {
2161 // The only exceptions are when the second operand is a constant and
2162 // we can use things like CHHSI.
2163 if (!ConstOp1)
2164 return true;
2165 // The unsigned memory-immediate instructions can handle 16-bit
2166 // unsigned integers.
2167 if (C.ICmpType != SystemZICMP::SignedOnly &&
2168 isUInt<16>(ConstOp1->getZExtValue()))
2169 return false;
2170 // The signed memory-immediate instructions can handle 16-bit
2171 // signed integers.
2172 if (C.ICmpType != SystemZICMP::UnsignedOnly &&
2173 isInt<16>(ConstOp1->getSExtValue()))
2174 return false;
2175 return true;
2176 }
2177
2178 // Try to promote the use of CGFR and CLGFR.
2179 unsigned Opcode0 = C.Op0.getOpcode();
2180 if (C.ICmpType != SystemZICMP::UnsignedOnly && Opcode0 == ISD::SIGN_EXTEND)
2181 return true;
2182 if (C.ICmpType != SystemZICMP::SignedOnly && Opcode0 == ISD::ZERO_EXTEND)
2183 return true;
2184 if (C.ICmpType != SystemZICMP::SignedOnly &&
2185 Opcode0 == ISD::AND &&
2186 C.Op0.getOperand(1).getOpcode() == ISD::Constant &&
2187 cast<ConstantSDNode>(C.Op0.getOperand(1))->getZExtValue() == 0xffffffff)
2188 return true;
2189
2190 return false;
2191}
2192
2193// Return a version of comparison CC mask CCMask in which the LT and GT
2194// actions are swapped.
2195static unsigned reverseCCMask(unsigned CCMask) {
2196 return ((CCMask & SystemZ::CCMASK_CMP_EQ) |
2197 (CCMask & SystemZ::CCMASK_CMP_GT ? SystemZ::CCMASK_CMP_LT : 0) |
2198 (CCMask & SystemZ::CCMASK_CMP_LT ? SystemZ::CCMASK_CMP_GT : 0) |
2199 (CCMask & SystemZ::CCMASK_CMP_UO));
2200}
2201
2202// Check whether C tests for equality between X and Y and whether X - Y
2203// or Y - X is also computed. In that case it's better to compare the
2204// result of the subtraction against zero.
2205static void adjustForSubtraction(SelectionDAG &DAG, const SDLoc &DL,
2206 Comparison &C) {
2207 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2208 C.CCMask == SystemZ::CCMASK_CMP_NE) {
2209 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
2210 SDNode *N = *I;
2211 if (N->getOpcode() == ISD::SUB &&
2212 ((N->getOperand(0) == C.Op0 && N->getOperand(1) == C.Op1) ||
2213 (N->getOperand(0) == C.Op1 && N->getOperand(1) == C.Op0))) {
2214 C.Op0 = SDValue(N, 0);
2215 C.Op1 = DAG.getConstant(0, DL, N->getValueType(0));
2216 return;
2217 }
2218 }
2219 }
2220}
2221
2222// Check whether C compares a floating-point value with zero and if that
2223// floating-point value is also negated. In this case we can use the
2224// negation to set CC, so avoiding separate LOAD AND TEST and
2225// LOAD (NEGATIVE/COMPLEMENT) instructions.
2226static void adjustForFNeg(Comparison &C) {
2227 // This optimization is invalid for strict comparisons, since FNEG
2228 // does not raise any exceptions.
2229 if (C.Chain)
2230 return;
2231 auto *C1 = dyn_cast<ConstantFPSDNode>(C.Op1);
2232 if (C1 && C1->isZero()) {
2233 for (auto I = C.Op0->use_begin(), E = C.Op0->use_end(); I != E; ++I) {
2234 SDNode *N = *I;
2235 if (N->getOpcode() == ISD::FNEG) {
2236 C.Op0 = SDValue(N, 0);
2237 C.CCMask = reverseCCMask(C.CCMask);
2238 return;
2239 }
2240 }
2241 }
2242}
2243
2244// Check whether C compares (shl X, 32) with 0 and whether X is
2245// also sign-extended. In that case it is better to test the result
2246// of the sign extension using LTGFR.
2247//
2248// This case is important because InstCombine transforms a comparison
2249// with (sext (trunc X)) into a comparison with (shl X, 32).
2250static void adjustForLTGFR(Comparison &C) {
2251 // Check for a comparison between (shl X, 32) and 0.
2252 if (C.Op0.getOpcode() == ISD::SHL &&
2253 C.Op0.getValueType() == MVT::i64 &&
2254 C.Op1.getOpcode() == ISD::Constant &&
2255 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2256 auto *C1 = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2257 if (C1 && C1->getZExtValue() == 32) {
2258 SDValue ShlOp0 = C.Op0.getOperand(0);
2259 // See whether X has any SIGN_EXTEND_INREG uses.
2260 for (auto I = ShlOp0->use_begin(), E = ShlOp0->use_end(); I != E; ++I) {
2261 SDNode *N = *I;
2262 if (N->getOpcode() == ISD::SIGN_EXTEND_INREG &&
2263 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32) {
2264 C.Op0 = SDValue(N, 0);
2265 return;
2266 }
2267 }
2268 }
2269 }
2270}
2271
2272// If C compares the truncation of an extending load, try to compare
2273// the untruncated value instead. This exposes more opportunities to
2274// reuse CC.
2275static void adjustICmpTruncate(SelectionDAG &DAG, const SDLoc &DL,
2276 Comparison &C) {
2277 if (C.Op0.getOpcode() == ISD::TRUNCATE &&
2278 C.Op0.getOperand(0).getOpcode() == ISD::LOAD &&
2279 C.Op1.getOpcode() == ISD::Constant &&
2280 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2281 auto *L = cast<LoadSDNode>(C.Op0.getOperand(0));
2282 if (L->getMemoryVT().getStoreSizeInBits() <= C.Op0.getValueSizeInBits()) {
2283 unsigned Type = L->getExtensionType();
2284 if ((Type == ISD::ZEXTLOAD && C.ICmpType != SystemZICMP::SignedOnly) ||
2285 (Type == ISD::SEXTLOAD && C.ICmpType != SystemZICMP::UnsignedOnly)) {
2286 C.Op0 = C.Op0.getOperand(0);
2287 C.Op1 = DAG.getConstant(0, DL, C.Op0.getValueType());
2288 }
2289 }
2290 }
2291}
2292
2293// Return true if shift operation N has an in-range constant shift value.
2294// Store it in ShiftVal if so.
2295static bool isSimpleShift(SDValue N, unsigned &ShiftVal) {
2296 auto *Shift = dyn_cast<ConstantSDNode>(N.getOperand(1));
2297 if (!Shift)
2298 return false;
2299
2300 uint64_t Amount = Shift->getZExtValue();
2301 if (Amount >= N.getValueSizeInBits())
2302 return false;
2303
2304 ShiftVal = Amount;
2305 return true;
2306}
2307
2308// Check whether an AND with Mask is suitable for a TEST UNDER MASK
2309// instruction and whether the CC value is descriptive enough to handle
2310// a comparison of type Opcode between the AND result and CmpVal.
2311// CCMask says which comparison result is being tested and BitSize is
2312// the number of bits in the operands. If TEST UNDER MASK can be used,
2313// return the corresponding CC mask, otherwise return 0.
2314static unsigned getTestUnderMaskCond(unsigned BitSize, unsigned CCMask,
2315 uint64_t Mask, uint64_t CmpVal,
2316 unsigned ICmpType) {
2317 assert(Mask != 0 && "ANDs with zero should have been removed by now")((Mask != 0 && "ANDs with zero should have been removed by now"
) ? static_cast<void> (0) : __assert_fail ("Mask != 0 && \"ANDs with zero should have been removed by now\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2317, __PRETTY_FUNCTION__))
;
2318
2319 // Check whether the mask is suitable for TMHH, TMHL, TMLH or TMLL.
2320 if (!SystemZ::isImmLL(Mask) && !SystemZ::isImmLH(Mask) &&
2321 !SystemZ::isImmHL(Mask) && !SystemZ::isImmHH(Mask))
2322 return 0;
2323
2324 // Work out the masks for the lowest and highest bits.
2325 unsigned HighShift = 63 - countLeadingZeros(Mask);
2326 uint64_t High = uint64_t(1) << HighShift;
2327 uint64_t Low = uint64_t(1) << countTrailingZeros(Mask);
2328
2329 // Signed ordered comparisons are effectively unsigned if the sign
2330 // bit is dropped.
2331 bool EffectivelyUnsigned = (ICmpType != SystemZICMP::SignedOnly);
2332
2333 // Check for equality comparisons with 0, or the equivalent.
2334 if (CmpVal == 0) {
2335 if (CCMask == SystemZ::CCMASK_CMP_EQ)
2336 return SystemZ::CCMASK_TM_ALL_0;
2337 if (CCMask == SystemZ::CCMASK_CMP_NE)
2338 return SystemZ::CCMASK_TM_SOME_1;
2339 }
2340 if (EffectivelyUnsigned && CmpVal > 0 && CmpVal <= Low) {
2341 if (CCMask == SystemZ::CCMASK_CMP_LT)
2342 return SystemZ::CCMASK_TM_ALL_0;
2343 if (CCMask == SystemZ::CCMASK_CMP_GE)
2344 return SystemZ::CCMASK_TM_SOME_1;
2345 }
2346 if (EffectivelyUnsigned && CmpVal < Low) {
2347 if (CCMask == SystemZ::CCMASK_CMP_LE)
2348 return SystemZ::CCMASK_TM_ALL_0;
2349 if (CCMask == SystemZ::CCMASK_CMP_GT)
2350 return SystemZ::CCMASK_TM_SOME_1;
2351 }
2352
2353 // Check for equality comparisons with the mask, or the equivalent.
2354 if (CmpVal == Mask) {
2355 if (CCMask == SystemZ::CCMASK_CMP_EQ)
2356 return SystemZ::CCMASK_TM_ALL_1;
2357 if (CCMask == SystemZ::CCMASK_CMP_NE)
2358 return SystemZ::CCMASK_TM_SOME_0;
2359 }
2360 if (EffectivelyUnsigned && CmpVal >= Mask - Low && CmpVal < Mask) {
2361 if (CCMask == SystemZ::CCMASK_CMP_GT)
2362 return SystemZ::CCMASK_TM_ALL_1;
2363 if (CCMask == SystemZ::CCMASK_CMP_LE)
2364 return SystemZ::CCMASK_TM_SOME_0;
2365 }
2366 if (EffectivelyUnsigned && CmpVal > Mask - Low && CmpVal <= Mask) {
2367 if (CCMask == SystemZ::CCMASK_CMP_GE)
2368 return SystemZ::CCMASK_TM_ALL_1;
2369 if (CCMask == SystemZ::CCMASK_CMP_LT)
2370 return SystemZ::CCMASK_TM_SOME_0;
2371 }
2372
2373 // Check for ordered comparisons with the top bit.
2374 if (EffectivelyUnsigned && CmpVal >= Mask - High && CmpVal < High) {
2375 if (CCMask == SystemZ::CCMASK_CMP_LE)
2376 return SystemZ::CCMASK_TM_MSB_0;
2377 if (CCMask == SystemZ::CCMASK_CMP_GT)
2378 return SystemZ::CCMASK_TM_MSB_1;
2379 }
2380 if (EffectivelyUnsigned && CmpVal > Mask - High && CmpVal <= High) {
2381 if (CCMask == SystemZ::CCMASK_CMP_LT)
2382 return SystemZ::CCMASK_TM_MSB_0;
2383 if (CCMask == SystemZ::CCMASK_CMP_GE)
2384 return SystemZ::CCMASK_TM_MSB_1;
2385 }
2386
2387 // If there are just two bits, we can do equality checks for Low and High
2388 // as well.
2389 if (Mask == Low + High) {
2390 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == Low)
2391 return SystemZ::CCMASK_TM_MIXED_MSB_0;
2392 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == Low)
2393 return SystemZ::CCMASK_TM_MIXED_MSB_0 ^ SystemZ::CCMASK_ANY;
2394 if (CCMask == SystemZ::CCMASK_CMP_EQ && CmpVal == High)
2395 return SystemZ::CCMASK_TM_MIXED_MSB_1;
2396 if (CCMask == SystemZ::CCMASK_CMP_NE && CmpVal == High)
2397 return SystemZ::CCMASK_TM_MIXED_MSB_1 ^ SystemZ::CCMASK_ANY;
2398 }
2399
2400 // Looks like we've exhausted our options.
2401 return 0;
2402}
2403
2404// See whether C can be implemented as a TEST UNDER MASK instruction.
2405// Update the arguments with the TM version if so.
2406static void adjustForTestUnderMask(SelectionDAG &DAG, const SDLoc &DL,
2407 Comparison &C) {
2408 // Check that we have a comparison with a constant.
2409 auto *ConstOp1 = dyn_cast<ConstantSDNode>(C.Op1);
2410 if (!ConstOp1)
2411 return;
2412 uint64_t CmpVal = ConstOp1->getZExtValue();
2413
2414 // Check whether the nonconstant input is an AND with a constant mask.
2415 Comparison NewC(C);
2416 uint64_t MaskVal;
2417 ConstantSDNode *Mask = nullptr;
2418 if (C.Op0.getOpcode() == ISD::AND) {
2419 NewC.Op0 = C.Op0.getOperand(0);
2420 NewC.Op1 = C.Op0.getOperand(1);
2421 Mask = dyn_cast<ConstantSDNode>(NewC.Op1);
2422 if (!Mask)
2423 return;
2424 MaskVal = Mask->getZExtValue();
2425 } else {
2426 // There is no instruction to compare with a 64-bit immediate
2427 // so use TMHH instead if possible. We need an unsigned ordered
2428 // comparison with an i64 immediate.
2429 if (NewC.Op0.getValueType() != MVT::i64 ||
2430 NewC.CCMask == SystemZ::CCMASK_CMP_EQ ||
2431 NewC.CCMask == SystemZ::CCMASK_CMP_NE ||
2432 NewC.ICmpType == SystemZICMP::SignedOnly)
2433 return;
2434 // Convert LE and GT comparisons into LT and GE.
2435 if (NewC.CCMask == SystemZ::CCMASK_CMP_LE ||
2436 NewC.CCMask == SystemZ::CCMASK_CMP_GT) {
2437 if (CmpVal == uint64_t(-1))
2438 return;
2439 CmpVal += 1;
2440 NewC.CCMask ^= SystemZ::CCMASK_CMP_EQ;
2441 }
2442 // If the low N bits of Op1 are zero than the low N bits of Op0 can
2443 // be masked off without changing the result.
2444 MaskVal = -(CmpVal & -CmpVal);
2445 NewC.ICmpType = SystemZICMP::UnsignedOnly;
2446 }
2447 if (!MaskVal)
2448 return;
2449
2450 // Check whether the combination of mask, comparison value and comparison
2451 // type are suitable.
2452 unsigned BitSize = NewC.Op0.getValueSizeInBits();
2453 unsigned NewCCMask, ShiftVal;
2454 if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2455 NewC.Op0.getOpcode() == ISD::SHL &&
2456 isSimpleShift(NewC.Op0, ShiftVal) &&
2457 (MaskVal >> ShiftVal != 0) &&
2458 ((CmpVal >> ShiftVal) << ShiftVal) == CmpVal &&
2459 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2460 MaskVal >> ShiftVal,
2461 CmpVal >> ShiftVal,
2462 SystemZICMP::Any))) {
2463 NewC.Op0 = NewC.Op0.getOperand(0);
2464 MaskVal >>= ShiftVal;
2465 } else if (NewC.ICmpType != SystemZICMP::SignedOnly &&
2466 NewC.Op0.getOpcode() == ISD::SRL &&
2467 isSimpleShift(NewC.Op0, ShiftVal) &&
2468 (MaskVal << ShiftVal != 0) &&
2469 ((CmpVal << ShiftVal) >> ShiftVal) == CmpVal &&
2470 (NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask,
2471 MaskVal << ShiftVal,
2472 CmpVal << ShiftVal,
2473 SystemZICMP::UnsignedOnly))) {
2474 NewC.Op0 = NewC.Op0.getOperand(0);
2475 MaskVal <<= ShiftVal;
2476 } else {
2477 NewCCMask = getTestUnderMaskCond(BitSize, NewC.CCMask, MaskVal, CmpVal,
2478 NewC.ICmpType);
2479 if (!NewCCMask)
2480 return;
2481 }
2482
2483 // Go ahead and make the change.
2484 C.Opcode = SystemZISD::TM;
2485 C.Op0 = NewC.Op0;
2486 if (Mask && Mask->getZExtValue() == MaskVal)
2487 C.Op1 = SDValue(Mask, 0);
2488 else
2489 C.Op1 = DAG.getConstant(MaskVal, DL, C.Op0.getValueType());
2490 C.CCValid = SystemZ::CCMASK_TM;
2491 C.CCMask = NewCCMask;
2492}
2493
2494// See whether the comparison argument contains a redundant AND
2495// and remove it if so. This sometimes happens due to the generic
2496// BRCOND expansion.
2497static void adjustForRedundantAnd(SelectionDAG &DAG, const SDLoc &DL,
2498 Comparison &C) {
2499 if (C.Op0.getOpcode() != ISD::AND)
2500 return;
2501 auto *Mask = dyn_cast<ConstantSDNode>(C.Op0.getOperand(1));
2502 if (!Mask)
2503 return;
2504 KnownBits Known = DAG.computeKnownBits(C.Op0.getOperand(0));
2505 if ((~Known.Zero).getZExtValue() & ~Mask->getZExtValue())
2506 return;
2507
2508 C.Op0 = C.Op0.getOperand(0);
2509}
2510
2511// Return a Comparison that tests the condition-code result of intrinsic
2512// node Call against constant integer CC using comparison code Cond.
2513// Opcode is the opcode of the SystemZISD operation for the intrinsic
2514// and CCValid is the set of possible condition-code results.
2515static Comparison getIntrinsicCmp(SelectionDAG &DAG, unsigned Opcode,
2516 SDValue Call, unsigned CCValid, uint64_t CC,
2517 ISD::CondCode Cond) {
2518 Comparison C(Call, SDValue(), SDValue());
2519 C.Opcode = Opcode;
2520 C.CCValid = CCValid;
2521 if (Cond == ISD::SETEQ)
2522 // bit 3 for CC==0, bit 0 for CC==3, always false for CC>3.
2523 C.CCMask = CC < 4 ? 1 << (3 - CC) : 0;
2524 else if (Cond == ISD::SETNE)
2525 // ...and the inverse of that.
2526 C.CCMask = CC < 4 ? ~(1 << (3 - CC)) : -1;
2527 else if (Cond == ISD::SETLT || Cond == ISD::SETULT)
2528 // bits above bit 3 for CC==0 (always false), bits above bit 0 for CC==3,
2529 // always true for CC>3.
2530 C.CCMask = CC < 4 ? ~0U << (4 - CC) : -1;
2531 else if (Cond == ISD::SETGE || Cond == ISD::SETUGE)
2532 // ...and the inverse of that.
2533 C.CCMask = CC < 4 ? ~(~0U << (4 - CC)) : 0;
2534 else if (Cond == ISD::SETLE || Cond == ISD::SETULE)
2535 // bit 3 and above for CC==0, bit 0 and above for CC==3 (always true),
2536 // always true for CC>3.
2537 C.CCMask = CC < 4 ? ~0U << (3 - CC) : -1;
2538 else if (Cond == ISD::SETGT || Cond == ISD::SETUGT)
2539 // ...and the inverse of that.
2540 C.CCMask = CC < 4 ? ~(~0U << (3 - CC)) : 0;
2541 else
2542 llvm_unreachable("Unexpected integer comparison type")::llvm::llvm_unreachable_internal("Unexpected integer comparison type"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2542)
;
2543 C.CCMask &= CCValid;
2544 return C;
2545}
2546
2547// Decide how to implement a comparison of type Cond between CmpOp0 with CmpOp1.
2548static Comparison getCmp(SelectionDAG &DAG, SDValue CmpOp0, SDValue CmpOp1,
2549 ISD::CondCode Cond, const SDLoc &DL,
2550 SDValue Chain = SDValue(),
2551 bool IsSignaling = false) {
2552 if (CmpOp1.getOpcode() == ISD::Constant) {
2553 assert(!Chain)((!Chain) ? static_cast<void> (0) : __assert_fail ("!Chain"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2553, __PRETTY_FUNCTION__))
;
2554 uint64_t Constant = cast<ConstantSDNode>(CmpOp1)->getZExtValue();
2555 unsigned Opcode, CCValid;
2556 if (CmpOp0.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
2557 CmpOp0.getResNo() == 0 && CmpOp0->hasNUsesOfValue(1, 0) &&
2558 isIntrinsicWithCCAndChain(CmpOp0, Opcode, CCValid))
2559 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2560 if (CmpOp0.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
2561 CmpOp0.getResNo() == CmpOp0->getNumValues() - 1 &&
2562 isIntrinsicWithCC(CmpOp0, Opcode, CCValid))
2563 return getIntrinsicCmp(DAG, Opcode, CmpOp0, CCValid, Constant, Cond);
2564 }
2565 Comparison C(CmpOp0, CmpOp1, Chain);
2566 C.CCMask = CCMaskForCondCode(Cond);
2567 if (C.Op0.getValueType().isFloatingPoint()) {
2568 C.CCValid = SystemZ::CCMASK_FCMP;
2569 if (!C.Chain)
2570 C.Opcode = SystemZISD::FCMP;
2571 else if (!IsSignaling)
2572 C.Opcode = SystemZISD::STRICT_FCMP;
2573 else
2574 C.Opcode = SystemZISD::STRICT_FCMPS;
2575 adjustForFNeg(C);
2576 } else {
2577 assert(!C.Chain)((!C.Chain) ? static_cast<void> (0) : __assert_fail ("!C.Chain"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2577, __PRETTY_FUNCTION__))
;
2578 C.CCValid = SystemZ::CCMASK_ICMP;
2579 C.Opcode = SystemZISD::ICMP;
2580 // Choose the type of comparison. Equality and inequality tests can
2581 // use either signed or unsigned comparisons. The choice also doesn't
2582 // matter if both sign bits are known to be clear. In those cases we
2583 // want to give the main isel code the freedom to choose whichever
2584 // form fits best.
2585 if (C.CCMask == SystemZ::CCMASK_CMP_EQ ||
2586 C.CCMask == SystemZ::CCMASK_CMP_NE ||
2587 (DAG.SignBitIsZero(C.Op0) && DAG.SignBitIsZero(C.Op1)))
2588 C.ICmpType = SystemZICMP::Any;
2589 else if (C.CCMask & SystemZ::CCMASK_CMP_UO)
2590 C.ICmpType = SystemZICMP::UnsignedOnly;
2591 else
2592 C.ICmpType = SystemZICMP::SignedOnly;
2593 C.CCMask &= ~SystemZ::CCMASK_CMP_UO;
2594 adjustForRedundantAnd(DAG, DL, C);
2595 adjustZeroCmp(DAG, DL, C);
2596 adjustSubwordCmp(DAG, DL, C);
2597 adjustForSubtraction(DAG, DL, C);
2598 adjustForLTGFR(C);
2599 adjustICmpTruncate(DAG, DL, C);
2600 }
2601
2602 if (shouldSwapCmpOperands(C)) {
2603 std::swap(C.Op0, C.Op1);
2604 C.CCMask = reverseCCMask(C.CCMask);
2605 }
2606
2607 adjustForTestUnderMask(DAG, DL, C);
2608 return C;
2609}
2610
2611// Emit the comparison instruction described by C.
2612static SDValue emitCmp(SelectionDAG &DAG, const SDLoc &DL, Comparison &C) {
2613 if (!C.Op1.getNode()) {
2614 SDNode *Node;
2615 switch (C.Op0.getOpcode()) {
2616 case ISD::INTRINSIC_W_CHAIN:
2617 Node = emitIntrinsicWithCCAndChain(DAG, C.Op0, C.Opcode);
2618 return SDValue(Node, 0);
2619 case ISD::INTRINSIC_WO_CHAIN:
2620 Node = emitIntrinsicWithCC(DAG, C.Op0, C.Opcode);
2621 return SDValue(Node, Node->getNumValues() - 1);
2622 default:
2623 llvm_unreachable("Invalid comparison operands")::llvm::llvm_unreachable_internal("Invalid comparison operands"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2623)
;
2624 }
2625 }
2626 if (C.Opcode == SystemZISD::ICMP)
2627 return DAG.getNode(SystemZISD::ICMP, DL, MVT::i32, C.Op0, C.Op1,
2628 DAG.getTargetConstant(C.ICmpType, DL, MVT::i32));
2629 if (C.Opcode == SystemZISD::TM) {
2630 bool RegisterOnly = (bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_0) !=
2631 bool(C.CCMask & SystemZ::CCMASK_TM_MIXED_MSB_1));
2632 return DAG.getNode(SystemZISD::TM, DL, MVT::i32, C.Op0, C.Op1,
2633 DAG.getTargetConstant(RegisterOnly, DL, MVT::i32));
2634 }
2635 if (C.Chain) {
2636 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
2637 return DAG.getNode(C.Opcode, DL, VTs, C.Chain, C.Op0, C.Op1);
2638 }
2639 return DAG.getNode(C.Opcode, DL, MVT::i32, C.Op0, C.Op1);
2640}
2641
2642// Implement a 32-bit *MUL_LOHI operation by extending both operands to
2643// 64 bits. Extend is the extension type to use. Store the high part
2644// in Hi and the low part in Lo.
2645static void lowerMUL_LOHI32(SelectionDAG &DAG, const SDLoc &DL, unsigned Extend,
2646 SDValue Op0, SDValue Op1, SDValue &Hi,
2647 SDValue &Lo) {
2648 Op0 = DAG.getNode(Extend, DL, MVT::i64, Op0);
2649 Op1 = DAG.getNode(Extend, DL, MVT::i64, Op1);
2650 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, Op0, Op1);
2651 Hi = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2652 DAG.getConstant(32, DL, MVT::i64));
2653 Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Hi);
2654 Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
2655}
2656
2657// Lower a binary operation that produces two VT results, one in each
2658// half of a GR128 pair. Op0 and Op1 are the VT operands to the operation,
2659// and Opcode performs the GR128 operation. Store the even register result
2660// in Even and the odd register result in Odd.
2661static void lowerGR128Binary(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
2662 unsigned Opcode, SDValue Op0, SDValue Op1,
2663 SDValue &Even, SDValue &Odd) {
2664 SDValue Result = DAG.getNode(Opcode, DL, MVT::Untyped, Op0, Op1);
2665 bool Is32Bit = is32Bit(VT);
2666 Even = DAG.getTargetExtractSubreg(SystemZ::even128(Is32Bit), DL, VT, Result);
2667 Odd = DAG.getTargetExtractSubreg(SystemZ::odd128(Is32Bit), DL, VT, Result);
2668}
2669
2670// Return an i32 value that is 1 if the CC value produced by CCReg is
2671// in the mask CCMask and 0 otherwise. CC is known to have a value
2672// in CCValid, so other values can be ignored.
2673static SDValue emitSETCC(SelectionDAG &DAG, const SDLoc &DL, SDValue CCReg,
2674 unsigned CCValid, unsigned CCMask) {
2675 SDValue Ops[] = {DAG.getConstant(1, DL, MVT::i32),
2676 DAG.getConstant(0, DL, MVT::i32),
2677 DAG.getTargetConstant(CCValid, DL, MVT::i32),
2678 DAG.getTargetConstant(CCMask, DL, MVT::i32), CCReg};
2679 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, MVT::i32, Ops);
2680}
2681
2682// Return the SystemISD vector comparison operation for CC, or 0 if it cannot
2683// be done directly. Mode is CmpMode::Int for integer comparisons, CmpMode::FP
2684// for regular floating-point comparisons, CmpMode::StrictFP for strict (quiet)
2685// floating-point comparisons, and CmpMode::SignalingFP for strict signaling
2686// floating-point comparisons.
2687enum class CmpMode { Int, FP, StrictFP, SignalingFP };
2688static unsigned getVectorComparison(ISD::CondCode CC, CmpMode Mode) {
2689 switch (CC) {
2690 case ISD::SETOEQ:
2691 case ISD::SETEQ:
2692 switch (Mode) {
2693 case CmpMode::Int: return SystemZISD::VICMPE;
2694 case CmpMode::FP: return SystemZISD::VFCMPE;
2695 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPE;
2696 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPES;
2697 }
2698 llvm_unreachable("Bad mode")::llvm::llvm_unreachable_internal("Bad mode", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2698)
;
2699
2700 case ISD::SETOGE:
2701 case ISD::SETGE:
2702 switch (Mode) {
2703 case CmpMode::Int: return 0;
2704 case CmpMode::FP: return SystemZISD::VFCMPHE;
2705 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPHE;
2706 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHES;
2707 }
2708 llvm_unreachable("Bad mode")::llvm::llvm_unreachable_internal("Bad mode", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2708)
;
2709
2710 case ISD::SETOGT:
2711 case ISD::SETGT:
2712 switch (Mode) {
2713 case CmpMode::Int: return SystemZISD::VICMPH;
2714 case CmpMode::FP: return SystemZISD::VFCMPH;
2715 case CmpMode::StrictFP: return SystemZISD::STRICT_VFCMPH;
2716 case CmpMode::SignalingFP: return SystemZISD::STRICT_VFCMPHS;
2717 }
2718 llvm_unreachable("Bad mode")::llvm::llvm_unreachable_internal("Bad mode", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2718)
;
2719
2720 case ISD::SETUGT:
2721 switch (Mode) {
2722 case CmpMode::Int: return SystemZISD::VICMPHL;
2723 case CmpMode::FP: return 0;
2724 case CmpMode::StrictFP: return 0;
2725 case CmpMode::SignalingFP: return 0;
2726 }
2727 llvm_unreachable("Bad mode")::llvm::llvm_unreachable_internal("Bad mode", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2727)
;
2728
2729 default:
2730 return 0;
2731 }
2732}
2733
2734// Return the SystemZISD vector comparison operation for CC or its inverse,
2735// or 0 if neither can be done directly. Indicate in Invert whether the
2736// result is for the inverse of CC. Mode is as above.
2737static unsigned getVectorComparisonOrInvert(ISD::CondCode CC, CmpMode Mode,
2738 bool &Invert) {
2739 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
2740 Invert = false;
2741 return Opcode;
2742 }
2743
2744 CC = ISD::getSetCCInverse(CC, Mode == CmpMode::Int ? MVT::i32 : MVT::f32);
2745 if (unsigned Opcode = getVectorComparison(CC, Mode)) {
2746 Invert = true;
2747 return Opcode;
2748 }
2749
2750 return 0;
2751}
2752
2753// Return a v2f64 that contains the extended form of elements Start and Start+1
2754// of v4f32 value Op. If Chain is nonnull, return the strict form.
2755static SDValue expandV4F32ToV2F64(SelectionDAG &DAG, int Start, const SDLoc &DL,
2756 SDValue Op, SDValue Chain) {
2757 int Mask[] = { Start, -1, Start + 1, -1 };
2758 Op = DAG.getVectorShuffle(MVT::v4f32, DL, Op, DAG.getUNDEF(MVT::v4f32), Mask);
2759 if (Chain) {
2760 SDVTList VTs = DAG.getVTList(MVT::v2f64, MVT::Other);
2761 return DAG.getNode(SystemZISD::STRICT_VEXTEND, DL, VTs, Chain, Op);
2762 }
2763 return DAG.getNode(SystemZISD::VEXTEND, DL, MVT::v2f64, Op);
2764}
2765
2766// Build a comparison of vectors CmpOp0 and CmpOp1 using opcode Opcode,
2767// producing a result of type VT. If Chain is nonnull, return the strict form.
2768SDValue SystemZTargetLowering::getVectorCmp(SelectionDAG &DAG, unsigned Opcode,
2769 const SDLoc &DL, EVT VT,
2770 SDValue CmpOp0,
2771 SDValue CmpOp1,
2772 SDValue Chain) const {
2773 // There is no hardware support for v4f32 (unless we have the vector
2774 // enhancements facility 1), so extend the vector into two v2f64s
2775 // and compare those.
2776 if (CmpOp0.getValueType() == MVT::v4f32 &&
2777 !Subtarget.hasVectorEnhancements1()) {
2778 SDValue H0 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp0, Chain);
2779 SDValue L0 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp0, Chain);
2780 SDValue H1 = expandV4F32ToV2F64(DAG, 0, DL, CmpOp1, Chain);
2781 SDValue L1 = expandV4F32ToV2F64(DAG, 2, DL, CmpOp1, Chain);
2782 if (Chain) {
2783 SDVTList VTs = DAG.getVTList(MVT::v2i64, MVT::Other);
2784 SDValue HRes = DAG.getNode(Opcode, DL, VTs, Chain, H0, H1);
2785 SDValue LRes = DAG.getNode(Opcode, DL, VTs, Chain, L0, L1);
2786 SDValue Res = DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2787 SDValue Chains[6] = { H0.getValue(1), L0.getValue(1),
2788 H1.getValue(1), L1.getValue(1),
2789 HRes.getValue(1), LRes.getValue(1) };
2790 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2791 SDValue Ops[2] = { Res, NewChain };
2792 return DAG.getMergeValues(Ops, DL);
2793 }
2794 SDValue HRes = DAG.getNode(Opcode, DL, MVT::v2i64, H0, H1);
2795 SDValue LRes = DAG.getNode(Opcode, DL, MVT::v2i64, L0, L1);
2796 return DAG.getNode(SystemZISD::PACK, DL, VT, HRes, LRes);
2797 }
2798 if (Chain) {
2799 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2800 return DAG.getNode(Opcode, DL, VTs, Chain, CmpOp0, CmpOp1);
2801 }
2802 return DAG.getNode(Opcode, DL, VT, CmpOp0, CmpOp1);
2803}
2804
2805// Lower a vector comparison of type CC between CmpOp0 and CmpOp1, producing
2806// an integer mask of type VT. If Chain is nonnull, we have a strict
2807// floating-point comparison. If in addition IsSignaling is true, we have
2808// a strict signaling floating-point comparison.
2809SDValue SystemZTargetLowering::lowerVectorSETCC(SelectionDAG &DAG,
2810 const SDLoc &DL, EVT VT,
2811 ISD::CondCode CC,
2812 SDValue CmpOp0,
2813 SDValue CmpOp1,
2814 SDValue Chain,
2815 bool IsSignaling) const {
2816 bool IsFP = CmpOp0.getValueType().isFloatingPoint();
2817 assert (!Chain || IsFP)((!Chain || IsFP) ? static_cast<void> (0) : __assert_fail
("!Chain || IsFP", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2817, __PRETTY_FUNCTION__))
;
2818 assert (!IsSignaling || Chain)((!IsSignaling || Chain) ? static_cast<void> (0) : __assert_fail
("!IsSignaling || Chain", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2818, __PRETTY_FUNCTION__))
;
2819 CmpMode Mode = IsSignaling ? CmpMode::SignalingFP :
2820 Chain ? CmpMode::StrictFP : IsFP ? CmpMode::FP : CmpMode::Int;
2821 bool Invert = false;
2822 SDValue Cmp;
2823 switch (CC) {
2824 // Handle tests for order using (or (ogt y x) (oge x y)).
2825 case ISD::SETUO:
2826 Invert = true;
2827 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2828 case ISD::SETO: {
2829 assert(IsFP && "Unexpected integer comparison")((IsFP && "Unexpected integer comparison") ? static_cast
<void> (0) : __assert_fail ("IsFP && \"Unexpected integer comparison\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2829, __PRETTY_FUNCTION__))
;
2830 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
2831 DL, VT, CmpOp1, CmpOp0, Chain);
2832 SDValue GE = getVectorCmp(DAG, getVectorComparison(ISD::SETOGE, Mode),
2833 DL, VT, CmpOp0, CmpOp1, Chain);
2834 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GE);
2835 if (Chain)
2836 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2837 LT.getValue(1), GE.getValue(1));
2838 break;
2839 }
2840
2841 // Handle <> tests using (or (ogt y x) (ogt x y)).
2842 case ISD::SETUEQ:
2843 Invert = true;
2844 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2845 case ISD::SETONE: {
2846 assert(IsFP && "Unexpected integer comparison")((IsFP && "Unexpected integer comparison") ? static_cast
<void> (0) : __assert_fail ("IsFP && \"Unexpected integer comparison\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2846, __PRETTY_FUNCTION__))
;
2847 SDValue LT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
2848 DL, VT, CmpOp1, CmpOp0, Chain);
2849 SDValue GT = getVectorCmp(DAG, getVectorComparison(ISD::SETOGT, Mode),
2850 DL, VT, CmpOp0, CmpOp1, Chain);
2851 Cmp = DAG.getNode(ISD::OR, DL, VT, LT, GT);
2852 if (Chain)
2853 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2854 LT.getValue(1), GT.getValue(1));
2855 break;
2856 }
2857
2858 // Otherwise a single comparison is enough. It doesn't really
2859 // matter whether we try the inversion or the swap first, since
2860 // there are no cases where both work.
2861 default:
2862 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
2863 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp0, CmpOp1, Chain);
2864 else {
2865 CC = ISD::getSetCCSwappedOperands(CC);
2866 if (unsigned Opcode = getVectorComparisonOrInvert(CC, Mode, Invert))
2867 Cmp = getVectorCmp(DAG, Opcode, DL, VT, CmpOp1, CmpOp0, Chain);
2868 else
2869 llvm_unreachable("Unhandled comparison")::llvm::llvm_unreachable_internal("Unhandled comparison", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 2869)
;
2870 }
2871 if (Chain)
2872 Chain = Cmp.getValue(1);
2873 break;
2874 }
2875 if (Invert) {
2876 SDValue Mask =
2877 DAG.getSplatBuildVector(VT, DL, DAG.getConstant(-1, DL, MVT::i64));
2878 Cmp = DAG.getNode(ISD::XOR, DL, VT, Cmp, Mask);
2879 }
2880 if (Chain && Chain.getNode() != Cmp.getNode()) {
2881 SDValue Ops[2] = { Cmp, Chain };
2882 Cmp = DAG.getMergeValues(Ops, DL);
2883 }
2884 return Cmp;
2885}
2886
2887SDValue SystemZTargetLowering::lowerSETCC(SDValue Op,
2888 SelectionDAG &DAG) const {
2889 SDValue CmpOp0 = Op.getOperand(0);
2890 SDValue CmpOp1 = Op.getOperand(1);
2891 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2892 SDLoc DL(Op);
2893 EVT VT = Op.getValueType();
2894 if (VT.isVector())
2895 return lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1);
2896
2897 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2898 SDValue CCReg = emitCmp(DAG, DL, C);
2899 return emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
2900}
2901
2902SDValue SystemZTargetLowering::lowerSTRICT_FSETCC(SDValue Op,
2903 SelectionDAG &DAG,
2904 bool IsSignaling) const {
2905 SDValue Chain = Op.getOperand(0);
2906 SDValue CmpOp0 = Op.getOperand(1);
2907 SDValue CmpOp1 = Op.getOperand(2);
2908 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
2909 SDLoc DL(Op);
2910 EVT VT = Op.getNode()->getValueType(0);
2911 if (VT.isVector()) {
2912 SDValue Res = lowerVectorSETCC(DAG, DL, VT, CC, CmpOp0, CmpOp1,
2913 Chain, IsSignaling);
2914 return Res.getValue(Op.getResNo());
2915 }
2916
2917 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL, Chain, IsSignaling));
2918 SDValue CCReg = emitCmp(DAG, DL, C);
2919 CCReg->setFlags(Op->getFlags());
2920 SDValue Result = emitSETCC(DAG, DL, CCReg, C.CCValid, C.CCMask);
2921 SDValue Ops[2] = { Result, CCReg.getValue(1) };
2922 return DAG.getMergeValues(Ops, DL);
2923}
2924
2925SDValue SystemZTargetLowering::lowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2926 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2927 SDValue CmpOp0 = Op.getOperand(2);
2928 SDValue CmpOp1 = Op.getOperand(3);
2929 SDValue Dest = Op.getOperand(4);
2930 SDLoc DL(Op);
2931
2932 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2933 SDValue CCReg = emitCmp(DAG, DL, C);
2934 return DAG.getNode(
2935 SystemZISD::BR_CCMASK, DL, Op.getValueType(), Op.getOperand(0),
2936 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
2937 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), Dest, CCReg);
2938}
2939
2940// Return true if Pos is CmpOp and Neg is the negative of CmpOp,
2941// allowing Pos and Neg to be wider than CmpOp.
2942static bool isAbsolute(SDValue CmpOp, SDValue Pos, SDValue Neg) {
2943 return (Neg.getOpcode() == ISD::SUB &&
2944 Neg.getOperand(0).getOpcode() == ISD::Constant &&
2945 cast<ConstantSDNode>(Neg.getOperand(0))->getZExtValue() == 0 &&
2946 Neg.getOperand(1) == Pos &&
2947 (Pos == CmpOp ||
2948 (Pos.getOpcode() == ISD::SIGN_EXTEND &&
2949 Pos.getOperand(0) == CmpOp)));
2950}
2951
2952// Return the absolute or negative absolute of Op; IsNegative decides which.
2953static SDValue getAbsolute(SelectionDAG &DAG, const SDLoc &DL, SDValue Op,
2954 bool IsNegative) {
2955 Op = DAG.getNode(SystemZISD::IABS, DL, Op.getValueType(), Op);
2956 if (IsNegative)
2957 Op = DAG.getNode(ISD::SUB, DL, Op.getValueType(),
2958 DAG.getConstant(0, DL, Op.getValueType()), Op);
2959 return Op;
2960}
2961
2962SDValue SystemZTargetLowering::lowerSELECT_CC(SDValue Op,
2963 SelectionDAG &DAG) const {
2964 SDValue CmpOp0 = Op.getOperand(0);
2965 SDValue CmpOp1 = Op.getOperand(1);
2966 SDValue TrueOp = Op.getOperand(2);
2967 SDValue FalseOp = Op.getOperand(3);
2968 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2969 SDLoc DL(Op);
2970
2971 Comparison C(getCmp(DAG, CmpOp0, CmpOp1, CC, DL));
2972
2973 // Check for absolute and negative-absolute selections, including those
2974 // where the comparison value is sign-extended (for LPGFR and LNGFR).
2975 // This check supplements the one in DAGCombiner.
2976 if (C.Opcode == SystemZISD::ICMP &&
2977 C.CCMask != SystemZ::CCMASK_CMP_EQ &&
2978 C.CCMask != SystemZ::CCMASK_CMP_NE &&
2979 C.Op1.getOpcode() == ISD::Constant &&
2980 cast<ConstantSDNode>(C.Op1)->getZExtValue() == 0) {
2981 if (isAbsolute(C.Op0, TrueOp, FalseOp))
2982 return getAbsolute(DAG, DL, TrueOp, C.CCMask & SystemZ::CCMASK_CMP_LT);
2983 if (isAbsolute(C.Op0, FalseOp, TrueOp))
2984 return getAbsolute(DAG, DL, FalseOp, C.CCMask & SystemZ::CCMASK_CMP_GT);
2985 }
2986
2987 SDValue CCReg = emitCmp(DAG, DL, C);
2988 SDValue Ops[] = {TrueOp, FalseOp,
2989 DAG.getTargetConstant(C.CCValid, DL, MVT::i32),
2990 DAG.getTargetConstant(C.CCMask, DL, MVT::i32), CCReg};
2991
2992 return DAG.getNode(SystemZISD::SELECT_CCMASK, DL, Op.getValueType(), Ops);
2993}
2994
2995SDValue SystemZTargetLowering::lowerGlobalAddress(GlobalAddressSDNode *Node,
2996 SelectionDAG &DAG) const {
2997 SDLoc DL(Node);
2998 const GlobalValue *GV = Node->getGlobal();
2999 int64_t Offset = Node->getOffset();
3000 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3001 CodeModel::Model CM = DAG.getTarget().getCodeModel();
3002
3003 SDValue Result;
3004 if (Subtarget.isPC32DBLSymbol(GV, CM)) {
3005 if (isInt<32>(Offset)) {
3006 // Assign anchors at 1<<12 byte boundaries.
3007 uint64_t Anchor = Offset & ~uint64_t(0xfff);
3008 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor);
3009 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3010
3011 // The offset can be folded into the address if it is aligned to a
3012 // halfword.
3013 Offset -= Anchor;
3014 if (Offset != 0 && (Offset & 1) == 0) {
3015 SDValue Full =
3016 DAG.getTargetGlobalAddress(GV, DL, PtrVT, Anchor + Offset);
3017 Result = DAG.getNode(SystemZISD::PCREL_OFFSET, DL, PtrVT, Full, Result);
3018 Offset = 0;
3019 }
3020 } else {
3021 // Conservatively load a constant offset greater than 32 bits into a
3022 // register below.
3023 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT);
3024 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3025 }
3026 } else {
3027 Result = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, SystemZII::MO_GOT);
3028 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3029 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3030 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3031 }
3032
3033 // If there was a non-zero offset that we didn't fold, create an explicit
3034 // addition for it.
3035 if (Offset != 0)
3036 Result = DAG.getNode(ISD::ADD, DL, PtrVT, Result,
3037 DAG.getConstant(Offset, DL, PtrVT));
3038
3039 return Result;
3040}
3041
3042SDValue SystemZTargetLowering::lowerTLSGetOffset(GlobalAddressSDNode *Node,
3043 SelectionDAG &DAG,
3044 unsigned Opcode,
3045 SDValue GOTOffset) const {
3046 SDLoc DL(Node);
3047 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3048 SDValue Chain = DAG.getEntryNode();
3049 SDValue Glue;
3050
3051 if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3052 CallingConv::GHC)
3053 report_fatal_error("In GHC calling convention TLS is not supported");
3054
3055 // __tls_get_offset takes the GOT offset in %r2 and the GOT in %r12.
3056 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
3057 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R12D, GOT, Glue);
3058 Glue = Chain.getValue(1);
3059 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R2D, GOTOffset, Glue);
3060 Glue = Chain.getValue(1);
3061
3062 // The first call operand is the chain and the second is the TLS symbol.
3063 SmallVector<SDValue, 8> Ops;
3064 Ops.push_back(Chain);
3065 Ops.push_back(DAG.getTargetGlobalAddress(Node->getGlobal(), DL,
3066 Node->getValueType(0),
3067 0, 0));
3068
3069 // Add argument registers to the end of the list so that they are
3070 // known live into the call.
3071 Ops.push_back(DAG.getRegister(SystemZ::R2D, PtrVT));
3072 Ops.push_back(DAG.getRegister(SystemZ::R12D, PtrVT));
3073
3074 // Add a register mask operand representing the call-preserved registers.
3075 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3076 const uint32_t *Mask =
3077 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3078 assert(Mask && "Missing call preserved mask for calling convention")((Mask && "Missing call preserved mask for calling convention"
) ? static_cast<void> (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 3078, __PRETTY_FUNCTION__))
;
3079 Ops.push_back(DAG.getRegisterMask(Mask));
3080
3081 // Glue the call to the argument copies.
3082 Ops.push_back(Glue);
3083
3084 // Emit the call.
3085 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3086 Chain = DAG.getNode(Opcode, DL, NodeTys, Ops);
3087 Glue = Chain.getValue(1);
3088
3089 // Copy the return value from %r2.
3090 return DAG.getCopyFromReg(Chain, DL, SystemZ::R2D, PtrVT, Glue);
3091}
3092
3093SDValue SystemZTargetLowering::lowerThreadPointer(const SDLoc &DL,
3094 SelectionDAG &DAG) const {
3095 SDValue Chain = DAG.getEntryNode();
3096 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3097
3098 // The high part of the thread pointer is in access register 0.
3099 SDValue TPHi = DAG.getCopyFromReg(Chain, DL, SystemZ::A0, MVT::i32);
3100 TPHi = DAG.getNode(ISD::ANY_EXTEND, DL, PtrVT, TPHi);
3101
3102 // The low part of the thread pointer is in access register 1.
3103 SDValue TPLo = DAG.getCopyFromReg(Chain, DL, SystemZ::A1, MVT::i32);
3104 TPLo = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TPLo);
3105
3106 // Merge them into a single 64-bit address.
3107 SDValue TPHiShifted = DAG.getNode(ISD::SHL, DL, PtrVT, TPHi,
3108 DAG.getConstant(32, DL, PtrVT));
3109 return DAG.getNode(ISD::OR, DL, PtrVT, TPHiShifted, TPLo);
3110}
3111
3112SDValue SystemZTargetLowering::lowerGlobalTLSAddress(GlobalAddressSDNode *Node,
3113 SelectionDAG &DAG) const {
3114 if (DAG.getTarget().useEmulatedTLS())
3115 return LowerToTLSEmulatedModel(Node, DAG);
3116 SDLoc DL(Node);
3117 const GlobalValue *GV = Node->getGlobal();
3118 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3119 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
3120
3121 if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3122 CallingConv::GHC)
3123 report_fatal_error("In GHC calling convention TLS is not supported");
3124
3125 SDValue TP = lowerThreadPointer(DL, DAG);
3126
3127 // Get the offset of GA from the thread pointer, based on the TLS model.
3128 SDValue Offset;
3129 switch (model) {
3130 case TLSModel::GeneralDynamic: {
3131 // Load the GOT offset of the tls_index (module ID / per-symbol offset).
3132 SystemZConstantPoolValue *CPV =
3133 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSGD);
3134
3135 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
3136 Offset = DAG.getLoad(
3137 PtrVT, DL, DAG.getEntryNode(), Offset,
3138 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3139
3140 // Call __tls_get_offset to retrieve the offset.
3141 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_GDCALL, Offset);
3142 break;
3143 }
3144
3145 case TLSModel::LocalDynamic: {
3146 // Load the GOT offset of the module ID.
3147 SystemZConstantPoolValue *CPV =
3148 SystemZConstantPoolValue::Create(GV, SystemZCP::TLSLDM);
3149
3150 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
3151 Offset = DAG.getLoad(
3152 PtrVT, DL, DAG.getEntryNode(), Offset,
3153 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3154
3155 // Call __tls_get_offset to retrieve the module base offset.
3156 Offset = lowerTLSGetOffset(Node, DAG, SystemZISD::TLS_LDCALL, Offset);
3157
3158 // Note: The SystemZLDCleanupPass will remove redundant computations
3159 // of the module base offset. Count total number of local-dynamic
3160 // accesses to trigger execution of that pass.
3161 SystemZMachineFunctionInfo* MFI =
3162 DAG.getMachineFunction().getInfo<SystemZMachineFunctionInfo>();
3163 MFI->incNumLocalDynamicTLSAccesses();
3164
3165 // Add the per-symbol offset.
3166 CPV = SystemZConstantPoolValue::Create(GV, SystemZCP::DTPOFF);
3167
3168 SDValue DTPOffset = DAG.getConstantPool(CPV, PtrVT, 8);
3169 DTPOffset = DAG.getLoad(
3170 PtrVT, DL, DAG.getEntryNode(), DTPOffset,
3171 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3172
3173 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Offset, DTPOffset);
3174 break;
3175 }
3176
3177 case TLSModel::InitialExec: {
3178 // Load the offset from the GOT.
3179 Offset = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3180 SystemZII::MO_INDNTPOFF);
3181 Offset = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Offset);
3182 Offset =
3183 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Offset,
3184 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3185 break;
3186 }
3187
3188 case TLSModel::LocalExec: {
3189 // Force the offset into the constant pool and load it from there.
3190 SystemZConstantPoolValue *CPV =
3191 SystemZConstantPoolValue::Create(GV, SystemZCP::NTPOFF);
3192
3193 Offset = DAG.getConstantPool(CPV, PtrVT, 8);
3194 Offset = DAG.getLoad(
3195 PtrVT, DL, DAG.getEntryNode(), Offset,
3196 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3197 break;
3198 }
3199 }
3200
3201 // Add the base and offset together.
3202 return DAG.getNode(ISD::ADD, DL, PtrVT, TP, Offset);
3203}
3204
3205SDValue SystemZTargetLowering::lowerBlockAddress(BlockAddressSDNode *Node,
3206 SelectionDAG &DAG) const {
3207 SDLoc DL(Node);
3208 const BlockAddress *BA = Node->getBlockAddress();
3209 int64_t Offset = Node->getOffset();
3210 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3211
3212 SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset);
3213 Result = DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3214 return Result;
3215}
3216
3217SDValue SystemZTargetLowering::lowerJumpTable(JumpTableSDNode *JT,
3218 SelectionDAG &DAG) const {
3219 SDLoc DL(JT);
3220 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3221 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3222
3223 // Use LARL to load the address of the table.
3224 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3225}
3226
3227SDValue SystemZTargetLowering::lowerConstantPool(ConstantPoolSDNode *CP,
3228 SelectionDAG &DAG) const {
3229 SDLoc DL(CP);
3230 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3231
3232 SDValue Result;
3233 if (CP->isMachineConstantPoolEntry())
3234 Result = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
3235 CP->getAlignment());
3236 else
3237 Result = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
3238 CP->getAlignment(), CP->getOffset());
3239
3240 // Use LARL to load the address of the constant pool entry.
3241 return DAG.getNode(SystemZISD::PCREL_WRAPPER, DL, PtrVT, Result);
3242}
3243
3244SDValue SystemZTargetLowering::lowerFRAMEADDR(SDValue Op,
3245 SelectionDAG &DAG) const {
3246 auto *TFL =
3247 static_cast<const SystemZFrameLowering *>(Subtarget.getFrameLowering());
3248 MachineFunction &MF = DAG.getMachineFunction();
3249 MachineFrameInfo &MFI = MF.getFrameInfo();
3250 MFI.setFrameAddressIsTaken(true);
3251
3252 SDLoc DL(Op);
3253 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3254 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3255
3256 // Return null if the back chain is not present.
3257 bool HasBackChain = MF.getFunction().hasFnAttribute("backchain");
3258 if (TFL->usePackedStack(MF) && !HasBackChain)
3259 return DAG.getConstant(0, DL, PtrVT);
3260
3261 // By definition, the frame address is the address of the back chain.
3262 int BackChainIdx = TFL->getOrCreateFramePointerSaveIndex(MF);
3263 SDValue BackChain = DAG.getFrameIndex(BackChainIdx, PtrVT);
3264
3265 // FIXME The frontend should detect this case.
3266 if (Depth > 0) {
3267 report_fatal_error("Unsupported stack frame traversal count");
3268 }
3269
3270 return BackChain;
3271}
3272
3273SDValue SystemZTargetLowering::lowerRETURNADDR(SDValue Op,
3274 SelectionDAG &DAG) const {
3275 MachineFunction &MF = DAG.getMachineFunction();
3276 MachineFrameInfo &MFI = MF.getFrameInfo();
3277 MFI.setReturnAddressIsTaken(true);
3278
3279 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3280 return SDValue();
3281
3282 SDLoc DL(Op);
3283 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3284 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3285
3286 // FIXME The frontend should detect this case.
3287 if (Depth > 0) {
3288 report_fatal_error("Unsupported stack frame traversal count");
3289 }
3290
3291 // Return R14D, which has the return address. Mark it an implicit live-in.
3292 unsigned LinkReg = MF.addLiveIn(SystemZ::R14D, &SystemZ::GR64BitRegClass);
3293 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, LinkReg, PtrVT);
3294}
3295
3296SDValue SystemZTargetLowering::lowerBITCAST(SDValue Op,
3297 SelectionDAG &DAG) const {
3298 SDLoc DL(Op);
3299 SDValue In = Op.getOperand(0);
3300 EVT InVT = In.getValueType();
3301 EVT ResVT = Op.getValueType();
3302
3303 // Convert loads directly. This is normally done by DAGCombiner,
3304 // but we need this case for bitcasts that are created during lowering
3305 // and which are then lowered themselves.
3306 if (auto *LoadN = dyn_cast<LoadSDNode>(In))
3307 if (ISD::isNormalLoad(LoadN)) {
3308 SDValue NewLoad = DAG.getLoad(ResVT, DL, LoadN->getChain(),
3309 LoadN->getBasePtr(), LoadN->getMemOperand());
3310 // Update the chain uses.
3311 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadN, 1), NewLoad.getValue(1));
3312 return NewLoad;
3313 }
3314
3315 if (InVT == MVT::i32 && ResVT == MVT::f32) {
3316 SDValue In64;
3317 if (Subtarget.hasHighWord()) {
3318 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL,
3319 MVT::i64);
3320 In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
3321 MVT::i64, SDValue(U64, 0), In);
3322 } else {
3323 In64 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, In);
3324 In64 = DAG.getNode(ISD::SHL, DL, MVT::i64, In64,
3325 DAG.getConstant(32, DL, MVT::i64));
3326 }
3327 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::f64, In64);
3328 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32,
3329 DL, MVT::f32, Out64);
3330 }
3331 if (InVT == MVT::f32 && ResVT == MVT::i32) {
3332 SDNode *U64 = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::f64);
3333 SDValue In64 = DAG.getTargetInsertSubreg(SystemZ::subreg_h32, DL,
3334 MVT::f64, SDValue(U64, 0), In);
3335 SDValue Out64 = DAG.getNode(ISD::BITCAST, DL, MVT::i64, In64);
3336 if (Subtarget.hasHighWord())
3337 return DAG.getTargetExtractSubreg(SystemZ::subreg_h32, DL,
3338 MVT::i32, Out64);
3339 SDValue Shift = DAG.getNode(ISD::SRL, DL, MVT::i64, Out64,
3340 DAG.getConstant(32, DL, MVT::i64));
3341 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Shift);
3342 }
3343 llvm_unreachable("Unexpected bitcast combination")::llvm::llvm_unreachable_internal("Unexpected bitcast combination"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 3343)
;
3344}
3345
3346SDValue SystemZTargetLowering::lowerVASTART(SDValue Op,
3347 SelectionDAG &DAG) const {
3348 MachineFunction &MF = DAG.getMachineFunction();
3349 SystemZMachineFunctionInfo *FuncInfo =
3350 MF.getInfo<SystemZMachineFunctionInfo>();
3351 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3352
3353 SDValue Chain = Op.getOperand(0);
3354 SDValue Addr = Op.getOperand(1);
3355 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3356 SDLoc DL(Op);
3357
3358 // The initial values of each field.
3359 const unsigned NumFields = 4;
3360 SDValue Fields[NumFields] = {
3361 DAG.getConstant(FuncInfo->getVarArgsFirstGPR(), DL, PtrVT),
3362 DAG.getConstant(FuncInfo->getVarArgsFirstFPR(), DL, PtrVT),
3363 DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT),
3364 DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT)
3365 };
3366
3367 // Store each field into its respective slot.
3368 SDValue MemOps[NumFields];
3369 unsigned Offset = 0;
3370 for (unsigned I = 0; I < NumFields; ++I) {
3371 SDValue FieldAddr = Addr;
3372 if (Offset != 0)
3373 FieldAddr = DAG.getNode(ISD::ADD, DL, PtrVT, FieldAddr,
3374 DAG.getIntPtrConstant(Offset, DL));
3375 MemOps[I] = DAG.getStore(Chain, DL, Fields[I], FieldAddr,
3376 MachinePointerInfo(SV, Offset));
3377 Offset += 8;
3378 }
3379 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3380}
3381
3382SDValue SystemZTargetLowering::lowerVACOPY(SDValue Op,
3383 SelectionDAG &DAG) const {
3384 SDValue Chain = Op.getOperand(0);
3385 SDValue DstPtr = Op.getOperand(1);
3386 SDValue SrcPtr = Op.getOperand(2);
3387 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3388 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3389 SDLoc DL(Op);
3390
3391 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr, DAG.getIntPtrConstant(32, DL),
3392 Align(8), /*isVolatile*/ false, /*AlwaysInline*/ false,
3393 /*isTailCall*/ false, MachinePointerInfo(DstSV),
3394 MachinePointerInfo(SrcSV));
3395}
3396
3397SDValue SystemZTargetLowering::
3398lowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
3399 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
3400 MachineFunction &MF = DAG.getMachineFunction();
3401 bool RealignOpt = !MF.getFunction().hasFnAttribute("no-realign-stack");
3402 bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
3403
3404 SDValue Chain = Op.getOperand(0);
3405 SDValue Size = Op.getOperand(1);
3406 SDValue Align = Op.getOperand(2);
3407 SDLoc DL(Op);
3408
3409 // If user has set the no alignment function attribute, ignore
3410 // alloca alignments.
3411 uint64_t AlignVal = (RealignOpt ?
3412 dyn_cast<ConstantSDNode>(Align)->getZExtValue() : 0);
3413
3414 uint64_t StackAlign = TFI->getStackAlignment();
3415 uint64_t RequiredAlign = std::max(AlignVal, StackAlign);
3416 uint64_t ExtraAlignSpace = RequiredAlign - StackAlign;
3417
3418 unsigned SPReg = getStackPointerRegisterToSaveRestore();
3419 SDValue NeededSpace = Size;
3420
3421 // Get a reference to the stack pointer.
3422 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SPReg, MVT::i64);
3423
3424 // If we need a backchain, save it now.
3425 SDValue Backchain;
3426 if (StoreBackchain)
3427 Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
3428
3429 // Add extra space for alignment if needed.
3430 if (ExtraAlignSpace)
3431 NeededSpace = DAG.getNode(ISD::ADD, DL, MVT::i64, NeededSpace,
3432 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3433
3434 // Get the new stack pointer value.
3435 SDValue NewSP = DAG.getNode(ISD::SUB, DL, MVT::i64, OldSP, NeededSpace);
3436
3437 // Copy the new stack pointer back.
3438 Chain = DAG.getCopyToReg(Chain, DL, SPReg, NewSP);
3439
3440 // The allocated data lives above the 160 bytes allocated for the standard
3441 // frame, plus any outgoing stack arguments. We don't know how much that
3442 // amounts to yet, so emit a special ADJDYNALLOC placeholder.
3443 SDValue ArgAdjust = DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
3444 SDValue Result = DAG.getNode(ISD::ADD, DL, MVT::i64, NewSP, ArgAdjust);
3445
3446 // Dynamically realign if needed.
3447 if (RequiredAlign > StackAlign) {
3448 Result =
3449 DAG.getNode(ISD::ADD, DL, MVT::i64, Result,
3450 DAG.getConstant(ExtraAlignSpace, DL, MVT::i64));
3451 Result =
3452 DAG.getNode(ISD::AND, DL, MVT::i64, Result,
3453 DAG.getConstant(~(RequiredAlign - 1), DL, MVT::i64));
3454 }
3455
3456 if (StoreBackchain)
3457 Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
3458
3459 SDValue Ops[2] = { Result, Chain };
3460 return DAG.getMergeValues(Ops, DL);
3461}
3462
3463SDValue SystemZTargetLowering::lowerGET_DYNAMIC_AREA_OFFSET(
3464 SDValue Op, SelectionDAG &DAG) const {
3465 SDLoc DL(Op);
3466
3467 return DAG.getNode(SystemZISD::ADJDYNALLOC, DL, MVT::i64);
3468}
3469
3470SDValue SystemZTargetLowering::lowerSMUL_LOHI(SDValue Op,
3471 SelectionDAG &DAG) const {
3472 EVT VT = Op.getValueType();
3473 SDLoc DL(Op);
3474 SDValue Ops[2];
3475 if (is32Bit(VT))
3476 // Just do a normal 64-bit multiplication and extract the results.
3477 // We define this so that it can be used for constant division.
3478 lowerMUL_LOHI32(DAG, DL, ISD::SIGN_EXTEND, Op.getOperand(0),
3479 Op.getOperand(1), Ops[1], Ops[0]);
3480 else if (Subtarget.hasMiscellaneousExtensions2())
3481 // SystemZISD::SMUL_LOHI returns the low result in the odd register and
3482 // the high result in the even register. ISD::SMUL_LOHI is defined to
3483 // return the low half first, so the results are in reverse order.
3484 lowerGR128Binary(DAG, DL, VT, SystemZISD::SMUL_LOHI,
3485 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3486 else {
3487 // Do a full 128-bit multiplication based on SystemZISD::UMUL_LOHI:
3488 //
3489 // (ll * rl) + ((lh * rl) << 64) + ((ll * rh) << 64)
3490 //
3491 // but using the fact that the upper halves are either all zeros
3492 // or all ones:
3493 //
3494 // (ll * rl) - ((lh & rl) << 64) - ((ll & rh) << 64)
3495 //
3496 // and grouping the right terms together since they are quicker than the
3497 // multiplication:
3498 //
3499 // (ll * rl) - (((lh & rl) + (ll & rh)) << 64)
3500 SDValue C63 = DAG.getConstant(63, DL, MVT::i64);
3501 SDValue LL = Op.getOperand(0);
3502 SDValue RL = Op.getOperand(1);
3503 SDValue LH = DAG.getNode(ISD::SRA, DL, VT, LL, C63);
3504 SDValue RH = DAG.getNode(ISD::SRA, DL, VT, RL, C63);
3505 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
3506 // the high result in the even register. ISD::SMUL_LOHI is defined to
3507 // return the low half first, so the results are in reverse order.
3508 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
3509 LL, RL, Ops[1], Ops[0]);
3510 SDValue NegLLTimesRH = DAG.getNode(ISD::AND, DL, VT, LL, RH);
3511 SDValue NegLHTimesRL = DAG.getNode(ISD::AND, DL, VT, LH, RL);
3512 SDValue NegSum = DAG.getNode(ISD::ADD, DL, VT, NegLLTimesRH, NegLHTimesRL);
3513 Ops[1] = DAG.getNode(ISD::SUB, DL, VT, Ops[1], NegSum);
3514 }
3515 return DAG.getMergeValues(Ops, DL);
3516}
3517
3518SDValue SystemZTargetLowering::lowerUMUL_LOHI(SDValue Op,
3519 SelectionDAG &DAG) const {
3520 EVT VT = Op.getValueType();
3521 SDLoc DL(Op);
3522 SDValue Ops[2];
3523 if (is32Bit(VT))
3524 // Just do a normal 64-bit multiplication and extract the results.
3525 // We define this so that it can be used for constant division.
3526 lowerMUL_LOHI32(DAG, DL, ISD::ZERO_EXTEND, Op.getOperand(0),
3527 Op.getOperand(1), Ops[1], Ops[0]);
3528 else
3529 // SystemZISD::UMUL_LOHI returns the low result in the odd register and
3530 // the high result in the even register. ISD::UMUL_LOHI is defined to
3531 // return the low half first, so the results are in reverse order.
3532 lowerGR128Binary(DAG, DL, VT, SystemZISD::UMUL_LOHI,
3533 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3534 return DAG.getMergeValues(Ops, DL);
3535}
3536
3537SDValue SystemZTargetLowering::lowerSDIVREM(SDValue Op,
3538 SelectionDAG &DAG) const {
3539 SDValue Op0 = Op.getOperand(0);
3540 SDValue Op1 = Op.getOperand(1);
3541 EVT VT = Op.getValueType();
3542 SDLoc DL(Op);
3543
3544 // We use DSGF for 32-bit division. This means the first operand must
3545 // always be 64-bit, and the second operand should be 32-bit whenever
3546 // that is possible, to improve performance.
3547 if (is32Bit(VT))
3548 Op0 = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Op0);
3549 else if (DAG.ComputeNumSignBits(Op1) > 32)
3550 Op1 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Op1);
3551
3552 // DSG(F) returns the remainder in the even register and the
3553 // quotient in the odd register.
3554 SDValue Ops[2];
3555 lowerGR128Binary(DAG, DL, VT, SystemZISD::SDIVREM, Op0, Op1, Ops[1], Ops[0]);
3556 return DAG.getMergeValues(Ops, DL);
3557}
3558
3559SDValue SystemZTargetLowering::lowerUDIVREM(SDValue Op,
3560 SelectionDAG &DAG) const {
3561 EVT VT = Op.getValueType();
3562 SDLoc DL(Op);
3563
3564 // DL(G) returns the remainder in the even register and the
3565 // quotient in the odd register.
3566 SDValue Ops[2];
3567 lowerGR128Binary(DAG, DL, VT, SystemZISD::UDIVREM,
3568 Op.getOperand(0), Op.getOperand(1), Ops[1], Ops[0]);
3569 return DAG.getMergeValues(Ops, DL);
3570}
3571
3572SDValue SystemZTargetLowering::lowerOR(SDValue Op, SelectionDAG &DAG) const {
3573 assert(Op.getValueType() == MVT::i64 && "Should be 64-bit operation")((Op.getValueType() == MVT::i64 && "Should be 64-bit operation"
) ? static_cast<void> (0) : __assert_fail ("Op.getValueType() == MVT::i64 && \"Should be 64-bit operation\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 3573, __PRETTY_FUNCTION__))
;
3574
3575 // Get the known-zero masks for each operand.
3576 SDValue Ops[] = {Op.getOperand(0), Op.getOperand(1)};
3577 KnownBits Known[2] = {DAG.computeKnownBits(Ops[0]),
3578 DAG.computeKnownBits(Ops[1])};
3579
3580 // See if the upper 32 bits of one operand and the lower 32 bits of the
3581 // other are known zero. They are the low and high operands respectively.
3582 uint64_t Masks[] = { Known[0].Zero.getZExtValue(),
3583 Known[1].Zero.getZExtValue() };
3584 unsigned High, Low;
3585 if ((Masks[0] >> 32) == 0xffffffff && uint32_t(Masks[1]) == 0xffffffff)
3586 High = 1, Low = 0;
3587 else if ((Masks[1] >> 32) == 0xffffffff && uint32_t(Masks[0]) == 0xffffffff)
3588 High = 0, Low = 1;
3589 else
3590 return Op;
3591
3592 SDValue LowOp = Ops[Low];
3593 SDValue HighOp = Ops[High];
3594
3595 // If the high part is a constant, we're better off using IILH.
3596 if (HighOp.getOpcode() == ISD::Constant)
3597 return Op;
3598
3599 // If the low part is a constant that is outside the range of LHI,
3600 // then we're better off using IILF.
3601 if (LowOp.getOpcode() == ISD::Constant) {
3602 int64_t Value = int32_t(cast<ConstantSDNode>(LowOp)->getZExtValue());
3603 if (!isInt<16>(Value))
3604 return Op;
3605 }
3606
3607 // Check whether the high part is an AND that doesn't change the
3608 // high 32 bits and just masks out low bits. We can skip it if so.
3609 if (HighOp.getOpcode() == ISD::AND &&
3610 HighOp.getOperand(1).getOpcode() == ISD::Constant) {
3611 SDValue HighOp0 = HighOp.getOperand(0);
3612 uint64_t Mask = cast<ConstantSDNode>(HighOp.getOperand(1))->getZExtValue();
3613 if (DAG.MaskedValueIsZero(HighOp0, APInt(64, ~(Mask | 0xffffffff))))
3614 HighOp = HighOp0;
3615 }
3616
3617 // Take advantage of the fact that all GR32 operations only change the
3618 // low 32 bits by truncating Low to an i32 and inserting it directly
3619 // using a subreg. The interesting cases are those where the truncation
3620 // can be folded.
3621 SDLoc DL(Op);
3622 SDValue Low32 = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, LowOp);
3623 return DAG.getTargetInsertSubreg(SystemZ::subreg_l32, DL,
3624 MVT::i64, HighOp, Low32);
3625}
3626
3627// Lower SADDO/SSUBO/UADDO/USUBO nodes.
3628SDValue SystemZTargetLowering::lowerXALUO(SDValue Op,
3629 SelectionDAG &DAG) const {
3630 SDNode *N = Op.getNode();
3631 SDValue LHS = N->getOperand(0);
3632 SDValue RHS = N->getOperand(1);
3633 SDLoc DL(N);
3634 unsigned BaseOp = 0;
3635 unsigned CCValid = 0;
3636 unsigned CCMask = 0;
3637
3638 switch (Op.getOpcode()) {
3639 default: llvm_unreachable("Unknown instruction!")::llvm::llvm_unreachable_internal("Unknown instruction!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 3639)
;
3640 case ISD::SADDO:
3641 BaseOp = SystemZISD::SADDO;
3642 CCValid = SystemZ::CCMASK_ARITH;
3643 CCMask = SystemZ::CCMASK_ARITH_OVERFLOW;
3644 break;
3645 case ISD::SSUBO:
3646 BaseOp = SystemZISD::SSUBO;
3647 CCValid = SystemZ::CCMASK_ARITH;
3648 CCMask = SystemZ::CCMASK_ARITH_OVERFLOW;
3649 break;
3650 case ISD::UADDO:
3651 BaseOp = SystemZISD::UADDO;
3652 CCValid = SystemZ::CCMASK_LOGICAL;
3653 CCMask = SystemZ::CCMASK_LOGICAL_CARRY;
3654 break;
3655 case ISD::USUBO:
3656 BaseOp = SystemZISD::USUBO;
3657 CCValid = SystemZ::CCMASK_LOGICAL;
3658 CCMask = SystemZ::CCMASK_LOGICAL_BORROW;
3659 break;
3660 }
3661
3662 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
3663 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
3664
3665 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
3666 if (N->getValueType(1) == MVT::i1)
3667 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
3668
3669 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
3670}
3671
3672static bool isAddCarryChain(SDValue Carry) {
3673 while (Carry.getOpcode() == ISD::ADDCARRY)
3674 Carry = Carry.getOperand(2);
3675 return Carry.getOpcode() == ISD::UADDO;
3676}
3677
3678static bool isSubBorrowChain(SDValue Carry) {
3679 while (Carry.getOpcode() == ISD::SUBCARRY)
3680 Carry = Carry.getOperand(2);
3681 return Carry.getOpcode() == ISD::USUBO;
3682}
3683
3684// Lower ADDCARRY/SUBCARRY nodes.
3685SDValue SystemZTargetLowering::lowerADDSUBCARRY(SDValue Op,
3686 SelectionDAG &DAG) const {
3687
3688 SDNode *N = Op.getNode();
3689 MVT VT = N->getSimpleValueType(0);
3690
3691 // Let legalize expand this if it isn't a legal type yet.
3692 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3693 return SDValue();
3694
3695 SDValue LHS = N->getOperand(0);
3696 SDValue RHS = N->getOperand(1);
3697 SDValue Carry = Op.getOperand(2);
3698 SDLoc DL(N);
3699 unsigned BaseOp = 0;
3700 unsigned CCValid = 0;
3701 unsigned CCMask = 0;
3702
3703 switch (Op.getOpcode()) {
3704 default: llvm_unreachable("Unknown instruction!")::llvm::llvm_unreachable_internal("Unknown instruction!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 3704)
;
3705 case ISD::ADDCARRY:
3706 if (!isAddCarryChain(Carry))
3707 return SDValue();
3708
3709 BaseOp = SystemZISD::ADDCARRY;
3710 CCValid = SystemZ::CCMASK_LOGICAL;
3711 CCMask = SystemZ::CCMASK_LOGICAL_CARRY;
3712 break;
3713 case ISD::SUBCARRY:
3714 if (!isSubBorrowChain(Carry))
3715 return SDValue();
3716
3717 BaseOp = SystemZISD::SUBCARRY;
3718 CCValid = SystemZ::CCMASK_LOGICAL;
3719 CCMask = SystemZ::CCMASK_LOGICAL_BORROW;
3720 break;
3721 }
3722
3723 // Set the condition code from the carry flag.
3724 Carry = DAG.getNode(SystemZISD::GET_CCMASK, DL, MVT::i32, Carry,
3725 DAG.getConstant(CCValid, DL, MVT::i32),
3726 DAG.getConstant(CCMask, DL, MVT::i32));
3727
3728 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
3729 SDValue Result = DAG.getNode(BaseOp, DL, VTs, LHS, RHS, Carry);
3730
3731 SDValue SetCC = emitSETCC(DAG, DL, Result.getValue(1), CCValid, CCMask);
3732 if (N->getValueType(1) == MVT::i1)
3733 SetCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, SetCC);
3734
3735 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, SetCC);
3736}
3737
3738SDValue SystemZTargetLowering::lowerCTPOP(SDValue Op,
3739 SelectionDAG &DAG) const {
3740 EVT VT = Op.getValueType();
3741 SDLoc DL(Op);
3742 Op = Op.getOperand(0);
3743
3744 // Handle vector types via VPOPCT.
3745 if (VT.isVector()) {
3746 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Op);
3747 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::v16i8, Op);
3748 switch (VT.getScalarSizeInBits()) {
3749 case 8:
3750 break;
3751 case 16: {
3752 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
3753 SDValue Shift = DAG.getConstant(8, DL, MVT::i32);
3754 SDValue Tmp = DAG.getNode(SystemZISD::VSHL_BY_SCALAR, DL, VT, Op, Shift);
3755 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3756 Op = DAG.getNode(SystemZISD::VSRL_BY_SCALAR, DL, VT, Op, Shift);
3757 break;
3758 }
3759 case 32: {
3760 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
3761 DAG.getConstant(0, DL, MVT::i32));
3762 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3763 break;
3764 }
3765 case 64: {
3766 SDValue Tmp = DAG.getSplatBuildVector(MVT::v16i8, DL,
3767 DAG.getConstant(0, DL, MVT::i32));
3768 Op = DAG.getNode(SystemZISD::VSUM, DL, MVT::v4i32, Op, Tmp);
3769 Op = DAG.getNode(SystemZISD::VSUM, DL, VT, Op, Tmp);
3770 break;
3771 }
3772 default:
3773 llvm_unreachable("Unexpected type")::llvm::llvm_unreachable_internal("Unexpected type", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 3773)
;
3774 }
3775 return Op;
3776 }
3777
3778 // Get the known-zero mask for the operand.
3779 KnownBits Known = DAG.computeKnownBits(Op);
3780 unsigned NumSignificantBits = Known.getMaxValue().getActiveBits();
3781 if (NumSignificantBits == 0)
3782 return DAG.getConstant(0, DL, VT);
3783
3784 // Skip known-zero high parts of the operand.
3785 int64_t OrigBitSize = VT.getSizeInBits();
3786 int64_t BitSize = (int64_t)1 << Log2_32_Ceil(NumSignificantBits);
3787 BitSize = std::min(BitSize, OrigBitSize);
3788
3789 // The POPCNT instruction counts the number of bits in each byte.
3790 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op);
3791 Op = DAG.getNode(SystemZISD::POPCNT, DL, MVT::i64, Op);
3792 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
3793
3794 // Add up per-byte counts in a binary tree. All bits of Op at
3795 // position larger than BitSize remain zero throughout.
3796 for (int64_t I = BitSize / 2; I >= 8; I = I / 2) {
3797 SDValue Tmp = DAG.getNode(ISD::SHL, DL, VT, Op, DAG.getConstant(I, DL, VT));
3798 if (BitSize != OrigBitSize)
3799 Tmp = DAG.getNode(ISD::AND, DL, VT, Tmp,
3800 DAG.getConstant(((uint64_t)1 << BitSize) - 1, DL, VT));
3801 Op = DAG.getNode(ISD::ADD, DL, VT, Op, Tmp);
3802 }
3803
3804 // Extract overall result from high byte.
3805 if (BitSize > 8)
3806 Op = DAG.getNode(ISD::SRL, DL, VT, Op,
3807 DAG.getConstant(BitSize - 8, DL, VT));
3808
3809 return Op;
3810}
3811
3812SDValue SystemZTargetLowering::lowerATOMIC_FENCE(SDValue Op,
3813 SelectionDAG &DAG) const {
3814 SDLoc DL(Op);
3815 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
3816 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
3817 SyncScope::ID FenceSSID = static_cast<SyncScope::ID>(
3818 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
3819
3820 // The only fence that needs an instruction is a sequentially-consistent
3821 // cross-thread fence.
3822 if (FenceOrdering == AtomicOrdering::SequentiallyConsistent &&
3823 FenceSSID == SyncScope::System) {
3824 return SDValue(DAG.getMachineNode(SystemZ::Serialize, DL, MVT::Other,
3825 Op.getOperand(0)),
3826 0);
3827 }
3828
3829 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
3830 return DAG.getNode(SystemZISD::MEMBARRIER, DL, MVT::Other, Op.getOperand(0));
3831}
3832
3833// Op is an atomic load. Lower it into a normal volatile load.
3834SDValue SystemZTargetLowering::lowerATOMIC_LOAD(SDValue Op,
3835 SelectionDAG &DAG) const {
3836 auto *Node = cast<AtomicSDNode>(Op.getNode());
3837 return DAG.getExtLoad(ISD::EXTLOAD, SDLoc(Op), Op.getValueType(),
3838 Node->getChain(), Node->getBasePtr(),
3839 Node->getMemoryVT(), Node->getMemOperand());
3840}
3841
3842// Op is an atomic store. Lower it into a normal volatile store.
3843SDValue SystemZTargetLowering::lowerATOMIC_STORE(SDValue Op,
3844 SelectionDAG &DAG) const {
3845 auto *Node = cast<AtomicSDNode>(Op.getNode());
3846 SDValue Chain = DAG.getTruncStore(Node->getChain(), SDLoc(Op), Node->getVal(),
3847 Node->getBasePtr(), Node->getMemoryVT(),
3848 Node->getMemOperand());
3849 // We have to enforce sequential consistency by performing a
3850 // serialization operation after the store.
3851 if (Node->getOrdering() == AtomicOrdering::SequentiallyConsistent)
3852 Chain = SDValue(DAG.getMachineNode(SystemZ::Serialize, SDLoc(Op),
3853 MVT::Other, Chain), 0);
3854 return Chain;
3855}
3856
3857// Op is an 8-, 16-bit or 32-bit ATOMIC_LOAD_* operation. Lower the first
3858// two into the fullword ATOMIC_LOADW_* operation given by Opcode.
3859SDValue SystemZTargetLowering::lowerATOMIC_LOAD_OP(SDValue Op,
3860 SelectionDAG &DAG,
3861 unsigned Opcode) const {
3862 auto *Node = cast<AtomicSDNode>(Op.getNode());
3863
3864 // 32-bit operations need no code outside the main loop.
3865 EVT NarrowVT = Node->getMemoryVT();
3866 EVT WideVT = MVT::i32;
3867 if (NarrowVT == WideVT)
3868 return Op;
3869
3870 int64_t BitSize = NarrowVT.getSizeInBits();
3871 SDValue ChainIn = Node->getChain();
3872 SDValue Addr = Node->getBasePtr();
3873 SDValue Src2 = Node->getVal();
3874 MachineMemOperand *MMO = Node->getMemOperand();
3875 SDLoc DL(Node);
3876 EVT PtrVT = Addr.getValueType();
3877
3878 // Convert atomic subtracts of constants into additions.
3879 if (Opcode == SystemZISD::ATOMIC_LOADW_SUB)
3880 if (auto *Const = dyn_cast<ConstantSDNode>(Src2)) {
3881 Opcode = SystemZISD::ATOMIC_LOADW_ADD;
3882 Src2 = DAG.getConstant(-Const->getSExtValue(), DL, Src2.getValueType());
3883 }
3884
3885 // Get the address of the containing word.
3886 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
3887 DAG.getConstant(-4, DL, PtrVT));
3888
3889 // Get the number of bits that the word must be rotated left in order
3890 // to bring the field to the top bits of a GR32.
3891 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
3892 DAG.getConstant(3, DL, PtrVT));
3893 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
3894
3895 // Get the complementing shift amount, for rotating a field in the top
3896 // bits back to its proper position.
3897 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
3898 DAG.getConstant(0, DL, WideVT), BitShift);
3899
3900 // Extend the source operand to 32 bits and prepare it for the inner loop.
3901 // ATOMIC_SWAPW uses RISBG to rotate the field left, but all other
3902 // operations require the source to be shifted in advance. (This shift
3903 // can be folded if the source is constant.) For AND and NAND, the lower
3904 // bits must be set, while for other opcodes they should be left clear.
3905 if (Opcode != SystemZISD::ATOMIC_SWAPW)
3906 Src2 = DAG.getNode(ISD::SHL, DL, WideVT, Src2,
3907 DAG.getConstant(32 - BitSize, DL, WideVT));
3908 if (Opcode == SystemZISD::ATOMIC_LOADW_AND ||
3909 Opcode == SystemZISD::ATOMIC_LOADW_NAND)
3910 Src2 = DAG.getNode(ISD::OR, DL, WideVT, Src2,
3911 DAG.getConstant(uint32_t(-1) >> BitSize, DL, WideVT));
3912
3913 // Construct the ATOMIC_LOADW_* node.
3914 SDVTList VTList = DAG.getVTList(WideVT, MVT::Other);
3915 SDValue Ops[] = { ChainIn, AlignedAddr, Src2, BitShift, NegBitShift,
3916 DAG.getConstant(BitSize, DL, WideVT) };
3917 SDValue AtomicOp = DAG.getMemIntrinsicNode(Opcode, DL, VTList, Ops,
3918 NarrowVT, MMO);
3919
3920 // Rotate the result of the final CS so that the field is in the lower
3921 // bits of a GR32, then truncate it.
3922 SDValue ResultShift = DAG.getNode(ISD::ADD, DL, WideVT, BitShift,
3923 DAG.getConstant(BitSize, DL, WideVT));
3924 SDValue Result = DAG.getNode(ISD::ROTL, DL, WideVT, AtomicOp, ResultShift);
3925
3926 SDValue RetOps[2] = { Result, AtomicOp.getValue(1) };
3927 return DAG.getMergeValues(RetOps, DL);
3928}
3929
3930// Op is an ATOMIC_LOAD_SUB operation. Lower 8- and 16-bit operations
3931// into ATOMIC_LOADW_SUBs and decide whether to convert 32- and 64-bit
3932// operations into additions.
3933SDValue SystemZTargetLowering::lowerATOMIC_LOAD_SUB(SDValue Op,
3934 SelectionDAG &DAG) const {
3935 auto *Node = cast<AtomicSDNode>(Op.getNode());
3936 EVT MemVT = Node->getMemoryVT();
3937 if (MemVT == MVT::i32 || MemVT == MVT::i64) {
3938 // A full-width operation.
3939 assert(Op.getValueType() == MemVT && "Mismatched VTs")((Op.getValueType() == MemVT && "Mismatched VTs") ? static_cast
<void> (0) : __assert_fail ("Op.getValueType() == MemVT && \"Mismatched VTs\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 3939, __PRETTY_FUNCTION__))
;
3940 SDValue Src2 = Node->getVal();
3941 SDValue NegSrc2;
3942 SDLoc DL(Src2);
3943
3944 if (auto *Op2 = dyn_cast<ConstantSDNode>(Src2)) {
3945 // Use an addition if the operand is constant and either LAA(G) is
3946 // available or the negative value is in the range of A(G)FHI.
3947 int64_t Value = (-Op2->getAPIntValue()).getSExtValue();
3948 if (isInt<32>(Value) || Subtarget.hasInterlockedAccess1())
3949 NegSrc2 = DAG.getConstant(Value, DL, MemVT);
3950 } else if (Subtarget.hasInterlockedAccess1())
3951 // Use LAA(G) if available.
3952 NegSrc2 = DAG.getNode(ISD::SUB, DL, MemVT, DAG.getConstant(0, DL, MemVT),
3953 Src2);
3954
3955 if (NegSrc2.getNode())
3956 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, DL, MemVT,
3957 Node->getChain(), Node->getBasePtr(), NegSrc2,
3958 Node->getMemOperand());
3959
3960 // Use the node as-is.
3961 return Op;
3962 }
3963
3964 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_SUB);
3965}
3966
3967// Lower 8/16/32/64-bit ATOMIC_CMP_SWAP_WITH_SUCCESS node.
3968SDValue SystemZTargetLowering::lowerATOMIC_CMP_SWAP(SDValue Op,
3969 SelectionDAG &DAG) const {
3970 auto *Node = cast<AtomicSDNode>(Op.getNode());
3971 SDValue ChainIn = Node->getOperand(0);
3972 SDValue Addr = Node->getOperand(1);
3973 SDValue CmpVal = Node->getOperand(2);
3974 SDValue SwapVal = Node->getOperand(3);
3975 MachineMemOperand *MMO = Node->getMemOperand();
3976 SDLoc DL(Node);
3977
3978 // We have native support for 32-bit and 64-bit compare and swap, but we
3979 // still need to expand extracting the "success" result from the CC.
3980 EVT NarrowVT = Node->getMemoryVT();
3981 EVT WideVT = NarrowVT == MVT::i64 ? MVT::i64 : MVT::i32;
3982 if (NarrowVT == WideVT) {
3983 SDVTList Tys = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
3984 SDValue Ops[] = { ChainIn, Addr, CmpVal, SwapVal };
3985 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP,
3986 DL, Tys, Ops, NarrowVT, MMO);
3987 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
3988 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ);
3989
3990 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
3991 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
3992 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
3993 return SDValue();
3994 }
3995
3996 // Convert 8-bit and 16-bit compare and swap to a loop, implemented
3997 // via a fullword ATOMIC_CMP_SWAPW operation.
3998 int64_t BitSize = NarrowVT.getSizeInBits();
3999 EVT PtrVT = Addr.getValueType();
4000
4001 // Get the address of the containing word.
4002 SDValue AlignedAddr = DAG.getNode(ISD::AND, DL, PtrVT, Addr,
4003 DAG.getConstant(-4, DL, PtrVT));
4004
4005 // Get the number of bits that the word must be rotated left in order
4006 // to bring the field to the top bits of a GR32.
4007 SDValue BitShift = DAG.getNode(ISD::SHL, DL, PtrVT, Addr,
4008 DAG.getConstant(3, DL, PtrVT));
4009 BitShift = DAG.getNode(ISD::TRUNCATE, DL, WideVT, BitShift);
4010
4011 // Get the complementing shift amount, for rotating a field in the top
4012 // bits back to its proper position.
4013 SDValue NegBitShift = DAG.getNode(ISD::SUB, DL, WideVT,
4014 DAG.getConstant(0, DL, WideVT), BitShift);
4015
4016 // Construct the ATOMIC_CMP_SWAPW node.
4017 SDVTList VTList = DAG.getVTList(WideVT, MVT::i32, MVT::Other);
4018 SDValue Ops[] = { ChainIn, AlignedAddr, CmpVal, SwapVal, BitShift,
4019 NegBitShift, DAG.getConstant(BitSize, DL, WideVT) };
4020 SDValue AtomicOp = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAPW, DL,
4021 VTList, Ops, NarrowVT, MMO);
4022 SDValue Success = emitSETCC(DAG, DL, AtomicOp.getValue(1),
4023 SystemZ::CCMASK_ICMP, SystemZ::CCMASK_CMP_EQ);
4024
4025 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), AtomicOp.getValue(0));
4026 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
4027 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), AtomicOp.getValue(2));
4028 return SDValue();
4029}
4030
4031MachineMemOperand::Flags
4032SystemZTargetLowering::getTargetMMOFlags(const Instruction &I) const {
4033 // Because of how we convert atomic_load and atomic_store to normal loads and
4034 // stores in the DAG, we need to ensure that the MMOs are marked volatile
4035 // since DAGCombine hasn't been updated to account for atomic, but non
4036 // volatile loads. (See D57601)
4037 if (auto *SI = dyn_cast<StoreInst>(&I))
4038 if (SI->isAtomic())
4039 return MachineMemOperand::MOVolatile;
4040 if (auto *LI = dyn_cast<LoadInst>(&I))
4041 if (LI->isAtomic())
4042 return MachineMemOperand::MOVolatile;
4043 if (auto *AI = dyn_cast<AtomicRMWInst>(&I))
4044 if (AI->isAtomic())
4045 return MachineMemOperand::MOVolatile;
4046 if (auto *AI = dyn_cast<AtomicCmpXchgInst>(&I))
4047 if (AI->isAtomic())
4048 return MachineMemOperand::MOVolatile;
4049 return MachineMemOperand::MONone;
4050}
4051
4052SDValue SystemZTargetLowering::lowerSTACKSAVE(SDValue Op,
4053 SelectionDAG &DAG) const {
4054 MachineFunction &MF = DAG.getMachineFunction();
4055 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
4056 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
4057 report_fatal_error("Variable-sized stack allocations are not supported "
4058 "in GHC calling convention");
4059 return DAG.getCopyFromReg(Op.getOperand(0), SDLoc(Op),
4060 SystemZ::R15D, Op.getValueType());
4061}
4062
4063SDValue SystemZTargetLowering::lowerSTACKRESTORE(SDValue Op,
4064 SelectionDAG &DAG) const {
4065 MachineFunction &MF = DAG.getMachineFunction();
4066 MF.getInfo<SystemZMachineFunctionInfo>()->setManipulatesSP(true);
4067 bool StoreBackchain = MF.getFunction().hasFnAttribute("backchain");
4068
4069 if (MF.getFunction().getCallingConv() == CallingConv::GHC)
4070 report_fatal_error("Variable-sized stack allocations are not supported "
4071 "in GHC calling convention");
4072
4073 SDValue Chain = Op.getOperand(0);
4074 SDValue NewSP = Op.getOperand(1);
4075 SDValue Backchain;
4076 SDLoc DL(Op);
4077
4078 if (StoreBackchain) {
4079 SDValue OldSP = DAG.getCopyFromReg(Chain, DL, SystemZ::R15D, MVT::i64);
4080 Backchain = DAG.getLoad(MVT::i64, DL, Chain, OldSP, MachinePointerInfo());
4081 }
4082
4083 Chain = DAG.getCopyToReg(Chain, DL, SystemZ::R15D, NewSP);
4084
4085 if (StoreBackchain)
4086 Chain = DAG.getStore(Chain, DL, Backchain, NewSP, MachinePointerInfo());
4087
4088 return Chain;
4089}
4090
4091SDValue SystemZTargetLowering::lowerPREFETCH(SDValue Op,
4092 SelectionDAG &DAG) const {
4093 bool IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4094 if (!IsData)
4095 // Just preserve the chain.
4096 return Op.getOperand(0);
4097
4098 SDLoc DL(Op);
4099 bool IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
4100 unsigned Code = IsWrite ? SystemZ::PFD_WRITE : SystemZ::PFD_READ;
4101 auto *Node = cast<MemIntrinsicSDNode>(Op.getNode());
4102 SDValue Ops[] = {Op.getOperand(0), DAG.getTargetConstant(Code, DL, MVT::i32),
4103 Op.getOperand(1)};
4104 return DAG.getMemIntrinsicNode(SystemZISD::PREFETCH, DL,
4105 Node->getVTList(), Ops,
4106 Node->getMemoryVT(), Node->getMemOperand());
4107}
4108
4109// Convert condition code in CCReg to an i32 value.
4110static SDValue getCCResult(SelectionDAG &DAG, SDValue CCReg) {
4111 SDLoc DL(CCReg);
4112 SDValue IPM = DAG.getNode(SystemZISD::IPM, DL, MVT::i32, CCReg);
4113 return DAG.getNode(ISD::SRL, DL, MVT::i32, IPM,
4114 DAG.getConstant(SystemZ::IPM_CC, DL, MVT::i32));
4115}
4116
4117SDValue
4118SystemZTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
4119 SelectionDAG &DAG) const {
4120 unsigned Opcode, CCValid;
4121 if (isIntrinsicWithCCAndChain(Op, Opcode, CCValid)) {
4122 assert(Op->getNumValues() == 2 && "Expected only CC result and chain")((Op->getNumValues() == 2 && "Expected only CC result and chain"
) ? static_cast<void> (0) : __assert_fail ("Op->getNumValues() == 2 && \"Expected only CC result and chain\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 4122, __PRETTY_FUNCTION__))
;
4123 SDNode *Node = emitIntrinsicWithCCAndChain(DAG, Op, Opcode);
4124 SDValue CC = getCCResult(DAG, SDValue(Node, 0));
4125 DAG.ReplaceAllUsesOfValueWith(SDValue(Op.getNode(), 0), CC);
4126 return SDValue();
4127 }
4128
4129 return SDValue();
4130}
4131
4132SDValue
4133SystemZTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
4134 SelectionDAG &DAG) const {
4135 unsigned Opcode, CCValid;
4136 if (isIntrinsicWithCC(Op, Opcode, CCValid)) {
4137 SDNode *Node = emitIntrinsicWithCC(DAG, Op, Opcode);
4138 if (Op->getNumValues() == 1)
4139 return getCCResult(DAG, SDValue(Node, 0));
4140 assert(Op->getNumValues() == 2 && "Expected a CC and non-CC result")((Op->getNumValues() == 2 && "Expected a CC and non-CC result"
) ? static_cast<void> (0) : __assert_fail ("Op->getNumValues() == 2 && \"Expected a CC and non-CC result\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 4140, __PRETTY_FUNCTION__))
;
4141 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), Op->getVTList(),
4142 SDValue(Node, 0), getCCResult(DAG, SDValue(Node, 1)));
4143 }
4144
4145 unsigned Id = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4146 switch (Id) {
4147 case Intrinsic::thread_pointer:
4148 return lowerThreadPointer(SDLoc(Op), DAG);
4149
4150 case Intrinsic::s390_vpdi:
4151 return DAG.getNode(SystemZISD::PERMUTE_DWORDS, SDLoc(Op), Op.getValueType(),
4152 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4153
4154 case Intrinsic::s390_vperm:
4155 return DAG.getNode(SystemZISD::PERMUTE, SDLoc(Op), Op.getValueType(),
4156 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4157
4158 case Intrinsic::s390_vuphb:
4159 case Intrinsic::s390_vuphh:
4160 case Intrinsic::s390_vuphf:
4161 return DAG.getNode(SystemZISD::UNPACK_HIGH, SDLoc(Op), Op.getValueType(),
4162 Op.getOperand(1));
4163
4164 case Intrinsic::s390_vuplhb:
4165 case Intrinsic::s390_vuplhh:
4166 case Intrinsic::s390_vuplhf:
4167 return DAG.getNode(SystemZISD::UNPACKL_HIGH, SDLoc(Op), Op.getValueType(),
4168 Op.getOperand(1));
4169
4170 case Intrinsic::s390_vuplb:
4171 case Intrinsic::s390_vuplhw:
4172 case Intrinsic::s390_vuplf:
4173 return DAG.getNode(SystemZISD::UNPACK_LOW, SDLoc(Op), Op.getValueType(),
4174 Op.getOperand(1));
4175
4176 case Intrinsic::s390_vupllb:
4177 case Intrinsic::s390_vupllh:
4178 case Intrinsic::s390_vupllf:
4179 return DAG.getNode(SystemZISD::UNPACKL_LOW, SDLoc(Op), Op.getValueType(),
4180 Op.getOperand(1));
4181
4182 case Intrinsic::s390_vsumb:
4183 case Intrinsic::s390_vsumh:
4184 case Intrinsic::s390_vsumgh:
4185 case Intrinsic::s390_vsumgf:
4186 case Intrinsic::s390_vsumqf:
4187 case Intrinsic::s390_vsumqg:
4188 return DAG.getNode(SystemZISD::VSUM, SDLoc(Op), Op.getValueType(),
4189 Op.getOperand(1), Op.getOperand(2));
4190 }
4191
4192 return SDValue();
4193}
4194
4195namespace {
4196// Says that SystemZISD operation Opcode can be used to perform the equivalent
4197// of a VPERM with permute vector Bytes. If Opcode takes three operands,
4198// Operand is the constant third operand, otherwise it is the number of
4199// bytes in each element of the result.
4200struct Permute {
4201 unsigned Opcode;
4202 unsigned Operand;
4203 unsigned char Bytes[SystemZ::VectorBytes];
4204};
4205}
4206
4207static const Permute PermuteForms[] = {
4208 // VMRHG
4209 { SystemZISD::MERGE_HIGH, 8,
4210 { 0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23 } },
4211 // VMRHF
4212 { SystemZISD::MERGE_HIGH, 4,
4213 { 0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23 } },
4214 // VMRHH
4215 { SystemZISD::MERGE_HIGH, 2,
4216 { 0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23 } },
4217 // VMRHB
4218 { SystemZISD::MERGE_HIGH, 1,
4219 { 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23 } },
4220 // VMRLG
4221 { SystemZISD::MERGE_LOW, 8,
4222 { 8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31 } },
4223 // VMRLF
4224 { SystemZISD::MERGE_LOW, 4,
4225 { 8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31 } },
4226 // VMRLH
4227 { SystemZISD::MERGE_LOW, 2,
4228 { 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31 } },
4229 // VMRLB
4230 { SystemZISD::MERGE_LOW, 1,
4231 { 8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31 } },
4232 // VPKG
4233 { SystemZISD::PACK, 4,
4234 { 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } },
4235 // VPKF
4236 { SystemZISD::PACK, 2,
4237 { 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 } },
4238 // VPKH
4239 { SystemZISD::PACK, 1,
4240 { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 } },
4241 // VPDI V1, V2, 4 (low half of V1, high half of V2)
4242 { SystemZISD::PERMUTE_DWORDS, 4,
4243 { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 } },
4244 // VPDI V1, V2, 1 (high half of V1, low half of V2)
4245 { SystemZISD::PERMUTE_DWORDS, 1,
4246 { 0, 1, 2, 3, 4, 5, 6, 7, 24, 25, 26, 27, 28, 29, 30, 31 } }
4247};
4248
4249// Called after matching a vector shuffle against a particular pattern.
4250// Both the original shuffle and the pattern have two vector operands.
4251// OpNos[0] is the operand of the original shuffle that should be used for
4252// operand 0 of the pattern, or -1 if operand 0 of the pattern can be anything.
4253// OpNos[1] is the same for operand 1 of the pattern. Resolve these -1s and
4254// set OpNo0 and OpNo1 to the shuffle operands that should actually be used
4255// for operands 0 and 1 of the pattern.
4256static bool chooseShuffleOpNos(int *OpNos, unsigned &OpNo0, unsigned &OpNo1) {
4257 if (OpNos[0] < 0) {
4258 if (OpNos[1] < 0)
4259 return false;
4260 OpNo0 = OpNo1 = OpNos[1];
4261 } else if (OpNos[1] < 0) {
4262 OpNo0 = OpNo1 = OpNos[0];
4263 } else {
4264 OpNo0 = OpNos[0];
4265 OpNo1 = OpNos[1];
4266 }
4267 return true;
4268}
4269
4270// Bytes is a VPERM-like permute vector, except that -1 is used for
4271// undefined bytes. Return true if the VPERM can be implemented using P.
4272// When returning true set OpNo0 to the VPERM operand that should be
4273// used for operand 0 of P and likewise OpNo1 for operand 1 of P.
4274//
4275// For example, if swapping the VPERM operands allows P to match, OpNo0
4276// will be 1 and OpNo1 will be 0. If instead Bytes only refers to one
4277// operand, but rewriting it to use two duplicated operands allows it to
4278// match P, then OpNo0 and OpNo1 will be the same.
4279static bool matchPermute(const SmallVectorImpl<int> &Bytes, const Permute &P,
4280 unsigned &OpNo0, unsigned &OpNo1) {
4281 int OpNos[] = { -1, -1 };
4282 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I) {
4283 int Elt = Bytes[I];
4284 if (Elt >= 0) {
4285 // Make sure that the two permute vectors use the same suboperand
4286 // byte number. Only the operand numbers (the high bits) are
4287 // allowed to differ.
4288 if ((Elt ^ P.Bytes[I]) & (SystemZ::VectorBytes - 1))
4289 return false;
4290 int ModelOpNo = P.Bytes[I] / SystemZ::VectorBytes;
4291 int RealOpNo = unsigned(Elt) / SystemZ::VectorBytes;
4292 // Make sure that the operand mappings are consistent with previous
4293 // elements.
4294 if (OpNos[ModelOpNo] == 1 - RealOpNo)
4295 return false;
4296 OpNos[ModelOpNo] = RealOpNo;
4297 }
4298 }
4299 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
4300}
4301
4302// As above, but search for a matching permute.
4303static const Permute *matchPermute(const SmallVectorImpl<int> &Bytes,
4304 unsigned &OpNo0, unsigned &OpNo1) {
4305 for (auto &P : PermuteForms)
4306 if (matchPermute(Bytes, P, OpNo0, OpNo1))
4307 return &P;
4308 return nullptr;
4309}
4310
4311// Bytes is a VPERM-like permute vector, except that -1 is used for
4312// undefined bytes. This permute is an operand of an outer permute.
4313// See whether redistributing the -1 bytes gives a shuffle that can be
4314// implemented using P. If so, set Transform to a VPERM-like permute vector
4315// that, when applied to the result of P, gives the original permute in Bytes.
4316static bool matchDoublePermute(const SmallVectorImpl<int> &Bytes,
4317 const Permute &P,
4318 SmallVectorImpl<int> &Transform) {
4319 unsigned To = 0;
4320 for (unsigned From = 0; From < SystemZ::VectorBytes; ++From) {
4321 int Elt = Bytes[From];
4322 if (Elt < 0)
4323 // Byte number From of the result is undefined.
4324 Transform[From] = -1;
4325 else {
4326 while (P.Bytes[To] != Elt) {
4327 To += 1;
4328 if (To == SystemZ::VectorBytes)
4329 return false;
4330 }
4331 Transform[From] = To;
4332 }
4333 }
4334 return true;
4335}
4336
4337// As above, but search for a matching permute.
4338static const Permute *matchDoublePermute(const SmallVectorImpl<int> &Bytes,
4339 SmallVectorImpl<int> &Transform) {
4340 for (auto &P : PermuteForms)
4341 if (matchDoublePermute(Bytes, P, Transform))
4342 return &P;
4343 return nullptr;
4344}
4345
4346// Convert the mask of the given shuffle op into a byte-level mask,
4347// as if it had type vNi8.
4348static bool getVPermMask(SDValue ShuffleOp,
4349 SmallVectorImpl<int> &Bytes) {
4350 EVT VT = ShuffleOp.getValueType();
4351 unsigned NumElements = VT.getVectorNumElements();
4352 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
4353
4354 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(ShuffleOp)) {
4355 Bytes.resize(NumElements * BytesPerElement, -1);
4356 for (unsigned I = 0; I < NumElements; ++I) {
4357 int Index = VSN->getMaskElt(I);
4358 if (Index >= 0)
4359 for (unsigned J = 0; J < BytesPerElement; ++J)
4360 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
4361 }
4362 return true;
4363 }
4364 if (SystemZISD::SPLAT == ShuffleOp.getOpcode() &&
4365 isa<ConstantSDNode>(ShuffleOp.getOperand(1))) {
4366 unsigned Index = ShuffleOp.getConstantOperandVal(1);
4367 Bytes.resize(NumElements * BytesPerElement, -1);
4368 for (unsigned I = 0; I < NumElements; ++I)
4369 for (unsigned J = 0; J < BytesPerElement; ++J)
4370 Bytes[I * BytesPerElement + J] = Index * BytesPerElement + J;
4371 return true;
4372 }
4373 return false;
4374}
4375
4376// Bytes is a VPERM-like permute vector, except that -1 is used for
4377// undefined bytes. See whether bytes [Start, Start + BytesPerElement) of
4378// the result come from a contiguous sequence of bytes from one input.
4379// Set Base to the selector for the first byte if so.
4380static bool getShuffleInput(const SmallVectorImpl<int> &Bytes, unsigned Start,
4381 unsigned BytesPerElement, int &Base) {
4382 Base = -1;
4383 for (unsigned I = 0; I < BytesPerElement; ++I) {
4384 if (Bytes[Start + I] >= 0) {
4385 unsigned Elem = Bytes[Start + I];
4386 if (Base < 0) {
4387 Base = Elem - I;
4388 // Make sure the bytes would come from one input operand.
4389 if (unsigned(Base) % Bytes.size() + BytesPerElement > Bytes.size())
4390 return false;
4391 } else if (unsigned(Base) != Elem - I)
4392 return false;
4393 }
4394 }
4395 return true;
4396}
4397
4398// Bytes is a VPERM-like permute vector, except that -1 is used for
4399// undefined bytes. Return true if it can be performed using VSLDI.
4400// When returning true, set StartIndex to the shift amount and OpNo0
4401// and OpNo1 to the VPERM operands that should be used as the first
4402// and second shift operand respectively.
4403static bool isShlDoublePermute(const SmallVectorImpl<int> &Bytes,
4404 unsigned &StartIndex, unsigned &OpNo0,
4405 unsigned &OpNo1) {
4406 int OpNos[] = { -1, -1 };
4407 int Shift = -1;
4408 for (unsigned I = 0; I < 16; ++I) {
4409 int Index = Bytes[I];
4410 if (Index >= 0) {
4411 int ExpectedShift = (Index - I) % SystemZ::VectorBytes;
4412 int ModelOpNo = unsigned(ExpectedShift + I) / SystemZ::VectorBytes;
4413 int RealOpNo = unsigned(Index) / SystemZ::VectorBytes;
4414 if (Shift < 0)
4415 Shift = ExpectedShift;
4416 else if (Shift != ExpectedShift)
4417 return false;
4418 // Make sure that the operand mappings are consistent with previous
4419 // elements.
4420 if (OpNos[ModelOpNo] == 1 - RealOpNo)
4421 return false;
4422 OpNos[ModelOpNo] = RealOpNo;
4423 }
4424 }
4425 StartIndex = Shift;
4426 return chooseShuffleOpNos(OpNos, OpNo0, OpNo1);
4427}
4428
4429// Create a node that performs P on operands Op0 and Op1, casting the
4430// operands to the appropriate type. The type of the result is determined by P.
4431static SDValue getPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
4432 const Permute &P, SDValue Op0, SDValue Op1) {
4433 // VPDI (PERMUTE_DWORDS) always operates on v2i64s. The input
4434 // elements of a PACK are twice as wide as the outputs.
4435 unsigned InBytes = (P.Opcode == SystemZISD::PERMUTE_DWORDS ? 8 :
4436 P.Opcode == SystemZISD::PACK ? P.Operand * 2 :
4437 P.Operand);
4438 // Cast both operands to the appropriate type.
4439 MVT InVT = MVT::getVectorVT(MVT::getIntegerVT(InBytes * 8),
4440 SystemZ::VectorBytes / InBytes);
4441 Op0 = DAG.getNode(ISD::BITCAST, DL, InVT, Op0);
4442 Op1 = DAG.getNode(ISD::BITCAST, DL, InVT, Op1);
4443 SDValue Op;
4444 if (P.Opcode == SystemZISD::PERMUTE_DWORDS) {
4445 SDValue Op2 = DAG.getTargetConstant(P.Operand, DL, MVT::i32);
4446 Op = DAG.getNode(SystemZISD::PERMUTE_DWORDS, DL, InVT, Op0, Op1, Op2);
4447 } else if (P.Opcode == SystemZISD::PACK) {
4448 MVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(P.Operand * 8),
4449 SystemZ::VectorBytes / P.Operand);
4450 Op = DAG.getNode(SystemZISD::PACK, DL, OutVT, Op0, Op1);
4451 } else {
4452 Op = DAG.getNode(P.Opcode, DL, InVT, Op0, Op1);
4453 }
4454 return Op;
4455}
4456
4457// Bytes is a VPERM-like permute vector, except that -1 is used for
4458// undefined bytes. Implement it on operands Ops[0] and Ops[1] using
4459// VSLDI or VPERM.
4460static SDValue getGeneralPermuteNode(SelectionDAG &DAG, const SDLoc &DL,
4461 SDValue *Ops,
4462 const SmallVectorImpl<int> &Bytes) {
4463 for (unsigned I = 0; I < 2; ++I)
4464 Ops[I] = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Ops[I]);
4465
4466 // First see whether VSLDI can be used.
4467 unsigned StartIndex, OpNo0, OpNo1;
4468 if (isShlDoublePermute(Bytes, StartIndex, OpNo0, OpNo1))
4469 return DAG.getNode(SystemZISD::SHL_DOUBLE, DL, MVT::v16i8, Ops[OpNo0],
4470 Ops[OpNo1],
4471 DAG.getTargetConstant(StartIndex, DL, MVT::i32));
4472
4473 // Fall back on VPERM. Construct an SDNode for the permute vector.
4474 SDValue IndexNodes[SystemZ::VectorBytes];
4475 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
4476 if (Bytes[I] >= 0)
4477 IndexNodes[I] = DAG.getConstant(Bytes[I], DL, MVT::i32);
4478 else
4479 IndexNodes[I] = DAG.getUNDEF(MVT::i32);
4480 SDValue Op2 = DAG.getBuildVector(MVT::v16i8, DL, IndexNodes);
4481 return DAG.getNode(SystemZISD::PERMUTE, DL, MVT::v16i8, Ops[0], Ops[1], Op2);
4482}
4483
4484namespace {
4485// Describes a general N-operand vector shuffle.
4486struct GeneralShuffle {
4487 GeneralShuffle(EVT vt) : VT(vt) {}
4488 void addUndef();
4489 bool add(SDValue, unsigned);
4490 SDValue getNode(SelectionDAG &, const SDLoc &);
4491
4492 // The operands of the shuffle.
4493 SmallVector<SDValue, SystemZ::VectorBytes> Ops;
4494
4495 // Index I is -1 if byte I of the result is undefined. Otherwise the
4496 // result comes from byte Bytes[I] % SystemZ::VectorBytes of operand
4497 // Bytes[I] / SystemZ::VectorBytes.
4498 SmallVector<int, SystemZ::VectorBytes> Bytes;
4499
4500 // The type of the shuffle result.
4501 EVT VT;
4502};
4503}
4504
4505// Add an extra undefined element to the shuffle.
4506void GeneralShuffle::addUndef() {
4507 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
4508 for (unsigned I = 0; I < BytesPerElement; ++I)
4509 Bytes.push_back(-1);
4510}
4511
4512// Add an extra element to the shuffle, taking it from element Elem of Op.
4513// A null Op indicates a vector input whose value will be calculated later;
4514// there is at most one such input per shuffle and it always has the same
4515// type as the result. Aborts and returns false if the source vector elements
4516// of an EXTRACT_VECTOR_ELT are smaller than the destination elements. Per
4517// LLVM they become implicitly extended, but this is rare and not optimized.
4518bool GeneralShuffle::add(SDValue Op, unsigned Elem) {
4519 unsigned BytesPerElement = VT.getVectorElementType().getStoreSize();
4520
4521 // The source vector can have wider elements than the result,
4522 // either through an explicit TRUNCATE or because of type legalization.
4523 // We want the least significant part.
4524 EVT FromVT = Op.getNode() ? Op.getValueType() : VT;
4525 unsigned FromBytesPerElement = FromVT.getVectorElementType().getStoreSize();
4526
4527 // Return false if the source elements are smaller than their destination
4528 // elements.
4529 if (FromBytesPerElement < BytesPerElement)
4530 return false;
4531
4532 unsigned Byte = ((Elem * FromBytesPerElement) % SystemZ::VectorBytes +
4533 (FromBytesPerElement - BytesPerElement));
4534
4535 // Look through things like shuffles and bitcasts.
4536 while (Op.getNode()) {
4537 if (Op.getOpcode() == ISD::BITCAST)
4538 Op = Op.getOperand(0);
4539 else if (Op.getOpcode() == ISD::VECTOR_SHUFFLE && Op.hasOneUse()) {
4540 // See whether the bytes we need come from a contiguous part of one
4541 // operand.
4542 SmallVector<int, SystemZ::VectorBytes> OpBytes;
4543 if (!getVPermMask(Op, OpBytes))
4544 break;
4545 int NewByte;
4546 if (!getShuffleInput(OpBytes, Byte, BytesPerElement, NewByte))
4547 break;
4548 if (NewByte < 0) {
4549 addUndef();
4550 return true;
4551 }
4552 Op = Op.getOperand(unsigned(NewByte) / SystemZ::VectorBytes);
4553 Byte = unsigned(NewByte) % SystemZ::VectorBytes;
4554 } else if (Op.isUndef()) {
4555 addUndef();
4556 return true;
4557 } else
4558 break;
4559 }
4560
4561 // Make sure that the source of the extraction is in Ops.
4562 unsigned OpNo = 0;
4563 for (; OpNo < Ops.size(); ++OpNo)
4564 if (Ops[OpNo] == Op)
4565 break;
4566 if (OpNo == Ops.size())
4567 Ops.push_back(Op);
4568
4569 // Add the element to Bytes.
4570 unsigned Base = OpNo * SystemZ::VectorBytes + Byte;
4571 for (unsigned I = 0; I < BytesPerElement; ++I)
4572 Bytes.push_back(Base + I);
4573
4574 return true;
4575}
4576
4577// Return SDNodes for the completed shuffle.
4578SDValue GeneralShuffle::getNode(SelectionDAG &DAG, const SDLoc &DL) {
4579 assert(Bytes.size() == SystemZ::VectorBytes && "Incomplete vector")((Bytes.size() == SystemZ::VectorBytes && "Incomplete vector"
) ? static_cast<void> (0) : __assert_fail ("Bytes.size() == SystemZ::VectorBytes && \"Incomplete vector\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 4579, __PRETTY_FUNCTION__))
;
4580
4581 if (Ops.size() == 0)
4582 return DAG.getUNDEF(VT);
4583
4584 // Make sure that there are at least two shuffle operands.
4585 if (Ops.size() == 1)
4586 Ops.push_back(DAG.getUNDEF(MVT::v16i8));
4587
4588 // Create a tree of shuffles, deferring root node until after the loop.
4589 // Try to redistribute the undefined elements of non-root nodes so that
4590 // the non-root shuffles match something like a pack or merge, then adjust
4591 // the parent node's permute vector to compensate for the new order.
4592 // Among other things, this copes with vectors like <2 x i16> that were
4593 // padded with undefined elements during type legalization.
4594 //
4595 // In the best case this redistribution will lead to the whole tree
4596 // using packs and merges. It should rarely be a loss in other cases.
4597 unsigned Stride = 1;
4598 for (; Stride * 2 < Ops.size(); Stride *= 2) {
4599 for (unsigned I = 0; I < Ops.size() - Stride; I += Stride * 2) {
4600 SDValue SubOps[] = { Ops[I], Ops[I + Stride] };
4601
4602 // Create a mask for just these two operands.
4603 SmallVector<int, SystemZ::VectorBytes> NewBytes(SystemZ::VectorBytes);
4604 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
4605 unsigned OpNo = unsigned(Bytes[J]) / SystemZ::VectorBytes;
4606 unsigned Byte = unsigned(Bytes[J]) % SystemZ::VectorBytes;
4607 if (OpNo == I)
4608 NewBytes[J] = Byte;
4609 else if (OpNo == I + Stride)
4610 NewBytes[J] = SystemZ::VectorBytes + Byte;
4611 else
4612 NewBytes[J] = -1;
4613 }
4614 // See if it would be better to reorganize NewMask to avoid using VPERM.
4615 SmallVector<int, SystemZ::VectorBytes> NewBytesMap(SystemZ::VectorBytes);
4616 if (const Permute *P = matchDoublePermute(NewBytes, NewBytesMap)) {
4617 Ops[I] = getPermuteNode(DAG, DL, *P, SubOps[0], SubOps[1]);
4618 // Applying NewBytesMap to Ops[I] gets back to NewBytes.
4619 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J) {
4620 if (NewBytes[J] >= 0) {
4621 assert(unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&((unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
"Invalid double permute") ? static_cast<void> (0) : __assert_fail
("unsigned(NewBytesMap[J]) < SystemZ::VectorBytes && \"Invalid double permute\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 4622, __PRETTY_FUNCTION__))
4622 "Invalid double permute")((unsigned(NewBytesMap[J]) < SystemZ::VectorBytes &&
"Invalid double permute") ? static_cast<void> (0) : __assert_fail
("unsigned(NewBytesMap[J]) < SystemZ::VectorBytes && \"Invalid double permute\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 4622, __PRETTY_FUNCTION__))
;
4623 Bytes[J] = I * SystemZ::VectorBytes + NewBytesMap[J];
4624 } else
4625 assert(NewBytesMap[J] < 0 && "Invalid double permute")((NewBytesMap[J] < 0 && "Invalid double permute") ?
static_cast<void> (0) : __assert_fail ("NewBytesMap[J] < 0 && \"Invalid double permute\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 4625, __PRETTY_FUNCTION__))
;
4626 }
4627 } else {
4628 // Just use NewBytes on the operands.
4629 Ops[I] = getGeneralPermuteNode(DAG, DL, SubOps, NewBytes);
4630 for (unsigned J = 0; J < SystemZ::VectorBytes; ++J)
4631 if (NewBytes[J] >= 0)
4632 Bytes[J] = I * SystemZ::VectorBytes + J;
4633 }
4634 }
4635 }
4636
4637 // Now we just have 2 inputs. Put the second operand in Ops[1].
4638 if (Stride > 1) {
4639 Ops[1] = Ops[Stride];
4640 for (unsigned I = 0; I < SystemZ::VectorBytes; ++I)
4641 if (Bytes[I] >= int(SystemZ::VectorBytes))
4642 Bytes[I] -= (Stride - 1) * SystemZ::VectorBytes;
4643 }
4644
4645 // Look for an instruction that can do the permute without resorting
4646 // to VPERM.
4647 unsigned OpNo0, OpNo1;
4648 SDValue Op;
4649 if (const Permute *P = matchPermute(Bytes, OpNo0, OpNo1))
4650 Op = getPermuteNode(DAG, DL, *P, Ops[OpNo0], Ops[OpNo1]);
4651 else
4652 Op = getGeneralPermuteNode(DAG, DL, &Ops[0], Bytes);
4653 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4654}
4655
4656// Return true if the given BUILD_VECTOR is a scalar-to-vector conversion.
4657static bool isScalarToVector(SDValue Op) {
4658 for (unsigned I = 1, E = Op.getNumOperands(); I != E; ++I)
4659 if (!Op.getOperand(I).isUndef())
4660 return false;
4661 return true;
4662}
4663
4664// Return a vector of type VT that contains Value in the first element.
4665// The other elements don't matter.
4666static SDValue buildScalarToVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4667 SDValue Value) {
4668 // If we have a constant, replicate it to all elements and let the
4669 // BUILD_VECTOR lowering take care of it.
4670 if (Value.getOpcode() == ISD::Constant ||
4671 Value.getOpcode() == ISD::ConstantFP) {
4672 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Value);
4673 return DAG.getBuildVector(VT, DL, Ops);
4674 }
4675 if (Value.isUndef())
4676 return DAG.getUNDEF(VT);
4677 return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Value);
4678}
4679
4680// Return a vector of type VT in which Op0 is in element 0 and Op1 is in
4681// element 1. Used for cases in which replication is cheap.
4682static SDValue buildMergeScalars(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4683 SDValue Op0, SDValue Op1) {
4684 if (Op0.isUndef()) {
4685 if (Op1.isUndef())
4686 return DAG.getUNDEF(VT);
4687 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op1);
4688 }
4689 if (Op1.isUndef())
4690 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0);
4691 return DAG.getNode(SystemZISD::MERGE_HIGH, DL, VT,
4692 buildScalarToVector(DAG, DL, VT, Op0),
4693 buildScalarToVector(DAG, DL, VT, Op1));
4694}
4695
4696// Extend GPR scalars Op0 and Op1 to doublewords and return a v2i64
4697// vector for them.
4698static SDValue joinDwords(SelectionDAG &DAG, const SDLoc &DL, SDValue Op0,
4699 SDValue Op1) {
4700 if (Op0.isUndef() && Op1.isUndef())
4701 return DAG.getUNDEF(MVT::v2i64);
4702 // If one of the two inputs is undefined then replicate the other one,
4703 // in order to avoid using another register unnecessarily.
4704 if (Op0.isUndef())
4705 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4706 else if (Op1.isUndef())
4707 Op0 = Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4708 else {
4709 Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
4710 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op1);
4711 }
4712 return DAG.getNode(SystemZISD::JOIN_DWORDS, DL, MVT::v2i64, Op0, Op1);
4713}
4714
4715// If a BUILD_VECTOR contains some EXTRACT_VECTOR_ELTs, it's usually
4716// better to use VECTOR_SHUFFLEs on them, only using BUILD_VECTOR for
4717// the non-EXTRACT_VECTOR_ELT elements. See if the given BUILD_VECTOR
4718// would benefit from this representation and return it if so.
4719static SDValue tryBuildVectorShuffle(SelectionDAG &DAG,
4720 BuildVectorSDNode *BVN) {
4721 EVT VT = BVN->getValueType(0);
4722 unsigned NumElements = VT.getVectorNumElements();
4723
4724 // Represent the BUILD_VECTOR as an N-operand VECTOR_SHUFFLE-like operation
4725 // on byte vectors. If there are non-EXTRACT_VECTOR_ELT elements that still
4726 // need a BUILD_VECTOR, add an additional placeholder operand for that
4727 // BUILD_VECTOR and store its operands in ResidueOps.
4728 GeneralShuffle GS(VT);
4729 SmallVector<SDValue, SystemZ::VectorBytes> ResidueOps;
4730 bool FoundOne = false;
4731 for (unsigned I = 0; I < NumElements; ++I) {
4732 SDValue Op = BVN->getOperand(I);
4733 if (Op.getOpcode() == ISD::TRUNCATE)
4734 Op = Op.getOperand(0);
4735 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4736 Op.getOperand(1).getOpcode() == ISD::Constant) {
4737 unsigned Elem = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4738 if (!GS.add(Op.getOperand(0), Elem))
4739 return SDValue();
4740 FoundOne = true;
4741 } else if (Op.isUndef()) {
4742 GS.addUndef();
4743 } else {
4744 if (!GS.add(SDValue(), ResidueOps.size()))
4745 return SDValue();
4746 ResidueOps.push_back(BVN->getOperand(I));
4747 }
4748 }
4749
4750 // Nothing to do if there are no EXTRACT_VECTOR_ELTs.
4751 if (!FoundOne)
4752 return SDValue();
4753
4754 // Create the BUILD_VECTOR for the remaining elements, if any.
4755 if (!ResidueOps.empty()) {
4756 while (ResidueOps.size() < NumElements)
4757 ResidueOps.push_back(DAG.getUNDEF(ResidueOps[0].getValueType()));
4758 for (auto &Op : GS.Ops) {
4759 if (!Op.getNode()) {
4760 Op = DAG.getBuildVector(VT, SDLoc(BVN), ResidueOps);
4761 break;
4762 }
4763 }
4764 }
4765 return GS.getNode(DAG, SDLoc(BVN));
4766}
4767
4768bool SystemZTargetLowering::isVectorElementLoad(SDValue Op) const {
4769 if (Op.getOpcode() == ISD::LOAD && cast<LoadSDNode>(Op)->isUnindexed())
4770 return true;
4771 if (Subtarget.hasVectorEnhancements2() && Op.getOpcode() == SystemZISD::LRV)
4772 return true;
4773 return false;
4774}
4775
4776// Combine GPR scalar values Elems into a vector of type VT.
4777SDValue
4778SystemZTargetLowering::buildVector(SelectionDAG &DAG, const SDLoc &DL, EVT VT,
4779 SmallVectorImpl<SDValue> &Elems) const {
4780 // See whether there is a single replicated value.
4781 SDValue Single;
4782 unsigned int NumElements = Elems.size();
4783 unsigned int Count = 0;
4784 for (auto Elem : Elems) {
4785 if (!Elem.isUndef()) {
4786 if (!Single.getNode())
4787 Single = Elem;
4788 else if (Elem != Single) {
4789 Single = SDValue();
4790 break;
4791 }
4792 Count += 1;
4793 }
4794 }
4795 // There are three cases here:
4796 //
4797 // - if the only defined element is a loaded one, the best sequence
4798 // is a replicating load.
4799 //
4800 // - otherwise, if the only defined element is an i64 value, we will
4801 // end up with the same VLVGP sequence regardless of whether we short-cut
4802 // for replication or fall through to the later code.
4803 //
4804 // - otherwise, if the only defined element is an i32 or smaller value,
4805 // we would need 2 instructions to replicate it: VLVGP followed by VREPx.
4806 // This is only a win if the single defined element is used more than once.
4807 // In other cases we're better off using a single VLVGx.
4808 if (Single.getNode() && (Count > 1 || isVectorElementLoad(Single)))
4809 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Single);
4810
4811 // If all elements are loads, use VLREP/VLEs (below).
4812 bool AllLoads = true;
4813 for (auto Elem : Elems)
4814 if (!isVectorElementLoad(Elem)) {
4815 AllLoads = false;
4816 break;
4817 }
4818
4819 // The best way of building a v2i64 from two i64s is to use VLVGP.
4820 if (VT == MVT::v2i64 && !AllLoads)
4821 return joinDwords(DAG, DL, Elems[0], Elems[1]);
4822
4823 // Use a 64-bit merge high to combine two doubles.
4824 if (VT == MVT::v2f64 && !AllLoads)
4825 return buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4826
4827 // Build v4f32 values directly from the FPRs:
4828 //
4829 // <Axxx> <Bxxx> <Cxxxx> <Dxxx>
4830 // V V VMRHF
4831 // <ABxx> <CDxx>
4832 // V VMRHG
4833 // <ABCD>
4834 if (VT == MVT::v4f32 && !AllLoads) {
4835 SDValue Op01 = buildMergeScalars(DAG, DL, VT, Elems[0], Elems[1]);
4836 SDValue Op23 = buildMergeScalars(DAG, DL, VT, Elems[2], Elems[3]);
4837 // Avoid unnecessary undefs by reusing the other operand.
4838 if (Op01.isUndef())
4839 Op01 = Op23;
4840 else if (Op23.isUndef())
4841 Op23 = Op01;
4842 // Merging identical replications is a no-op.
4843 if (Op01.getOpcode() == SystemZISD::REPLICATE && Op01 == Op23)
4844 return Op01;
4845 Op01 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op01);
4846 Op23 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Op23);
4847 SDValue Op = DAG.getNode(SystemZISD::MERGE_HIGH,
4848 DL, MVT::v2i64, Op01, Op23);
4849 return DAG.getNode(ISD::BITCAST, DL, VT, Op);
4850 }
4851
4852 // Collect the constant terms.
4853 SmallVector<SDValue, SystemZ::VectorBytes> Constants(NumElements, SDValue());
4854 SmallVector<bool, SystemZ::VectorBytes> Done(NumElements, false);
4855
4856 unsigned NumConstants = 0;
4857 for (unsigned I = 0; I < NumElements; ++I) {
4858 SDValue Elem = Elems[I];
4859 if (Elem.getOpcode() == ISD::Constant ||
4860 Elem.getOpcode() == ISD::ConstantFP) {
4861 NumConstants += 1;
4862 Constants[I] = Elem;
4863 Done[I] = true;
4864 }
4865 }
4866 // If there was at least one constant, fill in the other elements of
4867 // Constants with undefs to get a full vector constant and use that
4868 // as the starting point.
4869 SDValue Result;
4870 SDValue ReplicatedVal;
4871 if (NumConstants > 0) {
4872 for (unsigned I = 0; I < NumElements; ++I)
4873 if (!Constants[I].getNode())
4874 Constants[I] = DAG.getUNDEF(Elems[I].getValueType());
4875 Result = DAG.getBuildVector(VT, DL, Constants);
4876 } else {
4877 // Otherwise try to use VLREP or VLVGP to start the sequence in order to
4878 // avoid a false dependency on any previous contents of the vector
4879 // register.
4880
4881 // Use a VLREP if at least one element is a load. Make sure to replicate
4882 // the load with the most elements having its value.
4883 std::map<const SDNode*, unsigned> UseCounts;
4884 SDNode *LoadMaxUses = nullptr;
4885 for (unsigned I = 0; I < NumElements; ++I)
4886 if (isVectorElementLoad(Elems[I])) {
4887 SDNode *Ld = Elems[I].getNode();
4888 UseCounts[Ld]++;
4889 if (LoadMaxUses == nullptr || UseCounts[LoadMaxUses] < UseCounts[Ld])
4890 LoadMaxUses = Ld;
4891 }
4892 if (LoadMaxUses != nullptr) {
4893 ReplicatedVal = SDValue(LoadMaxUses, 0);
4894 Result = DAG.getNode(SystemZISD::REPLICATE, DL, VT, ReplicatedVal);
4895 } else {
4896 // Try to use VLVGP.
4897 unsigned I1 = NumElements / 2 - 1;
4898 unsigned I2 = NumElements - 1;
4899 bool Def1 = !Elems[I1].isUndef();
4900 bool Def2 = !Elems[I2].isUndef();
4901 if (Def1 || Def2) {
4902 SDValue Elem1 = Elems[Def1 ? I1 : I2];
4903 SDValue Elem2 = Elems[Def2 ? I2 : I1];
4904 Result = DAG.getNode(ISD::BITCAST, DL, VT,
4905 joinDwords(DAG, DL, Elem1, Elem2));
4906 Done[I1] = true;
4907 Done[I2] = true;
4908 } else
4909 Result = DAG.getUNDEF(VT);
4910 }
4911 }
4912
4913 // Use VLVGx to insert the other elements.
4914 for (unsigned I = 0; I < NumElements; ++I)
4915 if (!Done[I] && !Elems[I].isUndef() && Elems[I] != ReplicatedVal)
4916 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Result, Elems[I],
4917 DAG.getConstant(I, DL, MVT::i32));
4918 return Result;
4919}
4920
4921SDValue SystemZTargetLowering::lowerBUILD_VECTOR(SDValue Op,
4922 SelectionDAG &DAG) const {
4923 auto *BVN = cast<BuildVectorSDNode>(Op.getNode());
4924 SDLoc DL(Op);
4925 EVT VT = Op.getValueType();
4926
4927 if (BVN->isConstant()) {
4928 if (SystemZVectorConstantInfo(BVN).isVectorConstantLegal(Subtarget))
4929 return Op;
4930
4931 // Fall back to loading it from memory.
4932 return SDValue();
4933 }
4934
4935 // See if we should use shuffles to construct the vector from other vectors.
4936 if (SDValue Res = tryBuildVectorShuffle(DAG, BVN))
4937 return Res;
4938
4939 // Detect SCALAR_TO_VECTOR conversions.
4940 if (isOperationLegal(ISD::SCALAR_TO_VECTOR, VT) && isScalarToVector(Op))
4941 return buildScalarToVector(DAG, DL, VT, Op.getOperand(0));
4942
4943 // Otherwise use buildVector to build the vector up from GPRs.
4944 unsigned NumElements = Op.getNumOperands();
4945 SmallVector<SDValue, SystemZ::VectorBytes> Ops(NumElements);
4946 for (unsigned I = 0; I < NumElements; ++I)
4947 Ops[I] = Op.getOperand(I);
4948 return buildVector(DAG, DL, VT, Ops);
4949}
4950
4951SDValue SystemZTargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4952 SelectionDAG &DAG) const {
4953 auto *VSN = cast<ShuffleVectorSDNode>(Op.getNode());
4954 SDLoc DL(Op);
4955 EVT VT = Op.getValueType();
4956 unsigned NumElements = VT.getVectorNumElements();
4957
4958 if (VSN->isSplat()) {
4959 SDValue Op0 = Op.getOperand(0);
4960 unsigned Index = VSN->getSplatIndex();
4961 assert(Index < VT.getVectorNumElements() &&((Index < VT.getVectorNumElements() && "Splat index should be defined and in first operand"
) ? static_cast<void> (0) : __assert_fail ("Index < VT.getVectorNumElements() && \"Splat index should be defined and in first operand\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 4962, __PRETTY_FUNCTION__))
4962 "Splat index should be defined and in first operand")((Index < VT.getVectorNumElements() && "Splat index should be defined and in first operand"
) ? static_cast<void> (0) : __assert_fail ("Index < VT.getVectorNumElements() && \"Splat index should be defined and in first operand\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 4962, __PRETTY_FUNCTION__))
;
4963 // See whether the value we're splatting is directly available as a scalar.
4964 if ((Index == 0 && Op0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
4965 Op0.getOpcode() == ISD::BUILD_VECTOR)
4966 return DAG.getNode(SystemZISD::REPLICATE, DL, VT, Op0.getOperand(Index));
4967 // Otherwise keep it as a vector-to-vector operation.
4968 return DAG.getNode(SystemZISD::SPLAT, DL, VT, Op.getOperand(0),
4969 DAG.getTargetConstant(Index, DL, MVT::i32));
4970 }
4971
4972 GeneralShuffle GS(VT);
4973 for (unsigned I = 0; I < NumElements; ++I) {
4974 int Elt = VSN->getMaskElt(I);
4975 if (Elt < 0)
4976 GS.addUndef();
4977 else if (!GS.add(Op.getOperand(unsigned(Elt) / NumElements),
4978 unsigned(Elt) % NumElements))
4979 return SDValue();
4980 }
4981 return GS.getNode(DAG, SDLoc(VSN));
4982}
4983
4984SDValue SystemZTargetLowering::lowerSCALAR_TO_VECTOR(SDValue Op,
4985 SelectionDAG &DAG) const {
4986 SDLoc DL(Op);
4987 // Just insert the scalar into element 0 of an undefined vector.
4988 return DAG.getNode(ISD::INSERT_VECTOR_ELT, DL,
4989 Op.getValueType(), DAG.getUNDEF(Op.getValueType()),
4990 Op.getOperand(0), DAG.getConstant(0, DL, MVT::i32));
4991}
4992
4993SDValue SystemZTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4994 SelectionDAG &DAG) const {
4995 // Handle insertions of floating-point values.
4996 SDLoc DL(Op);
4997 SDValue Op0 = Op.getOperand(0);
4998 SDValue Op1 = Op.getOperand(1);
4999 SDValue Op2 = Op.getOperand(2);
5000 EVT VT = Op.getValueType();
5001
5002 // Insertions into constant indices of a v2f64 can be done using VPDI.
5003 // However, if the inserted value is a bitcast or a constant then it's
5004 // better to use GPRs, as below.
5005 if (VT == MVT::v2f64 &&
5006 Op1.getOpcode() != ISD::BITCAST &&
5007 Op1.getOpcode() != ISD::ConstantFP &&
5008 Op2.getOpcode() == ISD::Constant) {
5009 uint64_t Index = cast<ConstantSDNode>(Op2)->getZExtValue();
5010 unsigned Mask = VT.getVectorNumElements() - 1;
5011 if (Index <= Mask)
5012 return Op;
5013 }
5014
5015 // Otherwise bitcast to the equivalent integer form and insert via a GPR.
5016 MVT IntVT = MVT::getIntegerVT(VT.getScalarSizeInBits());
5017 MVT IntVecVT = MVT::getVectorVT(IntVT, VT.getVectorNumElements());
5018 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntVecVT,
5019 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0),
5020 DAG.getNode(ISD::BITCAST, DL, IntVT, Op1), Op2);
5021 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
5022}
5023
5024SDValue
5025SystemZTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5026 SelectionDAG &DAG) const {
5027 // Handle extractions of floating-point values.
5028 SDLoc DL(Op);
5029 SDValue Op0 = Op.getOperand(0);
5030 SDValue Op1 = Op.getOperand(1);
5031 EVT VT = Op.getValueType();
5032 EVT VecVT = Op0.getValueType();
5033
5034 // Extractions of constant indices can be done directly.
5035 if (auto *CIndexN = dyn_cast<ConstantSDNode>(Op1)) {
5036 uint64_t Index = CIndexN->getZExtValue();
5037 unsigned Mask = VecVT.getVectorNumElements() - 1;
5038 if (Index <= Mask)
5039 return Op;
5040 }
5041
5042 // Otherwise bitcast to the equivalent integer form and extract via a GPR.
5043 MVT IntVT = MVT::getIntegerVT(VT.getSizeInBits());
5044 MVT IntVecVT = MVT::getVectorVT(IntVT, VecVT.getVectorNumElements());
5045 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntVT,
5046 DAG.getNode(ISD::BITCAST, DL, IntVecVT, Op0), Op1);
5047 return DAG.getNode(ISD::BITCAST, DL, VT, Res);
5048}
5049
5050SDValue
5051SystemZTargetLowering::lowerExtendVectorInreg(SDValue Op, SelectionDAG &DAG,
5052 unsigned UnpackHigh) const {
5053 SDValue PackedOp = Op.getOperand(0);
5054 EVT OutVT = Op.getValueType();
5055 EVT InVT = PackedOp.getValueType();
5056 unsigned ToBits = OutVT.getScalarSizeInBits();
5057 unsigned FromBits = InVT.getScalarSizeInBits();
5058 do {
5059 FromBits *= 2;
5060 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(FromBits),
5061 SystemZ::VectorBits / FromBits);
5062 PackedOp = DAG.getNode(UnpackHigh, SDLoc(PackedOp), OutVT, PackedOp);
5063 } while (FromBits != ToBits);
5064 return PackedOp;
5065}
5066
5067SDValue SystemZTargetLowering::lowerShift(SDValue Op, SelectionDAG &DAG,
5068 unsigned ByScalar) const {
5069 // Look for cases where a vector shift can use the *_BY_SCALAR form.
5070 SDValue Op0 = Op.getOperand(0);
5071 SDValue Op1 = Op.getOperand(1);
5072 SDLoc DL(Op);
5073 EVT VT = Op.getValueType();
5074 unsigned ElemBitSize = VT.getScalarSizeInBits();
5075
5076 // See whether the shift vector is a splat represented as BUILD_VECTOR.
5077 if (auto *BVN = dyn_cast<BuildVectorSDNode>(Op1)) {
5078 APInt SplatBits, SplatUndef;
5079 unsigned SplatBitSize;
5080 bool HasAnyUndefs;
5081 // Check for constant splats. Use ElemBitSize as the minimum element
5082 // width and reject splats that need wider elements.
5083 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
5084 ElemBitSize, true) &&
5085 SplatBitSize == ElemBitSize) {
5086 SDValue Shift = DAG.getConstant(SplatBits.getZExtValue() & 0xfff,
5087 DL, MVT::i32);
5088 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
5089 }
5090 // Check for variable splats.
5091 BitVector UndefElements;
5092 SDValue Splat = BVN->getSplatValue(&UndefElements);
5093 if (Splat) {
5094 // Since i32 is the smallest legal type, we either need a no-op
5095 // or a truncation.
5096 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Splat);
5097 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
5098 }
5099 }
5100
5101 // See whether the shift vector is a splat represented as SHUFFLE_VECTOR,
5102 // and the shift amount is directly available in a GPR.
5103 if (auto *VSN = dyn_cast<ShuffleVectorSDNode>(Op1)) {
5104 if (VSN->isSplat()) {
5105 SDValue VSNOp0 = VSN->getOperand(0);
5106 unsigned Index = VSN->getSplatIndex();
5107 assert(Index < VT.getVectorNumElements() &&((Index < VT.getVectorNumElements() && "Splat index should be defined and in first operand"
) ? static_cast<void> (0) : __assert_fail ("Index < VT.getVectorNumElements() && \"Splat index should be defined and in first operand\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 5108, __PRETTY_FUNCTION__))
5108 "Splat index should be defined and in first operand")((Index < VT.getVectorNumElements() && "Splat index should be defined and in first operand"
) ? static_cast<void> (0) : __assert_fail ("Index < VT.getVectorNumElements() && \"Splat index should be defined and in first operand\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 5108, __PRETTY_FUNCTION__))
;
5109 if ((Index == 0 && VSNOp0.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
5110 VSNOp0.getOpcode() == ISD::BUILD_VECTOR) {
5111 // Since i32 is the smallest legal type, we either need a no-op
5112 // or a truncation.
5113 SDValue Shift = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32,
5114 VSNOp0.getOperand(Index));
5115 return DAG.getNode(ByScalar, DL, VT, Op0, Shift);
5116 }
5117 }
5118 }
5119
5120 // Otherwise just treat the current form as legal.
5121 return Op;
5122}
5123
5124SDValue SystemZTargetLowering::LowerOperation(SDValue Op,
5125 SelectionDAG &DAG) const {
5126 switch (Op.getOpcode()) {
5127 case ISD::FRAMEADDR:
5128 return lowerFRAMEADDR(Op, DAG);
5129 case ISD::RETURNADDR:
5130 return lowerRETURNADDR(Op, DAG);
5131 case ISD::BR_CC:
5132 return lowerBR_CC(Op, DAG);
5133 case ISD::SELECT_CC:
5134 return lowerSELECT_CC(Op, DAG);
5135 case ISD::SETCC:
5136 return lowerSETCC(Op, DAG);
5137 case ISD::STRICT_FSETCC:
5138 return lowerSTRICT_FSETCC(Op, DAG, false);
5139 case ISD::STRICT_FSETCCS:
5140 return lowerSTRICT_FSETCC(Op, DAG, true);
5141 case ISD::GlobalAddress:
5142 return lowerGlobalAddress(cast<GlobalAddressSDNode>(Op), DAG);
5143 case ISD::GlobalTLSAddress:
5144 return lowerGlobalTLSAddress(cast<GlobalAddressSDNode>(Op), DAG);
5145 case ISD::BlockAddress:
5146 return lowerBlockAddress(cast<BlockAddressSDNode>(Op), DAG);
5147 case ISD::JumpTable:
5148 return lowerJumpTable(cast<JumpTableSDNode>(Op), DAG);
5149 case ISD::ConstantPool:
5150 return lowerConstantPool(cast<ConstantPoolSDNode>(Op), DAG);
5151 case ISD::BITCAST:
5152 return lowerBITCAST(Op, DAG);
5153 case ISD::VASTART:
5154 return lowerVASTART(Op, DAG);
5155 case ISD::VACOPY:
5156 return lowerVACOPY(Op, DAG);
5157 case ISD::DYNAMIC_STACKALLOC:
5158 return lowerDYNAMIC_STACKALLOC(Op, DAG);
5159 case ISD::GET_DYNAMIC_AREA_OFFSET:
5160 return lowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
5161 case ISD::SMUL_LOHI:
5162 return lowerSMUL_LOHI(Op, DAG);
5163 case ISD::UMUL_LOHI:
5164 return lowerUMUL_LOHI(Op, DAG);
5165 case ISD::SDIVREM:
5166 return lowerSDIVREM(Op, DAG);
5167 case ISD::UDIVREM:
5168 return lowerUDIVREM(Op, DAG);
5169 case ISD::SADDO:
5170 case ISD::SSUBO:
5171 case ISD::UADDO:
5172 case ISD::USUBO:
5173 return lowerXALUO(Op, DAG);
5174 case ISD::ADDCARRY:
5175 case ISD::SUBCARRY:
5176 return lowerADDSUBCARRY(Op, DAG);
5177 case ISD::OR:
5178 return lowerOR(Op, DAG);
5179 case ISD::CTPOP:
5180 return lowerCTPOP(Op, DAG);
5181 case ISD::ATOMIC_FENCE:
5182 return lowerATOMIC_FENCE(Op, DAG);
5183 case ISD::ATOMIC_SWAP:
5184 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_SWAPW);
5185 case ISD::ATOMIC_STORE:
5186 return lowerATOMIC_STORE(Op, DAG);
5187 case ISD::ATOMIC_LOAD:
5188 return lowerATOMIC_LOAD(Op, DAG);
5189 case ISD::ATOMIC_LOAD_ADD:
5190 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_ADD);
5191 case ISD::ATOMIC_LOAD_SUB:
5192 return lowerATOMIC_LOAD_SUB(Op, DAG);
5193 case ISD::ATOMIC_LOAD_AND:
5194 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_AND);
5195 case ISD::ATOMIC_LOAD_OR:
5196 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_OR);
5197 case ISD::ATOMIC_LOAD_XOR:
5198 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_XOR);
5199 case ISD::ATOMIC_LOAD_NAND:
5200 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_NAND);
5201 case ISD::ATOMIC_LOAD_MIN:
5202 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MIN);
5203 case ISD::ATOMIC_LOAD_MAX:
5204 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_MAX);
5205 case ISD::ATOMIC_LOAD_UMIN:
5206 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMIN);
5207 case ISD::ATOMIC_LOAD_UMAX:
5208 return lowerATOMIC_LOAD_OP(Op, DAG, SystemZISD::ATOMIC_LOADW_UMAX);
5209 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
5210 return lowerATOMIC_CMP_SWAP(Op, DAG);
5211 case ISD::STACKSAVE:
5212 return lowerSTACKSAVE(Op, DAG);
5213 case ISD::STACKRESTORE:
5214 return lowerSTACKRESTORE(Op, DAG);
5215 case ISD::PREFETCH:
5216 return lowerPREFETCH(Op, DAG);
5217 case ISD::INTRINSIC_W_CHAIN:
5218 return lowerINTRINSIC_W_CHAIN(Op, DAG);
5219 case ISD::INTRINSIC_WO_CHAIN:
5220 return lowerINTRINSIC_WO_CHAIN(Op, DAG);
5221 case ISD::BUILD_VECTOR:
5222 return lowerBUILD_VECTOR(Op, DAG);
5223 case ISD::VECTOR_SHUFFLE:
5224 return lowerVECTOR_SHUFFLE(Op, DAG);
5225 case ISD::SCALAR_TO_VECTOR:
5226 return lowerSCALAR_TO_VECTOR(Op, DAG);
5227 case ISD::INSERT_VECTOR_ELT:
5228 return lowerINSERT_VECTOR_ELT(Op, DAG);
5229 case ISD::EXTRACT_VECTOR_ELT:
5230 return lowerEXTRACT_VECTOR_ELT(Op, DAG);
5231 case ISD::SIGN_EXTEND_VECTOR_INREG:
5232 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACK_HIGH);
5233 case ISD::ZERO_EXTEND_VECTOR_INREG:
5234 return lowerExtendVectorInreg(Op, DAG, SystemZISD::UNPACKL_HIGH);
5235 case ISD::SHL:
5236 return lowerShift(Op, DAG, SystemZISD::VSHL_BY_SCALAR);
5237 case ISD::SRL:
5238 return lowerShift(Op, DAG, SystemZISD::VSRL_BY_SCALAR);
5239 case ISD::SRA:
5240 return lowerShift(Op, DAG, SystemZISD::VSRA_BY_SCALAR);
5241 default:
5242 llvm_unreachable("Unexpected node to lower")::llvm::llvm_unreachable_internal("Unexpected node to lower",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 5242)
;
5243 }
5244}
5245
5246// Lower operations with invalid operand or result types (currently used
5247// only for 128-bit integer types).
5248
5249static SDValue lowerI128ToGR128(SelectionDAG &DAG, SDValue In) {
5250 SDLoc DL(In);
5251 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, In,
5252 DAG.getIntPtrConstant(0, DL));
5253 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, In,
5254 DAG.getIntPtrConstant(1, DL));
5255 SDNode *Pair = DAG.getMachineNode(SystemZ::PAIR128, DL,
5256 MVT::Untyped, Hi, Lo);
5257 return SDValue(Pair, 0);
5258}
5259
5260static SDValue lowerGR128ToI128(SelectionDAG &DAG, SDValue In) {
5261 SDLoc DL(In);
5262 SDValue Hi = DAG.getTargetExtractSubreg(SystemZ::subreg_h64,
5263 DL, MVT::i64, In);
5264 SDValue Lo = DAG.getTargetExtractSubreg(SystemZ::subreg_l64,
5265 DL, MVT::i64, In);
5266 return DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i128, Lo, Hi);
5267}
5268
5269void
5270SystemZTargetLowering::LowerOperationWrapper(SDNode *N,
5271 SmallVectorImpl<SDValue> &Results,
5272 SelectionDAG &DAG) const {
5273 switch (N->getOpcode()) {
5274 case ISD::ATOMIC_LOAD: {
5275 SDLoc DL(N);
5276 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::Other);
5277 SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
5278 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
5279 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_LOAD_128,
5280 DL, Tys, Ops, MVT::i128, MMO);
5281 Results.push_back(lowerGR128ToI128(DAG, Res));
5282 Results.push_back(Res.getValue(1));
5283 break;
5284 }
5285 case ISD::ATOMIC_STORE: {
5286 SDLoc DL(N);
5287 SDVTList Tys = DAG.getVTList(MVT::Other);
5288 SDValue Ops[] = { N->getOperand(0),
5289 lowerI128ToGR128(DAG, N->getOperand(2)),
5290 N->getOperand(1) };
5291 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
5292 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_STORE_128,
5293 DL, Tys, Ops, MVT::i128, MMO);
5294 // We have to enforce sequential consistency by performing a
5295 // serialization operation after the store.
5296 if (cast<AtomicSDNode>(N)->getOrdering() ==
5297 AtomicOrdering::SequentiallyConsistent)
5298 Res = SDValue(DAG.getMachineNode(SystemZ::Serialize, DL,
5299 MVT::Other, Res), 0);
5300 Results.push_back(Res);
5301 break;
5302 }
5303 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
5304 SDLoc DL(N);
5305 SDVTList Tys = DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other);
5306 SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
5307 lowerI128ToGR128(DAG, N->getOperand(2)),
5308 lowerI128ToGR128(DAG, N->getOperand(3)) };
5309 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
5310 SDValue Res = DAG.getMemIntrinsicNode(SystemZISD::ATOMIC_CMP_SWAP_128,
5311 DL, Tys, Ops, MVT::i128, MMO);
5312 SDValue Success = emitSETCC(DAG, DL, Res.getValue(1),
5313 SystemZ::CCMASK_CS, SystemZ::CCMASK_CS_EQ);
5314 Success = DAG.getZExtOrTrunc(Success, DL, N->getValueType(1));
5315 Results.push_back(lowerGR128ToI128(DAG, Res));
5316 Results.push_back(Success);
5317 Results.push_back(Res.getValue(2));
5318 break;
5319 }
5320 default:
5321 llvm_unreachable("Unexpected node to lower")::llvm::llvm_unreachable_internal("Unexpected node to lower",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/SystemZ/SystemZISelLowering.cpp"
, 5321)
;
5322 }
5323}
5324
5325void
5326SystemZTargetLowering::ReplaceNodeResults(SDNode *N,
5327 SmallVectorImpl<SDValue> &Results,
5328 SelectionDAG &DAG) const {
5329 return LowerOperationWrapper(N, Results, DAG);
5330}
5331
5332const char *SystemZTargetLowering::getTargetNodeName(unsigned Opcode) const {
5333#define OPCODE(NAME) case SystemZISD::NAME: return "SystemZISD::" #NAME
5334 switch ((SystemZISD::NodeType)Opcode) {
5335 case SystemZISD::FIRST_NUMBER: break;
5336 OPCODE(RET_FLAG);
5337 OPCODE(CALL);
5338 OPCODE(SIBCALL);
5339 OPCODE(TLS_GDCALL);
5340 OPCODE(TLS_LDCALL);
5341 OPCODE(PCREL_WRAPPER);
5342 OPCODE(PCREL_OFFSET);
5343 OPCODE(IABS);
5344 OPCODE(ICMP);
5345 OPCODE(FCMP);
5346 OPCODE(STRICT_FCMP);
5347 OPCODE(STRICT_FCMPS);
5348 OPCODE(TM);
5349 OPCODE(BR_CCMASK);
5350 OPCODE(SELECT_CCMASK);
5351 OPCODE(ADJDYNALLOC);
5352 OPCODE(POPCNT);
5353 OPCODE(SMUL_LOHI);
5354 OPCODE(UMUL_LOHI);
5355 OPCODE(SDIVREM);
5356 OPCODE(UDIVREM);
5357 OPCODE(SADDO);
5358 OPCODE(SSUBO);
5359 OPCODE(UADDO);
5360 OPCODE(USUBO);
5361 OPCODE(ADDCARRY);
5362 OPCODE(SUBCARRY);
5363 OPCODE(GET_CCMASK);
5364 OPCODE(MVC);
5365 OPCODE(MVC_LOOP);
5366 OPCODE(NC);
5367 OPCODE(NC_LOOP);
5368 OPCODE(OC);
5369 OPCODE(OC_LOOP);
5370 OPCODE(XC);
5371 OPCODE(XC_LOOP);
5372 OPCODE(CLC);
5373 OPCODE(CLC_LOOP);
5374 OPCODE(STPCPY);
5375 OPCODE(STRCMP);
5376 OPCODE(SEARCH_STRING);
5377 OPCODE(IPM);
5378 OPCODE(MEMBARRIER);
5379 OPCODE(TBEGIN);
5380 OPCODE(TBEGIN_NOFLOAT);
5381 OPCODE(TEND);
5382 OPCODE(BYTE_MASK);
5383 OPCODE(ROTATE_MASK);
5384 OPCODE(REPLICATE);
5385 OPCODE(JOIN_DWORDS);
5386 OPCODE(SPLAT);
5387 OPCODE(MERGE_HIGH);
5388 OPCODE(MERGE_LOW);
5389 OPCODE(SHL_DOUBLE);
5390 OPCODE(PERMUTE_DWORDS);
5391 OPCODE(PERMUTE);
5392 OPCODE(PACK);
5393 OPCODE(PACKS_CC);
5394 OPCODE(PACKLS_CC);
5395 OPCODE(UNPACK_HIGH);
5396 OPCODE(UNPACKL_HIGH);
5397 OPCODE(UNPACK_LOW);
5398 OPCODE(UNPACKL_LOW);
5399 OPCODE(VSHL_BY_SCALAR);
5400 OPCODE(VSRL_BY_SCALAR);
5401 OPCODE(VSRA_BY_SCALAR);
5402 OPCODE(VSUM);
5403 OPCODE(VICMPE);
5404 OPCODE(VICMPH);
5405 OPCODE(VICMPHL);
5406 OPCODE(VICMPES);
5407 OPCODE(VICMPHS);
5408 OPCODE(VICMPHLS);
5409 OPCODE(VFCMPE);
5410 OPCODE(STRICT_VFCMPE);
5411 OPCODE(STRICT_VFCMPES);
5412 OPCODE(VFCMPH);
5413 OPCODE(STRICT_VFCMPH);
5414 OPCODE(STRICT_VFCMPHS);
5415 OPCODE(VFCMPHE);
5416 OPCODE(STRICT_VFCMPHE);
5417 OPCODE(STRICT_VFCMPHES);
5418 OPCODE(VFCMPES);
5419 OPCODE(VFCMPHS);
5420 OPCODE(VFCMPHES);
5421 OPCODE(VFTCI);
5422 OPCODE(VEXTEND);
5423 OPCODE(STRICT_VEXTEND);
5424 OPCODE(VROUND);
5425 OPCODE(STRICT_VROUND);
5426 OPCODE(VTM);
5427 OPCODE(VFAE_CC);
5428 OPCODE(VFAEZ_CC);
5429 OPCODE(VFEE_CC);
5430 OPCODE(VFEEZ_CC);
5431 OPCODE(VFENE_CC);
5432 OPCODE(VFENEZ_CC);
5433 OPCODE(VISTR_CC);
5434 OPCODE(VSTRC_CC);
5435 OPCODE(VSTRCZ_CC);
5436 OPCODE(VSTRS_CC);
5437 OPCODE(VSTRSZ_CC);
5438 OPCODE(TDC);
5439 OPCODE(ATOMIC_SWAPW);
5440 OPCODE(ATOMIC_LOADW_ADD);
5441 OPCODE(ATOMIC_LOADW_SUB);
5442 OPCODE(ATOMIC_LOADW_AND);
5443 OPCODE(ATOMIC_LOADW_OR);
5444 OPCODE(ATOMIC_LOADW_XOR);
5445 OPCODE(ATOMIC_LOADW_NAND);
5446 OPCODE(ATOMIC_LOADW_MIN);
5447 OPCODE(ATOMIC_LOADW_MAX);
5448 OPCODE(ATOMIC_LOADW_UMIN);
5449 OPCODE(ATOMIC_LOADW_UMAX);
5450 OPCODE(ATOMIC_CMP_SWAPW);
5451 OPCODE(ATOMIC_CMP_SWAP);
5452 OPCODE(ATOMIC_LOAD_128);
5453 OPCODE(ATOMIC_STORE_128);
5454 OPCODE(ATOMIC_CMP_SWAP_128);
5455 OPCODE(LRV);
5456 OPCODE(STRV);
5457 OPCODE(VLER);
5458 OPCODE(VSTER);
5459 OPCODE(PREFETCH);
5460 }
5461 return nullptr;
5462#undef OPCODE
5463}
5464
5465// Return true if VT is a vector whose elements are a whole number of bytes
5466// in width. Also check for presence of vector support.
5467bool SystemZTargetLowering::canTreatAsByteVector(EVT VT) const {
5468 if (!Subtarget.hasVector())
5469 return false;
5470
5471 return VT.isVector() && VT.getScalarSizeInBits() % 8 == 0 && VT.isSimple();
5472}
5473
5474// Try to simplify an EXTRACT_VECTOR_ELT from a vector of type VecVT
5475// producing a result of type ResVT. Op is a possibly bitcast version
5476// of the input vector and Index is the index (based on type VecVT) that
5477// should be extracted. Return the new extraction if a simplification
5478// was possible or if Force is true.
5479SDValue SystemZTargetLowering::combineExtract(const SDLoc &DL, EVT ResVT,
5480 EVT VecVT, SDValue Op,
5481 unsigned Index,
5482 DAGCombinerInfo &DCI,
5483 bool Force) const {
5484 SelectionDAG &DAG = DCI.DAG;
5485
5486 // The number of bytes being extracted.
5487 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
5488
5489 for (;;) {
5490 unsigned Opcode = Op.getOpcode();
5491 if (Opcode == ISD::BITCAST)
5492 // Look through bitcasts.
5493 Op = Op.getOperand(0);
5494 else if ((Opcode == ISD::VECTOR_SHUFFLE || Opcode == SystemZISD::SPLAT) &&
5495 canTreatAsByteVector(Op.getValueType())) {
5496 // Get a VPERM-like permute mask and see whether the bytes covered
5497 // by the extracted element are a contiguous sequence from one
5498 // source operand.
5499 SmallVector<int, SystemZ::VectorBytes> Bytes;
5500 if (!getVPermMask(Op, Bytes))
5501 break;
5502 int First;
5503 if (!getShuffleInput(Bytes, Index * BytesPerElement,
5504 BytesPerElement, First))
5505 break;
5506 if (First < 0)
5507 return DAG.getUNDEF(ResVT);
5508 // Make sure the contiguous sequence starts at a multiple of the
5509 // original element size.
5510 unsigned Byte = unsigned(First) % Bytes.size();
5511 if (Byte % BytesPerElement != 0)
5512 break;
5513 // We can get the extracted value directly from an input.
5514 Index = Byte / BytesPerElement;
5515 Op = Op.getOperand(unsigned(First) / Bytes.size());
5516 Force = true;
5517 } else if (Opcode == ISD::BUILD_VECTOR &&
5518 canTreatAsByteVector(Op.getValueType())) {
5519 // We can only optimize this case if the BUILD_VECTOR elements are
5520 // at least as wide as the extracted value.
5521 EVT OpVT = Op.getValueType();
5522 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
5523 if (OpBytesPerElement < BytesPerElement)
5524 break;
5525 // Make sure that the least-significant bit of the extracted value
5526 // is the least significant bit of an input.
5527 unsigned End = (Index + 1) * BytesPerElement;
5528 if (End % OpBytesPerElement != 0)
5529 break;
5530 // We're extracting the low part of one operand of the BUILD_VECTOR.
5531 Op = Op.getOperand(End / OpBytesPerElement - 1);
5532 if (!Op.getValueType().isInteger()) {
5533 EVT VT = MVT::getIntegerVT(Op.getValueSizeInBits());
5534 Op = DAG.getNode(ISD::BITCAST, DL, VT, Op);
5535 DCI.AddToWorklist(Op.getNode());
5536 }
5537 EVT VT = MVT::getIntegerVT(ResVT.getSizeInBits());
5538 Op = DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
5539 if (VT != ResVT) {
5540 DCI.AddToWorklist(Op.getNode());
5541 Op = DAG.getNode(ISD::BITCAST, DL, ResVT, Op);
5542 }
5543 return Op;
5544 } else if ((Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
5545 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG ||
5546 Opcode == ISD::ANY_EXTEND_VECTOR_INREG) &&
5547 canTreatAsByteVector(Op.getValueType()) &&
5548 canTreatAsByteVector(Op.getOperand(0).getValueType())) {
5549 // Make sure that only the unextended bits are significant.
5550 EVT ExtVT = Op.getValueType();
5551 EVT OpVT = Op.getOperand(0).getValueType();
5552 unsigned ExtBytesPerElement = ExtVT.getVectorElementType().getStoreSize();
5553 unsigned OpBytesPerElement = OpVT.getVectorElementType().getStoreSize();
5554 unsigned Byte = Index * BytesPerElement;
5555 unsigned SubByte = Byte % ExtBytesPerElement;
5556 unsigned MinSubByte = ExtBytesPerElement - OpBytesPerElement;
5557 if (SubByte < MinSubByte ||
5558 SubByte + BytesPerElement > ExtBytesPerElement)
5559 break;
5560 // Get the byte offset of the unextended element
5561 Byte = Byte / ExtBytesPerElement * OpBytesPerElement;
5562 // ...then add the byte offset relative to that element.
5563 Byte += SubByte - MinSubByte;
5564 if (Byte % BytesPerElement != 0)
5565 break;
5566 Op = Op.getOperand(0);
5567 Index = Byte / BytesPerElement;
5568 Force = true;
5569 } else
5570 break;
5571 }
5572 if (Force) {
5573 if (Op.getValueType() != VecVT) {
5574 Op = DAG.getNode(ISD::BITCAST, DL, VecVT, Op);
5575 DCI.AddToWorklist(Op.getNode());
5576 }
5577 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Op,
5578 DAG.getConstant(Index, DL, MVT::i32));
5579 }
5580 return SDValue();
5581}
5582
5583// Optimize vector operations in scalar value Op on the basis that Op
5584// is truncated to TruncVT.
5585SDValue SystemZTargetLowering::combineTruncateExtract(
5586 const SDLoc &DL, EVT TruncVT, SDValue Op, DAGCombinerInfo &DCI) const {
5587 // If we have (trunc (extract_vector_elt X, Y)), try to turn it into
5588 // (extract_vector_elt (bitcast X), Y'), where (bitcast X) has elements
5589 // of type TruncVT.
5590 if (Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5591 TruncVT.getSizeInBits() % 8 == 0) {
5592 SDValue Vec = Op.getOperand(0);
5593 EVT VecVT = Vec.getValueType();
5594 if (canTreatAsByteVector(VecVT)) {
5595 if (auto *IndexN = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
5596 unsigned BytesPerElement = VecVT.getVectorElementType().getStoreSize();
5597 unsigned TruncBytes = TruncVT.getStoreSize();
5598 if (BytesPerElement % TruncBytes == 0) {
5599 // Calculate the value of Y' in the above description. We are
5600 // splitting the original elements into Scale equal-sized pieces
5601 // and for truncation purposes want the last (least-significant)
5602 // of these pieces for IndexN. This is easiest to do by calculating
5603 // the start index of the following element and then subtracting 1.
5604 unsigned Scale = BytesPerElement / TruncBytes;
5605 unsigned NewIndex = (IndexN->getZExtValue() + 1) * Scale - 1;
5606
5607 // Defer the creation of the bitcast from X to combineExtract,
5608 // which might be able to optimize the extraction.
5609 VecVT = MVT::getVectorVT(MVT::getIntegerVT(TruncBytes * 8),
5610 VecVT.getStoreSize() / TruncBytes);
5611 EVT ResVT = (TruncBytes < 4 ? MVT::i32 : TruncVT);
5612 return combineExtract(DL, ResVT, VecVT, Vec, NewIndex, DCI, true);
5613 }
5614 }
5615 }
5616 }
5617 return SDValue();
5618}
5619
5620SDValue SystemZTargetLowering::combineZERO_EXTEND(
5621 SDNode *N, DAGCombinerInfo &DCI) const {
5622 // Convert (zext (select_ccmask C1, C2)) into (select_ccmask C1', C2')
5623 SelectionDAG &DAG = DCI.DAG;
5624 SDValue N0 = N->getOperand(0);
5625 EVT VT = N->getValueType(0);
5626 if (N0.getOpcode() == SystemZISD::SELECT_CCMASK) {
5627 auto *TrueOp = dyn_cast<ConstantSDNode>(N0.getOperand(0));
5628 auto *FalseOp = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5629 if (TrueOp && FalseOp) {
5630 SDLoc DL(N0);
5631 SDValue Ops[] = { DAG.getConstant(TrueOp->getZExtValue(), DL, VT),
5632 DAG.getConstant(FalseOp->getZExtValue(), DL, VT),
5633 N0.getOperand(2), N0.getOperand(3), N0.getOperand(4) };
5634 SDValue NewSelect = DAG.getNode(SystemZISD::SELECT_CCMASK, DL, VT, Ops);
5635 // If N0 has multiple uses, change other uses as well.
5636 if (!N0.hasOneUse()) {
5637 SDValue TruncSelect =
5638 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), NewSelect);
5639 DCI.CombineTo(N0.getNode(), TruncSelect);
5640 }
5641 return NewSelect;
5642 }
5643 }
5644 return SDValue();
5645}
5646
5647SDValue SystemZTargetLowering::combineSIGN_EXTEND_INREG(
5648 SDNode *N, DAGCombinerInfo &DCI) const {
5649 // Convert (sext_in_reg (setcc LHS, RHS, COND), i1)
5650 // and (sext_in_reg (any_extend (setcc LHS, RHS, COND)), i1)
5651 // into (select_cc LHS, RHS, -1, 0, COND)
5652 SelectionDAG &DAG = DCI.DAG;
5653 SDValue N0 = N->getOperand(0);
5654 EVT VT = N->getValueType(0);
5655 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5656 if (N0.hasOneUse() && N0.getOpcode() == ISD::ANY_EXTEND)
5657 N0 = N0.getOperand(0);
5658 if (EVT == MVT::i1 && N0.hasOneUse() && N0.getOpcode() == ISD::SETCC) {
5659 SDLoc DL(N0);
5660 SDValue Ops[] = { N0.getOperand(0), N0.getOperand(1),
5661 DAG.getConstant(-1, DL, VT), DAG.getConstant(0, DL, VT),
5662 N0.getOperand(2) };
5663 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
5664 }
5665 return SDValue();
5666}
5667
5668SDValue SystemZTargetLowering::combineSIGN_EXTEND(
5669 SDNode *N, DAGCombinerInfo &DCI) const {
5670 // Convert (sext (ashr (shl X, C1), C2)) to
5671 // (ashr (shl (anyext X), C1'), C2')), since wider shifts are as
5672 // cheap as narrower ones.
5673 SelectionDAG &DAG = DCI.DAG;
5674 SDValue N0 = N->getOperand(0);
5675 EVT VT = N->getValueType(0);
5676 if (N0.hasOneUse() && N0.getOpcode() == ISD::SRA) {
5677 auto *SraAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5678 SDValue Inner = N0.getOperand(0);
5679 if (SraAmt && Inner.hasOneUse() && Inner.getOpcode() == ISD::SHL) {
5680 if (auto *ShlAmt = dyn_cast<ConstantSDNode>(Inner.getOperand(1))) {
5681 unsigned Extra = (VT.getSizeInBits() - N0.getValueSizeInBits());
5682 unsigned NewShlAmt = ShlAmt->getZExtValue() + Extra;
5683 unsigned NewSraAmt = SraAmt->getZExtValue() + Extra;
5684 EVT ShiftVT = N0.getOperand(1).getValueType();
5685 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SDLoc(Inner), VT,
5686 Inner.getOperand(0));
5687 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(Inner), VT, Ext,
5688 DAG.getConstant(NewShlAmt, SDLoc(Inner),
5689 ShiftVT));
5690 return DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl,
5691 DAG.getConstant(NewSraAmt, SDLoc(N0), ShiftVT));
5692 }
5693 }
5694 }
5695 return SDValue();
5696}
5697
5698SDValue SystemZTargetLowering::combineMERGE(
5699 SDNode *N, DAGCombinerInfo &DCI) const {
5700 SelectionDAG &DAG = DCI.DAG;
5701 unsigned Opcode = N->getOpcode();
5702 SDValue Op0 = N->getOperand(0);
5703 SDValue Op1 = N->getOperand(1);
5704 if (Op0.getOpcode() == ISD::BITCAST)
5705 Op0 = Op0.getOperand(0);
5706 if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5707 // (z_merge_* 0, 0) -> 0. This is mostly useful for using VLLEZF
5708 // for v4f32.
5709 if (Op1 == N->getOperand(0))
5710 return Op1;
5711 // (z_merge_? 0, X) -> (z_unpackl_? 0, X).
5712 EVT VT = Op1.getValueType();
5713 unsigned ElemBytes = VT.getVectorElementType().getStoreSize();
5714 if (ElemBytes <= 4) {
5715 Opcode = (Opcode == SystemZISD::MERGE_HIGH ?
5716 SystemZISD::UNPACKL_HIGH : SystemZISD::UNPACKL_LOW);
5717 EVT InVT = VT.changeVectorElementTypeToInteger();
5718 EVT OutVT = MVT::getVectorVT(MVT::getIntegerVT(ElemBytes * 16),
5719 SystemZ::VectorBytes / ElemBytes / 2);
5720 if (VT != InVT) {
5721 Op1 = DAG.getNode(ISD::BITCAST, SDLoc(N), InVT, Op1);
5722 DCI.AddToWorklist(Op1.getNode());
5723 }
5724 SDValue Op = DAG.getNode(Opcode, SDLoc(N), OutVT, Op1);
5725 DCI.AddToWorklist(Op.getNode());
5726 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
5727 }
5728 }
5729 return SDValue();
5730}
5731
5732SDValue SystemZTargetLowering::combineLOAD(
5733 SDNode *N, DAGCombinerInfo &DCI) const {
5734 SelectionDAG &DAG = DCI.DAG;
5735 EVT LdVT = N->getValueType(0);
5736 if (LdVT.isVector() || LdVT.isInteger())
5737 return SDValue();
5738 // Transform a scalar load that is REPLICATEd as well as having other
5739 // use(s) to the form where the other use(s) use the first element of the
5740 // REPLICATE instead of the load. Otherwise instruction selection will not
5741 // produce a VLREP. Avoid extracting to a GPR, so only do this for floating
5742 // point loads.
5743
5744 SDValue Replicate;
5745 SmallVector<SDNode*, 8> OtherUses;
5746 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5747 UI != UE; ++UI) {
5748 if (UI->getOpcode() == SystemZISD::REPLICATE) {
5749 if (Replicate)
5750 return SDValue(); // Should never happen
5751 Replicate = SDValue(*UI, 0);
5752 }
5753 else if (UI.getUse().getResNo() == 0)
5754 OtherUses.push_back(*UI);
5755 }
5756 if (!Replicate || OtherUses.empty())
5757 return SDValue();
5758
5759 SDLoc DL(N);
5760 SDValue Extract0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, LdVT,
5761 Replicate, DAG.getConstant(0, DL, MVT::i32));
5762 // Update uses of the loaded Value while preserving old chains.
5763 for (SDNode *U : OtherUses) {
5764 SmallVector<SDValue, 8> Ops;
5765 for (SDValue Op : U->ops())
5766 Ops.push_back((Op.getNode() == N && Op.getResNo() == 0) ? Extract0 : Op);
5767 DAG.UpdateNodeOperands(U, Ops);
5768 }
5769 return SDValue(N, 0);
5770}
5771
5772bool SystemZTargetLowering::canLoadStoreByteSwapped(EVT VT) const {
5773 if (VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)
5774 return true;
5775 if (Subtarget.hasVectorEnhancements2())
5776 if (VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64)
5777 return true;
5778 return false;
5779}
5780
5781static bool isVectorElementSwap(ArrayRef<int> M, EVT VT) {
5782 if (!VT.isVector() || !VT.isSimple() ||
5783 VT.getSizeInBits() != 128 ||
5784 VT.getScalarSizeInBits() % 8 != 0)
5785 return false;
5786
5787 unsigned NumElts = VT.getVectorNumElements();
5788 for (unsigned i = 0; i < NumElts; ++i) {
5789 if (M[i] < 0) continue; // ignore UNDEF indices
5790 if ((unsigned) M[i] != NumElts - 1 - i)
5791 return false;
5792 }
5793
5794 return true;
5795}
5796
5797SDValue SystemZTargetLowering::combineSTORE(
5798 SDNode *N, DAGCombinerInfo &DCI) const {
5799 SelectionDAG &DAG = DCI.DAG;
5800 auto *SN = cast<StoreSDNode>(N);
5801 auto &Op1 = N->getOperand(1);
5802 EVT MemVT = SN->getMemoryVT();
5803 // If we have (truncstoreiN (extract_vector_elt X, Y), Z) then it is better
5804 // for the extraction to be done on a vMiN value, so that we can use VSTE.
5805 // If X has wider elements then convert it to:
5806 // (truncstoreiN (extract_vector_elt (bitcast X), Y2), Z).
5807 if (MemVT.isInteger() && SN->isTruncatingStore()) {
5808 if (SDValue Value =
5809 combineTruncateExtract(SDLoc(N), MemVT, SN->getValue(), DCI)) {
5810 DCI.AddToWorklist(Value.getNode());
5811
5812 // Rewrite the store with the new form of stored value.
5813 return DAG.getTruncStore(SN->getChain(), SDLoc(SN), Value,
5814 SN->getBasePtr(), SN->getMemoryVT(),
5815 SN->getMemOperand());
5816 }
5817 }
5818 // Combine STORE (BSWAP) into STRVH/STRV/STRVG/VSTBR
5819 if (!SN->isTruncatingStore() &&
5820 Op1.getOpcode() == ISD::BSWAP &&
5821 Op1.getNode()->hasOneUse() &&
5822 canLoadStoreByteSwapped(Op1.getValueType())) {
5823
5824 SDValue BSwapOp = Op1.getOperand(0);
5825
5826 if (BSwapOp.getValueType() == MVT::i16)
5827 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), MVT::i32, BSwapOp);
5828
5829 SDValue Ops[] = {
5830 N->getOperand(0), BSwapOp, N->getOperand(2)
5831 };
5832
5833 return
5834 DAG.getMemIntrinsicNode(SystemZISD::STRV, SDLoc(N), DAG.getVTList(MVT::Other),
5835 Ops, MemVT, SN->getMemOperand());
5836 }
5837 // Combine STORE (element-swap) into VSTER
5838 if (!SN->isTruncatingStore() &&
5839 Op1.getOpcode() == ISD::VECTOR_SHUFFLE &&
5840 Op1.getNode()->hasOneUse() &&
5841 Subtarget.hasVectorEnhancements2()) {
5842 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op1.getNode());
5843 ArrayRef<int> ShuffleMask = SVN->getMask();
5844 if (isVectorElementSwap(ShuffleMask, Op1.getValueType())) {
5845 SDValue Ops[] = {
5846 N->getOperand(0), Op1.getOperand(0), N->getOperand(2)
5847 };
5848
5849 return DAG.getMemIntrinsicNode(SystemZISD::VSTER, SDLoc(N),
5850 DAG.getVTList(MVT::Other),
5851 Ops, MemVT, SN->getMemOperand());
5852 }
5853 }
5854
5855 return SDValue();
5856}
5857
5858SDValue SystemZTargetLowering::combineVECTOR_SHUFFLE(
5859 SDNode *N, DAGCombinerInfo &DCI) const {
5860 SelectionDAG &DAG = DCI.DAG;
5861 // Combine element-swap (LOAD) into VLER
5862 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
5863 N->getOperand(0).hasOneUse() &&
5864 Subtarget.hasVectorEnhancements2()) {
5865 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
5866 ArrayRef<int> ShuffleMask = SVN->getMask();
5867 if (isVectorElementSwap(ShuffleMask, N->getValueType(0))) {
5868 SDValue Load = N->getOperand(0);
5869 LoadSDNode *LD = cast<LoadSDNode>(Load);
5870
5871 // Create the element-swapping load.
5872 SDValue Ops[] = {
5873 LD->getChain(), // Chain
5874 LD->getBasePtr() // Ptr
5875 };
5876 SDValue ESLoad =
5877 DAG.getMemIntrinsicNode(SystemZISD::VLER, SDLoc(N),
5878 DAG.getVTList(LD->getValueType(0), MVT::Other),
5879 Ops, LD->getMemoryVT(), LD->getMemOperand());
5880
5881 // First, combine the VECTOR_SHUFFLE away. This makes the value produced
5882 // by the load dead.
5883 DCI.CombineTo(N, ESLoad);
5884
5885 // Next, combine the load away, we give it a bogus result value but a real
5886 // chain result. The result value is dead because the shuffle is dead.
5887 DCI.CombineTo(Load.getNode(), ESLoad, ESLoad.getValue(1));
5888
5889 // Return N so it doesn't get rechecked!
5890 return SDValue(N, 0);
5891 }
5892 }
5893
5894 return SDValue();
5895}
5896
5897SDValue SystemZTargetLowering::combineEXTRACT_VECTOR_ELT(
5898 SDNode *N, DAGCombinerInfo &DCI) const {
5899 SelectionDAG &DAG = DCI.DAG;
5900
5901 if (!Subtarget.hasVector())
5902 return SDValue();
5903
5904 // Look through bitcasts that retain the number of vector elements.
5905 SDValue Op = N->getOperand(0);
5906 if (Op.getOpcode() == ISD::BITCAST &&
5907 Op.getValueType().isVector() &&
5908 Op.getOperand(0).getValueType().isVector() &&
5909 Op.getValueType().getVectorNumElements() ==
5910 Op.getOperand(0).getValueType().getVectorNumElements())
5911 Op = Op.getOperand(0);
5912
5913 // Pull BSWAP out of a vector extraction.
5914 if (Op.getOpcode() == ISD::BSWAP && Op.hasOneUse()) {
5915 EVT VecVT = Op.getValueType();
5916 EVT EltVT = VecVT.getVectorElementType();
5917 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), EltVT,
5918 Op.getOperand(0), N->getOperand(1));
5919 DCI.AddToWorklist(Op.getNode());
5920 Op = DAG.getNode(ISD::BSWAP, SDLoc(N), EltVT, Op);
5921 if (EltVT != N->getValueType(0)) {
5922 DCI.AddToWorklist(Op.getNode());
5923 Op = DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Op);
5924 }
5925 return Op;
5926 }
5927
5928 // Try to simplify a vector extraction.
5929 if (auto *IndexN = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
5930 SDValue Op0 = N->getOperand(0);
5931 EVT VecVT = Op0.getValueType();
5932 return combineExtract(SDLoc(N), N->getValueType(0), VecVT, Op0,
5933 IndexN->getZExtValue(), DCI, false);
5934 }
5935 return SDValue();
5936}
5937
5938SDValue SystemZTargetLowering::combineJOIN_DWORDS(
5939 SDNode *N, DAGCombinerInfo &DCI) const {
5940 SelectionDAG &DAG = DCI.DAG;
5941 // (join_dwords X, X) == (replicate X)
5942 if (N->getOperand(0) == N->getOperand(1))
5943 return DAG.getNode(SystemZISD::REPLICATE, SDLoc(N), N->getValueType(0),
5944 N->getOperand(0));
5945 return SDValue();
5946}
5947
5948static SDValue MergeInputChains(SDNode *N1, SDNode *N2) {
5949 SDValue Chain1 = N1->getOperand(0);
5950 SDValue Chain2 = N2->getOperand(0);
5951
5952 // Trivial case: both nodes take the same chain.
5953 if (Chain1 == Chain2)
5954 return Chain1;
5955
5956 // FIXME - we could handle more complex cases via TokenFactor,
5957 // assuming we can verify that this would not create a cycle.
5958 return SDValue();
5959}
5960
5961SDValue SystemZTargetLowering::combineFP_ROUND(
5962 SDNode *N, DAGCombinerInfo &DCI) const {
5963
5964 if (!Subtarget.hasVector())
5965 return SDValue();
5966
5967 // (fpround (extract_vector_elt X 0))
5968 // (fpround (extract_vector_elt X 1)) ->
5969 // (extract_vector_elt (VROUND X) 0)
5970 // (extract_vector_elt (VROUND X) 2)
5971 //
5972 // This is a special case since the target doesn't really support v2f32s.
5973 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
5974 SelectionDAG &DAG = DCI.DAG;
5975 SDValue Op0 = N->getOperand(OpNo);
5976 if (N->getValueType(0) == MVT::f32 &&
5977 Op0.hasOneUse() &&
5978 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5979 Op0.getOperand(0).getValueType() == MVT::v2f64 &&
5980 Op0.getOperand(1).getOpcode() == ISD::Constant &&
5981 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
5982 SDValue Vec = Op0.getOperand(0);
5983 for (auto *U : Vec->uses()) {
5984 if (U != Op0.getNode() &&
5985 U->hasOneUse() &&
5986 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5987 U->getOperand(0) == Vec &&
5988 U->getOperand(1).getOpcode() == ISD::Constant &&
5989 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 1) {
5990 SDValue OtherRound = SDValue(*U->use_begin(), 0);
5991 if (OtherRound.getOpcode() == N->getOpcode() &&
5992 OtherRound.getOperand(OpNo) == SDValue(U, 0) &&
5993 OtherRound.getValueType() == MVT::f32) {
5994 SDValue VRound, Chain;
5995 if (N->isStrictFPOpcode()) {
5996 Chain = MergeInputChains(N, OtherRound.getNode());
5997 if (!Chain)
5998 continue;
5999 VRound = DAG.getNode(SystemZISD::STRICT_VROUND, SDLoc(N),
6000 {MVT::v4f32, MVT::Other}, {Chain, Vec});
6001 Chain = VRound.getValue(1);
6002 } else
6003 VRound = DAG.getNode(SystemZISD::VROUND, SDLoc(N),
6004 MVT::v4f32, Vec);
6005 DCI.AddToWorklist(VRound.getNode());
6006 SDValue Extract1 =
6007 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f32,
6008 VRound, DAG.getConstant(2, SDLoc(U), MVT::i32));
6009 DCI.AddToWorklist(Extract1.getNode());
6010 DAG.ReplaceAllUsesOfValueWith(OtherRound, Extract1);
6011 if (Chain)
6012 DAG.ReplaceAllUsesOfValueWith(OtherRound.getValue(1), Chain);
6013 SDValue Extract0 =
6014 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f32,
6015 VRound, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
6016 if (Chain)
6017 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
6018 N->getVTList(), Extract0, Chain);
6019 return Extract0;
6020 }
6021 }
6022 }
6023 }
6024 return SDValue();
6025}
6026
6027SDValue SystemZTargetLowering::combineFP_EXTEND(
6028 SDNode *N, DAGCombinerInfo &DCI) const {
6029
6030 if (!Subtarget.hasVector())
6031 return SDValue();
6032
6033 // (fpextend (extract_vector_elt X 0))
6034 // (fpextend (extract_vector_elt X 2)) ->
6035 // (extract_vector_elt (VEXTEND X) 0)
6036 // (extract_vector_elt (VEXTEND X) 1)
6037 //
6038 // This is a special case since the target doesn't really support v2f32s.
6039 unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
6040 SelectionDAG &DAG = DCI.DAG;
6041 SDValue Op0 = N->getOperand(OpNo);
6042 if (N->getValueType(0) == MVT::f64 &&
6043 Op0.hasOneUse() &&
6044 Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6045 Op0.getOperand(0).getValueType() == MVT::v4f32 &&
6046 Op0.getOperand(1).getOpcode() == ISD::Constant &&
6047 cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue() == 0) {
6048 SDValue Vec = Op0.getOperand(0);
6049 for (auto *U : Vec->uses()) {
6050 if (U != Op0.getNode() &&
6051 U->hasOneUse() &&
6052 U->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6053 U->getOperand(0) == Vec &&
6054 U->getOperand(1).getOpcode() == ISD::Constant &&
6055 cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() == 2) {
6056 SDValue OtherExtend = SDValue(*U->use_begin(), 0);
6057 if (OtherExtend.getOpcode() == N->getOpcode() &&
6058 OtherExtend.getOperand(OpNo) == SDValue(U, 0) &&
6059 OtherExtend.getValueType() == MVT::f64) {
6060 SDValue VExtend, Chain;
6061 if (N->isStrictFPOpcode()) {
6062 Chain = MergeInputChains(N, OtherExtend.getNode());
6063 if (!Chain)
6064 continue;
6065 VExtend = DAG.getNode(SystemZISD::STRICT_VEXTEND, SDLoc(N),
6066 {MVT::v2f64, MVT::Other}, {Chain, Vec});
6067 Chain = VExtend.getValue(1);
6068 } else
6069 VExtend = DAG.getNode(SystemZISD::VEXTEND, SDLoc(N),
6070 MVT::v2f64, Vec);
6071 DCI.AddToWorklist(VExtend.getNode());
6072 SDValue Extract1 =
6073 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(U), MVT::f64,
6074 VExtend, DAG.getConstant(1, SDLoc(U), MVT::i32));
6075 DCI.AddToWorklist(Extract1.getNode());
6076 DAG.ReplaceAllUsesOfValueWith(OtherExtend, Extract1);
6077 if (Chain)
6078 DAG.ReplaceAllUsesOfValueWith(OtherExtend.getValue(1), Chain);
6079 SDValue Extract0 =
6080 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(Op0), MVT::f64,
6081 VExtend, DAG.getConstant(0, SDLoc(Op0), MVT::i32));
6082 if (Chain)
6083 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op0),
6084 N->getVTList(), Extract0, Chain);
6085 return Extract0;
6086 }
6087 }
6088 }
6089 }
6090 return SDValue();
6091}
6092
6093SDValue SystemZTargetLowering::combineBSWAP(
6094 SDNode *N, DAGCombinerInfo &DCI) const {
6095 SelectionDAG &DAG = DCI.DAG;
6096 // Combine BSWAP (LOAD) into LRVH/LRV/LRVG/VLBR
6097 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6098 N->getOperand(0).hasOneUse() &&
6099 canLoadStoreByteSwapped(N->getValueType(0))) {
6100 SDValue Load = N->getOperand(0);
6101 LoadSDNode *LD = cast<LoadSDNode>(Load);
6102
6103 // Create the byte-swapping load.
6104 SDValue Ops[] = {
6105 LD->getChain(), // Chain
6106 LD->getBasePtr() // Ptr
6107 };
6108 EVT LoadVT = N->getValueType(0);
6109 if (LoadVT == MVT::i16)
6110 LoadVT = MVT::i32;
6111 SDValue BSLoad =
6112 DAG.getMemIntrinsicNode(SystemZISD::LRV, SDLoc(N),
6113 DAG.getVTList(LoadVT, MVT::Other),
6114 Ops, LD->getMemoryVT(), LD->getMemOperand());
6115
6116 // If this is an i16 load, insert the truncate.
6117 SDValue ResVal = BSLoad;
6118 if (N->getValueType(0) == MVT::i16)
6119 ResVal = DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16, BSLoad);
6120
6121 // First, combine the bswap away. This makes the value produced by the
6122 // load dead.
6123 DCI.CombineTo(N, ResVal);
6124
6125 // Next, combine the load away, we give it a bogus result value but a real
6126 // chain result. The result value is dead because the bswap is dead.
6127 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
6128
6129 // Return N so it doesn't get rechecked!
6130 return SDValue(N, 0);
6131 }
6132
6133 // Look through bitcasts that retain the number of vector elements.
6134 SDValue Op = N->getOperand(0);
6135 if (Op.getOpcode() == ISD::BITCAST &&
6136 Op.getValueType().isVector() &&
6137 Op.getOperand(0).getValueType().isVector() &&
6138 Op.getValueType().getVectorNumElements() ==
6139 Op.getOperand(0).getValueType().getVectorNumElements())
6140 Op = Op.getOperand(0);
6141
6142 // Push BSWAP into