Bug Summary

File:include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1171, column 10
Called C++ object pointer is null

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 X86ISelLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374814/build-llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86 -I /build/llvm-toolchain-snapshot-10~svn374814/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374814/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-10/lib/clang/10.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-10~svn374814/build-llvm/lib/Target/X86 -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374814=. -ferror-limit 19 -fmessage-length 0 -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-2019-10-15-035155-28452-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp

/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp

1//===-- X86ISelLowering.cpp - X86 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 defines the interfaces that X86 uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "X86ISelLowering.h"
15#include "Utils/X86ShuffleDecode.h"
16#include "X86CallingConv.h"
17#include "X86FrameLowering.h"
18#include "X86InstrBuilder.h"
19#include "X86IntrinsicsInfo.h"
20#include "X86MachineFunctionInfo.h"
21#include "X86TargetMachine.h"
22#include "X86TargetObjectFile.h"
23#include "llvm/ADT/SmallBitVector.h"
24#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/StringExtras.h"
27#include "llvm/ADT/StringSwitch.h"
28#include "llvm/Analysis/EHPersonalities.h"
29#include "llvm/CodeGen/IntrinsicLowering.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/TargetLowering.h"
37#include "llvm/CodeGen/WinEHFuncInfo.h"
38#include "llvm/IR/CallSite.h"
39#include "llvm/IR/CallingConv.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DerivedTypes.h"
42#include "llvm/IR/DiagnosticInfo.h"
43#include "llvm/IR/Function.h"
44#include "llvm/IR/GlobalAlias.h"
45#include "llvm/IR/GlobalVariable.h"
46#include "llvm/IR/Instructions.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/MC/MCAsmInfo.h"
49#include "llvm/MC/MCContext.h"
50#include "llvm/MC/MCExpr.h"
51#include "llvm/MC/MCSymbol.h"
52#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Debug.h"
54#include "llvm/Support/ErrorHandling.h"
55#include "llvm/Support/KnownBits.h"
56#include "llvm/Support/MathExtras.h"
57#include "llvm/Target/TargetOptions.h"
58#include <algorithm>
59#include <bitset>
60#include <cctype>
61#include <numeric>
62using namespace llvm;
63
64#define DEBUG_TYPE"x86-isel" "x86-isel"
65
66STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"x86-isel", "NumTailCalls"
, "Number of tail calls"}
;
67
68static cl::opt<int> ExperimentalPrefLoopAlignment(
69 "x86-experimental-pref-loop-alignment", cl::init(4),
70 cl::desc(
71 "Sets the preferable loop alignment for experiments (as log2 bytes)"
72 "(the last x86-experimental-pref-loop-alignment bits"
73 " of the loop header PC will be 0)."),
74 cl::Hidden);
75
76// Added in 10.0.
77static cl::opt<bool> EnableOldKNLABI(
78 "x86-enable-old-knl-abi", cl::init(false),
79 cl::desc("Enables passing v32i16 and v64i8 in 2 YMM registers instead of "
80 "one ZMM register on AVX512F, but not AVX512BW targets."),
81 cl::Hidden);
82
83static cl::opt<bool> MulConstantOptimization(
84 "mul-constant-optimization", cl::init(true),
85 cl::desc("Replace 'mul x, Const' with more effective instructions like "
86 "SHIFT, LEA, etc."),
87 cl::Hidden);
88
89static cl::opt<bool> ExperimentalUnorderedISEL(
90 "x86-experimental-unordered-atomic-isel", cl::init(false),
91 cl::desc("Use LoadSDNode and StoreSDNode instead of "
92 "AtomicSDNode for unordered atomic loads and "
93 "stores respectively."),
94 cl::Hidden);
95
96/// Call this when the user attempts to do something unsupported, like
97/// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
98/// report_fatal_error, so calling code should attempt to recover without
99/// crashing.
100static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
101 const char *Msg) {
102 MachineFunction &MF = DAG.getMachineFunction();
103 DAG.getContext()->diagnose(
104 DiagnosticInfoUnsupported(MF.getFunction(), Msg, dl.getDebugLoc()));
105}
106
107X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
108 const X86Subtarget &STI)
109 : TargetLowering(TM), Subtarget(STI) {
110 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
111 X86ScalarSSEf64 = Subtarget.hasSSE2();
112 X86ScalarSSEf32 = Subtarget.hasSSE1();
113 MVT PtrVT = MVT::getIntegerVT(TM.getPointerSizeInBits(0));
114
115 // Set up the TargetLowering object.
116
117 // X86 is weird. It always uses i8 for shift amounts and setcc results.
118 setBooleanContents(ZeroOrOneBooleanContent);
119 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
120 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
121
122 // For 64-bit, since we have so many registers, use the ILP scheduler.
123 // For 32-bit, use the register pressure specific scheduling.
124 // For Atom, always use ILP scheduling.
125 if (Subtarget.isAtom())
126 setSchedulingPreference(Sched::ILP);
127 else if (Subtarget.is64Bit())
128 setSchedulingPreference(Sched::ILP);
129 else
130 setSchedulingPreference(Sched::RegPressure);
131 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
132 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
133
134 // Bypass expensive divides and use cheaper ones.
135 if (TM.getOptLevel() >= CodeGenOpt::Default) {
136 if (Subtarget.hasSlowDivide32())
137 addBypassSlowDiv(32, 8);
138 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
139 addBypassSlowDiv(64, 32);
140 }
141
142 if (Subtarget.isTargetWindowsMSVC() ||
143 Subtarget.isTargetWindowsItanium()) {
144 // Setup Windows compiler runtime calls.
145 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
146 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
147 setLibcallName(RTLIB::SREM_I64, "_allrem");
148 setLibcallName(RTLIB::UREM_I64, "_aullrem");
149 setLibcallName(RTLIB::MUL_I64, "_allmul");
150 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
151 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
152 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
153 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
154 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
155 }
156
157 if (Subtarget.isTargetDarwin()) {
158 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
159 setUseUnderscoreSetJmp(false);
160 setUseUnderscoreLongJmp(false);
161 } else if (Subtarget.isTargetWindowsGNU()) {
162 // MS runtime is weird: it exports _setjmp, but longjmp!
163 setUseUnderscoreSetJmp(true);
164 setUseUnderscoreLongJmp(false);
165 } else {
166 setUseUnderscoreSetJmp(true);
167 setUseUnderscoreLongJmp(true);
168 }
169
170 // If we don't have cmpxchg8b(meaing this is a 386/486), limit atomic size to
171 // 32 bits so the AtomicExpandPass will expand it so we don't need cmpxchg8b.
172 // FIXME: Should we be limitting the atomic size on other configs? Default is
173 // 1024.
174 if (!Subtarget.hasCmpxchg8b())
175 setMaxAtomicSizeInBitsSupported(32);
176
177 // Set up the register classes.
178 addRegisterClass(MVT::i8, &X86::GR8RegClass);
179 addRegisterClass(MVT::i16, &X86::GR16RegClass);
180 addRegisterClass(MVT::i32, &X86::GR32RegClass);
181 if (Subtarget.is64Bit())
182 addRegisterClass(MVT::i64, &X86::GR64RegClass);
183
184 for (MVT VT : MVT::integer_valuetypes())
185 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
186
187 // We don't accept any truncstore of integer registers.
188 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
189 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
190 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
191 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
192 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
193 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
194
195 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
196
197 // SETOEQ and SETUNE require checking two conditions.
198 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
199 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
200 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
201 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
202 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
203 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
204
205 // Integer absolute.
206 if (Subtarget.hasCMov()) {
207 setOperationAction(ISD::ABS , MVT::i16 , Custom);
208 setOperationAction(ISD::ABS , MVT::i32 , Custom);
209 }
210 setOperationAction(ISD::ABS , MVT::i64 , Custom);
211
212 // Funnel shifts.
213 for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
214 setOperationAction(ShiftOp , MVT::i16 , Custom);
215 setOperationAction(ShiftOp , MVT::i32 , Custom);
216 if (Subtarget.is64Bit())
217 setOperationAction(ShiftOp , MVT::i64 , Custom);
218 }
219
220 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
221 // operation.
222 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
223 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
224 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
225
226 if (!Subtarget.useSoftFloat()) {
227 // We have an algorithm for SSE2->double, and we turn this into a
228 // 64-bit FILD followed by conditional FADD for other targets.
229 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
230 // We have an algorithm for SSE2, and we turn this into a 64-bit
231 // FILD or VCVTUSI2SS/SD for other targets.
232 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
233 } else {
234 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
235 }
236
237 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
238 // this operation.
239 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
240 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
241
242 if (!Subtarget.useSoftFloat()) {
243 // SSE has no i16 to fp conversion, only i32.
244 if (X86ScalarSSEf32) {
245 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
246 // f32 and f64 cases are Legal, f80 case is not
247 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
248 } else {
249 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
250 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
251 }
252 } else {
253 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
254 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Expand);
255 }
256
257 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
258 // this operation.
259 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
260 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
261
262 if (!Subtarget.useSoftFloat()) {
263 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
264 // are Legal, f80 is custom lowered.
265 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
266 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
267
268 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
269 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
270 } else {
271 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
272 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Expand);
273 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Expand);
274 }
275
276 // Handle FP_TO_UINT by promoting the destination to a larger signed
277 // conversion.
278 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
279 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
280 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
281
282 if (!Subtarget.useSoftFloat()) {
283 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
284 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
285 }
286
287 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
288 if (!X86ScalarSSEf64) {
289 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
290 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
291 if (Subtarget.is64Bit()) {
292 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
293 // Without SSE, i64->f64 goes through memory.
294 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
295 }
296 } else if (!Subtarget.is64Bit())
297 setOperationAction(ISD::BITCAST , MVT::i64 , Custom);
298
299 // Scalar integer divide and remainder are lowered to use operations that
300 // produce two results, to match the available instructions. This exposes
301 // the two-result form to trivial CSE, which is able to combine x/y and x%y
302 // into a single instruction.
303 //
304 // Scalar integer multiply-high is also lowered to use two-result
305 // operations, to match the available instructions. However, plain multiply
306 // (low) operations are left as Legal, as there are single-result
307 // instructions for this in x86. Using the two-result multiply instructions
308 // when both high and low results are needed must be arranged by dagcombine.
309 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
310 setOperationAction(ISD::MULHS, VT, Expand);
311 setOperationAction(ISD::MULHU, VT, Expand);
312 setOperationAction(ISD::SDIV, VT, Expand);
313 setOperationAction(ISD::UDIV, VT, Expand);
314 setOperationAction(ISD::SREM, VT, Expand);
315 setOperationAction(ISD::UREM, VT, Expand);
316 }
317
318 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
319 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
320 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
321 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
322 setOperationAction(ISD::BR_CC, VT, Expand);
323 setOperationAction(ISD::SELECT_CC, VT, Expand);
324 }
325 if (Subtarget.is64Bit())
326 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
327 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
328 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
329 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
330
331 setOperationAction(ISD::FREM , MVT::f32 , Expand);
332 setOperationAction(ISD::FREM , MVT::f64 , Expand);
333 setOperationAction(ISD::FREM , MVT::f80 , Expand);
334 setOperationAction(ISD::FREM , MVT::f128 , Expand);
335 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
336
337 // Promote the i8 variants and force them on up to i32 which has a shorter
338 // encoding.
339 setOperationPromotedToType(ISD::CTTZ , MVT::i8 , MVT::i32);
340 setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
341 if (!Subtarget.hasBMI()) {
342 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
343 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
344 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Legal);
345 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Legal);
346 if (Subtarget.is64Bit()) {
347 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
348 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
349 }
350 }
351
352 if (Subtarget.hasLZCNT()) {
353 // When promoting the i8 variants, force them to i32 for a shorter
354 // encoding.
355 setOperationPromotedToType(ISD::CTLZ , MVT::i8 , MVT::i32);
356 setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
357 } else {
358 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
359 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
360 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
362 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
363 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
364 if (Subtarget.is64Bit()) {
365 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
366 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
367 }
368 }
369
370 // Special handling for half-precision floating point conversions.
371 // If we don't have F16C support, then lower half float conversions
372 // into library calls.
373 if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
374 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
375 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
376 }
377
378 // There's never any support for operations beyond MVT::f32.
379 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
380 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
381 setOperationAction(ISD::FP16_TO_FP, MVT::f128, Expand);
382 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
383 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
384 setOperationAction(ISD::FP_TO_FP16, MVT::f128, Expand);
385
386 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
387 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
388 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
389 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f16, Expand);
390 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
391 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
392 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
393 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
394
395 if (Subtarget.hasPOPCNT()) {
396 setOperationPromotedToType(ISD::CTPOP, MVT::i8, MVT::i32);
397 } else {
398 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
399 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
400 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
401 if (Subtarget.is64Bit())
402 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
403 else
404 setOperationAction(ISD::CTPOP , MVT::i64 , Custom);
405 }
406
407 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
408
409 if (!Subtarget.hasMOVBE())
410 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
411
412 // These should be promoted to a larger select which is supported.
413 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
414 // X86 wants to expand cmov itself.
415 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
416 setOperationAction(ISD::SELECT, VT, Custom);
417 setOperationAction(ISD::SETCC, VT, Custom);
418 }
419 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
420 if (VT == MVT::i64 && !Subtarget.is64Bit())
421 continue;
422 setOperationAction(ISD::SELECT, VT, Custom);
423 setOperationAction(ISD::SETCC, VT, Custom);
424 }
425
426 // Custom action for SELECT MMX and expand action for SELECT_CC MMX
427 setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
428 setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
429
430 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
431 // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
432 // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
433 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
434 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
435 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
436 if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
437 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
438
439 // Darwin ABI issue.
440 for (auto VT : { MVT::i32, MVT::i64 }) {
441 if (VT == MVT::i64 && !Subtarget.is64Bit())
442 continue;
443 setOperationAction(ISD::ConstantPool , VT, Custom);
444 setOperationAction(ISD::JumpTable , VT, Custom);
445 setOperationAction(ISD::GlobalAddress , VT, Custom);
446 setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
447 setOperationAction(ISD::ExternalSymbol , VT, Custom);
448 setOperationAction(ISD::BlockAddress , VT, Custom);
449 }
450
451 // 64-bit shl, sra, srl (iff 32-bit x86)
452 for (auto VT : { MVT::i32, MVT::i64 }) {
453 if (VT == MVT::i64 && !Subtarget.is64Bit())
454 continue;
455 setOperationAction(ISD::SHL_PARTS, VT, Custom);
456 setOperationAction(ISD::SRA_PARTS, VT, Custom);
457 setOperationAction(ISD::SRL_PARTS, VT, Custom);
458 }
459
460 if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
461 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
462
463 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
464
465 // Expand certain atomics
466 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
467 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
468 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
469 setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
470 setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
471 setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
472 setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
473 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
474 }
475
476 if (!Subtarget.is64Bit())
477 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
478
479 if (Subtarget.hasCmpxchg16b()) {
480 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
481 }
482
483 // FIXME - use subtarget debug flags
484 if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
485 !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
486 TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
487 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
488 }
489
490 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
491 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
492
493 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
494 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
495
496 setOperationAction(ISD::TRAP, MVT::Other, Legal);
497 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
498
499 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
500 setOperationAction(ISD::VASTART , MVT::Other, Custom);
501 setOperationAction(ISD::VAEND , MVT::Other, Expand);
502 bool Is64Bit = Subtarget.is64Bit();
503 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
504 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
505
506 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
507 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
508
509 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
510
511 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
512 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
513 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
514
515 if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
516 // f32 and f64 use SSE.
517 // Set up the FP register classes.
518 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
519 : &X86::FR32RegClass);
520 addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
521 : &X86::FR64RegClass);
522
523 // Disable f32->f64 extload as we can only generate this in one instruction
524 // under optsize. So its easier to pattern match (fpext (load)) for that
525 // case instead of needing to emit 2 instructions for extload in the
526 // non-optsize case.
527 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
528
529 for (auto VT : { MVT::f32, MVT::f64 }) {
530 // Use ANDPD to simulate FABS.
531 setOperationAction(ISD::FABS, VT, Custom);
532
533 // Use XORP to simulate FNEG.
534 setOperationAction(ISD::FNEG, VT, Custom);
535
536 // Use ANDPD and ORPD to simulate FCOPYSIGN.
537 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
538
539 // These might be better off as horizontal vector ops.
540 setOperationAction(ISD::FADD, VT, Custom);
541 setOperationAction(ISD::FSUB, VT, Custom);
542
543 // We don't support sin/cos/fmod
544 setOperationAction(ISD::FSIN , VT, Expand);
545 setOperationAction(ISD::FCOS , VT, Expand);
546 setOperationAction(ISD::FSINCOS, VT, Expand);
547 }
548
549 // Lower this to MOVMSK plus an AND.
550 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
551 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
552
553 } else if (!useSoftFloat() && X86ScalarSSEf32 && (UseX87 || Is64Bit)) {
554 // Use SSE for f32, x87 for f64.
555 // Set up the FP register classes.
556 addRegisterClass(MVT::f32, &X86::FR32RegClass);
557 if (UseX87)
558 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
559
560 // Use ANDPS to simulate FABS.
561 setOperationAction(ISD::FABS , MVT::f32, Custom);
562
563 // Use XORP to simulate FNEG.
564 setOperationAction(ISD::FNEG , MVT::f32, Custom);
565
566 if (UseX87)
567 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
568
569 // Use ANDPS and ORPS to simulate FCOPYSIGN.
570 if (UseX87)
571 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
572 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
573
574 // We don't support sin/cos/fmod
575 setOperationAction(ISD::FSIN , MVT::f32, Expand);
576 setOperationAction(ISD::FCOS , MVT::f32, Expand);
577 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
578
579 if (UseX87) {
580 // Always expand sin/cos functions even though x87 has an instruction.
581 setOperationAction(ISD::FSIN, MVT::f64, Expand);
582 setOperationAction(ISD::FCOS, MVT::f64, Expand);
583 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
584 }
585 } else if (UseX87) {
586 // f32 and f64 in x87.
587 // Set up the FP register classes.
588 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
589 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
590
591 for (auto VT : { MVT::f32, MVT::f64 }) {
592 setOperationAction(ISD::UNDEF, VT, Expand);
593 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
594
595 // Always expand sin/cos functions even though x87 has an instruction.
596 setOperationAction(ISD::FSIN , VT, Expand);
597 setOperationAction(ISD::FCOS , VT, Expand);
598 setOperationAction(ISD::FSINCOS, VT, Expand);
599 }
600 }
601
602 // Expand FP32 immediates into loads from the stack, save special cases.
603 if (isTypeLegal(MVT::f32)) {
604 if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
605 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
606 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
607 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
608 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
609 } else // SSE immediates.
610 addLegalFPImmediate(APFloat(+0.0f)); // xorps
611 }
612 // Expand FP64 immediates into loads from the stack, save special cases.
613 if (isTypeLegal(MVT::f64)) {
614 if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
615 addLegalFPImmediate(APFloat(+0.0)); // FLD0
616 addLegalFPImmediate(APFloat(+1.0)); // FLD1
617 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
618 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
619 } else // SSE immediates.
620 addLegalFPImmediate(APFloat(+0.0)); // xorpd
621 }
622
623 // We don't support FMA.
624 setOperationAction(ISD::FMA, MVT::f64, Expand);
625 setOperationAction(ISD::FMA, MVT::f32, Expand);
626
627 // f80 always uses X87.
628 if (UseX87) {
629 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
630 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
631 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
632 {
633 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
634 addLegalFPImmediate(TmpFlt); // FLD0
635 TmpFlt.changeSign();
636 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
637
638 bool ignored;
639 APFloat TmpFlt2(+1.0);
640 TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
641 &ignored);
642 addLegalFPImmediate(TmpFlt2); // FLD1
643 TmpFlt2.changeSign();
644 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
645 }
646
647 // Always expand sin/cos functions even though x87 has an instruction.
648 setOperationAction(ISD::FSIN , MVT::f80, Expand);
649 setOperationAction(ISD::FCOS , MVT::f80, Expand);
650 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
651
652 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
653 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
654 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
655 setOperationAction(ISD::FRINT, MVT::f80, Expand);
656 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
657 setOperationAction(ISD::FMA, MVT::f80, Expand);
658 setOperationAction(ISD::LROUND, MVT::f80, Expand);
659 setOperationAction(ISD::LLROUND, MVT::f80, Expand);
660 setOperationAction(ISD::LRINT, MVT::f80, Expand);
661 setOperationAction(ISD::LLRINT, MVT::f80, Expand);
662 }
663
664 // f128 uses xmm registers, but most operations require libcalls.
665 if (!Subtarget.useSoftFloat() && Subtarget.is64Bit() && Subtarget.hasSSE1()) {
666 addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
667 : &X86::VR128RegClass);
668
669 addLegalFPImmediate(APFloat::getZero(APFloat::IEEEquad())); // xorps
670
671 setOperationAction(ISD::FADD, MVT::f128, Custom);
672 setOperationAction(ISD::FSUB, MVT::f128, Custom);
673 setOperationAction(ISD::FDIV, MVT::f128, Custom);
674 setOperationAction(ISD::FMUL, MVT::f128, Custom);
675 setOperationAction(ISD::FMA, MVT::f128, Expand);
676
677 setOperationAction(ISD::FABS, MVT::f128, Custom);
678 setOperationAction(ISD::FNEG, MVT::f128, Custom);
679 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
680
681 setOperationAction(ISD::FSIN, MVT::f128, Expand);
682 setOperationAction(ISD::FCOS, MVT::f128, Expand);
683 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
684 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
685
686 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
687 // We need to custom handle any FP_ROUND with an f128 input, but
688 // LegalizeDAG uses the result type to know when to run a custom handler.
689 // So we have to list all legal floating point result types here.
690 if (isTypeLegal(MVT::f32)) {
691 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
692 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
693 }
694 if (isTypeLegal(MVT::f64)) {
695 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
696 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
697 }
698 if (isTypeLegal(MVT::f80)) {
699 setOperationAction(ISD::FP_ROUND, MVT::f80, Custom);
700 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f80, Custom);
701 }
702
703 setOperationAction(ISD::SETCC, MVT::f128, Custom);
704
705 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f32, Expand);
706 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
707 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f80, Expand);
708 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
709 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
710 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
711 }
712
713 // Always use a library call for pow.
714 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
715 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
716 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f128 , Expand);
718
719 setOperationAction(ISD::FLOG, MVT::f80, Expand);
720 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722 setOperationAction(ISD::FEXP, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
724 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
725 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
726
727 // Some FP actions are always expanded for vector types.
728 for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
729 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
730 setOperationAction(ISD::FSIN, VT, Expand);
731 setOperationAction(ISD::FSINCOS, VT, Expand);
732 setOperationAction(ISD::FCOS, VT, Expand);
733 setOperationAction(ISD::FREM, VT, Expand);
734 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
735 setOperationAction(ISD::FPOW, VT, Expand);
736 setOperationAction(ISD::FLOG, VT, Expand);
737 setOperationAction(ISD::FLOG2, VT, Expand);
738 setOperationAction(ISD::FLOG10, VT, Expand);
739 setOperationAction(ISD::FEXP, VT, Expand);
740 setOperationAction(ISD::FEXP2, VT, Expand);
741 }
742
743 // First set operation action for all vector types to either promote
744 // (for widening) or expand (for scalarization). Then we will selectively
745 // turn on ones that can be effectively codegen'd.
746 for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
747 setOperationAction(ISD::SDIV, VT, Expand);
748 setOperationAction(ISD::UDIV, VT, Expand);
749 setOperationAction(ISD::SREM, VT, Expand);
750 setOperationAction(ISD::UREM, VT, Expand);
751 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
752 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
753 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
754 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
755 setOperationAction(ISD::FMA, VT, Expand);
756 setOperationAction(ISD::FFLOOR, VT, Expand);
757 setOperationAction(ISD::FCEIL, VT, Expand);
758 setOperationAction(ISD::FTRUNC, VT, Expand);
759 setOperationAction(ISD::FRINT, VT, Expand);
760 setOperationAction(ISD::FNEARBYINT, VT, Expand);
761 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
762 setOperationAction(ISD::MULHS, VT, Expand);
763 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764 setOperationAction(ISD::MULHU, VT, Expand);
765 setOperationAction(ISD::SDIVREM, VT, Expand);
766 setOperationAction(ISD::UDIVREM, VT, Expand);
767 setOperationAction(ISD::CTPOP, VT, Expand);
768 setOperationAction(ISD::CTTZ, VT, Expand);
769 setOperationAction(ISD::CTLZ, VT, Expand);
770 setOperationAction(ISD::ROTL, VT, Expand);
771 setOperationAction(ISD::ROTR, VT, Expand);
772 setOperationAction(ISD::BSWAP, VT, Expand);
773 setOperationAction(ISD::SETCC, VT, Expand);
774 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
775 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
776 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
777 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
778 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
779 setOperationAction(ISD::TRUNCATE, VT, Expand);
780 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
781 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
782 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
783 setOperationAction(ISD::SELECT_CC, VT, Expand);
784 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
785 setTruncStoreAction(InnerVT, VT, Expand);
786
787 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
788 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
789
790 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
791 // types, we have to deal with them whether we ask for Expansion or not.
792 // Setting Expand causes its own optimisation problems though, so leave
793 // them legal.
794 if (VT.getVectorElementType() == MVT::i1)
795 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
796
797 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
798 // split/scalarized right now.
799 if (VT.getVectorElementType() == MVT::f16)
800 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
801 }
802 }
803
804 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
805 // with -msoft-float, disable use of MMX as well.
806 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
807 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
808 // No operations on x86mmx supported, everything uses intrinsics.
809 }
810
811 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
812 addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
813 : &X86::VR128RegClass);
814
815 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
816 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
817 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Custom);
818 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
819 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
820 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
822 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
823 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
824
825 setOperationAction(ISD::LOAD, MVT::v2f32, Custom);
826 setOperationAction(ISD::STORE, MVT::v2f32, Custom);
827
828 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v4f32, Custom);
829 }
830
831 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
832 addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
833 : &X86::VR128RegClass);
834
835 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
836 // registers cannot be used even for integer operations.
837 addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
838 : &X86::VR128RegClass);
839 addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
840 : &X86::VR128RegClass);
841 addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
842 : &X86::VR128RegClass);
843 addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
844 : &X86::VR128RegClass);
845
846 for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
847 MVT::v2i16, MVT::v4i16, MVT::v2i32 }) {
848 setOperationAction(ISD::SDIV, VT, Custom);
849 setOperationAction(ISD::SREM, VT, Custom);
850 setOperationAction(ISD::UDIV, VT, Custom);
851 setOperationAction(ISD::UREM, VT, Custom);
852 }
853
854 setOperationAction(ISD::MUL, MVT::v2i8, Custom);
855 setOperationAction(ISD::MUL, MVT::v4i8, Custom);
856 setOperationAction(ISD::MUL, MVT::v8i8, Custom);
857
858 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
859 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
860 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
861 setOperationAction(ISD::MULHU, MVT::v4i32, Custom);
862 setOperationAction(ISD::MULHS, MVT::v4i32, Custom);
863 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
864 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
865 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
866 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
867 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
868 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
869 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
870 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Custom);
871
872 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
873 setOperationAction(ISD::SMAX, VT, VT == MVT::v8i16 ? Legal : Custom);
874 setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
875 setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
876 setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
877 }
878
879 setOperationAction(ISD::UADDSAT, MVT::v16i8, Legal);
880 setOperationAction(ISD::SADDSAT, MVT::v16i8, Legal);
881 setOperationAction(ISD::USUBSAT, MVT::v16i8, Legal);
882 setOperationAction(ISD::SSUBSAT, MVT::v16i8, Legal);
883 setOperationAction(ISD::UADDSAT, MVT::v8i16, Legal);
884 setOperationAction(ISD::SADDSAT, MVT::v8i16, Legal);
885 setOperationAction(ISD::USUBSAT, MVT::v8i16, Legal);
886 setOperationAction(ISD::SSUBSAT, MVT::v8i16, Legal);
887 setOperationAction(ISD::UADDSAT, MVT::v4i32, Custom);
888 setOperationAction(ISD::USUBSAT, MVT::v4i32, Custom);
889 setOperationAction(ISD::UADDSAT, MVT::v2i64, Custom);
890 setOperationAction(ISD::USUBSAT, MVT::v2i64, Custom);
891
892 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
893 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
894 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
895
896 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
897 setOperationAction(ISD::SETCC, VT, Custom);
898 setOperationAction(ISD::CTPOP, VT, Custom);
899 setOperationAction(ISD::ABS, VT, Custom);
900
901 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
902 // setcc all the way to isel and prefer SETGT in some isel patterns.
903 setCondCodeAction(ISD::SETLT, VT, Custom);
904 setCondCodeAction(ISD::SETLE, VT, Custom);
905 }
906
907 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
908 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
909 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
910 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
911 setOperationAction(ISD::VSELECT, VT, Custom);
912 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
913 }
914
915 for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
916 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
917 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
918 setOperationAction(ISD::VSELECT, VT, Custom);
919
920 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
921 continue;
922
923 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
924 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
925 }
926
927 // Custom lower v2i64 and v2f64 selects.
928 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
929 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
930 setOperationAction(ISD::SELECT, MVT::v4i32, Custom);
931 setOperationAction(ISD::SELECT, MVT::v8i16, Custom);
932 setOperationAction(ISD::SELECT, MVT::v16i8, Custom);
933
934 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
935 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
936
937 // Custom legalize these to avoid over promotion or custom promotion.
938 setOperationAction(ISD::FP_TO_SINT, MVT::v2i8, Custom);
939 setOperationAction(ISD::FP_TO_SINT, MVT::v4i8, Custom);
940 setOperationAction(ISD::FP_TO_SINT, MVT::v8i8, Custom);
941 setOperationAction(ISD::FP_TO_SINT, MVT::v2i16, Custom);
942 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
943 setOperationAction(ISD::FP_TO_UINT, MVT::v2i8, Custom);
944 setOperationAction(ISD::FP_TO_UINT, MVT::v4i8, Custom);
945 setOperationAction(ISD::FP_TO_UINT, MVT::v8i8, Custom);
946 setOperationAction(ISD::FP_TO_UINT, MVT::v2i16, Custom);
947 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
948
949 // By marking FP_TO_SINT v8i16 as Custom, will trick type legalization into
950 // promoting v8i8 FP_TO_UINT into FP_TO_SINT. When the v8i16 FP_TO_SINT is
951 // split again based on the input type, this will cause an AssertSExt i16 to
952 // be emitted instead of an AssertZExt. This will allow packssdw followed by
953 // packuswb to be used to truncate to v8i8. This is necessary since packusdw
954 // isn't available until sse4.1.
955 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
956
957 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
958 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
959
960 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
961
962 // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
963 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
964
965 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
966 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
967
968 // We want to legalize this to an f64 load rather than an i64 load on
969 // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
970 // store.
971 setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
972 setOperationAction(ISD::LOAD, MVT::v4i16, Custom);
973 setOperationAction(ISD::LOAD, MVT::v8i8, Custom);
974 setOperationAction(ISD::STORE, MVT::v2i32, Custom);
975 setOperationAction(ISD::STORE, MVT::v4i16, Custom);
976 setOperationAction(ISD::STORE, MVT::v8i8, Custom);
977
978 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
979 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
980 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
981 if (!Subtarget.hasAVX512())
982 setOperationAction(ISD::BITCAST, MVT::v16i1, Custom);
983
984 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
985 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
986 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
987
988 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
989
990 setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
991 setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
992 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Custom);
993 setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
994 setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
995 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
996
997 // In the customized shift lowering, the legal v4i32/v2i64 cases
998 // in AVX2 will be recognized.
999 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1000 setOperationAction(ISD::SRL, VT, Custom);
1001 setOperationAction(ISD::SHL, VT, Custom);
1002 setOperationAction(ISD::SRA, VT, Custom);
1003 }
1004
1005 setOperationAction(ISD::ROTL, MVT::v4i32, Custom);
1006 setOperationAction(ISD::ROTL, MVT::v8i16, Custom);
1007
1008 // With AVX512, expanding (and promoting the shifts) is better.
1009 if (!Subtarget.hasAVX512())
1010 setOperationAction(ISD::ROTL, MVT::v16i8, Custom);
1011 }
1012
1013 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1014 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
1015 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
1016 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
1017 setOperationAction(ISD::BITREVERSE, MVT::v16i8, Custom);
1018 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
1019 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
1020 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
1021 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
1022
1023 // These might be better off as horizontal vector ops.
1024 setOperationAction(ISD::ADD, MVT::i16, Custom);
1025 setOperationAction(ISD::ADD, MVT::i32, Custom);
1026 setOperationAction(ISD::SUB, MVT::i16, Custom);
1027 setOperationAction(ISD::SUB, MVT::i32, Custom);
1028 }
1029
1030 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1031 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1032 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
1033 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1034 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
1035 setOperationAction(ISD::FRINT, RoundedTy, Legal);
1036 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
1037 }
1038
1039 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
1040 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
1041 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
1042 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
1043 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
1044 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
1045 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
1046 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
1047
1048 // FIXME: Do we need to handle scalar-to-vector here?
1049 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1050
1051 // We directly match byte blends in the backend as they match the VSELECT
1052 // condition form.
1053 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1054
1055 // SSE41 brings specific instructions for doing vector sign extend even in
1056 // cases where we don't have SRA.
1057 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1058 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
1059 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
1060 }
1061
1062 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1063 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1064 setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8, Legal);
1065 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8, Legal);
1066 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8, Legal);
1067 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
1068 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
1069 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
1070 }
1071
1072 // i8 vectors are custom because the source register and source
1073 // source memory operand types are not the same width.
1074 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1075 }
1076
1077 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1078 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1079 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1080 setOperationAction(ISD::ROTL, VT, Custom);
1081
1082 // XOP can efficiently perform BITREVERSE with VPPERM.
1083 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1084 setOperationAction(ISD::BITREVERSE, VT, Custom);
1085
1086 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1087 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
1088 setOperationAction(ISD::BITREVERSE, VT, Custom);
1089 }
1090
1091 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1092 bool HasInt256 = Subtarget.hasInt256();
1093
1094 addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1095 : &X86::VR256RegClass);
1096 addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1097 : &X86::VR256RegClass);
1098 addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1099 : &X86::VR256RegClass);
1100 addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1101 : &X86::VR256RegClass);
1102 addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1103 : &X86::VR256RegClass);
1104 addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1105 : &X86::VR256RegClass);
1106
1107 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1108 setOperationAction(ISD::FFLOOR, VT, Legal);
1109 setOperationAction(ISD::FCEIL, VT, Legal);
1110 setOperationAction(ISD::FTRUNC, VT, Legal);
1111 setOperationAction(ISD::FRINT, VT, Legal);
1112 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1113 setOperationAction(ISD::FNEG, VT, Custom);
1114 setOperationAction(ISD::FABS, VT, Custom);
1115 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1116 }
1117
1118 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1119 // even though v8i16 is a legal type.
1120 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i16, MVT::v8i32);
1121 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i16, MVT::v8i32);
1122 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1123
1124 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1125
1126 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v8f32, Custom);
1127
1128 if (!Subtarget.hasAVX512())
1129 setOperationAction(ISD::BITCAST, MVT::v32i1, Custom);
1130
1131 // In the customized shift lowering, the legal v8i32/v4i64 cases
1132 // in AVX2 will be recognized.
1133 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1134 setOperationAction(ISD::SRL, VT, Custom);
1135 setOperationAction(ISD::SHL, VT, Custom);
1136 setOperationAction(ISD::SRA, VT, Custom);
1137 }
1138
1139 // These types need custom splitting if their input is a 128-bit vector.
1140 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1141 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1142 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1143 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1144
1145 setOperationAction(ISD::ROTL, MVT::v8i32, Custom);
1146 setOperationAction(ISD::ROTL, MVT::v16i16, Custom);
1147
1148 // With BWI, expanding (and promoting the shifts) is the better.
1149 if (!Subtarget.hasBWI())
1150 setOperationAction(ISD::ROTL, MVT::v32i8, Custom);
1151
1152 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1153 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1154 setOperationAction(ISD::SELECT, MVT::v8i32, Custom);
1155 setOperationAction(ISD::SELECT, MVT::v16i16, Custom);
1156 setOperationAction(ISD::SELECT, MVT::v32i8, Custom);
1157 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1158
1159 for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1160 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1161 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1162 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1163 }
1164
1165 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1166 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1167 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1168 setOperationAction(ISD::BITREVERSE, MVT::v32i8, Custom);
1169
1170 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1171 setOperationAction(ISD::SETCC, VT, Custom);
1172 setOperationAction(ISD::CTPOP, VT, Custom);
1173 setOperationAction(ISD::CTLZ, VT, Custom);
1174
1175 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1176 // setcc all the way to isel and prefer SETGT in some isel patterns.
1177 setCondCodeAction(ISD::SETLT, VT, Custom);
1178 setCondCodeAction(ISD::SETLE, VT, Custom);
1179 }
1180
1181 if (Subtarget.hasAnyFMA()) {
1182 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1183 MVT::v2f64, MVT::v4f64 })
1184 setOperationAction(ISD::FMA, VT, Legal);
1185 }
1186
1187 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1188 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1189 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1190 }
1191
1192 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1193 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1194 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1195 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1196
1197 setOperationAction(ISD::MULHU, MVT::v8i32, Custom);
1198 setOperationAction(ISD::MULHS, MVT::v8i32, Custom);
1199 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1200 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1201 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1202 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1203
1204 setOperationAction(ISD::ABS, MVT::v4i64, Custom);
1205 setOperationAction(ISD::SMAX, MVT::v4i64, Custom);
1206 setOperationAction(ISD::UMAX, MVT::v4i64, Custom);
1207 setOperationAction(ISD::SMIN, MVT::v4i64, Custom);
1208 setOperationAction(ISD::UMIN, MVT::v4i64, Custom);
1209
1210 setOperationAction(ISD::UADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1211 setOperationAction(ISD::SADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1212 setOperationAction(ISD::USUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1213 setOperationAction(ISD::SSUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1214 setOperationAction(ISD::UADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1215 setOperationAction(ISD::SADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1216 setOperationAction(ISD::USUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1217 setOperationAction(ISD::SSUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1218
1219 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1220 setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1221 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1222 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1223 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1224 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1225 }
1226
1227 for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1228 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1229 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1230 }
1231
1232 if (HasInt256) {
1233 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1234 // when we have a 256bit-wide blend with immediate.
1235 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1236
1237 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1238 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1239 setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1240 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i8, Legal);
1241 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i8, Legal);
1242 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i16, Legal);
1243 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i16, Legal);
1244 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i32, Legal);
1245 }
1246 }
1247
1248 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1249 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1250 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1251 setOperationAction(ISD::MSTORE, VT, Legal);
1252 }
1253
1254 // Extract subvector is special because the value type
1255 // (result) is 128-bit but the source is 256-bit wide.
1256 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1257 MVT::v4f32, MVT::v2f64 }) {
1258 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1259 }
1260
1261 // Custom lower several nodes for 256-bit types.
1262 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1263 MVT::v8f32, MVT::v4f64 }) {
1264 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1265 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1266 setOperationAction(ISD::VSELECT, VT, Custom);
1267 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1268 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1269 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1270 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1271 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1272 setOperationAction(ISD::STORE, VT, Custom);
1273 }
1274
1275 if (HasInt256) {
1276 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1277
1278 // Custom legalize 2x32 to get a little better code.
1279 setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1280 setOperationAction(ISD::MGATHER, MVT::v2i32, Custom);
1281
1282 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1283 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1284 setOperationAction(ISD::MGATHER, VT, Custom);
1285 }
1286 }
1287
1288 // This block controls legalization of the mask vector sizes that are
1289 // available with AVX512. 512-bit vectors are in a separate block controlled
1290 // by useAVX512Regs.
1291 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1292 addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1293 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1294 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1295 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1296 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1297
1298 setOperationAction(ISD::SELECT, MVT::v1i1, Custom);
1299 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1300 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i1, Custom);
1301
1302 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v8i1, MVT::v8i32);
1303 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v8i1, MVT::v8i32);
1304 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v4i1, MVT::v4i32);
1305 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v4i1, MVT::v4i32);
1306 setOperationAction(ISD::FP_TO_SINT, MVT::v2i1, Custom);
1307 setOperationAction(ISD::FP_TO_UINT, MVT::v2i1, Custom);
1308
1309 // There is no byte sized k-register load or store without AVX512DQ.
1310 if (!Subtarget.hasDQI()) {
1311 setOperationAction(ISD::LOAD, MVT::v1i1, Custom);
1312 setOperationAction(ISD::LOAD, MVT::v2i1, Custom);
1313 setOperationAction(ISD::LOAD, MVT::v4i1, Custom);
1314 setOperationAction(ISD::LOAD, MVT::v8i1, Custom);
1315
1316 setOperationAction(ISD::STORE, MVT::v1i1, Custom);
1317 setOperationAction(ISD::STORE, MVT::v2i1, Custom);
1318 setOperationAction(ISD::STORE, MVT::v4i1, Custom);
1319 setOperationAction(ISD::STORE, MVT::v8i1, Custom);
1320 }
1321
1322 // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1323 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1324 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1325 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1326 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1327 }
1328
1329 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1330 setOperationAction(ISD::ADD, VT, Custom);
1331 setOperationAction(ISD::SUB, VT, Custom);
1332 setOperationAction(ISD::MUL, VT, Custom);
1333 setOperationAction(ISD::SETCC, VT, Custom);
1334 setOperationAction(ISD::SELECT, VT, Custom);
1335 setOperationAction(ISD::TRUNCATE, VT, Custom);
1336 setOperationAction(ISD::UADDSAT, VT, Custom);
1337 setOperationAction(ISD::SADDSAT, VT, Custom);
1338 setOperationAction(ISD::USUBSAT, VT, Custom);
1339 setOperationAction(ISD::SSUBSAT, VT, Custom);
1340
1341 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1342 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1343 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1344 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1345 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1346 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1347 setOperationAction(ISD::VSELECT, VT, Expand);
1348 }
1349
1350 for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1351 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1352 }
1353
1354 // This block controls legalization for 512-bit operations with 32/64 bit
1355 // elements. 512-bits can be disabled based on prefer-vector-width and
1356 // required-vector-width function attributes.
1357 if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1358 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1359 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1360 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1361 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1362
1363 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1364 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1365 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1366 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1367 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1368 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1369 }
1370
1371 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1372 setOperationAction(ISD::FNEG, VT, Custom);
1373 setOperationAction(ISD::FABS, VT, Custom);
1374 setOperationAction(ISD::FMA, VT, Legal);
1375 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1376 }
1377
1378 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1379 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i16, MVT::v16i32);
1380 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i8, MVT::v16i32);
1381 setOperationPromotedToType(ISD::FP_TO_SINT, MVT::v16i1, MVT::v16i32);
1382 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1383 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i1, MVT::v16i32);
1384 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i8, MVT::v16i32);
1385 setOperationPromotedToType(ISD::FP_TO_UINT, MVT::v16i16, MVT::v16i32);
1386 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1387 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1388
1389 setOperationAction(ISD::STRICT_FP_ROUND, MVT::v16f32, Custom);
1390
1391 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1392 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1393 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1394 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1395 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1396
1397 // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1398 // to 512-bit rather than use the AVX2 instructions so that we can use
1399 // k-masks.
1400 if (!Subtarget.hasVLX()) {
1401 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1402 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1403 setOperationAction(ISD::MLOAD, VT, Custom);
1404 setOperationAction(ISD::MSTORE, VT, Custom);
1405 }
1406 }
1407
1408 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1409 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1410 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1411 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1412 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1413 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1414 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1415 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1416
1417 // Need to custom widen this if we don't have AVX512BW.
1418 setOperationAction(ISD::ANY_EXTEND, MVT::v8i8, Custom);
1419 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i8, Custom);
1420 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i8, Custom);
1421
1422 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1423 setOperationAction(ISD::FFLOOR, VT, Legal);
1424 setOperationAction(ISD::FCEIL, VT, Legal);
1425 setOperationAction(ISD::FTRUNC, VT, Legal);
1426 setOperationAction(ISD::FRINT, VT, Legal);
1427 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1428
1429 setOperationAction(ISD::SELECT, VT, Custom);
1430 }
1431
1432 // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1433 for (auto VT : {MVT::v16i32, MVT::v8i64, MVT::v64i8}) {
1434 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Custom);
1435 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Custom);
1436 }
1437
1438 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1439 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1440 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1441 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1442
1443 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1444 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1445
1446 setOperationAction(ISD::MULHU, MVT::v16i32, Custom);
1447 setOperationAction(ISD::MULHS, MVT::v16i32, Custom);
1448
1449 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1450 setOperationAction(ISD::SMAX, VT, Legal);
1451 setOperationAction(ISD::UMAX, VT, Legal);
1452 setOperationAction(ISD::SMIN, VT, Legal);
1453 setOperationAction(ISD::UMIN, VT, Legal);
1454 setOperationAction(ISD::ABS, VT, Legal);
1455 setOperationAction(ISD::SRL, VT, Custom);
1456 setOperationAction(ISD::SHL, VT, Custom);
1457 setOperationAction(ISD::SRA, VT, Custom);
1458 setOperationAction(ISD::CTPOP, VT, Custom);
1459 setOperationAction(ISD::ROTL, VT, Custom);
1460 setOperationAction(ISD::ROTR, VT, Custom);
1461 setOperationAction(ISD::SETCC, VT, Custom);
1462 setOperationAction(ISD::SELECT, VT, Custom);
1463
1464 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1465 // setcc all the way to isel and prefer SETGT in some isel patterns.
1466 setCondCodeAction(ISD::SETLT, VT, Custom);
1467 setCondCodeAction(ISD::SETLE, VT, Custom);
1468 }
1469
1470 if (Subtarget.hasDQI()) {
1471 setOperationAction(ISD::SINT_TO_FP, MVT::v8i64, Legal);
1472 setOperationAction(ISD::UINT_TO_FP, MVT::v8i64, Legal);
1473 setOperationAction(ISD::FP_TO_SINT, MVT::v8i64, Legal);
1474 setOperationAction(ISD::FP_TO_UINT, MVT::v8i64, Legal);
1475
1476 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1477 }
1478
1479 if (Subtarget.hasCDI()) {
1480 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1481 for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1482 setOperationAction(ISD::CTLZ, VT, Legal);
1483 }
1484 } // Subtarget.hasCDI()
1485
1486 if (Subtarget.hasVPOPCNTDQ()) {
1487 for (auto VT : { MVT::v16i32, MVT::v8i64 })
1488 setOperationAction(ISD::CTPOP, VT, Legal);
1489 }
1490
1491 // Extract subvector is special because the value type
1492 // (result) is 256-bit but the source is 512-bit wide.
1493 // 128-bit was made Legal under AVX1.
1494 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1495 MVT::v8f32, MVT::v4f64 })
1496 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1497
1498 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1499 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1500 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1501 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1502 setOperationAction(ISD::VSELECT, VT, Custom);
1503 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1504 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1505 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1506 setOperationAction(ISD::MLOAD, VT, Legal);
1507 setOperationAction(ISD::MSTORE, VT, Legal);
1508 setOperationAction(ISD::MGATHER, VT, Custom);
1509 setOperationAction(ISD::MSCATTER, VT, Custom);
1510 }
1511 if (!Subtarget.hasBWI()) {
1512 // Need to custom split v32i16/v64i8 bitcasts.
1513 setOperationAction(ISD::BITCAST, MVT::v32i16, Custom);
1514 setOperationAction(ISD::BITCAST, MVT::v64i8, Custom);
1515
1516 // Better to split these into two 256-bit ops.
1517 setOperationAction(ISD::BITREVERSE, MVT::v8i64, Custom);
1518 setOperationAction(ISD::BITREVERSE, MVT::v16i32, Custom);
1519 }
1520
1521 if (Subtarget.hasVBMI2()) {
1522 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1523 setOperationAction(ISD::FSHL, VT, Custom);
1524 setOperationAction(ISD::FSHR, VT, Custom);
1525 }
1526 }
1527 }// has AVX-512
1528
1529 // This block controls legalization for operations that don't have
1530 // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1531 // narrower widths.
1532 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1533 // These operations are handled on non-VLX by artificially widening in
1534 // isel patterns.
1535 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1536
1537 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1538 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1539 setOperationAction(ISD::FP_TO_UINT, MVT::v2i32, Custom);
1540 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1541 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1542
1543 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1544 setOperationAction(ISD::SMAX, VT, Legal);
1545 setOperationAction(ISD::UMAX, VT, Legal);
1546 setOperationAction(ISD::SMIN, VT, Legal);
1547 setOperationAction(ISD::UMIN, VT, Legal);
1548 setOperationAction(ISD::ABS, VT, Legal);
1549 }
1550
1551 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1552 setOperationAction(ISD::ROTL, VT, Custom);
1553 setOperationAction(ISD::ROTR, VT, Custom);
1554 }
1555
1556 // Custom legalize 2x32 to get a little better code.
1557 setOperationAction(ISD::MSCATTER, MVT::v2f32, Custom);
1558 setOperationAction(ISD::MSCATTER, MVT::v2i32, Custom);
1559
1560 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1561 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1562 setOperationAction(ISD::MSCATTER, VT, Custom);
1563
1564 if (Subtarget.hasDQI()) {
1565 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1566 setOperationAction(ISD::SINT_TO_FP, VT, Legal);
1567 setOperationAction(ISD::UINT_TO_FP, VT, Legal);
1568 setOperationAction(ISD::FP_TO_SINT, VT, Legal);
1569 setOperationAction(ISD::FP_TO_UINT, VT, Legal);
1570
1571 setOperationAction(ISD::MUL, VT, Legal);
1572 }
1573 }
1574
1575 if (Subtarget.hasCDI()) {
1576 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1577 setOperationAction(ISD::CTLZ, VT, Legal);
1578 }
1579 } // Subtarget.hasCDI()
1580
1581 if (Subtarget.hasVPOPCNTDQ()) {
1582 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1583 setOperationAction(ISD::CTPOP, VT, Legal);
1584 }
1585 }
1586
1587 // This block control legalization of v32i1/v64i1 which are available with
1588 // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1589 // useBWIRegs.
1590 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1591 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1592 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1593
1594 for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1595 setOperationAction(ISD::ADD, VT, Custom);
1596 setOperationAction(ISD::SUB, VT, Custom);
1597 setOperationAction(ISD::MUL, VT, Custom);
1598 setOperationAction(ISD::VSELECT, VT, Expand);
1599 setOperationAction(ISD::UADDSAT, VT, Custom);
1600 setOperationAction(ISD::SADDSAT, VT, Custom);
1601 setOperationAction(ISD::USUBSAT, VT, Custom);
1602 setOperationAction(ISD::SSUBSAT, VT, Custom);
1603
1604 setOperationAction(ISD::TRUNCATE, VT, Custom);
1605 setOperationAction(ISD::SETCC, VT, Custom);
1606 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1607 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1608 setOperationAction(ISD::SELECT, VT, Custom);
1609 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1610 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1611 }
1612
1613 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1614 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1615 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1616 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1617 for (auto VT : { MVT::v16i1, MVT::v32i1 })
1618 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1619
1620 // Extends from v32i1 masks to 256-bit vectors.
1621 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1622 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1623 setOperationAction(ISD::ANY_EXTEND, MVT::v32i8, Custom);
1624 }
1625
1626 // This block controls legalization for v32i16 and v64i8. 512-bits can be
1627 // disabled based on prefer-vector-width and required-vector-width function
1628 // attributes.
1629 if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1630 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1631 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1632
1633 // Extends from v64i1 masks to 512-bit vectors.
1634 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1635 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1636 setOperationAction(ISD::ANY_EXTEND, MVT::v64i8, Custom);
1637
1638 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1639 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
1640 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1641 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1642 setOperationAction(ISD::MULHS, MVT::v64i8, Custom);
1643 setOperationAction(ISD::MULHU, MVT::v64i8, Custom);
1644 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1645 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1646 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Legal);
1647 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Legal);
1648 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i16, Custom);
1651 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v64i8, Custom);
1652 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1653 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1654 setOperationAction(ISD::ANY_EXTEND, MVT::v32i16, Custom);
1655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1656 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1657 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1658 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1659 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1660 setOperationAction(ISD::BITREVERSE, MVT::v64i8, Custom);
1661
1662 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v32i16, Custom);
1663 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, MVT::v32i16, Custom);
1664
1665 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1666
1667 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1668 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1669 setOperationAction(ISD::VSELECT, VT, Custom);
1670 setOperationAction(ISD::ABS, VT, Legal);
1671 setOperationAction(ISD::SRL, VT, Custom);
1672 setOperationAction(ISD::SHL, VT, Custom);
1673 setOperationAction(ISD::SRA, VT, Custom);
1674 setOperationAction(ISD::MLOAD, VT, Legal);
1675 setOperationAction(ISD::MSTORE, VT, Legal);
1676 setOperationAction(ISD::CTPOP, VT, Custom);
1677 setOperationAction(ISD::CTLZ, VT, Custom);
1678 setOperationAction(ISD::SMAX, VT, Legal);
1679 setOperationAction(ISD::UMAX, VT, Legal);
1680 setOperationAction(ISD::SMIN, VT, Legal);
1681 setOperationAction(ISD::UMIN, VT, Legal);
1682 setOperationAction(ISD::SETCC, VT, Custom);
1683 setOperationAction(ISD::UADDSAT, VT, Legal);
1684 setOperationAction(ISD::SADDSAT, VT, Legal);
1685 setOperationAction(ISD::USUBSAT, VT, Legal);
1686 setOperationAction(ISD::SSUBSAT, VT, Legal);
1687 setOperationAction(ISD::SELECT, VT, Custom);
1688
1689 // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1690 // setcc all the way to isel and prefer SETGT in some isel patterns.
1691 setCondCodeAction(ISD::SETLT, VT, Custom);
1692 setCondCodeAction(ISD::SETLE, VT, Custom);
1693 }
1694
1695 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1696 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1697 }
1698
1699 if (Subtarget.hasBITALG()) {
1700 for (auto VT : { MVT::v64i8, MVT::v32i16 })
1701 setOperationAction(ISD::CTPOP, VT, Legal);
1702 }
1703
1704 if (Subtarget.hasVBMI2()) {
1705 setOperationAction(ISD::FSHL, MVT::v32i16, Custom);
1706 setOperationAction(ISD::FSHR, MVT::v32i16, Custom);
1707 }
1708 }
1709
1710 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1711 for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1712 setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1713 setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1714 }
1715
1716 // These operations are handled on non-VLX by artificially widening in
1717 // isel patterns.
1718 // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1719
1720 if (Subtarget.hasBITALG()) {
1721 for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1722 setOperationAction(ISD::CTPOP, VT, Legal);
1723 }
1724 }
1725
1726 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1727 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1728 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1729 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1730 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1731 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1732
1733 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1734 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1735 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1736 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1737 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1738
1739 if (Subtarget.hasDQI()) {
1740 // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1741 // v2f32 UINT_TO_FP is already custom under SSE2.
1742 setOperationAction(ISD::SINT_TO_FP, MVT::v2f32, Custom);
1743 assert(isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) &&((isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && "Unexpected operation action!"
) ? static_cast<void> (0) : __assert_fail ("isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && \"Unexpected operation action!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 1744, __PRETTY_FUNCTION__))
1744 "Unexpected operation action!")((isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && "Unexpected operation action!"
) ? static_cast<void> (0) : __assert_fail ("isOperationCustom(ISD::UINT_TO_FP, MVT::v2f32) && \"Unexpected operation action!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 1744, __PRETTY_FUNCTION__))
;
1745 // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1746 setOperationAction(ISD::FP_TO_SINT, MVT::v2f32, Custom);
1747 setOperationAction(ISD::FP_TO_UINT, MVT::v2f32, Custom);
1748 }
1749
1750 if (Subtarget.hasBWI()) {
1751 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1752 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1753 }
1754
1755 if (Subtarget.hasVBMI2()) {
1756 // TODO: Make these legal even without VLX?
1757 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64,
1758 MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1759 setOperationAction(ISD::FSHL, VT, Custom);
1760 setOperationAction(ISD::FSHR, VT, Custom);
1761 }
1762 }
1763
1764 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Custom);
1765 setOperationAction(ISD::TRUNCATE, MVT::v8i64, Custom);
1766 setOperationAction(ISD::TRUNCATE, MVT::v16i64, Custom);
1767 }
1768
1769 // We want to custom lower some of our intrinsics.
1770 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1771 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1772 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1773 if (!Subtarget.is64Bit()) {
1774 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1775 }
1776
1777 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1778 // handle type legalization for these operations here.
1779 //
1780 // FIXME: We really should do custom legalization for addition and
1781 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1782 // than generic legalization for 64-bit multiplication-with-overflow, though.
1783 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1784 if (VT == MVT::i64 && !Subtarget.is64Bit())
1785 continue;
1786 // Add/Sub/Mul with overflow operations are custom lowered.
1787 setOperationAction(ISD::SADDO, VT, Custom);
1788 setOperationAction(ISD::UADDO, VT, Custom);
1789 setOperationAction(ISD::SSUBO, VT, Custom);
1790 setOperationAction(ISD::USUBO, VT, Custom);
1791 setOperationAction(ISD::SMULO, VT, Custom);
1792 setOperationAction(ISD::UMULO, VT, Custom);
1793
1794 // Support carry in as value rather than glue.
1795 setOperationAction(ISD::ADDCARRY, VT, Custom);
1796 setOperationAction(ISD::SUBCARRY, VT, Custom);
1797 setOperationAction(ISD::SETCCCARRY, VT, Custom);
1798 }
1799
1800 if (!Subtarget.is64Bit()) {
1801 // These libcalls are not available in 32-bit.
1802 setLibcallName(RTLIB::SHL_I128, nullptr);
1803 setLibcallName(RTLIB::SRL_I128, nullptr);
1804 setLibcallName(RTLIB::SRA_I128, nullptr);
1805 setLibcallName(RTLIB::MUL_I128, nullptr);
1806 }
1807
1808 // Combine sin / cos into _sincos_stret if it is available.
1809 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1810 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1811 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1812 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1813 }
1814
1815 if (Subtarget.isTargetWin64()) {
1816 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1817 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1818 setOperationAction(ISD::SREM, MVT::i128, Custom);
1819 setOperationAction(ISD::UREM, MVT::i128, Custom);
1820 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1821 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1822 }
1823
1824 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1825 // is. We should promote the value to 64-bits to solve this.
1826 // This is what the CRT headers do - `fmodf` is an inline header
1827 // function casting to f64 and calling `fmod`.
1828 if (Subtarget.is32Bit() &&
1829 (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
1830 for (ISD::NodeType Op :
1831 {ISD::FCEIL, ISD::FCOS, ISD::FEXP, ISD::FFLOOR, ISD::FREM, ISD::FLOG,
1832 ISD::FLOG10, ISD::FPOW, ISD::FSIN})
1833 if (isOperationExpand(Op, MVT::f32))
1834 setOperationAction(Op, MVT::f32, Promote);
1835
1836 // We have target-specific dag combine patterns for the following nodes:
1837 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1838 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
1839 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1840 setTargetDAGCombine(ISD::CONCAT_VECTORS);
1841 setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
1842 setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
1843 setTargetDAGCombine(ISD::BITCAST);
1844 setTargetDAGCombine(ISD::VSELECT);
1845 setTargetDAGCombine(ISD::SELECT);
1846 setTargetDAGCombine(ISD::SHL);
1847 setTargetDAGCombine(ISD::SRA);
1848 setTargetDAGCombine(ISD::SRL);
1849 setTargetDAGCombine(ISD::OR);
1850 setTargetDAGCombine(ISD::AND);
1851 setTargetDAGCombine(ISD::ADD);
1852 setTargetDAGCombine(ISD::FADD);
1853 setTargetDAGCombine(ISD::FSUB);
1854 setTargetDAGCombine(ISD::FNEG);
1855 setTargetDAGCombine(ISD::FMA);
1856 setTargetDAGCombine(ISD::FMINNUM);
1857 setTargetDAGCombine(ISD::FMAXNUM);
1858 setTargetDAGCombine(ISD::SUB);
1859 setTargetDAGCombine(ISD::LOAD);
1860 setTargetDAGCombine(ISD::MLOAD);
1861 setTargetDAGCombine(ISD::STORE);
1862 setTargetDAGCombine(ISD::MSTORE);
1863 setTargetDAGCombine(ISD::TRUNCATE);
1864 setTargetDAGCombine(ISD::ZERO_EXTEND);
1865 setTargetDAGCombine(ISD::ANY_EXTEND);
1866 setTargetDAGCombine(ISD::SIGN_EXTEND);
1867 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1868 setTargetDAGCombine(ISD::ANY_EXTEND_VECTOR_INREG);
1869 setTargetDAGCombine(ISD::SIGN_EXTEND_VECTOR_INREG);
1870 setTargetDAGCombine(ISD::ZERO_EXTEND_VECTOR_INREG);
1871 setTargetDAGCombine(ISD::SINT_TO_FP);
1872 setTargetDAGCombine(ISD::UINT_TO_FP);
1873 setTargetDAGCombine(ISD::SETCC);
1874 setTargetDAGCombine(ISD::MUL);
1875 setTargetDAGCombine(ISD::XOR);
1876 setTargetDAGCombine(ISD::MSCATTER);
1877 setTargetDAGCombine(ISD::MGATHER);
1878
1879 computeRegisterProperties(Subtarget.getRegisterInfo());
1880
1881 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1882 MaxStoresPerMemsetOptSize = 8;
1883 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1884 MaxStoresPerMemcpyOptSize = 4;
1885 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1886 MaxStoresPerMemmoveOptSize = 4;
1887
1888 // TODO: These control memcmp expansion in CGP and could be raised higher, but
1889 // that needs to benchmarked and balanced with the potential use of vector
1890 // load/store types (PR33329, PR33914).
1891 MaxLoadsPerMemcmp = 2;
1892 MaxLoadsPerMemcmpOptSize = 2;
1893
1894 // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1895 setPrefLoopAlignment(Align(1ULL << ExperimentalPrefLoopAlignment));
1896
1897 // An out-of-order CPU can speculatively execute past a predictable branch,
1898 // but a conditional move could be stalled by an expensive earlier operation.
1899 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1900 EnableExtLdPromotion = true;
1901 setPrefFunctionAlignment(Align(16));
1902
1903 verifyIntrinsicTables();
1904}
1905
1906// This has so far only been implemented for 64-bit MachO.
1907bool X86TargetLowering::useLoadStackGuardNode() const {
1908 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1909}
1910
1911bool X86TargetLowering::useStackGuardXorFP() const {
1912 // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
1913 return Subtarget.getTargetTriple().isOSMSVCRT();
1914}
1915
1916SDValue X86TargetLowering::emitStackGuardXorFP(SelectionDAG &DAG, SDValue Val,
1917 const SDLoc &DL) const {
1918 EVT PtrTy = getPointerTy(DAG.getDataLayout());
1919 unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
1920 MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
1921 return SDValue(Node, 0);
1922}
1923
1924TargetLoweringBase::LegalizeTypeAction
1925X86TargetLowering::getPreferredVectorAction(MVT VT) const {
1926 if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1927 return TypeSplitVector;
1928
1929 if (VT.getVectorNumElements() != 1 &&
1930 VT.getVectorElementType() != MVT::i1)
1931 return TypeWidenVector;
1932
1933 return TargetLoweringBase::getPreferredVectorAction(VT);
1934}
1935
1936MVT X86TargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1937 CallingConv::ID CC,
1938 EVT VT) const {
1939 // v32i1 vectors should be promoted to v32i8 to match avx2.
1940 if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1941 return MVT::v32i8;
1942 // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
1943 if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
1944 Subtarget.hasAVX512() &&
1945 (!isPowerOf2_32(VT.getVectorNumElements()) ||
1946 (VT.getVectorNumElements() > 16 && !Subtarget.hasBWI()) ||
1947 (VT.getVectorNumElements() > 64 && Subtarget.hasBWI())))
1948 return MVT::i8;
1949 // FIXME: Should we just make these types legal and custom split operations?
1950 if ((VT == MVT::v32i16 || VT == MVT::v64i8) &&
1951 Subtarget.hasAVX512() && !Subtarget.hasBWI() && !EnableOldKNLABI)
1952 return MVT::v16i32;
1953 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1954}
1955
1956unsigned X86TargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1957 CallingConv::ID CC,
1958 EVT VT) const {
1959 // v32i1 vectors should be promoted to v32i8 to match avx2.
1960 if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1961 return 1;
1962 // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
1963 if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
1964 Subtarget.hasAVX512() &&
1965 (!isPowerOf2_32(VT.getVectorNumElements()) ||
1966 (VT.getVectorNumElements() > 16 && !Subtarget.hasBWI()) ||
1967 (VT.getVectorNumElements() > 64 && Subtarget.hasBWI())))
1968 return VT.getVectorNumElements();
1969 // FIXME: Should we just make these types legal and custom split operations?
1970 if ((VT == MVT::v32i16 || VT == MVT::v64i8) &&
1971 Subtarget.hasAVX512() && !Subtarget.hasBWI() && !EnableOldKNLABI)
1972 return 1;
1973 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1974}
1975
1976unsigned X86TargetLowering::getVectorTypeBreakdownForCallingConv(
1977 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
1978 unsigned &NumIntermediates, MVT &RegisterVT) const {
1979 // Break wide or odd vXi1 vectors into scalars to match avx2 behavior.
1980 if (VT.isVector() && VT.getVectorElementType() == MVT::i1 &&
1981 Subtarget.hasAVX512() &&
1982 (!isPowerOf2_32(VT.getVectorNumElements()) ||
1983 (VT.getVectorNumElements() > 16 && !Subtarget.hasBWI()) ||
1984 (VT.getVectorNumElements() > 64 && Subtarget.hasBWI()))) {
1985 RegisterVT = MVT::i8;
1986 IntermediateVT = MVT::i1;
1987 NumIntermediates = VT.getVectorNumElements();
1988 return NumIntermediates;
1989 }
1990
1991 return TargetLowering::getVectorTypeBreakdownForCallingConv(Context, CC, VT, IntermediateVT,
1992 NumIntermediates, RegisterVT);
1993}
1994
1995EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
1996 LLVMContext& Context,
1997 EVT VT) const {
1998 if (!VT.isVector())
1999 return MVT::i8;
2000
2001 if (Subtarget.hasAVX512()) {
2002 const unsigned NumElts = VT.getVectorNumElements();
2003
2004 // Figure out what this type will be legalized to.
2005 EVT LegalVT = VT;
2006 while (getTypeAction(Context, LegalVT) != TypeLegal)
2007 LegalVT = getTypeToTransformTo(Context, LegalVT);
2008
2009 // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
2010 if (LegalVT.getSimpleVT().is512BitVector())
2011 return EVT::getVectorVT(Context, MVT::i1, NumElts);
2012
2013 if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
2014 // If we legalized to less than a 512-bit vector, then we will use a vXi1
2015 // compare for vXi32/vXi64 for sure. If we have BWI we will also support
2016 // vXi16/vXi8.
2017 MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
2018 if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
2019 return EVT::getVectorVT(Context, MVT::i1, NumElts);
2020 }
2021 }
2022
2023 return VT.changeVectorElementTypeToInteger();
2024}
2025
2026/// Helper for getByValTypeAlignment to determine
2027/// the desired ByVal argument alignment.
2028static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
2029 if (MaxAlign == 16)
2030 return;
2031 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2032 if (VTy->getBitWidth() == 128)
2033 MaxAlign = 16;
2034 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2035 unsigned EltAlign = 0;
2036 getMaxByValAlign(ATy->getElementType(), EltAlign);
2037 if (EltAlign > MaxAlign)
2038 MaxAlign = EltAlign;
2039 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2040 for (auto *EltTy : STy->elements()) {
2041 unsigned EltAlign = 0;
2042 getMaxByValAlign(EltTy, EltAlign);
2043 if (EltAlign > MaxAlign)
2044 MaxAlign = EltAlign;
2045 if (MaxAlign == 16)
2046 break;
2047 }
2048 }
2049}
2050
2051/// Return the desired alignment for ByVal aggregate
2052/// function arguments in the caller parameter area. For X86, aggregates
2053/// that contain SSE vectors are placed at 16-byte boundaries while the rest
2054/// are at 4-byte boundaries.
2055unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
2056 const DataLayout &DL) const {
2057 if (Subtarget.is64Bit()) {
2058 // Max of 8 and alignment of type.
2059 unsigned TyAlign = DL.getABITypeAlignment(Ty);
2060 if (TyAlign > 8)
2061 return TyAlign;
2062 return 8;
2063 }
2064
2065 unsigned Align = 4;
2066 if (Subtarget.hasSSE1())
2067 getMaxByValAlign(Ty, Align);
2068 return Align;
2069}
2070
2071/// Returns the target specific optimal type for load
2072/// and store operations as a result of memset, memcpy, and memmove
2073/// lowering. If DstAlign is zero that means it's safe to destination
2074/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
2075/// means there isn't a need to check it against alignment requirement,
2076/// probably because the source does not need to be loaded. If 'IsMemset' is
2077/// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
2078/// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
2079/// source is constant so it does not need to be loaded.
2080/// It returns EVT::Other if the type should be determined using generic
2081/// target-independent logic.
2082/// For vector ops we check that the overall size isn't larger than our
2083/// preferred vector width.
2084EVT X86TargetLowering::getOptimalMemOpType(
2085 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
2086 bool ZeroMemset, bool MemcpyStrSrc,
2087 const AttributeList &FuncAttributes) const {
2088 if (!FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
2089 if (Size >= 16 && (!Subtarget.isUnalignedMem16Slow() ||
2090 ((DstAlign == 0 || DstAlign >= 16) &&
2091 (SrcAlign == 0 || SrcAlign >= 16)))) {
2092 // FIXME: Check if unaligned 64-byte accesses are slow.
2093 if (Size >= 64 && Subtarget.hasAVX512() &&
2094 (Subtarget.getPreferVectorWidth() >= 512)) {
2095 return Subtarget.hasBWI() ? MVT::v64i8 : MVT::v16i32;
2096 }
2097 // FIXME: Check if unaligned 32-byte accesses are slow.
2098 if (Size >= 32 && Subtarget.hasAVX() &&
2099 (Subtarget.getPreferVectorWidth() >= 256)) {
2100 // Although this isn't a well-supported type for AVX1, we'll let
2101 // legalization and shuffle lowering produce the optimal codegen. If we
2102 // choose an optimal type with a vector element larger than a byte,
2103 // getMemsetStores() may create an intermediate splat (using an integer
2104 // multiply) before we splat as a vector.
2105 return MVT::v32i8;
2106 }
2107 if (Subtarget.hasSSE2() && (Subtarget.getPreferVectorWidth() >= 128))
2108 return MVT::v16i8;
2109 // TODO: Can SSE1 handle a byte vector?
2110 // If we have SSE1 registers we should be able to use them.
2111 if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()) &&
2112 (Subtarget.getPreferVectorWidth() >= 128))
2113 return MVT::v4f32;
2114 } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
2115 !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2116 // Do not use f64 to lower memcpy if source is string constant. It's
2117 // better to use i32 to avoid the loads.
2118 // Also, do not use f64 to lower memset unless this is a memset of zeros.
2119 // The gymnastics of splatting a byte value into an XMM register and then
2120 // only using 8-byte stores (because this is a CPU with slow unaligned
2121 // 16-byte accesses) makes that a loser.
2122 return MVT::f64;
2123 }
2124 }
2125 // This is a compromise. If we reach here, unaligned accesses may be slow on
2126 // this target. However, creating smaller, aligned accesses could be even
2127 // slower and would certainly be a lot more code.
2128 if (Subtarget.is64Bit() && Size >= 8)
2129 return MVT::i64;
2130 return MVT::i32;
2131}
2132
2133bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
2134 if (VT == MVT::f32)
2135 return X86ScalarSSEf32;
2136 else if (VT == MVT::f64)
2137 return X86ScalarSSEf64;
2138 return true;
2139}
2140
2141bool X86TargetLowering::allowsMisalignedMemoryAccesses(
2142 EVT VT, unsigned, unsigned Align, MachineMemOperand::Flags Flags,
2143 bool *Fast) const {
2144 if (Fast) {
2145 switch (VT.getSizeInBits()) {
2146 default:
2147 // 8-byte and under are always assumed to be fast.
2148 *Fast = true;
2149 break;
2150 case 128:
2151 *Fast = !Subtarget.isUnalignedMem16Slow();
2152 break;
2153 case 256:
2154 *Fast = !Subtarget.isUnalignedMem32Slow();
2155 break;
2156 // TODO: What about AVX-512 (512-bit) accesses?
2157 }
2158 }
2159 // NonTemporal vector memory ops must be aligned.
2160 if (!!(Flags & MachineMemOperand::MONonTemporal) && VT.isVector()) {
2161 // NT loads can only be vector aligned, so if its less aligned than the
2162 // minimum vector size (which we can split the vector down to), we might as
2163 // well use a regular unaligned vector load.
2164 // We don't have any NT loads pre-SSE41.
2165 if (!!(Flags & MachineMemOperand::MOLoad))
2166 return (Align < 16 || !Subtarget.hasSSE41());
2167 return false;
2168 }
2169 // Misaligned accesses of any size are always allowed.
2170 return true;
2171}
2172
2173/// Return the entry encoding for a jump table in the
2174/// current function. The returned value is a member of the
2175/// MachineJumpTableInfo::JTEntryKind enum.
2176unsigned X86TargetLowering::getJumpTableEncoding() const {
2177 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2178 // symbol.
2179 if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2180 return MachineJumpTableInfo::EK_Custom32;
2181
2182 // Otherwise, use the normal jump table encoding heuristics.
2183 return TargetLowering::getJumpTableEncoding();
2184}
2185
2186bool X86TargetLowering::useSoftFloat() const {
2187 return Subtarget.useSoftFloat();
2188}
2189
2190void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
2191 ArgListTy &Args) const {
2192
2193 // Only relabel X86-32 for C / Stdcall CCs.
2194 if (Subtarget.is64Bit())
2195 return;
2196 if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2197 return;
2198 unsigned ParamRegs = 0;
2199 if (auto *M = MF->getFunction().getParent())
2200 ParamRegs = M->getNumberRegisterParameters();
2201
2202 // Mark the first N int arguments as having reg
2203 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2204 Type *T = Args[Idx].Ty;
2205 if (T->isIntOrPtrTy())
2206 if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2207 unsigned numRegs = 1;
2208 if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2209 numRegs = 2;
2210 if (ParamRegs < numRegs)
2211 return;
2212 ParamRegs -= numRegs;
2213 Args[Idx].IsInReg = true;
2214 }
2215 }
2216}
2217
2218const MCExpr *
2219X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
2220 const MachineBasicBlock *MBB,
2221 unsigned uid,MCContext &Ctx) const{
2222 assert(isPositionIndependent() && Subtarget.isPICStyleGOT())((isPositionIndependent() && Subtarget.isPICStyleGOT(
)) ? static_cast<void> (0) : __assert_fail ("isPositionIndependent() && Subtarget.isPICStyleGOT()"
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2222, __PRETTY_FUNCTION__))
;
2223 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2224 // entries.
2225 return MCSymbolRefExpr::create(MBB->getSymbol(),
2226 MCSymbolRefExpr::VK_GOTOFF, Ctx);
2227}
2228
2229/// Returns relocation base for the given PIC jumptable.
2230SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
2231 SelectionDAG &DAG) const {
2232 if (!Subtarget.is64Bit())
2233 // This doesn't have SDLoc associated with it, but is not really the
2234 // same as a Register.
2235 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2236 getPointerTy(DAG.getDataLayout()));
2237 return Table;
2238}
2239
2240/// This returns the relocation base for the given PIC jumptable,
2241/// the same as getPICJumpTableRelocBase, but as an MCExpr.
2242const MCExpr *X86TargetLowering::
2243getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
2244 MCContext &Ctx) const {
2245 // X86-64 uses RIP relative addressing based on the jump table label.
2246 if (Subtarget.isPICStyleRIPRel())
2247 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2248
2249 // Otherwise, the reference is relative to the PIC base.
2250 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2251}
2252
2253std::pair<const TargetRegisterClass *, uint8_t>
2254X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
2255 MVT VT) const {
2256 const TargetRegisterClass *RRC = nullptr;
2257 uint8_t Cost = 1;
2258 switch (VT.SimpleTy) {
2259 default:
2260 return TargetLowering::findRepresentativeClass(TRI, VT);
2261 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2262 RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2263 break;
2264 case MVT::x86mmx:
2265 RRC = &X86::VR64RegClass;
2266 break;
2267 case MVT::f32: case MVT::f64:
2268 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2269 case MVT::v4f32: case MVT::v2f64:
2270 case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2271 case MVT::v8f32: case MVT::v4f64:
2272 case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2273 case MVT::v16f32: case MVT::v8f64:
2274 RRC = &X86::VR128XRegClass;
2275 break;
2276 }
2277 return std::make_pair(RRC, Cost);
2278}
2279
2280unsigned X86TargetLowering::getAddressSpace() const {
2281 if (Subtarget.is64Bit())
2282 return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2283 return 256;
2284}
2285
2286static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2287 return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2288 (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2289}
2290
2291static Constant* SegmentOffset(IRBuilder<> &IRB,
2292 unsigned Offset, unsigned AddressSpace) {
2293 return ConstantExpr::getIntToPtr(
2294 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2295 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2296}
2297
2298Value *X86TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
2299 // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2300 // tcbhead_t; use it instead of the usual global variable (see
2301 // sysdeps/{i386,x86_64}/nptl/tls.h)
2302 if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2303 if (Subtarget.isTargetFuchsia()) {
2304 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2305 return SegmentOffset(IRB, 0x10, getAddressSpace());
2306 } else {
2307 // %fs:0x28, unless we're using a Kernel code model, in which case
2308 // it's %gs:0x28. gs:0x14 on i386.
2309 unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2310 return SegmentOffset(IRB, Offset, getAddressSpace());
2311 }
2312 }
2313
2314 return TargetLowering::getIRStackGuard(IRB);
2315}
2316
2317void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2318 // MSVC CRT provides functionalities for stack protection.
2319 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2320 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2321 // MSVC CRT has a global variable holding security cookie.
2322 M.getOrInsertGlobal("__security_cookie",
2323 Type::getInt8PtrTy(M.getContext()));
2324
2325 // MSVC CRT has a function to validate security cookie.
2326 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
2327 "__security_check_cookie", Type::getVoidTy(M.getContext()),
2328 Type::getInt8PtrTy(M.getContext()));
2329 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
2330 F->setCallingConv(CallingConv::X86_FastCall);
2331 F->addAttribute(1, Attribute::AttrKind::InReg);
2332 }
2333 return;
2334 }
2335 // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2336 if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2337 return;
2338 TargetLowering::insertSSPDeclarations(M);
2339}
2340
2341Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2342 // MSVC CRT has a global variable holding security cookie.
2343 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2344 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2345 return M.getGlobalVariable("__security_cookie");
2346 }
2347 return TargetLowering::getSDagStackGuard(M);
2348}
2349
2350Function *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2351 // MSVC CRT has a function to validate security cookie.
2352 if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2353 Subtarget.getTargetTriple().isWindowsItaniumEnvironment()) {
2354 return M.getFunction("__security_check_cookie");
2355 }
2356 return TargetLowering::getSSPStackGuardCheck(M);
2357}
2358
2359Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2360 if (Subtarget.getTargetTriple().isOSContiki())
2361 return getDefaultSafeStackPointerLocation(IRB, false);
2362
2363 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2364 // definition of TLS_SLOT_SAFESTACK in
2365 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2366 if (Subtarget.isTargetAndroid()) {
2367 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2368 // %gs:0x24 on i386
2369 unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2370 return SegmentOffset(IRB, Offset, getAddressSpace());
2371 }
2372
2373 // Fuchsia is similar.
2374 if (Subtarget.isTargetFuchsia()) {
2375 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2376 return SegmentOffset(IRB, 0x18, getAddressSpace());
2377 }
2378
2379 return TargetLowering::getSafeStackPointerLocation(IRB);
2380}
2381
2382bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2383 unsigned DestAS) const {
2384 assert(SrcAS != DestAS && "Expected different address spaces!")((SrcAS != DestAS && "Expected different address spaces!"
) ? static_cast<void> (0) : __assert_fail ("SrcAS != DestAS && \"Expected different address spaces!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2384, __PRETTY_FUNCTION__))
;
2385
2386 return SrcAS < 256 && DestAS < 256;
2387}
2388
2389//===----------------------------------------------------------------------===//
2390// Return Value Calling Convention Implementation
2391//===----------------------------------------------------------------------===//
2392
2393bool X86TargetLowering::CanLowerReturn(
2394 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2395 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2396 SmallVector<CCValAssign, 16> RVLocs;
2397 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2398 return CCInfo.CheckReturn(Outs, RetCC_X86);
2399}
2400
2401const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2402 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2403 return ScratchRegs;
2404}
2405
2406/// Lowers masks values (v*i1) to the local register values
2407/// \returns DAG node after lowering to register type
2408static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2409 const SDLoc &Dl, SelectionDAG &DAG) {
2410 EVT ValVT = ValArg.getValueType();
2411
2412 if (ValVT == MVT::v1i1)
2413 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2414 DAG.getIntPtrConstant(0, Dl));
2415
2416 if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2417 (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2418 // Two stage lowering might be required
2419 // bitcast: v8i1 -> i8 / v16i1 -> i16
2420 // anyextend: i8 -> i32 / i16 -> i32
2421 EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2422 SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2423 if (ValLoc == MVT::i32)
2424 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2425 return ValToCopy;
2426 }
2427
2428 if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2429 (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2430 // One stage lowering is required
2431 // bitcast: v32i1 -> i32 / v64i1 -> i64
2432 return DAG.getBitcast(ValLoc, ValArg);
2433 }
2434
2435 return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2436}
2437
2438/// Breaks v64i1 value into two registers and adds the new node to the DAG
2439static void Passv64i1ArgInRegs(
2440 const SDLoc &Dl, SelectionDAG &DAG, SDValue &Arg,
2441 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, CCValAssign &VA,
2442 CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2443 assert(Subtarget.hasBWI() && "Expected AVX512BW target!")((Subtarget.hasBWI() && "Expected AVX512BW target!") ?
static_cast<void> (0) : __assert_fail ("Subtarget.hasBWI() && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2443, __PRETTY_FUNCTION__))
;
2444 assert(Subtarget.is32Bit() && "Expecting 32 bit target")((Subtarget.is32Bit() && "Expecting 32 bit target") ?
static_cast<void> (0) : __assert_fail ("Subtarget.is32Bit() && \"Expecting 32 bit target\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2444, __PRETTY_FUNCTION__))
;
2445 assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value")((Arg.getValueType() == MVT::i64 && "Expecting 64 bit value"
) ? static_cast<void> (0) : __assert_fail ("Arg.getValueType() == MVT::i64 && \"Expecting 64 bit value\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2445, __PRETTY_FUNCTION__))
;
2446 assert(VA.isRegLoc() && NextVA.isRegLoc() &&((VA.isRegLoc() && NextVA.isRegLoc() && "The value should reside in two registers"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The value should reside in two registers\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2447, __PRETTY_FUNCTION__))
2447 "The value should reside in two registers")((VA.isRegLoc() && NextVA.isRegLoc() && "The value should reside in two registers"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The value should reside in two registers\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2447, __PRETTY_FUNCTION__))
;
2448
2449 // Before splitting the value we cast it to i64
2450 Arg = DAG.getBitcast(MVT::i64, Arg);
2451
2452 // Splitting the value into two i32 types
2453 SDValue Lo, Hi;
2454 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2455 DAG.getConstant(0, Dl, MVT::i32));
2456 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2457 DAG.getConstant(1, Dl, MVT::i32));
2458
2459 // Attach the two i32 types into corresponding registers
2460 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2461 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2462}
2463
2464SDValue
2465X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2466 bool isVarArg,
2467 const SmallVectorImpl<ISD::OutputArg> &Outs,
2468 const SmallVectorImpl<SDValue> &OutVals,
2469 const SDLoc &dl, SelectionDAG &DAG) const {
2470 MachineFunction &MF = DAG.getMachineFunction();
2471 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2472
2473 // In some cases we need to disable registers from the default CSR list.
2474 // For example, when they are used for argument passing.
2475 bool ShouldDisableCalleeSavedRegister =
2476 CallConv == CallingConv::X86_RegCall ||
2477 MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2478
2479 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2480 report_fatal_error("X86 interrupts may not return any value");
2481
2482 SmallVector<CCValAssign, 16> RVLocs;
2483 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2484 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2485
2486 SDValue Flag;
2487 SmallVector<SDValue, 6> RetOps;
2488 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2489 // Operand #1 = Bytes To Pop
2490 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2491 MVT::i32));
2492
2493 // Copy the result values into the output registers.
2494 for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2495 ++I, ++OutsIndex) {
2496 CCValAssign &VA = RVLocs[I];
2497 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-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2497, __PRETTY_FUNCTION__))
;
2498
2499 // Add the register to the CalleeSaveDisableRegs list.
2500 if (ShouldDisableCalleeSavedRegister)
2501 MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
2502
2503 SDValue ValToCopy = OutVals[OutsIndex];
2504 EVT ValVT = ValToCopy.getValueType();
2505
2506 // Promote values to the appropriate types.
2507 if (VA.getLocInfo() == CCValAssign::SExt)
2508 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2509 else if (VA.getLocInfo() == CCValAssign::ZExt)
2510 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2511 else if (VA.getLocInfo() == CCValAssign::AExt) {
2512 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2513 ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2514 else
2515 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2516 }
2517 else if (VA.getLocInfo() == CCValAssign::BCvt)
2518 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2519
2520 assert(VA.getLocInfo() != CCValAssign::FPExt &&((VA.getLocInfo() != CCValAssign::FPExt && "Unexpected FP-extend for return value."
) ? static_cast<void> (0) : __assert_fail ("VA.getLocInfo() != CCValAssign::FPExt && \"Unexpected FP-extend for return value.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2521, __PRETTY_FUNCTION__))
2521 "Unexpected FP-extend for return value.")((VA.getLocInfo() != CCValAssign::FPExt && "Unexpected FP-extend for return value."
) ? static_cast<void> (0) : __assert_fail ("VA.getLocInfo() != CCValAssign::FPExt && \"Unexpected FP-extend for return value.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2521, __PRETTY_FUNCTION__))
;
2522
2523 // If this is x86-64, and we disabled SSE, we can't return FP values,
2524 // or SSE or MMX vectors.
2525 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2526 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2527 (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2528 errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2529 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2530 } else if (ValVT == MVT::f64 &&
2531 (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2532 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2533 // llvm-gcc has never done it right and no one has noticed, so this
2534 // should be OK for now.
2535 errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2536 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2537 }
2538
2539 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2540 // the RET instruction and handled by the FP Stackifier.
2541 if (VA.getLocReg() == X86::FP0 ||
2542 VA.getLocReg() == X86::FP1) {
2543 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2544 // change the value to the FP stack register class.
2545 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2546 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2547 RetOps.push_back(ValToCopy);
2548 // Don't emit a copytoreg.
2549 continue;
2550 }
2551
2552 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2553 // which is returned in RAX / RDX.
2554 if (Subtarget.is64Bit()) {
2555 if (ValVT == MVT::x86mmx) {
2556 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2557 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2558 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2559 ValToCopy);
2560 // If we don't have SSE2 available, convert to v4f32 so the generated
2561 // register is legal.
2562 if (!Subtarget.hasSSE2())
2563 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2564 }
2565 }
2566 }
2567
2568 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2569
2570 if (VA.needsCustom()) {
2571 assert(VA.getValVT() == MVT::v64i1 &&((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2572, __PRETTY_FUNCTION__))
2572 "Currently the only custom case is when we split v64i1 to 2 regs")((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2572, __PRETTY_FUNCTION__))
;
2573
2574 Passv64i1ArgInRegs(dl, DAG, ValToCopy, RegsToPass, VA, RVLocs[++I],
2575 Subtarget);
2576
2577 assert(2 == RegsToPass.size() &&((2 == RegsToPass.size() && "Expecting two registers after Pass64BitArgInRegs"
) ? static_cast<void> (0) : __assert_fail ("2 == RegsToPass.size() && \"Expecting two registers after Pass64BitArgInRegs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2578, __PRETTY_FUNCTION__))
2578 "Expecting two registers after Pass64BitArgInRegs")((2 == RegsToPass.size() && "Expecting two registers after Pass64BitArgInRegs"
) ? static_cast<void> (0) : __assert_fail ("2 == RegsToPass.size() && \"Expecting two registers after Pass64BitArgInRegs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2578, __PRETTY_FUNCTION__))
;
2579
2580 // Add the second register to the CalleeSaveDisableRegs list.
2581 if (ShouldDisableCalleeSavedRegister)
2582 MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2583 } else {
2584 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2585 }
2586
2587 // Add nodes to the DAG and add the values into the RetOps list
2588 for (auto &Reg : RegsToPass) {
2589 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2590 Flag = Chain.getValue(1);
2591 RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2592 }
2593 }
2594
2595 // Swift calling convention does not require we copy the sret argument
2596 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2597
2598 // All x86 ABIs require that for returning structs by value we copy
2599 // the sret argument into %rax/%eax (depending on ABI) for the return.
2600 // We saved the argument into a virtual register in the entry block,
2601 // so now we copy the value out and into %rax/%eax.
2602 //
2603 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2604 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2605 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2606 // either case FuncInfo->setSRetReturnReg() will have been called.
2607 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2608 // When we have both sret and another return value, we should use the
2609 // original Chain stored in RetOps[0], instead of the current Chain updated
2610 // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2611
2612 // For the case of sret and another return value, we have
2613 // Chain_0 at the function entry
2614 // Chain_1 = getCopyToReg(Chain_0) in the above loop
2615 // If we use Chain_1 in getCopyFromReg, we will have
2616 // Val = getCopyFromReg(Chain_1)
2617 // Chain_2 = getCopyToReg(Chain_1, Val) from below
2618
2619 // getCopyToReg(Chain_0) will be glued together with
2620 // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2621 // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2622 // Data dependency from Unit B to Unit A due to usage of Val in
2623 // getCopyToReg(Chain_1, Val)
2624 // Chain dependency from Unit A to Unit B
2625
2626 // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2627 SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2628 getPointerTy(MF.getDataLayout()));
2629
2630 unsigned RetValReg
2631 = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2632 X86::RAX : X86::EAX;
2633 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2634 Flag = Chain.getValue(1);
2635
2636 // RAX/EAX now acts like a return value.
2637 RetOps.push_back(
2638 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2639
2640 // Add the returned register to the CalleeSaveDisableRegs list.
2641 if (ShouldDisableCalleeSavedRegister)
2642 MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2643 }
2644
2645 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2646 const MCPhysReg *I =
2647 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2648 if (I) {
2649 for (; *I; ++I) {
2650 if (X86::GR64RegClass.contains(*I))
2651 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2652 else
2653 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2653)
;
2654 }
2655 }
2656
2657 RetOps[0] = Chain; // Update chain.
2658
2659 // Add the flag if we have it.
2660 if (Flag.getNode())
2661 RetOps.push_back(Flag);
2662
2663 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2664 if (CallConv == CallingConv::X86_INTR)
2665 opcode = X86ISD::IRET;
2666 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2667}
2668
2669bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2670 if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2671 return false;
2672
2673 SDValue TCChain = Chain;
2674 SDNode *Copy = *N->use_begin();
2675 if (Copy->getOpcode() == ISD::CopyToReg) {
2676 // If the copy has a glue operand, we conservatively assume it isn't safe to
2677 // perform a tail call.
2678 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2679 return false;
2680 TCChain = Copy->getOperand(0);
2681 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2682 return false;
2683
2684 bool HasRet = false;
2685 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2686 UI != UE; ++UI) {
2687 if (UI->getOpcode() != X86ISD::RET_FLAG)
2688 return false;
2689 // If we are returning more than one value, we can definitely
2690 // not make a tail call see PR19530
2691 if (UI->getNumOperands() > 4)
2692 return false;
2693 if (UI->getNumOperands() == 4 &&
2694 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2695 return false;
2696 HasRet = true;
2697 }
2698
2699 if (!HasRet)
2700 return false;
2701
2702 Chain = TCChain;
2703 return true;
2704}
2705
2706EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2707 ISD::NodeType ExtendKind) const {
2708 MVT ReturnMVT = MVT::i32;
2709
2710 bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2711 if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2712 // The ABI does not require i1, i8 or i16 to be extended.
2713 //
2714 // On Darwin, there is code in the wild relying on Clang's old behaviour of
2715 // always extending i8/i16 return values, so keep doing that for now.
2716 // (PR26665).
2717 ReturnMVT = MVT::i8;
2718 }
2719
2720 EVT MinVT = getRegisterType(Context, ReturnMVT);
2721 return VT.bitsLT(MinVT) ? MinVT : VT;
2722}
2723
2724/// Reads two 32 bit registers and creates a 64 bit mask value.
2725/// \param VA The current 32 bit value that need to be assigned.
2726/// \param NextVA The next 32 bit value that need to be assigned.
2727/// \param Root The parent DAG node.
2728/// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2729/// glue purposes. In the case the DAG is already using
2730/// physical register instead of virtual, we should glue
2731/// our new SDValue to InFlag SDvalue.
2732/// \return a new SDvalue of size 64bit.
2733static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
2734 SDValue &Root, SelectionDAG &DAG,
2735 const SDLoc &Dl, const X86Subtarget &Subtarget,
2736 SDValue *InFlag = nullptr) {
2737 assert((Subtarget.hasBWI()) && "Expected AVX512BW target!")(((Subtarget.hasBWI()) && "Expected AVX512BW target!"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.hasBWI()) && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2737, __PRETTY_FUNCTION__))
;
2738 assert(Subtarget.is32Bit() && "Expecting 32 bit target")((Subtarget.is32Bit() && "Expecting 32 bit target") ?
static_cast<void> (0) : __assert_fail ("Subtarget.is32Bit() && \"Expecting 32 bit target\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2738, __PRETTY_FUNCTION__))
;
2739 assert(VA.getValVT() == MVT::v64i1 &&((VA.getValVT() == MVT::v64i1 && "Expecting first location of 64 bit width type"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Expecting first location of 64 bit width type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2740, __PRETTY_FUNCTION__))
2740 "Expecting first location of 64 bit width type")((VA.getValVT() == MVT::v64i1 && "Expecting first location of 64 bit width type"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Expecting first location of 64 bit width type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2740, __PRETTY_FUNCTION__))
;
2741 assert(NextVA.getValVT() == VA.getValVT() &&((NextVA.getValVT() == VA.getValVT() && "The locations should have the same type"
) ? static_cast<void> (0) : __assert_fail ("NextVA.getValVT() == VA.getValVT() && \"The locations should have the same type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2742, __PRETTY_FUNCTION__))
2742 "The locations should have the same type")((NextVA.getValVT() == VA.getValVT() && "The locations should have the same type"
) ? static_cast<void> (0) : __assert_fail ("NextVA.getValVT() == VA.getValVT() && \"The locations should have the same type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2742, __PRETTY_FUNCTION__))
;
2743 assert(VA.isRegLoc() && NextVA.isRegLoc() &&((VA.isRegLoc() && NextVA.isRegLoc() && "The values should reside in two registers"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The values should reside in two registers\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2744, __PRETTY_FUNCTION__))
2744 "The values should reside in two registers")((VA.isRegLoc() && NextVA.isRegLoc() && "The values should reside in two registers"
) ? static_cast<void> (0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The values should reside in two registers\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2744, __PRETTY_FUNCTION__))
;
2745
2746 SDValue Lo, Hi;
2747 SDValue ArgValueLo, ArgValueHi;
2748
2749 MachineFunction &MF = DAG.getMachineFunction();
2750 const TargetRegisterClass *RC = &X86::GR32RegClass;
2751
2752 // Read a 32 bit value from the registers.
2753 if (nullptr == InFlag) {
2754 // When no physical register is present,
2755 // create an intermediate virtual register.
2756 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2757 ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2758 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2759 ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2760 } else {
2761 // When a physical register is available read the value from it and glue
2762 // the reads together.
2763 ArgValueLo =
2764 DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2765 *InFlag = ArgValueLo.getValue(2);
2766 ArgValueHi =
2767 DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2768 *InFlag = ArgValueHi.getValue(2);
2769 }
2770
2771 // Convert the i32 type into v32i1 type.
2772 Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2773
2774 // Convert the i32 type into v32i1 type.
2775 Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2776
2777 // Concatenate the two values together.
2778 return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2779}
2780
2781/// The function will lower a register of various sizes (8/16/32/64)
2782/// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2783/// \returns a DAG node contains the operand after lowering to mask type.
2784static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2785 const EVT &ValLoc, const SDLoc &Dl,
2786 SelectionDAG &DAG) {
2787 SDValue ValReturned = ValArg;
2788
2789 if (ValVT == MVT::v1i1)
2790 return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2791
2792 if (ValVT == MVT::v64i1) {
2793 // In 32 bit machine, this case is handled by getv64i1Argument
2794 assert(ValLoc == MVT::i64 && "Expecting only i64 locations")((ValLoc == MVT::i64 && "Expecting only i64 locations"
) ? static_cast<void> (0) : __assert_fail ("ValLoc == MVT::i64 && \"Expecting only i64 locations\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2794, __PRETTY_FUNCTION__))
;
2795 // In 64 bit machine, There is no need to truncate the value only bitcast
2796 } else {
2797 MVT maskLen;
2798 switch (ValVT.getSimpleVT().SimpleTy) {
2799 case MVT::v8i1:
2800 maskLen = MVT::i8;
2801 break;
2802 case MVT::v16i1:
2803 maskLen = MVT::i16;
2804 break;
2805 case MVT::v32i1:
2806 maskLen = MVT::i32;
2807 break;
2808 default:
2809 llvm_unreachable("Expecting a vector of i1 types")::llvm::llvm_unreachable_internal("Expecting a vector of i1 types"
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2809)
;
2810 }
2811
2812 ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2813 }
2814 return DAG.getBitcast(ValVT, ValReturned);
2815}
2816
2817/// Lower the result values of a call into the
2818/// appropriate copies out of appropriate physical registers.
2819///
2820SDValue X86TargetLowering::LowerCallResult(
2821 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2822 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2823 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2824 uint32_t *RegMask) const {
2825
2826 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2827 // Assign locations to each value returned by this call.
2828 SmallVector<CCValAssign, 16> RVLocs;
2829 bool Is64Bit = Subtarget.is64Bit();
2830 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2831 *DAG.getContext());
2832 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2833
2834 // Copy all of the result registers out of their specified physreg.
2835 for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2836 ++I, ++InsIndex) {
2837 CCValAssign &VA = RVLocs[I];
2838 EVT CopyVT = VA.getLocVT();
2839
2840 // In some calling conventions we need to remove the used registers
2841 // from the register mask.
2842 if (RegMask) {
2843 for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2844 SubRegs.isValid(); ++SubRegs)
2845 RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2846 }
2847
2848 // If this is x86-64, and we disabled SSE, we can't return FP values
2849 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2850 ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2851 errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2852 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2853 } else if (CopyVT == MVT::f64 &&
2854 (Is64Bit && !Subtarget.hasSSE2())) {
2855 errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2856 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2857 }
2858
2859 // If we prefer to use the value in xmm registers, copy it out as f80 and
2860 // use a truncate to move it from fp stack reg to xmm reg.
2861 bool RoundAfterCopy = false;
2862 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2863 isScalarFPTypeInSSEReg(VA.getValVT())) {
2864 if (!Subtarget.hasX87())
2865 report_fatal_error("X87 register return with X87 disabled");
2866 CopyVT = MVT::f80;
2867 RoundAfterCopy = (CopyVT != VA.getLocVT());
2868 }
2869
2870 SDValue Val;
2871 if (VA.needsCustom()) {
2872 assert(VA.getValVT() == MVT::v64i1 &&((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2873, __PRETTY_FUNCTION__))
2873 "Currently the only custom case is when we split v64i1 to 2 regs")((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 2873, __PRETTY_FUNCTION__))
;
2874 Val =
2875 getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2876 } else {
2877 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2878 .getValue(1);
2879 Val = Chain.getValue(0);
2880 InFlag = Chain.getValue(2);
2881 }
2882
2883 if (RoundAfterCopy)
2884 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2885 // This truncation won't change the value.
2886 DAG.getIntPtrConstant(1, dl));
2887
2888 if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2889 if (VA.getValVT().isVector() &&
2890 ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2891 (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2892 // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2893 Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2894 } else
2895 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2896 }
2897
2898 InVals.push_back(Val);
2899 }
2900
2901 return Chain;
2902}
2903
2904//===----------------------------------------------------------------------===//
2905// C & StdCall & Fast Calling Convention implementation
2906//===----------------------------------------------------------------------===//
2907// StdCall calling convention seems to be standard for many Windows' API
2908// routines and around. It differs from C calling convention just a little:
2909// callee should clean up the stack, not caller. Symbols should be also
2910// decorated in some fancy way :) It doesn't support any vector arguments.
2911// For info on fast calling convention see Fast Calling Convention (tail call)
2912// implementation LowerX86_32FastCCCallTo.
2913
2914/// CallIsStructReturn - Determines whether a call uses struct return
2915/// semantics.
2916enum StructReturnType {
2917 NotStructReturn,
2918 RegStructReturn,
2919 StackStructReturn
2920};
2921static StructReturnType
2922callIsStructReturn(ArrayRef<ISD::OutputArg> Outs, bool IsMCU) {
2923 if (Outs.empty())
2924 return NotStructReturn;
2925
2926 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2927 if (!Flags.isSRet())
2928 return NotStructReturn;
2929 if (Flags.isInReg() || IsMCU)
2930 return RegStructReturn;
2931 return StackStructReturn;
2932}
2933
2934/// Determines whether a function uses struct return semantics.
2935static StructReturnType
2936argsAreStructReturn(ArrayRef<ISD::InputArg> Ins, bool IsMCU) {
2937 if (Ins.empty())
2938 return NotStructReturn;
2939
2940 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2941 if (!Flags.isSRet())
2942 return NotStructReturn;
2943 if (Flags.isInReg() || IsMCU)
2944 return RegStructReturn;
2945 return StackStructReturn;
2946}
2947
2948/// Make a copy of an aggregate at address specified by "Src" to address
2949/// "Dst" with size and alignment information specified by the specific
2950/// parameter attribute. The copy will be passed as a byval function parameter.
2951static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
2952 SDValue Chain, ISD::ArgFlagsTy Flags,
2953 SelectionDAG &DAG, const SDLoc &dl) {
2954 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2955
2956 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2957 /*isVolatile*/false, /*AlwaysInline=*/true,
2958 /*isTailCall*/false,
2959 MachinePointerInfo(), MachinePointerInfo());
2960}
2961
2962/// Return true if the calling convention is one that we can guarantee TCO for.
2963static bool canGuaranteeTCO(CallingConv::ID CC) {
2964 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2965 CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
2966 CC == CallingConv::HHVM || CC == CallingConv::Tail);
2967}
2968
2969/// Return true if we might ever do TCO for calls with this calling convention.
2970static bool mayTailCallThisCC(CallingConv::ID CC) {
2971 switch (CC) {
2972 // C calling conventions:
2973 case CallingConv::C:
2974 case CallingConv::Win64:
2975 case CallingConv::X86_64_SysV:
2976 // Callee pop conventions:
2977 case CallingConv::X86_ThisCall:
2978 case CallingConv::X86_StdCall:
2979 case CallingConv::X86_VectorCall:
2980 case CallingConv::X86_FastCall:
2981 // Swift:
2982 case CallingConv::Swift:
2983 return true;
2984 default:
2985 return canGuaranteeTCO(CC);
2986 }
2987}
2988
2989/// Return true if the function is being made into a tailcall target by
2990/// changing its ABI.
2991static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2992 return (GuaranteedTailCallOpt && canGuaranteeTCO(CC)) || CC == CallingConv::Tail;
2993}
2994
2995bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2996 auto Attr =
2997 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2998 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2999 return false;
3000
3001 ImmutableCallSite CS(CI);
3002 CallingConv::ID CalleeCC = CS.getCallingConv();
3003 if (!mayTailCallThisCC(CalleeCC))
3004 return false;
3005
3006 return true;
3007}
3008
3009SDValue
3010X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
3011 const SmallVectorImpl<ISD::InputArg> &Ins,
3012 const SDLoc &dl, SelectionDAG &DAG,
3013 const CCValAssign &VA,
3014 MachineFrameInfo &MFI, unsigned i) const {
3015 // Create the nodes corresponding to a load from this parameter slot.
3016 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3017 bool AlwaysUseMutable = shouldGuaranteeTCO(
3018 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
3019 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
3020 EVT ValVT;
3021 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3022
3023 // If value is passed by pointer we have address passed instead of the value
3024 // itself. No need to extend if the mask value and location share the same
3025 // absolute size.
3026 bool ExtendedInMem =
3027 VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
3028 VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
3029
3030 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
3031 ValVT = VA.getLocVT();
3032 else
3033 ValVT = VA.getValVT();
3034
3035 // FIXME: For now, all byval parameter objects are marked mutable. This can be
3036 // changed with more analysis.
3037 // In case of tail call optimization mark all arguments mutable. Since they
3038 // could be overwritten by lowering of arguments in case of a tail call.
3039 if (Flags.isByVal()) {
3040 unsigned Bytes = Flags.getByValSize();
3041 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3042
3043 // FIXME: For now, all byval parameter objects are marked as aliasing. This
3044 // can be improved with deeper analysis.
3045 int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3046 /*isAliased=*/true);
3047 return DAG.getFrameIndex(FI, PtrVT);
3048 }
3049
3050 // This is an argument in memory. We might be able to perform copy elision.
3051 // If the argument is passed directly in memory without any extension, then we
3052 // can perform copy elision. Large vector types, for example, may be passed
3053 // indirectly by pointer.
3054 if (Flags.isCopyElisionCandidate() &&
3055 VA.getLocInfo() != CCValAssign::Indirect && !ExtendedInMem) {
3056 EVT ArgVT = Ins[i].ArgVT;
3057 SDValue PartAddr;
3058 if (Ins[i].PartOffset == 0) {
3059 // If this is a one-part value or the first part of a multi-part value,
3060 // create a stack object for the entire argument value type and return a
3061 // load from our portion of it. This assumes that if the first part of an
3062 // argument is in memory, the rest will also be in memory.
3063 int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3064 /*IsImmutable=*/false);
3065 PartAddr = DAG.getFrameIndex(FI, PtrVT);
3066 return DAG.getLoad(
3067 ValVT, dl, Chain, PartAddr,
3068 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3069 } else {
3070 // This is not the first piece of an argument in memory. See if there is
3071 // already a fixed stack object including this offset. If so, assume it
3072 // was created by the PartOffset == 0 branch above and create a load from
3073 // the appropriate offset into it.
3074 int64_t PartBegin = VA.getLocMemOffset();
3075 int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3076 int FI = MFI.getObjectIndexBegin();
3077 for (; MFI.isFixedObjectIndex(FI); ++FI) {
3078 int64_t ObjBegin = MFI.getObjectOffset(FI);
3079 int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3080 if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3081 break;
3082 }
3083 if (MFI.isFixedObjectIndex(FI)) {
3084 SDValue Addr =
3085 DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3086 DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3087 return DAG.getLoad(
3088 ValVT, dl, Chain, Addr,
3089 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
3090 Ins[i].PartOffset));
3091 }
3092 }
3093 }
3094
3095 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3096 VA.getLocMemOffset(), isImmutable);
3097
3098 // Set SExt or ZExt flag.
3099 if (VA.getLocInfo() == CCValAssign::ZExt) {
3100 MFI.setObjectZExt(FI, true);
3101 } else if (VA.getLocInfo() == CCValAssign::SExt) {
3102 MFI.setObjectSExt(FI, true);
3103 }
3104
3105 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3106 SDValue Val = DAG.getLoad(
3107 ValVT, dl, Chain, FIN,
3108 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3109 return ExtendedInMem
3110 ? (VA.getValVT().isVector()
3111 ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3112 : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3113 : Val;
3114}
3115
3116// FIXME: Get this from tablegen.
3117static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
3118 const X86Subtarget &Subtarget) {
3119 assert(Subtarget.is64Bit())((Subtarget.is64Bit()) ? static_cast<void> (0) : __assert_fail
("Subtarget.is64Bit()", "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3119, __PRETTY_FUNCTION__))
;
3120
3121 if (Subtarget.isCallingConvWin64(CallConv)) {
3122 static const MCPhysReg GPR64ArgRegsWin64[] = {
3123 X86::RCX, X86::RDX, X86::R8, X86::R9
3124 };
3125 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3126 }
3127
3128 static const MCPhysReg GPR64ArgRegs64Bit[] = {
3129 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3130 };
3131 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3132}
3133
3134// FIXME: Get this from tablegen.
3135static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
3136 CallingConv::ID CallConv,
3137 const X86Subtarget &Subtarget) {
3138 assert(Subtarget.is64Bit())((Subtarget.is64Bit()) ? static_cast<void> (0) : __assert_fail
("Subtarget.is64Bit()", "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3138, __PRETTY_FUNCTION__))
;
3139 if (Subtarget.isCallingConvWin64(CallConv)) {
3140 // The XMM registers which might contain var arg parameters are shadowed
3141 // in their paired GPR. So we only need to save the GPR to their home
3142 // slots.
3143 // TODO: __vectorcall will change this.
3144 return None;
3145 }
3146
3147 const Function &F = MF.getFunction();
3148 bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
3149 bool isSoftFloat = Subtarget.useSoftFloat();
3150 assert(!(isSoftFloat && NoImplicitFloatOps) &&((!(isSoftFloat && NoImplicitFloatOps) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(isSoftFloat && NoImplicitFloatOps) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3151, __PRETTY_FUNCTION__))
3151 "SSE register cannot be used when SSE is disabled!")((!(isSoftFloat && NoImplicitFloatOps) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(isSoftFloat && NoImplicitFloatOps) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3151, __PRETTY_FUNCTION__))
;
3152 if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
3153 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3154 // registers.
3155 return None;
3156
3157 static const MCPhysReg XMMArgRegs64Bit[] = {
3158 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3159 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3160 };
3161 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3162}
3163
3164#ifndef NDEBUG
3165static bool isSortedByValueNo(ArrayRef<CCValAssign> ArgLocs) {
3166 return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
3167 [](const CCValAssign &A, const CCValAssign &B) -> bool {
3168 return A.getValNo() < B.getValNo();
3169 });
3170}
3171#endif
3172
3173SDValue X86TargetLowering::LowerFormalArguments(
3174 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3175 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3176 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3177 MachineFunction &MF = DAG.getMachineFunction();
3178 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3179 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3180
3181 const Function &F = MF.getFunction();
3182 if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3183 F.getName() == "main")
3184 FuncInfo->setForceFramePointer(true);
3185
3186 MachineFrameInfo &MFI = MF.getFrameInfo();
3187 bool Is64Bit = Subtarget.is64Bit();
3188 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3189
3190 assert(((!(isVarArg && canGuaranteeTCO(CallConv)) &&
"Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? static_cast<void> (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3192, __PRETTY_FUNCTION__))
3191 !(isVarArg && canGuaranteeTCO(CallConv)) &&((!(isVarArg && canGuaranteeTCO(CallConv)) &&
"Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? static_cast<void> (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3192, __PRETTY_FUNCTION__))
3192 "Var args not supported with calling conv' regcall, fastcc, ghc or hipe")((!(isVarArg && canGuaranteeTCO(CallConv)) &&
"Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? static_cast<void> (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3192, __PRETTY_FUNCTION__))
;
3193
3194 // Assign locations to all of the incoming arguments.
3195 SmallVector<CCValAssign, 16> ArgLocs;
3196 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3197
3198 // Allocate shadow area for Win64.
3199 if (IsWin64)
3200 CCInfo.AllocateStack(32, 8);
3201
3202 CCInfo.AnalyzeArguments(Ins, CC_X86);
3203
3204 // In vectorcall calling convention a second pass is required for the HVA
3205 // types.
3206 if (CallingConv::X86_VectorCall == CallConv) {
3207 CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3208 }
3209
3210 // The next loop assumes that the locations are in the same order of the
3211 // input arguments.
3212 assert(isSortedByValueNo(ArgLocs) &&((isSortedByValueNo(ArgLocs) && "Argument Location list must be sorted before lowering"
) ? static_cast<void> (0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3213, __PRETTY_FUNCTION__))
3213 "Argument Location list must be sorted before lowering")((isSortedByValueNo(ArgLocs) && "Argument Location list must be sorted before lowering"
) ? static_cast<void> (0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3213, __PRETTY_FUNCTION__))
;
3214
3215 SDValue ArgValue;
3216 for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3217 ++I, ++InsIndex) {
3218 assert(InsIndex < Ins.size() && "Invalid Ins index")((InsIndex < Ins.size() && "Invalid Ins index") ? static_cast
<void> (0) : __assert_fail ("InsIndex < Ins.size() && \"Invalid Ins index\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3218, __PRETTY_FUNCTION__))
;
3219 CCValAssign &VA = ArgLocs[I];
3220
3221 if (VA.isRegLoc()) {
3222 EVT RegVT = VA.getLocVT();
3223 if (VA.needsCustom()) {
3224 assert(((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3226, __PRETTY_FUNCTION__))
3225 VA.getValVT() == MVT::v64i1 &&((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3226, __PRETTY_FUNCTION__))
3226 "Currently the only custom case is when we split v64i1 to 2 regs")((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3226, __PRETTY_FUNCTION__))
;
3227
3228 // v64i1 values, in regcall calling convention, that are
3229 // compiled to 32 bit arch, are split up into two registers.
3230 ArgValue =
3231 getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3232 } else {
3233 const TargetRegisterClass *RC;
3234 if (RegVT == MVT::i8)
3235 RC = &X86::GR8RegClass;
3236 else if (RegVT == MVT::i16)
3237 RC = &X86::GR16RegClass;
3238 else if (RegVT == MVT::i32)
3239 RC = &X86::GR32RegClass;
3240 else if (Is64Bit && RegVT == MVT::i64)
3241 RC = &X86::GR64RegClass;
3242 else if (RegVT == MVT::f32)
3243 RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3244 else if (RegVT == MVT::f64)
3245 RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3246 else if (RegVT == MVT::f80)
3247 RC = &X86::RFP80RegClass;
3248 else if (RegVT == MVT::f128)
3249 RC = &X86::VR128RegClass;
3250 else if (RegVT.is512BitVector())
3251 RC = &X86::VR512RegClass;
3252 else if (RegVT.is256BitVector())
3253 RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3254 else if (RegVT.is128BitVector())
3255 RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3256 else if (RegVT == MVT::x86mmx)
3257 RC = &X86::VR64RegClass;
3258 else if (RegVT == MVT::v1i1)
3259 RC = &X86::VK1RegClass;
3260 else if (RegVT == MVT::v8i1)
3261 RC = &X86::VK8RegClass;
3262 else if (RegVT == MVT::v16i1)
3263 RC = &X86::VK16RegClass;
3264 else if (RegVT == MVT::v32i1)
3265 RC = &X86::VK32RegClass;
3266 else if (RegVT == MVT::v64i1)
3267 RC = &X86::VK64RegClass;
3268 else
3269 llvm_unreachable("Unknown argument type!")::llvm::llvm_unreachable_internal("Unknown argument type!", "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3269)
;
3270
3271 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3272 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3273 }
3274
3275 // If this is an 8 or 16-bit value, it is really passed promoted to 32
3276 // bits. Insert an assert[sz]ext to capture this, then truncate to the
3277 // right size.
3278 if (VA.getLocInfo() == CCValAssign::SExt)
3279 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3280 DAG.getValueType(VA.getValVT()));
3281 else if (VA.getLocInfo() == CCValAssign::ZExt)
3282 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3283 DAG.getValueType(VA.getValVT()));
3284 else if (VA.getLocInfo() == CCValAssign::BCvt)
3285 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3286
3287 if (VA.isExtInLoc()) {
3288 // Handle MMX values passed in XMM regs.
3289 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3290 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3291 else if (VA.getValVT().isVector() &&
3292 VA.getValVT().getScalarType() == MVT::i1 &&
3293 ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3294 (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3295 // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3296 ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3297 } else
3298 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3299 }
3300 } else {
3301 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3301, __PRETTY_FUNCTION__))
;
3302 ArgValue =
3303 LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3304 }
3305
3306 // If value is passed via pointer - do a load.
3307 if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3308 ArgValue =
3309 DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3310
3311 InVals.push_back(ArgValue);
3312 }
3313
3314 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3315 // Swift calling convention does not require we copy the sret argument
3316 // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3317 if (CallConv == CallingConv::Swift)
3318 continue;
3319
3320 // All x86 ABIs require that for returning structs by value we copy the
3321 // sret argument into %rax/%eax (depending on ABI) for the return. Save
3322 // the argument into a virtual register so that we can access it from the
3323 // return points.
3324 if (Ins[I].Flags.isSRet()) {
3325 unsigned Reg = FuncInfo->getSRetReturnReg();
3326 if (!Reg) {
3327 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3328 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3329 FuncInfo->setSRetReturnReg(Reg);
3330 }
3331 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3332 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3333 break;
3334 }
3335 }
3336
3337 unsigned StackSize = CCInfo.getNextStackOffset();
3338 // Align stack specially for tail calls.
3339 if (shouldGuaranteeTCO(CallConv,
3340 MF.getTarget().Options.GuaranteedTailCallOpt))
3341 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3342
3343 // If the function takes variable number of arguments, make a frame index for
3344 // the start of the first vararg value... for expansion of llvm.va_start. We
3345 // can skip this if there are no va_start calls.
3346 if (MFI.hasVAStart() &&
3347 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3348 CallConv != CallingConv::X86_ThisCall))) {
3349 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3350 }
3351
3352 // Figure out if XMM registers are in use.
3353 assert(!(Subtarget.useSoftFloat() &&((!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute
::NoImplicitFloat)) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3355, __PRETTY_FUNCTION__))
3354 F.hasFnAttribute(Attribute::NoImplicitFloat)) &&((!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute
::NoImplicitFloat)) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3355, __PRETTY_FUNCTION__))
3355 "SSE register cannot be used when SSE is disabled!")((!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute
::NoImplicitFloat)) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(Subtarget.useSoftFloat() && F.hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3355, __PRETTY_FUNCTION__))
;
3356
3357 // 64-bit calling conventions support varargs and register parameters, so we
3358 // have to do extra work to spill them in the prologue.
3359 if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3360 // Find the first unallocated argument registers.
3361 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3362 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3363 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3364 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3365 assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&((!(NumXMMRegs && !Subtarget.hasSSE1()) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(NumXMMRegs && !Subtarget.hasSSE1()) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3366, __PRETTY_FUNCTION__))
3366 "SSE register cannot be used when SSE is disabled!")((!(NumXMMRegs && !Subtarget.hasSSE1()) && "SSE register cannot be used when SSE is disabled!"
) ? static_cast<void> (0) : __assert_fail ("!(NumXMMRegs && !Subtarget.hasSSE1()) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3366, __PRETTY_FUNCTION__))
;
3367
3368 // Gather all the live in physical registers.
3369 SmallVector<SDValue, 6> LiveGPRs;
3370 SmallVector<SDValue, 8> LiveXMMRegs;
3371 SDValue ALVal;
3372 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3373 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3374 LiveGPRs.push_back(
3375 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3376 }
3377 if (!ArgXMMs.empty()) {
3378 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3379 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3380 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3381 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3382 LiveXMMRegs.push_back(
3383 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3384 }
3385 }
3386
3387 if (IsWin64) {
3388 // Get to the caller-allocated home save location. Add 8 to account
3389 // for the return address.
3390 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3391 FuncInfo->setRegSaveFrameIndex(
3392 MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3393 // Fixup to set vararg frame on shadow area (4 x i64).
3394 if (NumIntRegs < 4)
3395 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3396 } else {
3397 // For X86-64, if there are vararg parameters that are passed via
3398 // registers, then we must store them to their spots on the stack so
3399 // they may be loaded by dereferencing the result of va_next.
3400 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3401 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3402 FuncInfo->setRegSaveFrameIndex(MFI.CreateStackObject(
3403 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3404 }
3405
3406 // Store the integer parameter registers.
3407 SmallVector<SDValue, 8> MemOps;
3408 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3409 getPointerTy(DAG.getDataLayout()));
3410 unsigned Offset = FuncInfo->getVarArgsGPOffset();
3411 for (SDValue Val : LiveGPRs) {
3412 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3413 RSFIN, DAG.getIntPtrConstant(Offset, dl));
3414 SDValue Store =
3415 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3416 MachinePointerInfo::getFixedStack(
3417 DAG.getMachineFunction(),
3418 FuncInfo->getRegSaveFrameIndex(), Offset));
3419 MemOps.push_back(Store);
3420 Offset += 8;
3421 }
3422
3423 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3424 // Now store the XMM (fp + vector) parameter registers.
3425 SmallVector<SDValue, 12> SaveXMMOps;
3426 SaveXMMOps.push_back(Chain);
3427 SaveXMMOps.push_back(ALVal);
3428 SaveXMMOps.push_back(DAG.getIntPtrConstant(
3429 FuncInfo->getRegSaveFrameIndex(), dl));
3430 SaveXMMOps.push_back(DAG.getIntPtrConstant(
3431 FuncInfo->getVarArgsFPOffset(), dl));
3432 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3433 LiveXMMRegs.end());
3434 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
3435 MVT::Other, SaveXMMOps));
3436 }
3437
3438 if (!MemOps.empty())
3439 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3440 }
3441
3442 if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3443 // Find the largest legal vector type.
3444 MVT VecVT = MVT::Other;
3445 // FIXME: Only some x86_32 calling conventions support AVX512.
3446 if (Subtarget.useAVX512Regs() &&
3447 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3448 CallConv == CallingConv::Intel_OCL_BI)))
3449 VecVT = MVT::v16f32;
3450 else if (Subtarget.hasAVX())
3451 VecVT = MVT::v8f32;
3452 else if (Subtarget.hasSSE2())
3453 VecVT = MVT::v4f32;
3454
3455 // We forward some GPRs and some vector types.
3456 SmallVector<MVT, 2> RegParmTypes;
3457 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3458 RegParmTypes.push_back(IntVT);
3459 if (VecVT != MVT::Other)
3460 RegParmTypes.push_back(VecVT);
3461
3462 // Compute the set of forwarded registers. The rest are scratch.
3463 SmallVectorImpl<ForwardedRegister> &Forwards =
3464 FuncInfo->getForwardedMustTailRegParms();
3465 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3466
3467 // Conservatively forward AL on x86_64, since it might be used for varargs.
3468 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3469 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3470 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3471 }
3472
3473 // Copy all forwards from physical to virtual registers.
3474 for (ForwardedRegister &FR : Forwards) {
3475 // FIXME: Can we use a less constrained schedule?
3476 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, FR.VReg, FR.VT);
3477 FR.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(FR.VT));
3478 Chain = DAG.getCopyToReg(Chain, dl, FR.VReg, RegVal);
3479 }
3480 }
3481
3482 // Some CCs need callee pop.
3483 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3484 MF.getTarget().Options.GuaranteedTailCallOpt)) {
3485 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3486 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3487 // X86 interrupts must pop the error code (and the alignment padding) if
3488 // present.
3489 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3490 } else {
3491 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3492 // If this is an sret function, the return should pop the hidden pointer.
3493 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3494 !Subtarget.getTargetTriple().isOSMSVCRT() &&
3495 argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3496 FuncInfo->setBytesToPopOnReturn(4);
3497 }
3498
3499 if (!Is64Bit) {
3500 // RegSaveFrameIndex is X86-64 only.
3501 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3502 if (CallConv == CallingConv::X86_FastCall ||
3503 CallConv == CallingConv::X86_ThisCall)
3504 // fastcc functions can't have varargs.
3505 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3506 }
3507
3508 FuncInfo->setArgumentStackSize(StackSize);
3509
3510 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3511 EHPersonality Personality = classifyEHPersonality(F.getPersonalityFn());
3512 if (Personality == EHPersonality::CoreCLR) {
3513 assert(Is64Bit)((Is64Bit) ? static_cast<void> (0) : __assert_fail ("Is64Bit"
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3513, __PRETTY_FUNCTION__))
;
3514 // TODO: Add a mechanism to frame lowering that will allow us to indicate
3515 // that we'd prefer this slot be allocated towards the bottom of the frame
3516 // (i.e. near the stack pointer after allocating the frame). Every
3517 // funclet needs a copy of this slot in its (mostly empty) frame, and the
3518 // offset from the bottom of this and each funclet's frame must be the
3519 // same, so the size of funclets' (mostly empty) frames is dictated by
3520 // how far this slot is from the bottom (since they allocate just enough
3521 // space to accommodate holding this slot at the correct offset).
3522 int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3523 EHInfo->PSPSymFrameIdx = PSPSymFI;
3524 }
3525 }
3526
3527 if (CallConv == CallingConv::X86_RegCall ||
3528 F.hasFnAttribute("no_caller_saved_registers")) {
3529 MachineRegisterInfo &MRI = MF.getRegInfo();
3530 for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3531 MRI.disableCalleeSavedRegister(Pair.first);
3532 }
3533
3534 return Chain;
3535}
3536
3537SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3538 SDValue Arg, const SDLoc &dl,
3539 SelectionDAG &DAG,
3540 const CCValAssign &VA,
3541 ISD::ArgFlagsTy Flags) const {
3542 unsigned LocMemOffset = VA.getLocMemOffset();
3543 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3544 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3545 StackPtr, PtrOff);
3546 if (Flags.isByVal())
3547 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3548
3549 return DAG.getStore(
3550 Chain, dl, Arg, PtrOff,
3551 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3552}
3553
3554/// Emit a load of return address if tail call
3555/// optimization is performed and it is required.
3556SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3557 SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3558 bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3559 // Adjust the Return address stack slot.
3560 EVT VT = getPointerTy(DAG.getDataLayout());
3561 OutRetAddr = getReturnAddressFrameIndex(DAG);
3562
3563 // Load the "old" Return address.
3564 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3565 return SDValue(OutRetAddr.getNode(), 1);
3566}
3567
3568/// Emit a store of the return address if tail call
3569/// optimization is performed and it is required (FPDiff!=0).
3570static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3571 SDValue Chain, SDValue RetAddrFrIdx,
3572 EVT PtrVT, unsigned SlotSize,
3573 int FPDiff, const SDLoc &dl) {
3574 // Store the return address to the appropriate stack slot.
3575 if (!FPDiff) return Chain;
3576 // Calculate the new stack slot for the return address.
3577 int NewReturnAddrFI =
3578 MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3579 false);
3580 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3581 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3582 MachinePointerInfo::getFixedStack(
3583 DAG.getMachineFunction(), NewReturnAddrFI));
3584 return Chain;
3585}
3586
3587/// Returns a vector_shuffle mask for an movs{s|d}, movd
3588/// operation of specified width.
3589static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3590 SDValue V2) {
3591 unsigned NumElems = VT.getVectorNumElements();
3592 SmallVector<int, 8> Mask;
3593 Mask.push_back(NumElems);
3594 for (unsigned i = 1; i != NumElems; ++i)
3595 Mask.push_back(i);
3596 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3597}
3598
3599SDValue
3600X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3601 SmallVectorImpl<SDValue> &InVals) const {
3602 SelectionDAG &DAG = CLI.DAG;
3603 SDLoc &dl = CLI.DL;
3604 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3605 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3606 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3607 SDValue Chain = CLI.Chain;
3608 SDValue Callee = CLI.Callee;
3609 CallingConv::ID CallConv = CLI.CallConv;
3610 bool &isTailCall = CLI.IsTailCall;
3611 bool isVarArg = CLI.IsVarArg;
3612
3613 MachineFunction &MF = DAG.getMachineFunction();
3614 bool Is64Bit = Subtarget.is64Bit();
3615 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3616 StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3617 bool IsSibcall = false;
3618 bool IsGuaranteeTCO = MF.getTarget().Options.GuaranteedTailCallOpt ||
3619 CallConv == CallingConv::Tail;
3620 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3621 auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
3622 const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3623 const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3624 bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3625 (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3626 const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CS.getInstruction());
3627 bool HasNoCfCheck =
3628 (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3629 const Module *M = MF.getMMI().getModule();
3630 Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3631
3632 MachineFunction::CallSiteInfo CSInfo;
3633
3634 if (CallConv == CallingConv::X86_INTR)
3635 report_fatal_error("X86 interrupts may not be called directly");
3636
3637 if (Attr.getValueAsString() == "true")
3638 isTailCall = false;
3639
3640 if (Subtarget.isPICStyleGOT() && !IsGuaranteeTCO) {
3641 // If we are using a GOT, disable tail calls to external symbols with
3642 // default visibility. Tail calling such a symbol requires using a GOT
3643 // relocation, which forces early binding of the symbol. This breaks code
3644 // that require lazy function symbol resolution. Using musttail or
3645 // GuaranteedTailCallOpt will override this.
3646 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3647 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3648 G->getGlobal()->hasDefaultVisibility()))
3649 isTailCall = false;
3650 }
3651
3652 bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3653 if (IsMustTail) {
3654 // Force this to be a tail call. The verifier rules are enough to ensure
3655 // that we can lower this successfully without moving the return address
3656 // around.
3657 isTailCall = true;
3658 } else if (isTailCall) {
3659 // Check if it's really possible to do a tail call.
3660 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3661 isVarArg, SR != NotStructReturn,
3662 MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3663 Outs, OutVals, Ins, DAG);
3664
3665 // Sibcalls are automatically detected tailcalls which do not require
3666 // ABI changes.
3667 if (!IsGuaranteeTCO && isTailCall)
3668 IsSibcall = true;
3669
3670 if (isTailCall)
3671 ++NumTailCalls;
3672 }
3673
3674 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&((!(isVarArg && canGuaranteeTCO(CallConv)) &&
"Var args not supported with calling convention fastcc, ghc or hipe"
) ? static_cast<void> (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling convention fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3675, __PRETTY_FUNCTION__))
3675 "Var args not supported with calling convention fastcc, ghc or hipe")((!(isVarArg && canGuaranteeTCO(CallConv)) &&
"Var args not supported with calling convention fastcc, ghc or hipe"
) ? static_cast<void> (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling convention fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3675, __PRETTY_FUNCTION__))
;
3676
3677 // Analyze operands of the call, assigning locations to each operand.
3678 SmallVector<CCValAssign, 16> ArgLocs;
3679 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3680
3681 // Allocate shadow area for Win64.
3682 if (IsWin64)
3683 CCInfo.AllocateStack(32, 8);
3684
3685 CCInfo.AnalyzeArguments(Outs, CC_X86);
3686
3687 // In vectorcall calling convention a second pass is required for the HVA
3688 // types.
3689 if (CallingConv::X86_VectorCall == CallConv) {
3690 CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3691 }
3692
3693 // Get a count of how many bytes are to be pushed on the stack.
3694 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3695 if (IsSibcall)
3696 // This is a sibcall. The memory operands are available in caller's
3697 // own caller's stack.
3698 NumBytes = 0;
3699 else if (IsGuaranteeTCO && canGuaranteeTCO(CallConv))
3700 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3701
3702 int FPDiff = 0;
3703 if (isTailCall && !IsSibcall && !IsMustTail) {
3704 // Lower arguments at fp - stackoffset + fpdiff.
3705 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3706
3707 FPDiff = NumBytesCallerPushed - NumBytes;
3708
3709 // Set the delta of movement of the returnaddr stackslot.
3710 // But only set if delta is greater than previous delta.
3711 if (FPDiff < X86Info->getTCReturnAddrDelta())
3712 X86Info->setTCReturnAddrDelta(FPDiff);
3713 }
3714
3715 unsigned NumBytesToPush = NumBytes;
3716 unsigned NumBytesToPop = NumBytes;
3717
3718 // If we have an inalloca argument, all stack space has already been allocated
3719 // for us and be right at the top of the stack. We don't support multiple
3720 // arguments passed in memory when using inalloca.
3721 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3722 NumBytesToPush = 0;
3723 if (!ArgLocs.back().isMemLoc())
3724 report_fatal_error("cannot use inalloca attribute on a register "
3725 "parameter");
3726 if (ArgLocs.back().getLocMemOffset() != 0)
3727 report_fatal_error("any parameter with the inalloca attribute must be "
3728 "the only memory argument");
3729 }
3730
3731 if (!IsSibcall)
3732 Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3733 NumBytes - NumBytesToPush, dl);
3734
3735 SDValue RetAddrFrIdx;
3736 // Load return address for tail calls.
3737 if (isTailCall && FPDiff)
3738 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3739 Is64Bit, FPDiff, dl);
3740
3741 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3742 SmallVector<SDValue, 8> MemOpChains;
3743 SDValue StackPtr;
3744
3745 // The next loop assumes that the locations are in the same order of the
3746 // input arguments.
3747 assert(isSortedByValueNo(ArgLocs) &&((isSortedByValueNo(ArgLocs) && "Argument Location list must be sorted before lowering"
) ? static_cast<void> (0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3748, __PRETTY_FUNCTION__))
3748 "Argument Location list must be sorted before lowering")((isSortedByValueNo(ArgLocs) && "Argument Location list must be sorted before lowering"
) ? static_cast<void> (0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3748, __PRETTY_FUNCTION__))
;
3749
3750 // Walk the register/memloc assignments, inserting copies/loads. In the case
3751 // of tail call optimization arguments are handle later.
3752 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3753 for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3754 ++I, ++OutIndex) {
3755 assert(OutIndex < Outs.size() && "Invalid Out index")((OutIndex < Outs.size() && "Invalid Out index") ?
static_cast<void> (0) : __assert_fail ("OutIndex < Outs.size() && \"Invalid Out index\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3755, __PRETTY_FUNCTION__))
;
3756 // Skip inalloca arguments, they have already been written.
3757 ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3758 if (Flags.isInAlloca())
3759 continue;
3760
3761 CCValAssign &VA = ArgLocs[I];
3762 EVT RegVT = VA.getLocVT();
3763 SDValue Arg = OutVals[OutIndex];
3764 bool isByVal = Flags.isByVal();
3765
3766 // Promote the value if needed.
3767 switch (VA.getLocInfo()) {
3768 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3768)
;
3769 case CCValAssign::Full: break;
3770 case CCValAssign::SExt:
3771 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3772 break;
3773 case CCValAssign::ZExt:
3774 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3775 break;
3776 case CCValAssign::AExt:
3777 if (Arg.getValueType().isVector() &&
3778 Arg.getValueType().getVectorElementType() == MVT::i1)
3779 Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
3780 else if (RegVT.is128BitVector()) {
3781 // Special case: passing MMX values in XMM registers.
3782 Arg = DAG.getBitcast(MVT::i64, Arg);
3783 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3784 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3785 } else
3786 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3787 break;
3788 case CCValAssign::BCvt:
3789 Arg = DAG.getBitcast(RegVT, Arg);
3790 break;
3791 case CCValAssign::Indirect: {
3792 if (isByVal) {
3793 // Memcpy the argument to a temporary stack slot to prevent
3794 // the caller from seeing any modifications the callee may make
3795 // as guaranteed by the `byval` attribute.
3796 int FrameIdx = MF.getFrameInfo().CreateStackObject(
3797 Flags.getByValSize(), std::max(16, (int)Flags.getByValAlign()),
3798 false);
3799 SDValue StackSlot =
3800 DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
3801 Chain =
3802 CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
3803 // From now on treat this as a regular pointer
3804 Arg = StackSlot;
3805 isByVal = false;
3806 } else {
3807 // Store the argument.
3808 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3809 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3810 Chain = DAG.getStore(
3811 Chain, dl, Arg, SpillSlot,
3812 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3813 Arg = SpillSlot;
3814 }
3815 break;
3816 }
3817 }
3818
3819 if (VA.needsCustom()) {
3820 assert(VA.getValVT() == MVT::v64i1 &&((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3821, __PRETTY_FUNCTION__))
3821 "Currently the only custom case is when we split v64i1 to 2 regs")((VA.getValVT() == MVT::v64i1 && "Currently the only custom case is when we split v64i1 to 2 regs"
) ? static_cast<void> (0) : __assert_fail ("VA.getValVT() == MVT::v64i1 && \"Currently the only custom case is when we split v64i1 to 2 regs\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3821, __PRETTY_FUNCTION__))
;
3822 // Split v64i1 value into two registers
3823 Passv64i1ArgInRegs(dl, DAG, Arg, RegsToPass, VA, ArgLocs[++I], Subtarget);
3824 } else if (VA.isRegLoc()) {
3825 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3826 const TargetOptions &Options = DAG.getTarget().Options;
3827 if (Options.EnableDebugEntryValues)
3828 CSInfo.emplace_back(VA.getLocReg(), I);
3829 if (isVarArg && IsWin64) {
3830 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3831 // shadow reg if callee is a varargs function.
3832 unsigned ShadowReg = 0;
3833 switch (VA.getLocReg()) {
3834 case X86::XMM0: ShadowReg = X86::RCX; break;
3835 case X86::XMM1: ShadowReg = X86::RDX; break;
3836 case X86::XMM2: ShadowReg = X86::R8; break;
3837 case X86::XMM3: ShadowReg = X86::R9; break;
3838 }
3839 if (ShadowReg)
3840 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3841 }
3842 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3843 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3843, __PRETTY_FUNCTION__))
;
3844 if (!StackPtr.getNode())
3845 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3846 getPointerTy(DAG.getDataLayout()));
3847 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3848 dl, DAG, VA, Flags));
3849 }
3850 }
3851
3852 if (!MemOpChains.empty())
3853 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3854
3855 if (Subtarget.isPICStyleGOT()) {
3856 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3857 // GOT pointer.
3858 if (!isTailCall) {
3859 RegsToPass.push_back(std::make_pair(
3860 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3861 getPointerTy(DAG.getDataLayout()))));
3862 } else {
3863 // If we are tail calling and generating PIC/GOT style code load the
3864 // address of the callee into ECX. The value in ecx is used as target of
3865 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3866 // for tail calls on PIC/GOT architectures. Normally we would just put the
3867 // address of GOT into ebx and then call target@PLT. But for tail calls
3868 // ebx would be restored (since ebx is callee saved) before jumping to the
3869 // target@PLT.
3870
3871 // Note: The actual moving to ECX is done further down.
3872 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3873 if (G && !G->getGlobal()->hasLocalLinkage() &&
3874 G->getGlobal()->hasDefaultVisibility())
3875 Callee = LowerGlobalAddress(Callee, DAG);
3876 else if (isa<ExternalSymbolSDNode>(Callee))
3877 Callee = LowerExternalSymbol(Callee, DAG);
3878 }
3879 }
3880
3881 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3882 // From AMD64 ABI document:
3883 // For calls that may call functions that use varargs or stdargs
3884 // (prototype-less calls or calls to functions containing ellipsis (...) in
3885 // the declaration) %al is used as hidden argument to specify the number
3886 // of SSE registers used. The contents of %al do not need to match exactly
3887 // the number of registers, but must be an ubound on the number of SSE
3888 // registers used and is in the range 0 - 8 inclusive.
3889
3890 // Count the number of XMM registers allocated.
3891 static const MCPhysReg XMMArgRegs[] = {
3892 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3893 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3894 };
3895 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3896 assert((Subtarget.hasSSE1() || !NumXMMRegs)(((Subtarget.hasSSE1() || !NumXMMRegs) && "SSE registers cannot be used when SSE is disabled"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3897, __PRETTY_FUNCTION__))
3897 && "SSE registers cannot be used when SSE is disabled")(((Subtarget.hasSSE1() || !NumXMMRegs) && "SSE registers cannot be used when SSE is disabled"
) ? static_cast<void> (0) : __assert_fail ("(Subtarget.hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3897, __PRETTY_FUNCTION__))
;
3898
3899 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3900 DAG.getConstant(NumXMMRegs, dl,
3901 MVT::i8)));
3902 }
3903
3904 if (isVarArg && IsMustTail) {
3905 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3906 for (const auto &F : Forwards) {
3907 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3908 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3909 }
3910 }
3911
3912 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3913 // don't need this because the eligibility check rejects calls that require
3914 // shuffling arguments passed in memory.
3915 if (!IsSibcall && isTailCall) {
3916 // Force all the incoming stack arguments to be loaded from the stack
3917 // before any new outgoing arguments are stored to the stack, because the
3918 // outgoing stack slots may alias the incoming argument stack slots, and
3919 // the alias isn't otherwise explicit. This is slightly more conservative
3920 // than necessary, because it means that each store effectively depends
3921 // on every argument instead of just those arguments it would clobber.
3922 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3923
3924 SmallVector<SDValue, 8> MemOpChains2;
3925 SDValue FIN;
3926 int FI = 0;
3927 for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
3928 ++I, ++OutsIndex) {
3929 CCValAssign &VA = ArgLocs[I];
3930
3931 if (VA.isRegLoc()) {
3932 if (VA.needsCustom()) {
3933 assert((CallConv == CallingConv::X86_RegCall) &&(((CallConv == CallingConv::X86_RegCall) && "Expecting custom case only in regcall calling convention"
) ? static_cast<void> (0) : __assert_fail ("(CallConv == CallingConv::X86_RegCall) && \"Expecting custom case only in regcall calling convention\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3934, __PRETTY_FUNCTION__))
3934 "Expecting custom case only in regcall calling convention")(((CallConv == CallingConv::X86_RegCall) && "Expecting custom case only in regcall calling convention"
) ? static_cast<void> (0) : __assert_fail ("(CallConv == CallingConv::X86_RegCall) && \"Expecting custom case only in regcall calling convention\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3934, __PRETTY_FUNCTION__))
;
3935 // This means that we are in special case where one argument was
3936 // passed through two register locations - Skip the next location
3937 ++I;
3938 }
3939
3940 continue;
3941 }
3942
3943 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3943, __PRETTY_FUNCTION__))
;
3944 SDValue Arg = OutVals[OutsIndex];
3945 ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
3946 // Skip inalloca arguments. They don't require any work.
3947 if (Flags.isInAlloca())
3948 continue;
3949 // Create frame index.
3950 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3951 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3952 FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3953 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3954
3955 if (Flags.isByVal()) {
3956 // Copy relative to framepointer.
3957 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3958 if (!StackPtr.getNode())
3959 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3960 getPointerTy(DAG.getDataLayout()));
3961 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3962 StackPtr, Source);
3963
3964 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3965 ArgChain,
3966 Flags, DAG, dl));
3967 } else {
3968 // Store relative to framepointer.
3969 MemOpChains2.push_back(DAG.getStore(
3970 ArgChain, dl, Arg, FIN,
3971 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
3972 }
3973 }
3974
3975 if (!MemOpChains2.empty())
3976 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3977
3978 // Store the return address to the appropriate stack slot.
3979 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3980 getPointerTy(DAG.getDataLayout()),
3981 RegInfo->getSlotSize(), FPDiff, dl);
3982 }
3983
3984 // Build a sequence of copy-to-reg nodes chained together with token chain
3985 // and flag operands which copy the outgoing args into registers.
3986 SDValue InFlag;
3987 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3988 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3989 RegsToPass[i].second, InFlag);
3990 InFlag = Chain.getValue(1);
3991 }
3992
3993 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3994 assert(Is64Bit && "Large code model is only legal in 64-bit mode.")((Is64Bit && "Large code model is only legal in 64-bit mode."
) ? static_cast<void> (0) : __assert_fail ("Is64Bit && \"Large code model is only legal in 64-bit mode.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 3994, __PRETTY_FUNCTION__))
;
3995 // In the 64-bit large code model, we have to make all calls
3996 // through a register, since the call instruction's 32-bit
3997 // pc-relative offset may not be large enough to hold the whole
3998 // address.
3999 } else if (Callee->getOpcode() == ISD::GlobalAddress ||
4000 Callee->getOpcode() == ISD::ExternalSymbol) {
4001 // Lower direct calls to global addresses and external symbols. Setting
4002 // ForCall to true here has the effect of removing WrapperRIP when possible
4003 // to allow direct calls to be selected without first materializing the
4004 // address into a register.
4005 Callee = LowerGlobalOrExternal(Callee, DAG, /*ForCall=*/true);
4006 } else if (Subtarget.isTarget64BitILP32() &&
4007 Callee->getValueType(0) == MVT::i32) {
4008 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
4009 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
4010 }
4011
4012 // Returns a chain & a flag for retval copy to use.
4013 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
4014 SmallVector<SDValue, 8> Ops;
4015
4016 if (!IsSibcall && isTailCall) {
4017 Chain = DAG.getCALLSEQ_END(Chain,
4018 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4019 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4020 InFlag = Chain.getValue(1);
4021 }
4022
4023 Ops.push_back(Chain);
4024 Ops.push_back(Callee);
4025
4026 if (isTailCall)
4027 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
4028
4029 // Add argument registers to the end of the list so that they are known live
4030 // into the call.
4031 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4032 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4033 RegsToPass[i].second.getValueType()));
4034
4035 // Add a register mask operand representing the call-preserved registers.
4036 // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists) then we
4037 // set X86_INTR calling convention because it has the same CSR mask
4038 // (same preserved registers).
4039 const uint32_t *Mask = RegInfo->getCallPreservedMask(
4040 MF, HasNCSR ? (CallingConv::ID)CallingConv::X86_INTR : CallConv);
4041 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-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 4041, __PRETTY_FUNCTION__))
;
4042
4043 // If this is an invoke in a 32-bit function using a funclet-based
4044 // personality, assume the function clobbers all registers. If an exception
4045 // is thrown, the runtime will not restore CSRs.
4046 // FIXME: Model this more precisely so that we can register allocate across
4047 // the normal edge and spill and fill across the exceptional edge.
4048 if (!Is64Bit && CLI.CS && CLI.CS.isInvoke()) {
4049 const Function &CallerFn = MF.getFunction();
4050 EHPersonality Pers =
4051 CallerFn.hasPersonalityFn()
4052 ? classifyEHPersonality(CallerFn.getPersonalityFn())
4053 : EHPersonality::Unknown;
4054 if (isFuncletEHPersonality(Pers))
4055 Mask = RegInfo->getNoPreservedMask();
4056 }
4057
4058 // Define a new register mask from the existing mask.
4059 uint32_t *RegMask = nullptr;
4060
4061 // In some calling conventions we need to remove the used physical registers
4062 // from the reg mask.
4063 if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
4064 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4065
4066 // Allocate a new Reg Mask and copy Mask.
4067 RegMask = MF.allocateRegMask();
4068 unsigned RegMaskSize = MachineOperand::getRegMaskSize(TRI->getNumRegs());
4069 memcpy(RegMask, Mask, sizeof(RegMask[0]) * RegMaskSize);
4070
4071 // Make sure all sub registers of the argument registers are reset
4072 // in the RegMask.
4073 for (auto const &RegPair : RegsToPass)
4074 for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
4075 SubRegs.isValid(); ++SubRegs)
4076 RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
4077
4078 // Create the RegMask Operand according to our updated mask.
4079 Ops.push_back(DAG.getRegisterMask(RegMask));
4080 } else {
4081 // Create the RegMask Operand according to the static mask.
4082 Ops.push_back(DAG.getRegisterMask(Mask));
4083 }
4084
4085 if (InFlag.getNode())
4086 Ops.push_back(InFlag);
4087
4088 if (isTailCall) {
4089 // We used to do:
4090 //// If this is the first return lowered for this function, add the regs
4091 //// to the liveout set for the function.
4092 // This isn't right, although it's probably harmless on x86; liveouts
4093 // should be computed from returns not tail calls. Consider a void
4094 // function making a tail call to a function returning int.
4095 MF.getFrameInfo().setHasTailCall();
4096 SDValue Ret = DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
4097 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
4098 return Ret;
4099 }
4100
4101 if (HasNoCfCheck && IsCFProtectionSupported) {
4102 Chain = DAG.getNode(X86ISD::NT_CALL, dl, NodeTys, Ops);
4103 } else {
4104 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
4105 }
4106 InFlag = Chain.getValue(1);
4107 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
4108
4109 // Save heapallocsite metadata.
4110 if (CLI.CS)
4111 if (MDNode *HeapAlloc = CLI.CS->getMetadata("heapallocsite"))
4112 DAG.addHeapAllocSite(Chain.getNode(), HeapAlloc);
4113
4114 // Create the CALLSEQ_END node.
4115 unsigned NumBytesForCalleeToPop;
4116 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
4117 DAG.getTarget().Options.GuaranteedTailCallOpt))
4118 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
4119 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
4120 !Subtarget.getTargetTriple().isOSMSVCRT() &&
4121 SR == StackStructReturn)
4122 // If this is a call to a struct-return function, the callee
4123 // pops the hidden struct pointer, so we have to push it back.
4124 // This is common for Darwin/X86, Linux & Mingw32 targets.
4125 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
4126 NumBytesForCalleeToPop = 4;
4127 else
4128 NumBytesForCalleeToPop = 0; // Callee pops nothing.
4129
4130 if (CLI.DoesNotReturn && !getTargetMachine().Options.TrapUnreachable) {
4131 // No need to reset the stack after the call if the call doesn't return. To
4132 // make the MI verify, we'll pretend the callee does it for us.
4133 NumBytesForCalleeToPop = NumBytes;
4134 }
4135
4136 // Returns a flag for retval copy to use.
4137 if (!IsSibcall) {
4138 Chain = DAG.getCALLSEQ_END(Chain,
4139 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
4140 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
4141 true),
4142 InFlag, dl);
4143 InFlag = Chain.getValue(1);
4144 }
4145
4146 // Handle result values, copying them out of physregs into vregs that we
4147 // return.
4148 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
4149 InVals, RegMask);
4150}
4151
4152//===----------------------------------------------------------------------===//
4153// Fast Calling Convention (tail call) implementation
4154//===----------------------------------------------------------------------===//
4155
4156// Like std call, callee cleans arguments, convention except that ECX is
4157// reserved for storing the tail called function address. Only 2 registers are
4158// free for argument passing (inreg). Tail call optimization is performed
4159// provided:
4160// * tailcallopt is enabled
4161// * caller/callee are fastcc
4162// On X86_64 architecture with GOT-style position independent code only local
4163// (within module) calls are supported at the moment.
4164// To keep the stack aligned according to platform abi the function
4165// GetAlignedArgumentStackSize ensures that argument delta is always multiples
4166// of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
4167// If a tail called function callee has more arguments than the caller the
4168// caller needs to make sure that there is room to move the RETADDR to. This is
4169// achieved by reserving an area the size of the argument delta right after the
4170// original RETADDR, but before the saved framepointer or the spilled registers
4171// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
4172// stack layout:
4173// arg1
4174// arg2
4175// RETADDR
4176// [ new RETADDR
4177// move area ]
4178// (possible EBP)
4179// ESI
4180// EDI
4181// local1 ..
4182
4183/// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
4184/// requirement.
4185unsigned
4186X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
4187 SelectionDAG& DAG) const {
4188 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4189 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
4190 unsigned StackAlignment = TFI.getStackAlignment();
4191 uint64_t AlignMask = StackAlignment - 1;
4192 int64_t Offset = StackSize;
4193 unsigned SlotSize = RegInfo->getSlotSize();
4194 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
4195 // Number smaller than 12 so just add the difference.
4196 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
4197 } else {
4198 // Mask out lower bits, add stackalignment once plus the 12 bytes.
4199 Offset = ((~AlignMask) & Offset) + StackAlignment +
4200 (StackAlignment-SlotSize);
4201 }
4202 return Offset;
4203}
4204
4205/// Return true if the given stack call argument is already available in the
4206/// same position (relatively) of the caller's incoming argument stack.
4207static
4208bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
4209 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
4210 const X86InstrInfo *TII, const CCValAssign &VA) {
4211 unsigned Bytes = Arg.getValueSizeInBits() / 8;
4212
4213 for (;;) {
4214 // Look through nodes that don't alter the bits of the incoming value.
4215 unsigned Op = Arg.getOpcode();
4216 if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
4217 Arg = Arg.getOperand(0);
4218 continue;
4219 }
4220 if (Op == ISD::TRUNCATE) {
4221 const SDValue &TruncInput = Arg.getOperand(0);
4222 if (TruncInput.getOpcode() == ISD::AssertZext &&
4223 cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
4224 Arg.getValueType()) {
4225 Arg = TruncInput.getOperand(0);
4226 continue;
4227 }
4228 }
4229 break;
4230 }
4231
4232 int FI = INT_MAX2147483647;
4233 if (Arg.getOpcode() == ISD::CopyFromReg) {
4234 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
4235 if (!Register::isVirtualRegister(VR))
4236 return false;
4237 MachineInstr *Def = MRI->getVRegDef(VR);
4238 if (!Def)
4239 return false;
4240 if (!Flags.isByVal()) {
4241 if (!TII->isLoadFromStackSlot(*Def, FI))
4242 return false;
4243 } else {
4244 unsigned Opcode = Def->getOpcode();
4245 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
4246 Opcode == X86::LEA64_32r) &&
4247 Def->getOperand(1).isFI()) {
4248 FI = Def->getOperand(1).getIndex();
4249 Bytes = Flags.getByValSize();
4250 } else
4251 return false;
4252 }
4253 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
4254 if (Flags.isByVal())
4255 // ByVal argument is passed in as a pointer but it's now being
4256 // dereferenced. e.g.
4257 // define @foo(%struct.X* %A) {
4258 // tail call @bar(%struct.X* byval %A)
4259 // }
4260 return false;
4261 SDValue Ptr = Ld->getBasePtr();
4262 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
4263 if (!FINode)
4264 return false;
4265 FI = FINode->getIndex();
4266 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
4267 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
4268 FI = FINode->getIndex();
4269 Bytes = Flags.getByValSize();
4270 } else
4271 return false;
4272
4273 assert(FI != INT_MAX)((FI != 2147483647) ? static_cast<void> (0) : __assert_fail
("FI != INT_MAX", "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 4273, __PRETTY_FUNCTION__))
;
4274 if (!MFI.isFixedObjectIndex(FI))
4275 return false;
4276
4277 if (Offset != MFI.getObjectOffset(FI))
4278 return false;
4279
4280 // If this is not byval, check that the argument stack object is immutable.
4281 // inalloca and argument copy elision can create mutable argument stack
4282 // objects. Byval objects can be mutated, but a byval call intends to pass the
4283 // mutated memory.
4284 if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
4285 return false;
4286
4287 if (VA.getLocVT().getSizeInBits() > Arg.getValueSizeInBits()) {
4288 // If the argument location is wider than the argument type, check that any
4289 // extension flags match.
4290 if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
4291 Flags.isSExt() != MFI.isObjectSExt(FI)) {
4292 return false;
4293 }
4294 }
4295
4296 return Bytes == MFI.getObjectSize(FI);
4297}
4298
4299/// Check whether the call is eligible for tail call optimization. Targets
4300/// that want to do tail call optimization should implement this function.
4301bool X86TargetLowering::IsEligibleForTailCallOptimization(
4302 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4303 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
4304 const SmallVectorImpl<ISD::OutputArg> &Outs,
4305 const SmallVectorImpl<SDValue> &OutVals,
4306 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4307 if (!mayTailCallThisCC(CalleeCC))
4308 return false;
4309
4310 // If -tailcallopt is specified, make fastcc functions tail-callable.
4311 MachineFunction &MF = DAG.getMachineFunction();
4312 const Function &CallerF = MF.getFunction();
4313
4314 // If the function return type is x86_fp80 and the callee return type is not,
4315 // then the FP_EXTEND of the call result is not a nop. It's not safe to
4316 // perform a tailcall optimization here.
4317 if (CallerF.getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
4318 return false;
4319
4320 CallingConv::ID CallerCC = CallerF.getCallingConv();
4321 bool CCMatch = CallerCC == CalleeCC;
4322 bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
4323 bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
4324 bool IsGuaranteeTCO = DAG.getTarget().Options.GuaranteedTailCallOpt ||
4325 CalleeCC == CallingConv::Tail;
4326
4327 // Win64 functions have extra shadow space for argument homing. Don't do the
4328 // sibcall if the caller and callee have mismatched expectations for this
4329 // space.
4330 if (IsCalleeWin64 != IsCallerWin64)
4331 return false;
4332
4333 if (IsGuaranteeTCO) {
4334 if (canGuaranteeTCO(CalleeCC) && CCMatch)
4335 return true;
4336 return false;
4337 }
4338
4339 // Look for obvious safe cases to perform tail call optimization that do not
4340 // require ABI changes. This is what gcc calls sibcall.
4341
4342 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
4343 // emit a special epilogue.
4344 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4345 if (RegInfo->needsStackRealignment(MF))
4346 return false;
4347
4348 // Also avoid sibcall optimization if either caller or callee uses struct
4349 // return semantics.
4350 if (isCalleeStructRet || isCallerStructRet)
4351 return false;
4352
4353 // Do not sibcall optimize vararg calls unless all arguments are passed via
4354 // registers.
4355 LLVMContext &C = *DAG.getContext();
4356 if (isVarArg && !Outs.empty()) {
4357 // Optimizing for varargs on Win64 is unlikely to be safe without
4358 // additional testing.
4359 if (IsCalleeWin64 || IsCallerWin64)
4360 return false;
4361
4362 SmallVector<CCValAssign, 16> ArgLocs;
4363 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4364
4365 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4366 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
4367 if (!ArgLocs[i].isRegLoc())
4368 return false;
4369 }
4370
4371 // If the call result is in ST0 / ST1, it needs to be popped off the x87
4372 // stack. Therefore, if it's not used by the call it is not safe to optimize
4373 // this into a sibcall.
4374 bool Unused = false;
4375 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4376 if (!Ins[i].Used) {
4377 Unused = true;
4378 break;
4379 }
4380 }
4381 if (Unused) {
4382 SmallVector<CCValAssign, 16> RVLocs;
4383 CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
4384 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
4385 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4386 CCValAssign &VA = RVLocs[i];
4387 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
4388 return false;
4389 }
4390 }
4391
4392 // Check that the call results are passed in the same way.
4393 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4394 RetCC_X86, RetCC_X86))
4395 return false;
4396 // The callee has to preserve all registers the caller needs to preserve.
4397 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4398 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4399 if (!CCMatch) {
4400 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4401 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4402 return false;
4403 }
4404
4405 unsigned StackArgsSize = 0;
4406
4407 // If the callee takes no arguments then go on to check the results of the
4408 // call.
4409 if (!Outs.empty()) {
4410 // Check if stack adjustment is needed. For now, do not do this if any
4411 // argument is passed on the stack.
4412 SmallVector<CCValAssign, 16> ArgLocs;
4413 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4414
4415 // Allocate shadow area for Win64
4416 if (IsCalleeWin64)
4417 CCInfo.AllocateStack(32, 8);
4418
4419 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4420 StackArgsSize = CCInfo.getNextStackOffset();
4421
4422 if (CCInfo.getNextStackOffset()) {
4423 // Check if the arguments are already laid out in the right way as
4424 // the caller's fixed stack objects.
4425 MachineFrameInfo &MFI = MF.getFrameInfo();
4426 const MachineRegisterInfo *MRI = &MF.getRegInfo();
4427 const X86InstrInfo *TII = Subtarget.getInstrInfo();
4428 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4429 CCValAssign &VA = ArgLocs[i];
4430 SDValue Arg = OutVals[i];
4431 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4432 if (VA.getLocInfo() == CCValAssign::Indirect)
4433 return false;
4434 if (!VA.isRegLoc()) {
4435 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
4436 MFI, MRI, TII, VA))
4437 return false;
4438 }
4439 }
4440 }
4441
4442 bool PositionIndependent = isPositionIndependent();
4443 // If the tailcall address may be in a register, then make sure it's
4444 // possible to register allocate for it. In 32-bit, the call address can
4445 // only target EAX, EDX, or ECX since the tail call must be scheduled after
4446 // callee-saved registers are restored. These happen to be the same
4447 // registers used to pass 'inreg' arguments so watch out for those.
4448 if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
4449 !isa<ExternalSymbolSDNode>(Callee)) ||
4450 PositionIndependent)) {
4451 unsigned NumInRegs = 0;
4452 // In PIC we need an extra register to formulate the address computation
4453 // for the callee.
4454 unsigned MaxInRegs = PositionIndependent ? 2 : 3;
4455
4456 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4457 CCValAssign &VA = ArgLocs[i];
4458 if (!VA.isRegLoc())
4459 continue;
4460 Register Reg = VA.getLocReg();
4461 switch (Reg) {
4462 default: break;
4463 case X86::EAX: case X86::EDX: case X86::ECX:
4464 if (++NumInRegs == MaxInRegs)
4465 return false;
4466 break;
4467 }
4468 }
4469 }
4470
4471 const MachineRegisterInfo &MRI = MF.getRegInfo();
4472 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4473 return false;
4474 }
4475
4476 bool CalleeWillPop =
4477 X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
4478 MF.getTarget().Options.GuaranteedTailCallOpt);
4479
4480 if (unsigned BytesToPop =
4481 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
4482 // If we have bytes to pop, the callee must pop them.
4483 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
4484 if (!CalleePopMatches)
4485 return false;
4486 } else if (CalleeWillPop && StackArgsSize > 0) {
4487 // If we don't have bytes to pop, make sure the callee doesn't pop any.
4488 return false;
4489 }
4490
4491 return true;
4492}
4493
4494FastISel *
4495X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
4496 const TargetLibraryInfo *libInfo) const {
4497 return X86::createFastISel(funcInfo, libInfo);
4498}
4499
4500//===----------------------------------------------------------------------===//
4501// Other Lowering Hooks
4502//===----------------------------------------------------------------------===//
4503
4504static bool MayFoldLoad(SDValue Op) {
4505 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
4506}
4507
4508static bool MayFoldIntoStore(SDValue Op) {
4509 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
4510}
4511
4512static bool MayFoldIntoZeroExtend(SDValue Op) {
4513 if (Op.hasOneUse()) {
4514 unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
4515 return (ISD::ZERO_EXTEND == Opcode);
4516 }
4517 return false;
4518}
4519
4520static bool isTargetShuffle(unsigned Opcode) {
4521 switch(Opcode) {
4522 default: return false;
4523 case X86ISD::BLENDI:
4524 case X86ISD::PSHUFB:
4525 case X86ISD::PSHUFD:
4526 case X86ISD::PSHUFHW:
4527 case X86ISD::PSHUFLW:
4528 case X86ISD::SHUFP:
4529 case X86ISD::INSERTPS:
4530 case X86ISD::EXTRQI:
4531 case X86ISD::INSERTQI:
4532 case X86ISD::PALIGNR:
4533 case X86ISD::VSHLDQ:
4534 case X86ISD::VSRLDQ:
4535 case X86ISD::MOVLHPS:
4536 case X86ISD::MOVHLPS:
4537 case X86ISD::MOVSHDUP:
4538 case X86ISD::MOVSLDUP:
4539 case X86ISD::MOVDDUP:
4540 case X86ISD::MOVSS:
4541 case X86ISD::MOVSD:
4542 case X86ISD::UNPCKL:
4543 case X86ISD::UNPCKH:
4544 case X86ISD::VBROADCAST:
4545 case X86ISD::VPERMILPI:
4546 case X86ISD::VPERMILPV:
4547 case X86ISD::VPERM2X128:
4548 case X86ISD::SHUF128:
4549 case X86ISD::VPERMIL2:
4550 case X86ISD::VPERMI:
4551 case X86ISD::VPPERM:
4552 case X86ISD::VPERMV:
4553 case X86ISD::VPERMV3:
4554 case X86ISD::VZEXT_MOVL:
4555 return true;
4556 }
4557}
4558
4559static bool isTargetShuffleVariableMask(unsigned Opcode) {
4560 switch (Opcode) {
4561 default: return false;
4562 // Target Shuffles.
4563 case X86ISD::PSHUFB:
4564 case X86ISD::VPERMILPV:
4565 case X86ISD::VPERMIL2:
4566 case X86ISD::VPPERM:
4567 case X86ISD::VPERMV:
4568 case X86ISD::VPERMV3:
4569 return true;
4570 // 'Faux' Target Shuffles.
4571 case ISD::OR:
4572 case ISD::AND:
4573 case X86ISD::ANDNP:
4574 return true;
4575 }
4576}
4577
4578SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
4579 MachineFunction &MF = DAG.getMachineFunction();
4580 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4581 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4582 int ReturnAddrIndex = FuncInfo->getRAIndex();
4583
4584 if (ReturnAddrIndex == 0) {
4585 // Set up a frame object for the return address.
4586 unsigned SlotSize = RegInfo->getSlotSize();
4587 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
4588 -(int64_t)SlotSize,
4589 false);
4590 FuncInfo->setRAIndex(ReturnAddrIndex);
4591 }
4592
4593 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
4594}
4595
4596bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
4597 bool hasSymbolicDisplacement) {
4598 // Offset should fit into 32 bit immediate field.
4599 if (!isInt<32>(Offset))
4600 return false;
4601
4602 // If we don't have a symbolic displacement - we don't have any extra
4603 // restrictions.
4604 if (!hasSymbolicDisplacement)
4605 return true;
4606
4607 // FIXME: Some tweaks might be needed for medium code model.
4608 if (M != CodeModel::Small && M != CodeModel::Kernel)
4609 return false;
4610
4611 // For small code model we assume that latest object is 16MB before end of 31
4612 // bits boundary. We may also accept pretty large negative constants knowing
4613 // that all objects are in the positive half of address space.
4614 if (M == CodeModel::Small && Offset < 16*1024*1024)
4615 return true;
4616
4617 // For kernel code model we know that all object resist in the negative half
4618 // of 32bits address space. We may not accept negative offsets, since they may
4619 // be just off and we may accept pretty large positive ones.
4620 if (M == CodeModel::Kernel && Offset >= 0)
4621 return true;
4622
4623 return false;
4624}
4625
4626/// Determines whether the callee is required to pop its own arguments.
4627/// Callee pop is necessary to support tail calls.
4628bool X86::isCalleePop(CallingConv::ID CallingConv,
4629 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4630 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4631 // can guarantee TCO.
4632 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4633 return true;
4634
4635 switch (CallingConv) {
4636 default:
4637 return false;
4638 case CallingConv::X86_StdCall:
4639 case CallingConv::X86_FastCall:
4640 case CallingConv::X86_ThisCall:
4641 case CallingConv::X86_VectorCall:
4642 return !is64Bit;
4643 }
4644}
4645
4646/// Return true if the condition is an unsigned comparison operation.
4647static bool isX86CCUnsigned(unsigned X86CC) {
4648 switch (X86CC) {
4649 default:
4650 llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 4650)
;
4651 case X86::COND_E:
4652 case X86::COND_NE:
4653 case X86::COND_B:
4654 case X86::COND_A:
4655 case X86::COND_BE:
4656 case X86::COND_AE:
4657 return true;
4658 case X86::COND_G:
4659 case X86::COND_GE:
4660 case X86::COND_L:
4661 case X86::COND_LE:
4662 return false;
4663 }
4664}
4665
4666static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4667 switch (SetCCOpcode) {
4668 default: llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 4668)
;
4669 case ISD::SETEQ: return X86::COND_E;
4670 case ISD::SETGT: return X86::COND_G;
4671 case ISD::SETGE: return X86::COND_GE;
4672 case ISD::SETLT: return X86::COND_L;
4673 case ISD::SETLE: return X86::COND_LE;
4674 case ISD::SETNE: return X86::COND_NE;
4675 case ISD::SETULT: return X86::COND_B;
4676 case ISD::SETUGT: return X86::COND_A;
4677 case ISD::SETULE: return X86::COND_BE;
4678 case ISD::SETUGE: return X86::COND_AE;
4679 }
4680}
4681
4682/// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4683/// condition code, returning the condition code and the LHS/RHS of the
4684/// comparison to make.
4685static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
4686 bool isFP, SDValue &LHS, SDValue &RHS,
4687 SelectionDAG &DAG) {
4688 if (!isFP) {
4689 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4690 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4691 // X > -1 -> X == 0, jump !sign.
4692 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4693 return X86::COND_NS;
4694 }
4695 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4696 // X < 0 -> X == 0, jump on sign.
4697 return X86::COND_S;
4698 }
4699 if (SetCCOpcode == ISD::SETGE && RHSC->isNullValue()) {
4700 // X >= 0 -> X == 0, jump on !sign.
4701 return X86::COND_NS;
4702 }
4703 if (SetCCOpcode == ISD::SETLT && RHSC->getAPIntValue() == 1) {
4704 // X < 1 -> X <= 0
4705 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4706 return X86::COND_LE;
4707 }
4708 }
4709
4710 return TranslateIntegerX86CC(SetCCOpcode);
4711 }
4712
4713 // First determine if it is required or is profitable to flip the operands.
4714
4715 // If LHS is a foldable load, but RHS is not, flip the condition.
4716 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4717 !ISD::isNON_EXTLoad(RHS.getNode())) {
4718 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4719 std::swap(LHS, RHS);
4720 }
4721
4722 switch (SetCCOpcode) {
4723 default: break;
4724 case ISD::SETOLT:
4725 case ISD::SETOLE:
4726 case ISD::SETUGT:
4727 case ISD::SETUGE:
4728 std::swap(LHS, RHS);
4729 break;
4730 }
4731
4732 // On a floating point condition, the flags are set as follows:
4733 // ZF PF CF op
4734 // 0 | 0 | 0 | X > Y
4735 // 0 | 0 | 1 | X < Y
4736 // 1 | 0 | 0 | X == Y
4737 // 1 | 1 | 1 | unordered
4738 switch (SetCCOpcode) {
4739 default: llvm_unreachable("Condcode should be pre-legalized away")::llvm::llvm_unreachable_internal("Condcode should be pre-legalized away"
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 4739)
;
4740 case ISD::SETUEQ:
4741 case ISD::SETEQ: return X86::COND_E;
4742 case ISD::SETOLT: // flipped
4743 case ISD::SETOGT:
4744 case ISD::SETGT: return X86::COND_A;
4745 case ISD::SETOLE: // flipped
4746 case ISD::SETOGE:
4747 case ISD::SETGE: return X86::COND_AE;
4748 case ISD::SETUGT: // flipped
4749 case ISD::SETULT:
4750 case ISD::SETLT: return X86::COND_B;
4751 case ISD::SETUGE: // flipped
4752 case ISD::SETULE:
4753 case ISD::SETLE: return X86::COND_BE;
4754 case ISD::SETONE:
4755 case ISD::SETNE: return X86::COND_NE;
4756 case ISD::SETUO: return X86::COND_P;
4757 case ISD::SETO: return X86::COND_NP;
4758 case ISD::SETOEQ:
4759 case ISD::SETUNE: return X86::COND_INVALID;
4760 }
4761}
4762
4763/// Is there a floating point cmov for the specific X86 condition code?
4764/// Current x86 isa includes the following FP cmov instructions:
4765/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4766static bool hasFPCMov(unsigned X86CC) {
4767 switch (X86CC) {
4768 default:
4769 return false;
4770 case X86::COND_B:
4771 case X86::COND_BE:
4772 case X86::COND_E:
4773 case X86::COND_P:
4774 case X86::COND_A:
4775 case X86::COND_AE:
4776 case X86::COND_NE:
4777 case X86::COND_NP:
4778 return true;
4779 }
4780}
4781
4782
4783bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4784 const CallInst &I,
4785 MachineFunction &MF,
4786 unsigned Intrinsic) const {
4787
4788 const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4789 if (!IntrData)
4790 return false;
4791
4792 Info.flags = MachineMemOperand::MONone;
4793 Info.offset = 0;
4794
4795 switch (IntrData->Type) {
4796 case TRUNCATE_TO_MEM_VI8:
4797 case TRUNCATE_TO_MEM_VI16:
4798 case TRUNCATE_TO_MEM_VI32: {
4799 Info.opc = ISD::INTRINSIC_VOID;
4800 Info.ptrVal = I.getArgOperand(0);
4801 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
4802 MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
4803 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
4804 ScalarVT = MVT::i8;
4805 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
4806 ScalarVT = MVT::i16;
4807 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
4808 ScalarVT = MVT::i32;
4809
4810 Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
4811 Info.align = Align::None();
4812 Info.flags |= MachineMemOperand::MOStore;
4813 break;
4814 }
4815 case GATHER:
4816 case GATHER_AVX2: {
4817 Info.opc = ISD::INTRINSIC_W_CHAIN;
4818 Info.ptrVal = nullptr;
4819 MVT DataVT = MVT::getVT(I.getType());
4820 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
4821 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
4822 IndexVT.getVectorNumElements());
4823 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
4824 Info.align = Align::None();
4825 Info.flags |= MachineMemOperand::MOLoad;
4826 break;
4827 }
4828 case SCATTER: {
4829 Info.opc = ISD::INTRINSIC_VOID;
4830 Info.ptrVal = nullptr;
4831 MVT DataVT = MVT::getVT(I.getArgOperand(3)->getType());
4832 MVT IndexVT = MVT::getVT(I.getArgOperand(2)->getType());
4833 unsigned NumElts = std::min(DataVT.getVectorNumElements(),
4834 IndexVT.getVectorNumElements());
4835 Info.memVT = MVT::getVectorVT(DataVT.getVectorElementType(), NumElts);
4836 Info.align = Align::None();
4837 Info.flags |= MachineMemOperand::MOStore;
4838 break;
4839 }
4840 default:
4841 return false;
4842 }
4843
4844 return true;
4845}
4846
4847/// Returns true if the target can instruction select the
4848/// specified FP immediate natively. If false, the legalizer will
4849/// materialize the FP immediate as a load from a constant pool.
4850bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
4851 bool ForCodeSize) const {
4852 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4853 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4854 return true;
4855 }
4856 return false;
4857}
4858
4859bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4860 ISD::LoadExtType ExtTy,
4861 EVT NewVT) const {
4862 assert(cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow")((cast<LoadSDNode>(Load)->isSimple() && "illegal to narrow"
) ? static_cast<void> (0) : __assert_fail ("cast<LoadSDNode>(Load)->isSimple() && \"illegal to narrow\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 4862, __PRETTY_FUNCTION__))
;
4863
4864 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4865 // relocation target a movq or addq instruction: don't let the load shrink.
4866 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4867 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4868 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4869 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4870
4871 // If this is an (1) AVX vector load with (2) multiple uses and (3) all of
4872 // those uses are extracted directly into a store, then the extract + store
4873 // can be store-folded. Therefore, it's probably not worth splitting the load.
4874 EVT VT = Load->getValueType(0);
4875 if ((VT.is256BitVector() || VT.is512BitVector()) && !Load->hasOneUse()) {
4876 for (auto UI = Load->use_begin(), UE = Load->use_end(); UI != UE; ++UI) {
4877 // Skip uses of the chain value. Result 0 of the node is the load value.
4878 if (UI.getUse().getResNo() != 0)
4879 continue;
4880
4881 // If this use is not an extract + store, it's probably worth splitting.
4882 if (UI->getOpcode() != ISD::EXTRACT_SUBVECTOR || !UI->hasOneUse() ||
4883 UI->use_begin()->getOpcode() != ISD::STORE)
4884 return true;
4885 }
4886 // All non-chain uses are extract + store.
4887 return false;
4888 }
4889
4890 return true;
4891}
4892
4893/// Returns true if it is beneficial to convert a load of a constant
4894/// to just the constant itself.
4895bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4896 Type *Ty) const {
4897 assert(Ty->isIntegerTy())((Ty->isIntegerTy()) ? static_cast<void> (0) : __assert_fail
("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 4897, __PRETTY_FUNCTION__))
;
4898
4899 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4900 if (BitSize == 0 || BitSize > 64)
4901 return false;
4902 return true;
4903}
4904
4905bool X86TargetLowering::reduceSelectOfFPConstantLoads(EVT CmpOpVT) const {
4906 // If we are using XMM registers in the ABI and the condition of the select is
4907 // a floating-point compare and we have blendv or conditional move, then it is
4908 // cheaper to select instead of doing a cross-register move and creating a
4909 // load that depends on the compare result.
4910 bool IsFPSetCC = CmpOpVT.isFloatingPoint() && CmpOpVT != MVT::f128;
4911 return !IsFPSetCC || !Subtarget.isTarget64BitLP64() || !Subtarget.hasAVX();
4912}
4913
4914bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
4915 // TODO: It might be a win to ease or lift this restriction, but the generic
4916 // folds in DAGCombiner conflict with vector folds for an AVX512 target.
4917 if (VT.isVector() && Subtarget.hasAVX512())
4918 return false;
4919
4920 return true;
4921}
4922
4923bool X86TargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
4924 SDValue C) const {
4925 // TODO: We handle scalars using custom code, but generic combining could make
4926 // that unnecessary.
4927 APInt MulC;
4928 if (!ISD::isConstantSplatVector(C.getNode(), MulC))
4929 return false;
4930
4931 // Find the type this will be legalized too. Otherwise we might prematurely
4932 // convert this to shl+add/sub and then still have to type legalize those ops.
4933 // Another choice would be to defer the decision for illegal types until
4934 // after type legalization. But constant splat vectors of i64 can't make it
4935 // through type legalization on 32-bit targets so we would need to special
4936 // case vXi64.
4937 while (getTypeAction(Context, VT) != TypeLegal)
4938 VT = getTypeToTransformTo(Context, VT);
4939
4940 // If vector multiply is legal, assume that's faster than shl + add/sub.
4941 // TODO: Multiply is a complex op with higher latency and lower throughput in
4942 // most implementations, so this check could be loosened based on type
4943 // and/or a CPU attribute.
4944 if (isOperationLegal(ISD::MUL, VT))
4945 return false;
4946
4947 // shl+add, shl+sub, shl+add+neg
4948 return (MulC + 1).isPowerOf2() || (MulC - 1).isPowerOf2() ||
4949 (1 - MulC).isPowerOf2() || (-(MulC + 1)).isPowerOf2();
4950}
4951
4952bool X86TargetLowering::shouldUseStrictFP_TO_INT(EVT FpVT, EVT IntVT,
4953 bool IsSigned) const {
4954 // f80 UINT_TO_FP is more efficient using Strict code if FCMOV is available.
4955 return !IsSigned && FpVT == MVT::f80 && Subtarget.hasCMov();
4956}
4957
4958bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
4959 unsigned Index) const {
4960 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4961 return false;
4962
4963 // Mask vectors support all subregister combinations and operations that
4964 // extract half of vector.
4965 if (ResVT.getVectorElementType() == MVT::i1)
4966 return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
4967 (Index == ResVT.getVectorNumElements()));
4968
4969 return (Index % ResVT.getVectorNumElements()) == 0;
4970}
4971
4972bool X86TargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
4973 unsigned Opc = VecOp.getOpcode();
4974
4975 // Assume target opcodes can't be scalarized.
4976 // TODO - do we have any exceptions?
4977 if (Opc >= ISD::BUILTIN_OP_END)
4978 return false;
4979
4980 // If the vector op is not supported, try to convert to scalar.
4981 EVT VecVT = VecOp.getValueType();
4982 if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
4983 return true;
4984
4985 // If the vector op is supported, but the scalar op is not, the transform may
4986 // not be worthwhile.
4987 EVT ScalarVT = VecVT.getScalarType();
4988 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
4989}
4990
4991bool X86TargetLowering::shouldFormOverflowOp(unsigned Opcode, EVT VT) const {
4992 // TODO: Allow vectors?
4993 if (VT.isVector())
4994 return false;
4995 return VT.isSimple() || !isOperationExpand(Opcode, VT);
4996}
4997
4998bool X86TargetLowering::isCheapToSpeculateCttz() const {
4999 // Speculate cttz only if we can directly use TZCNT.
5000 return Subtarget.hasBMI();
5001}
5002
5003bool X86TargetLowering::isCheapToSpeculateCtlz() const {
5004 // Speculate ctlz only if we can directly use LZCNT.
5005 return Subtarget.hasLZCNT();
5006}
5007
5008bool X86TargetLowering::isLoadBitCastBeneficial(EVT LoadVT, EVT BitcastVT,
5009 const SelectionDAG &DAG,
5010 const MachineMemOperand &MMO) const {
5011 if (!Subtarget.hasAVX512() && !LoadVT.isVector() && BitcastVT.isVector() &&
5012 BitcastVT.getVectorElementType() == MVT::i1)
5013 return false;
5014
5015 if (!Subtarget.hasDQI() && BitcastVT == MVT::v8i1 && LoadVT == MVT::i8)
5016 return false;
5017
5018 // If both types are legal vectors, it's always ok to convert them.
5019 if (LoadVT.isVector() && BitcastVT.isVector() &&
5020 isTypeLegal(LoadVT) && isTypeLegal(BitcastVT))
5021 return true;
5022
5023 return TargetLowering::isLoadBitCastBeneficial(LoadVT, BitcastVT, DAG, MMO);
5024}
5025
5026bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
5027 const SelectionDAG &DAG) const {
5028 // Do not merge to float value size (128 bytes) if no implicit
5029 // float attribute is set.
5030 bool NoFloat = DAG.getMachineFunction().getFunction().hasFnAttribute(
5031 Attribute::NoImplicitFloat);
5032
5033 if (NoFloat) {
5034 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
5035 return (MemVT.getSizeInBits() <= MaxIntSize);
5036 }
5037 // Make sure we don't merge greater than our preferred vector
5038 // width.
5039 if (MemVT.getSizeInBits() > Subtarget.getPreferVectorWidth())
5040 return false;
5041 return true;
5042}
5043
5044bool X86TargetLowering::isCtlzFast() const {
5045 return Subtarget.hasFastLZCNT();
5046}
5047
5048bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
5049 const Instruction &AndI) const {
5050 return true;
5051}
5052
5053bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
5054 EVT VT = Y.getValueType();
5055
5056 if (VT.isVector())
5057 return false;
5058
5059 if (!Subtarget.hasBMI())
5060 return false;
5061
5062 // There are only 32-bit and 64-bit forms for 'andn'.
5063 if (VT != MVT::i32 && VT != MVT::i64)
5064 return false;
5065
5066 return !isa<ConstantSDNode>(Y);
5067}
5068
5069bool X86TargetLowering::hasAndNot(SDValue Y) const {
5070 EVT VT = Y.getValueType();
5071
5072 if (!VT.isVector())
5073 return hasAndNotCompare(Y);
5074
5075 // Vector.
5076
5077 if (!Subtarget.hasSSE1() || VT.getSizeInBits() < 128)
5078 return false;
5079
5080 if (VT == MVT::v4i32)
5081 return true;
5082
5083 return Subtarget.hasSSE2();
5084}
5085
5086bool X86TargetLowering::hasBitTest(SDValue X, SDValue Y) const {
5087 return X.getValueType().isScalarInteger(); // 'bt'
5088}
5089
5090bool X86TargetLowering::
5091 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5092 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
5093 unsigned OldShiftOpcode, unsigned NewShiftOpcode,
5094 SelectionDAG &DAG) const {
5095 // Does baseline recommend not to perform the fold by default?
5096 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
5097 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
5098 return false;
5099 // For scalars this transform is always beneficial.
5100 if (X.getValueType().isScalarInteger())
5101 return true;
5102 // If all the shift amounts are identical, then transform is beneficial even
5103 // with rudimentary SSE2 shifts.
5104 if (DAG.isSplatValue(Y, /*AllowUndefs=*/true))
5105 return true;
5106 // If we have AVX2 with it's powerful shift operations, then it's also good.
5107 if (Subtarget.hasAVX2())
5108 return true;
5109 // Pre-AVX2 vector codegen for this pattern is best for variant with 'shl'.
5110 return NewShiftOpcode == ISD::SHL;
5111}
5112
5113bool X86TargetLowering::shouldFoldConstantShiftPairToMask(
5114 const SDNode *N, CombineLevel Level) const {
5115 assert(((N->getOpcode() == ISD::SHL &&((((N->getOpcode() == ISD::SHL && N->getOperand
(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL
&& N->getOperand(0).getOpcode() == ISD::SHL)) &&
"Expected shift-shift mask") ? static_cast<void> (0) :
__assert_fail ("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5119, __PRETTY_FUNCTION__))
5116 N->getOperand(0).getOpcode() == ISD::SRL) ||((((N->getOpcode() == ISD::SHL && N->getOperand
(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL
&& N->getOperand(0).getOpcode() == ISD::SHL)) &&
"Expected shift-shift mask") ? static_cast<void> (0) :
__assert_fail ("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5119, __PRETTY_FUNCTION__))
5117 (N->getOpcode() == ISD::SRL &&((((N->getOpcode() == ISD::SHL && N->getOperand
(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL
&& N->getOperand(0).getOpcode() == ISD::SHL)) &&
"Expected shift-shift mask") ? static_cast<void> (0) :
__assert_fail ("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5119, __PRETTY_FUNCTION__))
5118 N->getOperand(0).getOpcode() == ISD::SHL)) &&((((N->getOpcode() == ISD::SHL && N->getOperand
(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL
&& N->getOperand(0).getOpcode() == ISD::SHL)) &&
"Expected shift-shift mask") ? static_cast<void> (0) :
__assert_fail ("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5119, __PRETTY_FUNCTION__))
5119 "Expected shift-shift mask")((((N->getOpcode() == ISD::SHL && N->getOperand
(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL
&& N->getOperand(0).getOpcode() == ISD::SHL)) &&
"Expected shift-shift mask") ? static_cast<void> (0) :
__assert_fail ("((N->getOpcode() == ISD::SHL && N->getOperand(0).getOpcode() == ISD::SRL) || (N->getOpcode() == ISD::SRL && N->getOperand(0).getOpcode() == ISD::SHL)) && \"Expected shift-shift mask\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5119, __PRETTY_FUNCTION__))
;
5120 EVT VT = N->getValueType(0);
5121 if ((Subtarget.hasFastVectorShiftMasks() && VT.isVector()) ||
5122 (Subtarget.hasFastScalarShiftMasks() && !VT.isVector())) {
5123 // Only fold if the shift values are equal - so it folds to AND.
5124 // TODO - we should fold if either is a non-uniform vector but we don't do
5125 // the fold for non-splats yet.
5126 return N->getOperand(1) == N->getOperand(0).getOperand(1);
5127 }
5128 return TargetLoweringBase::shouldFoldConstantShiftPairToMask(N, Level);
5129}
5130
5131bool X86TargetLowering::shouldFoldMaskToVariableShiftPair(SDValue Y) const {
5132 EVT VT = Y.getValueType();
5133
5134 // For vectors, we don't have a preference, but we probably want a mask.
5135 if (VT.isVector())
5136 return false;
5137
5138 // 64-bit shifts on 32-bit targets produce really bad bloated code.
5139 if (VT == MVT::i64 && !Subtarget.is64Bit())
5140 return false;
5141
5142 return true;
5143}
5144
5145bool X86TargetLowering::shouldExpandShift(SelectionDAG &DAG,
5146 SDNode *N) const {
5147 if (DAG.getMachineFunction().getFunction().hasMinSize() &&
5148 !Subtarget.isOSWindows())
5149 return false;
5150 return true;
5151}
5152
5153bool X86TargetLowering::shouldSplatInsEltVarIndex(EVT VT) const {
5154 // Any legal vector type can be splatted more efficiently than
5155 // loading/spilling from memory.
5156 return isTypeLegal(VT);
5157}
5158
5159MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
5160 MVT VT = MVT::getIntegerVT(NumBits);
5161 if (isTypeLegal(VT))
5162 return VT;
5163
5164 // PMOVMSKB can handle this.
5165 if (NumBits == 128 && isTypeLegal(MVT::v16i8))
5166 return MVT::v16i8;
5167
5168 // VPMOVMSKB can handle this.
5169 if (NumBits == 256 && isTypeLegal(MVT::v32i8))
5170 return MVT::v32i8;
5171
5172 // TODO: Allow 64-bit type for 32-bit target.
5173 // TODO: 512-bit types should be allowed, but make sure that those
5174 // cases are handled in combineVectorSizedSetCCEquality().
5175
5176 return MVT::INVALID_SIMPLE_VALUE_TYPE;
5177}
5178
5179/// Val is the undef sentinel value or equal to the specified value.
5180static bool isUndefOrEqual(int Val, int CmpVal) {
5181 return ((Val == SM_SentinelUndef) || (Val == CmpVal));
5182}
5183
5184/// Val is either the undef or zero sentinel value.
5185static bool isUndefOrZero(int Val) {
5186 return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
5187}
5188
5189/// Return true if every element in Mask, beginning from position Pos and ending
5190/// in Pos+Size is the undef sentinel value.
5191static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
5192 return llvm::all_of(Mask.slice(Pos, Size),
5193 [](int M) { return M == SM_SentinelUndef; });
5194}
5195
5196/// Return true if the mask creates a vector whose lower half is undefined.
5197static bool isUndefLowerHalf(ArrayRef<int> Mask) {
5198 unsigned NumElts = Mask.size();
5199 return isUndefInRange(Mask, 0, NumElts / 2);
5200}
5201
5202/// Return true if the mask creates a vector whose upper half is undefined.
5203static bool isUndefUpperHalf(ArrayRef<int> Mask) {
5204 unsigned NumElts = Mask.size();
5205 return isUndefInRange(Mask, NumElts / 2, NumElts / 2);
5206}
5207
5208/// Return true if Val falls within the specified range (L, H].
5209static bool isInRange(int Val, int Low, int Hi) {
5210 return (Val >= Low && Val < Hi);
5211}
5212
5213/// Return true if the value of any element in Mask falls within the specified
5214/// range (L, H].
5215static bool isAnyInRange(ArrayRef<int> Mask, int Low, int Hi) {
5216 return llvm::any_of(Mask, [Low, Hi](int M) { return isInRange(M, Low, Hi); });
5217}
5218
5219/// Return true if Val is undef or if its value falls within the
5220/// specified range (L, H].
5221static bool isUndefOrInRange(int Val, int Low, int Hi) {
5222 return (Val == SM_SentinelUndef) || isInRange(Val, Low, Hi);
5223}
5224
5225/// Return true if every element in Mask is undef or if its value
5226/// falls within the specified range (L, H].
5227static bool isUndefOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5228 return llvm::all_of(
5229 Mask, [Low, Hi](int M) { return isUndefOrInRange(M, Low, Hi); });
5230}
5231
5232/// Return true if Val is undef, zero or if its value falls within the
5233/// specified range (L, H].
5234static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
5235 return isUndefOrZero(Val) || isInRange(Val, Low, Hi);
5236}
5237
5238/// Return true if every element in Mask is undef, zero or if its value
5239/// falls within the specified range (L, H].
5240static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
5241 return llvm::all_of(
5242 Mask, [Low, Hi](int M) { return isUndefOrZeroOrInRange(M, Low, Hi); });
5243}
5244
5245/// Return true if every element in Mask, beginning
5246/// from position Pos and ending in Pos + Size, falls within the specified
5247/// sequence (Low, Low + Step, ..., Low + (Size - 1) * Step) or is undef.
5248static bool isSequentialOrUndefInRange(ArrayRef<int> Mask, unsigned Pos,
5249 unsigned Size, int Low, int Step = 1) {
5250 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5251 if (!isUndefOrEqual(Mask[i], Low))
5252 return false;
5253 return true;
5254}
5255
5256/// Return true if every element in Mask, beginning
5257/// from position Pos and ending in Pos+Size, falls within the specified
5258/// sequential range (Low, Low+Size], or is undef or is zero.
5259static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5260 unsigned Size, int Low,
5261 int Step = 1) {
5262 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, Low += Step)
5263 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
5264 return false;
5265 return true;
5266}
5267
5268/// Return true if every element in Mask, beginning
5269/// from position Pos and ending in Pos+Size is undef or is zero.
5270static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
5271 unsigned Size) {
5272 return llvm::all_of(Mask.slice(Pos, Size),
5273 [](int M) { return isUndefOrZero(M); });
5274}
5275
5276/// Helper function to test whether a shuffle mask could be
5277/// simplified by widening the elements being shuffled.
5278///
5279/// Appends the mask for wider elements in WidenedMask if valid. Otherwise
5280/// leaves it in an unspecified state.
5281///
5282/// NOTE: This must handle normal vector shuffle masks and *target* vector
5283/// shuffle masks. The latter have the special property of a '-2' representing
5284/// a zero-ed lane of a vector.
5285static bool canWidenShuffleElements(ArrayRef<int> Mask,
5286 SmallVectorImpl<int> &WidenedMask) {
5287 WidenedMask.assign(Mask.size() / 2, 0);
5288 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
5289 int M0 = Mask[i];
5290 int M1 = Mask[i + 1];
5291
5292 // If both elements are undef, its trivial.
5293 if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
5294 WidenedMask[i / 2] = SM_SentinelUndef;
5295 continue;
5296 }
5297
5298 // Check for an undef mask and a mask value properly aligned to fit with
5299 // a pair of values. If we find such a case, use the non-undef mask's value.
5300 if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
5301 WidenedMask[i / 2] = M1 / 2;
5302 continue;
5303 }
5304 if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
5305 WidenedMask[i / 2] = M0 / 2;
5306 continue;
5307 }
5308
5309 // When zeroing, we need to spread the zeroing across both lanes to widen.
5310 if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
5311 if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
5312 (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
5313 WidenedMask[i / 2] = SM_SentinelZero;
5314 continue;
5315 }
5316 return false;
5317 }
5318
5319 // Finally check if the two mask values are adjacent and aligned with
5320 // a pair.
5321 if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
5322 WidenedMask[i / 2] = M0 / 2;
5323 continue;
5324 }
5325
5326 // Otherwise we can't safely widen the elements used in this shuffle.
5327 return false;
5328 }
5329 assert(WidenedMask.size() == Mask.size() / 2 &&((WidenedMask.size() == Mask.size() / 2 && "Incorrect size of mask after widening the elements!"
) ? static_cast<void> (0) : __assert_fail ("WidenedMask.size() == Mask.size() / 2 && \"Incorrect size of mask after widening the elements!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5330, __PRETTY_FUNCTION__))
5330 "Incorrect size of mask after widening the elements!")((WidenedMask.size() == Mask.size() / 2 && "Incorrect size of mask after widening the elements!"
) ? static_cast<void> (0) : __assert_fail ("WidenedMask.size() == Mask.size() / 2 && \"Incorrect size of mask after widening the elements!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5330, __PRETTY_FUNCTION__))
;
5331
5332 return true;
5333}
5334
5335static bool canWidenShuffleElements(ArrayRef<int> Mask,
5336 const APInt &Zeroable,
5337 SmallVectorImpl<int> &WidenedMask) {
5338 SmallVector<int, 32> TargetMask(Mask.begin(), Mask.end());
5339 for (int i = 0, Size = TargetMask.size(); i < Size; ++i) {
5340 if (TargetMask[i] == SM_SentinelUndef)
5341 continue;
5342 if (Zeroable[i])
5343 TargetMask[i] = SM_SentinelZero;
5344 }
5345 return canWidenShuffleElements(TargetMask, WidenedMask);
5346}
5347
5348static bool canWidenShuffleElements(ArrayRef<int> Mask) {
5349 SmallVector<int, 32> WidenedMask;
5350 return canWidenShuffleElements(Mask, WidenedMask);
5351}
5352
5353/// Returns true if Elt is a constant zero or a floating point constant +0.0.
5354bool X86::isZeroNode(SDValue Elt) {
5355 return isNullConstant(Elt) || isNullFPConstant(Elt);
5356}
5357
5358// Build a vector of constants.
5359// Use an UNDEF node if MaskElt == -1.
5360// Split 64-bit constants in the 32-bit mode.
5361static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
5362 const SDLoc &dl, bool IsMask = false) {
5363
5364 SmallVector<SDValue, 32> Ops;
5365 bool Split = false;
5366
5367 MVT ConstVecVT = VT;
5368 unsigned NumElts = VT.getVectorNumElements();
5369 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5370 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5371 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5372 Split = true;
5373 }
5374
5375 MVT EltVT = ConstVecVT.getVectorElementType();
5376 for (unsigned i = 0; i < NumElts; ++i) {
5377 bool IsUndef = Values[i] < 0 && IsMask;
5378 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
5379 DAG.getConstant(Values[i], dl, EltVT);
5380 Ops.push_back(OpNode);
5381 if (Split)
5382 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
5383 DAG.getConstant(0, dl, EltVT));
5384 }
5385 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5386 if (Split)
5387 ConstsNode = DAG.getBitcast(VT, ConstsNode);
5388 return ConstsNode;
5389}
5390
5391static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
5392 MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5393 assert(Bits.size() == Undefs.getBitWidth() &&((Bits.size() == Undefs.getBitWidth() && "Unequal constant and undef arrays"
) ? static_cast<void> (0) : __assert_fail ("Bits.size() == Undefs.getBitWidth() && \"Unequal constant and undef arrays\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5394, __PRETTY_FUNCTION__))
5394 "Unequal constant and undef arrays")((Bits.size() == Undefs.getBitWidth() && "Unequal constant and undef arrays"
) ? static_cast<void> (0) : __assert_fail ("Bits.size() == Undefs.getBitWidth() && \"Unequal constant and undef arrays\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5394, __PRETTY_FUNCTION__))
;
5395 SmallVector<SDValue, 32> Ops;
5396 bool Split = false;
5397
5398 MVT ConstVecVT = VT;
5399 unsigned NumElts = VT.getVectorNumElements();
5400 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
5401 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
5402 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
5403 Split = true;
5404 }
5405
5406 MVT EltVT = ConstVecVT.getVectorElementType();
5407 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
5408 if (Undefs[i]) {
5409 Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
5410 continue;
5411 }
5412 const APInt &V = Bits[i];
5413 assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes")((V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes"
) ? static_cast<void> (0) : __assert_fail ("V.getBitWidth() == VT.getScalarSizeInBits() && \"Unexpected sizes\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5413, __PRETTY_FUNCTION__))
;
5414 if (Split) {
5415 Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
5416 Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
5417 } else if (EltVT == MVT::f32) {
5418 APFloat FV(APFloat::IEEEsingle(), V);
5419 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5420 } else if (EltVT == MVT::f64) {
5421 APFloat FV(APFloat::IEEEdouble(), V);
5422 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
5423 } else {
5424 Ops.push_back(DAG.getConstant(V, dl, EltVT));
5425 }
5426 }
5427
5428 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
5429 return DAG.getBitcast(VT, ConstsNode);
5430}
5431
5432/// Returns a vector of specified type with all zero elements.
5433static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
5434 SelectionDAG &DAG, const SDLoc &dl) {
5435 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
() || VT.getVectorElementType() == MVT::i1) && "Unexpected vector type"
) ? static_cast<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5437, __PRETTY_FUNCTION__))
5436 VT.getVectorElementType() == MVT::i1) &&(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
() || VT.getVectorElementType() == MVT::i1) && "Unexpected vector type"
) ? static_cast<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5437, __PRETTY_FUNCTION__))
5437 "Unexpected vector type")(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
() || VT.getVectorElementType() == MVT::i1) && "Unexpected vector type"
) ? static_cast<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5437, __PRETTY_FUNCTION__))
;
5438
5439 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
5440 // type. This ensures they get CSE'd. But if the integer type is not
5441 // available, use a floating-point +0.0 instead.
5442 SDValue Vec;
5443 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
5444 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
5445 } else if (VT.isFloatingPoint()) {
5446 Vec = DAG.getConstantFP(+0.0, dl, VT);
5447 } else if (VT.getVectorElementType() == MVT::i1) {
5448 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&(((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
"Unexpected vector type") ? static_cast<void> (0) : __assert_fail
("(Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5449, __PRETTY_FUNCTION__))
5449 "Unexpected vector type")(((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&
"Unexpected vector type") ? static_cast<void> (0) : __assert_fail
("(Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5449, __PRETTY_FUNCTION__))
;
5450 Vec = DAG.getConstant(0, dl, VT);
5451 } else {
5452 unsigned Num32BitElts = VT.getSizeInBits() / 32;
5453 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
5454 }
5455 return DAG.getBitcast(VT, Vec);
5456}
5457
5458static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
5459 const SDLoc &dl, unsigned vectorWidth) {
5460 EVT VT = Vec.getValueType();
5461 EVT ElVT = VT.getVectorElementType();
5462 unsigned Factor = VT.getSizeInBits()/vectorWidth;
5463 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
5464 VT.getVectorNumElements()/Factor);
5465
5466 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
5467 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
5468 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")((isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5468, __PRETTY_FUNCTION__))
;
5469
5470 // This is the index of the first element of the vectorWidth-bit chunk
5471 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5472 IdxVal &= ~(ElemsPerChunk - 1);
5473
5474 // If the input is a buildvector just emit a smaller one.
5475 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
5476 return DAG.getBuildVector(ResultVT, dl,
5477 Vec->ops().slice(IdxVal, ElemsPerChunk));
5478
5479 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5480 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
5481}
5482
5483/// Generate a DAG to grab 128-bits from a vector > 128 bits. This
5484/// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
5485/// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
5486/// instructions or a simple subregister reference. Idx is an index in the
5487/// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
5488/// lowering EXTRACT_VECTOR_ELT operations easier.
5489static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
5490 SelectionDAG &DAG, const SDLoc &dl) {
5491 assert((Vec.getValueType().is256BitVector() ||(((Vec.getValueType().is256BitVector() || Vec.getValueType().
is512BitVector()) && "Unexpected vector size!") ? static_cast
<void> (0) : __assert_fail ("(Vec.getValueType().is256BitVector() || Vec.getValueType().is512BitVector()) && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5492, __PRETTY_FUNCTION__))
5492 Vec.getValueType().is512BitVector()) && "Unexpected vector size!")(((Vec.getValueType().is256BitVector() || Vec.getValueType().
is512BitVector()) && "Unexpected vector size!") ? static_cast
<void> (0) : __assert_fail ("(Vec.getValueType().is256BitVector() || Vec.getValueType().is512BitVector()) && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5492, __PRETTY_FUNCTION__))
;
5493 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
5494}
5495
5496/// Generate a DAG to grab 256-bits from a 512-bit vector.
5497static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
5498 SelectionDAG &DAG, const SDLoc &dl) {
5499 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!")((Vec.getValueType().is512BitVector() && "Unexpected vector size!"
) ? static_cast<void> (0) : __assert_fail ("Vec.getValueType().is512BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5499, __PRETTY_FUNCTION__))
;
5500 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
5501}
5502
5503static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5504 SelectionDAG &DAG, const SDLoc &dl,
5505 unsigned vectorWidth) {
5506 assert((vectorWidth == 128 || vectorWidth == 256) &&(((vectorWidth == 128 || vectorWidth == 256) && "Unsupported vector width"
) ? static_cast<void> (0) : __assert_fail ("(vectorWidth == 128 || vectorWidth == 256) && \"Unsupported vector width\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5507, __PRETTY_FUNCTION__))
5507 "Unsupported vector width")(((vectorWidth == 128 || vectorWidth == 256) && "Unsupported vector width"
) ? static_cast<void> (0) : __assert_fail ("(vectorWidth == 128 || vectorWidth == 256) && \"Unsupported vector width\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5507, __PRETTY_FUNCTION__))
;
5508 // Inserting UNDEF is Result
5509 if (Vec.isUndef())
5510 return Result;
5511 EVT VT = Vec.getValueType();
5512 EVT ElVT = VT.getVectorElementType();
5513 EVT ResultVT = Result.getValueType();
5514
5515 // Insert the relevant vectorWidth bits.
5516 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
5517 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")((isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2"
) ? static_cast<void> (0) : __assert_fail ("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5517, __PRETTY_FUNCTION__))
;
5518
5519 // This is the index of the first element of the vectorWidth-bit chunk
5520 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
5521 IdxVal &= ~(ElemsPerChunk - 1);
5522
5523 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
5524 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
5525}
5526
5527/// Generate a DAG to put 128-bits into a vector > 128 bits. This
5528/// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
5529/// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
5530/// simple superregister reference. Idx is an index in the 128 bits
5531/// we want. It need not be aligned to a 128-bit boundary. That makes
5532/// lowering INSERT_VECTOR_ELT operations easier.
5533static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5534 SelectionDAG &DAG, const SDLoc &dl) {
5535 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!")((Vec.getValueType().is128BitVector() && "Unexpected vector size!"
) ? static_cast<void> (0) : __assert_fail ("Vec.getValueType().is128BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5535, __PRETTY_FUNCTION__))
;
5536 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
5537}
5538
5539/// Widen a vector to a larger size with the same scalar type, with the new
5540/// elements either zero or undef.
5541static SDValue widenSubVector(MVT VT, SDValue Vec, bool ZeroNewElements,
5542 const X86Subtarget &Subtarget, SelectionDAG &DAG,
5543 const SDLoc &dl) {
5544 assert(Vec.getValueSizeInBits() < VT.getSizeInBits() &&((Vec.getValueSizeInBits() < VT.getSizeInBits() &&
Vec.getValueType().getScalarType() == VT.getScalarType() &&
"Unsupported vector widening type") ? static_cast<void>
(0) : __assert_fail ("Vec.getValueSizeInBits() < VT.getSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5546, __PRETTY_FUNCTION__))
5545 Vec.getValueType().getScalarType() == VT.getScalarType() &&((Vec.getValueSizeInBits() < VT.getSizeInBits() &&
Vec.getValueType().getScalarType() == VT.getScalarType() &&
"Unsupported vector widening type") ? static_cast<void>
(0) : __assert_fail ("Vec.getValueSizeInBits() < VT.getSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5546, __PRETTY_FUNCTION__))
5546 "Unsupported vector widening type")((Vec.getValueSizeInBits() < VT.getSizeInBits() &&
Vec.getValueType().getScalarType() == VT.getScalarType() &&
"Unsupported vector widening type") ? static_cast<void>
(0) : __assert_fail ("Vec.getValueSizeInBits() < VT.getSizeInBits() && Vec.getValueType().getScalarType() == VT.getScalarType() && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5546, __PRETTY_FUNCTION__))
;
5547 SDValue Res = ZeroNewElements ? getZeroVector(VT, Subtarget, DAG, dl)
5548 : DAG.getUNDEF(VT);
5549 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, Vec,
5550 DAG.getIntPtrConstant(0, dl));
5551}
5552
5553/// Widen a vector to a larger size with the same scalar type, with the new
5554/// elements either zero or undef.
5555static SDValue widenSubVector(SDValue Vec, bool ZeroNewElements,
5556 const X86Subtarget &Subtarget, SelectionDAG &DAG,
5557 const SDLoc &dl, unsigned WideSizeInBits) {
5558 assert(Vec.getValueSizeInBits() < WideSizeInBits &&((Vec.getValueSizeInBits() < WideSizeInBits && (WideSizeInBits
% Vec.getScalarValueSizeInBits()) == 0 && "Unsupported vector widening type"
) ? static_cast<void> (0) : __assert_fail ("Vec.getValueSizeInBits() < WideSizeInBits && (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5560, __PRETTY_FUNCTION__))
5559 (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 &&((Vec.getValueSizeInBits() < WideSizeInBits && (WideSizeInBits
% Vec.getScalarValueSizeInBits()) == 0 && "Unsupported vector widening type"
) ? static_cast<void> (0) : __assert_fail ("Vec.getValueSizeInBits() < WideSizeInBits && (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5560, __PRETTY_FUNCTION__))
5560 "Unsupported vector widening type")((Vec.getValueSizeInBits() < WideSizeInBits && (WideSizeInBits
% Vec.getScalarValueSizeInBits()) == 0 && "Unsupported vector widening type"
) ? static_cast<void> (0) : __assert_fail ("Vec.getValueSizeInBits() < WideSizeInBits && (WideSizeInBits % Vec.getScalarValueSizeInBits()) == 0 && \"Unsupported vector widening type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5560, __PRETTY_FUNCTION__))
;
5561 unsigned WideNumElts = WideSizeInBits / Vec.getScalarValueSizeInBits();
5562 MVT SVT = Vec.getSimpleValueType().getScalarType();
5563 MVT VT = MVT::getVectorVT(SVT, WideNumElts);
5564 return widenSubVector(VT, Vec, ZeroNewElements, Subtarget, DAG, dl);
5565}
5566
5567// Helper function to collect subvector ops that are concated together,
5568// either by ISD::CONCAT_VECTORS or a ISD::INSERT_SUBVECTOR series.
5569// The subvectors in Ops are guaranteed to be the same type.
5570static bool collectConcatOps(SDNode *N, SmallVectorImpl<SDValue> &Ops) {
5571 assert(Ops.empty() && "Expected an empty ops vector")((Ops.empty() && "Expected an empty ops vector") ? static_cast
<void> (0) : __assert_fail ("Ops.empty() && \"Expected an empty ops vector\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5571, __PRETTY_FUNCTION__))
;
5572
5573 if (N->getOpcode() == ISD::CONCAT_VECTORS) {
5574 Ops.append(N->op_begin(), N->op_end());
5575 return true;
5576 }
5577
5578 if (N->getOpcode() == ISD::INSERT_SUBVECTOR &&
5579 isa<ConstantSDNode>(N->getOperand(2))) {
5580 SDValue Src = N->getOperand(0);
5581 SDValue Sub = N->getOperand(1);
5582 const APInt &Idx = N->getConstantOperandAPInt(2);
5583 EVT VT = Src.getValueType();
5584 EVT SubVT = Sub.getValueType();
5585
5586 // TODO - Handle more general insert_subvector chains.
5587 if (VT.getSizeInBits() == (SubVT.getSizeInBits() * 2) &&
5588 Idx == (VT.getVectorNumElements() / 2) &&
5589 Src.getOpcode() == ISD::INSERT_SUBVECTOR &&
5590 Src.getOperand(1).getValueType() == SubVT &&
5591 isNullConstant(Src.getOperand(2))) {
5592 Ops.push_back(Src.getOperand(1));
5593 Ops.push_back(Sub);
5594 return true;
5595 }
5596 }
5597
5598 return false;
5599}
5600
5601// Helper for splitting operands of an operation to legal target size and
5602// apply a function on each part.
5603// Useful for operations that are available on SSE2 in 128-bit, on AVX2 in
5604// 256-bit and on AVX512BW in 512-bit. The argument VT is the type used for
5605// deciding if/how to split Ops. Ops elements do *not* have to be of type VT.
5606// The argument Builder is a function that will be applied on each split part:
5607// SDValue Builder(SelectionDAG&G, SDLoc, ArrayRef<SDValue>)
5608template <typename F>
5609SDValue SplitOpsAndApply(SelectionDAG &DAG, const X86Subtarget &Subtarget,
5610 const SDLoc &DL, EVT VT, ArrayRef<SDValue> Ops,
5611 F Builder, bool CheckBWI = true) {
5612 assert(Subtarget.hasSSE2() && "Target assumed to support at least SSE2")((Subtarget.hasSSE2() && "Target assumed to support at least SSE2"
) ? static_cast<void> (0) : __assert_fail ("Subtarget.hasSSE2() && \"Target assumed to support at least SSE2\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5612, __PRETTY_FUNCTION__))
;
5613 unsigned NumSubs = 1;
5614 if ((CheckBWI && Subtarget.useBWIRegs()) ||
5615 (!CheckBWI && Subtarget.useAVX512Regs())) {
5616 if (VT.getSizeInBits() > 512) {
5617 NumSubs = VT.getSizeInBits() / 512;
5618 assert((VT.getSizeInBits() % 512) == 0 && "Illegal vector size")(((VT.getSizeInBits() % 512) == 0 && "Illegal vector size"
) ? static_cast<void> (0) : __assert_fail ("(VT.getSizeInBits() % 512) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5618, __PRETTY_FUNCTION__))
;
5619 }
5620 } else if (Subtarget.hasAVX2()) {
5621 if (VT.getSizeInBits() > 256) {
5622 NumSubs = VT.getSizeInBits() / 256;
5623 assert((VT.getSizeInBits() % 256) == 0 && "Illegal vector size")(((VT.getSizeInBits() % 256) == 0 && "Illegal vector size"
) ? static_cast<void> (0) : __assert_fail ("(VT.getSizeInBits() % 256) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5623, __PRETTY_FUNCTION__))
;
5624 }
5625 } else {
5626 if (VT.getSizeInBits() > 128) {
5627 NumSubs = VT.getSizeInBits() / 128;
5628 assert((VT.getSizeInBits() % 128) == 0 && "Illegal vector size")(((VT.getSizeInBits() % 128) == 0 && "Illegal vector size"
) ? static_cast<void> (0) : __assert_fail ("(VT.getSizeInBits() % 128) == 0 && \"Illegal vector size\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5628, __PRETTY_FUNCTION__))
;
5629 }
5630 }
5631
5632 if (NumSubs == 1)
5633 return Builder(DAG, DL, Ops);
5634
5635 SmallVector<SDValue, 4> Subs;
5636 for (unsigned i = 0; i != NumSubs; ++i) {
5637 SmallVector<SDValue, 2> SubOps;
5638 for (SDValue Op : Ops) {
5639 EVT OpVT = Op.getValueType();
5640 unsigned NumSubElts = OpVT.getVectorNumElements() / NumSubs;
5641 unsigned SizeSub = OpVT.getSizeInBits() / NumSubs;
5642 SubOps.push_back(extractSubVector(Op, i * NumSubElts, DAG, DL, SizeSub));
5643 }
5644 Subs.push_back(Builder(DAG, DL, SubOps));
5645 }
5646 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Subs);
5647}
5648
5649/// Insert i1-subvector to i1-vector.
5650static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
5651 const X86Subtarget &Subtarget) {
5652
5653 SDLoc dl(Op);
5654 SDValue Vec = Op.getOperand(0);
5655 SDValue SubVec = Op.getOperand(1);
5656 SDValue Idx = Op.getOperand(2);
5657
5658 if (!isa<ConstantSDNode>(Idx))
5659 return SDValue();
5660
5661 // Inserting undef is a nop. We can just return the original vector.
5662 if (SubVec.isUndef())
5663 return Vec;
5664
5665 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5666 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
5667 return Op;
5668
5669 MVT OpVT = Op.getSimpleValueType();
5670 unsigned NumElems = OpVT.getVectorNumElements();
5671
5672 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
5673
5674 // Extend to natively supported kshift.
5675 MVT WideOpVT = OpVT;
5676 if ((!Subtarget.hasDQI() && NumElems == 8) || NumElems < 8)
5677 WideOpVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
5678
5679 // Inserting into the lsbs of a zero vector is legal. ISel will insert shifts
5680 // if necessary.
5681 if (IdxVal == 0 && ISD::isBuildVectorAllZeros(Vec.getNode())) {
5682 // May need to promote to a legal type.
5683 Op = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5684 DAG.getConstant(0, dl, WideOpVT),
5685 SubVec, Idx);
5686 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5687 }
5688
5689 MVT SubVecVT = SubVec.getSimpleValueType();
5690 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
5691
5692 assert(IdxVal + SubVecNumElems <= NumElems &&((IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT
.getSizeInBits() == 0 && "Unexpected index value in INSERT_SUBVECTOR"
) ? static_cast<void> (0) : __assert_fail ("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5694, __PRETTY_FUNCTION__))
5693 IdxVal % SubVecVT.getSizeInBits() == 0 &&((IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT
.getSizeInBits() == 0 && "Unexpected index value in INSERT_SUBVECTOR"
) ? static_cast<void> (0) : __assert_fail ("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5694, __PRETTY_FUNCTION__))
5694 "Unexpected index value in INSERT_SUBVECTOR")((IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT
.getSizeInBits() == 0 && "Unexpected index value in INSERT_SUBVECTOR"
) ? static_cast<void> (0) : __assert_fail ("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5694, __PRETTY_FUNCTION__))
;
5695
5696 SDValue Undef = DAG.getUNDEF(WideOpVT);
5697
5698 if (IdxVal == 0) {
5699 // Zero lower bits of the Vec
5700 SDValue ShiftBits = DAG.getTargetConstant(SubVecNumElems, dl, MVT::i8);
5701 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec,
5702 ZeroIdx);
5703 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5704 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5705 // Merge them together, SubVec should be zero extended.
5706 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5707 DAG.getConstant(0, dl, WideOpVT),
5708 SubVec, ZeroIdx);
5709 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5710 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5711 }
5712
5713 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5714 Undef, SubVec, ZeroIdx);
5715
5716 if (Vec.isUndef()) {
5717 assert(IdxVal != 0 && "Unexpected index")((IdxVal != 0 && "Unexpected index") ? static_cast<
void> (0) : __assert_fail ("IdxVal != 0 && \"Unexpected index\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5717, __PRETTY_FUNCTION__))
;
5718 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5719 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
5720 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5721 }
5722
5723 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
5724 assert(IdxVal != 0 && "Unexpected index")((IdxVal != 0 && "Unexpected index") ? static_cast<
void> (0) : __assert_fail ("IdxVal != 0 && \"Unexpected index\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5724, __PRETTY_FUNCTION__))
;
5725 NumElems = WideOpVT.getVectorNumElements();
5726 unsigned ShiftLeft = NumElems - SubVecNumElems;
5727 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5728 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5729 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
5730 if (ShiftRight != 0)
5731 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
5732 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
5733 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5734 }
5735
5736 // Simple case when we put subvector in the upper part
5737 if (IdxVal + SubVecNumElems == NumElems) {
5738 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5739 DAG.getTargetConstant(IdxVal, dl, MVT::i8));
5740 if (SubVecNumElems * 2 == NumElems) {
5741 // Special case, use legal zero extending insert_subvector. This allows
5742 // isel to opimitize when bits are known zero.
5743 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVecVT, Vec, ZeroIdx);
5744 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5745 DAG.getConstant(0, dl, WideOpVT),
5746 Vec, ZeroIdx);
5747 } else {
5748 // Otherwise use explicit shifts to zero the bits.
5749 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5750 Undef, Vec, ZeroIdx);
5751 NumElems = WideOpVT.getVectorNumElements();
5752 SDValue ShiftBits = DAG.getTargetConstant(NumElems - IdxVal, dl, MVT::i8);
5753 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5754 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5755 }
5756 Op = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, SubVec);
5757 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, Op, ZeroIdx);
5758 }
5759
5760 // Inserting into the middle is more complicated.
5761
5762 NumElems = WideOpVT.getVectorNumElements();
5763
5764 // Widen the vector if needed.
5765 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
5766
5767 // Clear the upper bits of the subvector and move it to its insert position.
5768 unsigned ShiftLeft = NumElems - SubVecNumElems;
5769 SubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, SubVec,
5770 DAG.getTargetConstant(ShiftLeft, dl, MVT::i8));
5771 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5772 SubVec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, SubVec,
5773 DAG.getTargetConstant(ShiftRight, dl, MVT::i8));
5774
5775 // Isolate the bits below the insertion point.
5776 unsigned LowShift = NumElems - IdxVal;
5777 SDValue Low = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec,
5778 DAG.getTargetConstant(LowShift, dl, MVT::i8));
5779 Low = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Low,
5780 DAG.getTargetConstant(LowShift, dl, MVT::i8));
5781
5782 // Isolate the bits after the last inserted bit.
5783 unsigned HighShift = IdxVal + SubVecNumElems;
5784 SDValue High = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
5785 DAG.getTargetConstant(HighShift, dl, MVT::i8));
5786 High = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, High,
5787 DAG.getTargetConstant(HighShift, dl, MVT::i8));
5788
5789 // Now OR all 3 pieces together.
5790 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Low, High);
5791 SubVec = DAG.getNode(ISD::OR, dl, WideOpVT, SubVec, Vec);
5792
5793 // Reduce to original width if needed.
5794 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OpVT, SubVec, ZeroIdx);
5795}
5796
5797static SDValue concatSubVectors(SDValue V1, SDValue V2, SelectionDAG &DAG,
5798 const SDLoc &dl) {
5799 assert(V1.getValueType() == V2.getValueType() && "subvector type mismatch")((V1.getValueType() == V2.getValueType() && "subvector type mismatch"
) ? static_cast<void> (0) : __assert_fail ("V1.getValueType() == V2.getValueType() && \"subvector type mismatch\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5799, __PRETTY_FUNCTION__))
;
5800 EVT SubVT = V1.getValueType();
5801 EVT SubSVT = SubVT.getScalarType();
5802 unsigned SubNumElts = SubVT.getVectorNumElements();
5803 unsigned SubVectorWidth = SubVT.getSizeInBits();
5804 EVT VT = EVT::getVectorVT(*DAG.getContext(), SubSVT, 2 * SubNumElts);
5805 SDValue V = insertSubVector(DAG.getUNDEF(VT), V1, 0, DAG, dl, SubVectorWidth);
5806 return insertSubVector(V, V2, SubNumElts, DAG, dl, SubVectorWidth);
5807}
5808
5809/// Returns a vector of specified type with all bits set.
5810/// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
5811/// Then bitcast to their original type, ensuring they get CSE'd.
5812static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5813 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
()) && "Expected a 128/256/512-bit vector type") ? static_cast
<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected a 128/256/512-bit vector type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5814, __PRETTY_FUNCTION__))
5814 "Expected a 128/256/512-bit vector type")(((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector
()) && "Expected a 128/256/512-bit vector type") ? static_cast
<void> (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected a 128/256/512-bit vector type\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5814, __PRETTY_FUNCTION__))
;
5815
5816 APInt Ones = APInt::getAllOnesValue(32);
5817 unsigned NumElts = VT.getSizeInBits() / 32;
5818 SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
5819 return DAG.getBitcast(VT, Vec);
5820}
5821
5822// Convert *_EXTEND to *_EXTEND_VECTOR_INREG opcode.
5823static unsigned getOpcode_EXTEND_VECTOR_INREG(unsigned Opcode) {
5824 switch (Opcode) {
5825 case ISD::ANY_EXTEND:
5826 case ISD::ANY_EXTEND_VECTOR_INREG:
5827 return ISD::ANY_EXTEND_VECTOR_INREG;
5828 case ISD::ZERO_EXTEND:
5829 case ISD::ZERO_EXTEND_VECTOR_INREG:
5830 return ISD::ZERO_EXTEND_VECTOR_INREG;
5831 case ISD::SIGN_EXTEND:
5832 case ISD::SIGN_EXTEND_VECTOR_INREG:
5833 return ISD::SIGN_EXTEND_VECTOR_INREG;
5834 }
5835 llvm_unreachable("Unknown opcode")::llvm::llvm_unreachable_internal("Unknown opcode", "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5835)
;
5836}
5837
5838static SDValue getExtendInVec(unsigned Opcode, const SDLoc &DL, EVT VT,
5839 SDValue In, SelectionDAG &DAG) {
5840 EVT InVT = In.getValueType();
5841 assert(VT.isVector() && InVT.isVector() && "Expected vector VTs.")((VT.isVector() && InVT.isVector() && "Expected vector VTs."
) ? static_cast<void> (0) : __assert_fail ("VT.isVector() && InVT.isVector() && \"Expected vector VTs.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5841, __PRETTY_FUNCTION__))
;
5842 assert((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||(((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
ISD::ZERO_EXTEND == Opcode) && "Unknown extension opcode"
) ? static_cast<void> (0) : __assert_fail ("(ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode || ISD::ZERO_EXTEND == Opcode) && \"Unknown extension opcode\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5844, __PRETTY_FUNCTION__))
5843 ISD::ZERO_EXTEND == Opcode) &&(((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
ISD::ZERO_EXTEND == Opcode) && "Unknown extension opcode"
) ? static_cast<void> (0) : __assert_fail ("(ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode || ISD::ZERO_EXTEND == Opcode) && \"Unknown extension opcode\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5844, __PRETTY_FUNCTION__))
5844 "Unknown extension opcode")(((ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode ||
ISD::ZERO_EXTEND == Opcode) && "Unknown extension opcode"
) ? static_cast<void> (0) : __assert_fail ("(ISD::ANY_EXTEND == Opcode || ISD::SIGN_EXTEND == Opcode || ISD::ZERO_EXTEND == Opcode) && \"Unknown extension opcode\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5844, __PRETTY_FUNCTION__))
;
5845
5846 // For 256-bit vectors, we only need the lower (128-bit) input half.
5847 // For 512-bit vectors, we only need the lower input half or quarter.
5848 if (InVT.getSizeInBits() > 128) {
5849 assert(VT.getSizeInBits() == InVT.getSizeInBits() &&((VT.getSizeInBits() == InVT.getSizeInBits() && "Expected VTs to be the same size!"
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() == InVT.getSizeInBits() && \"Expected VTs to be the same size!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5850, __PRETTY_FUNCTION__))
5850 "Expected VTs to be the same size!")((VT.getSizeInBits() == InVT.getSizeInBits() && "Expected VTs to be the same size!"
) ? static_cast<void> (0) : __assert_fail ("VT.getSizeInBits() == InVT.getSizeInBits() && \"Expected VTs to be the same size!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/lib/Target/X86/X86ISelLowering.cpp"
, 5850, __PRETTY_FUNCTION__))
;
5851 unsigned Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
5852 In = extractSubVector(In, 0, DAG, DL,
5853 std::max(128U, VT.getSizeInBits() / Scale));
5854 InVT = In.getValueType();
5855 }
5856
5857 if (VT.getVectorNumElements() != InVT.getVectorNumElements())
5858 Opcode = getOpcode_EXTEND_VECTOR_INREG(Opcode);
5859
5860 return DAG.getNode(Opcode, DL, VT, In);
5861}
5862
5863// Match (xor X, -1) -> X.
5864// Match extract_subvector(xor X, -1) -> extract_subvector(X).
5865// Match concat_vectors(xor X, -1, xor Y, -1) -> concat_vectors(X, Y).
5866static SDValue IsNOT(SDValue V, SelectionDAG &DAG) {
5867 V = peekThroughBitcasts(V);
5868 if (V.getOpcode() == ISD::XOR &&
5869 ISD::isBuildVectorAllOnes(V.getOperand(1).getNode()))
5870 return V.getOperand(0);
5871 if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5872 (isNullConstant(V.getOperand(1)) || V.getOperand(0).hasOneUse())) {
5873 if (SDValue Not = IsNOT(V.getOperand(0), DAG)) {
5874 Not = DAG.getBitcast(V.getOperand(0).getValueType(), Not);
5875 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Not), V.getValueType(),
5876 Not, V.getOperand(1));
5877 }
5878 }
5879 SmallVector<SDValue, 2> CatOps;
5880 if (collectConcatOps(V.getNode(), CatOps)) {
5881 for (SDValue &CatOp : CatOps) {
5882 SDValue NotCat = IsNOT(CatOp, DAG);
5883 if (!NotCat) return SDValue();
5884 CatOp = DAG.getBitcast(CatOp.getValueType(), NotCat);
5885 }