Bug Summary

File:lib/Target/X86/X86ISelLowering.cpp
Warning:line 6667, column 1
Potential leak of memory pointed to by 'ZeroMask.X'

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp

1//===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the interfaces that X86 uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86ISelLowering.h"
16#include "Utils/X86ShuffleDecode.h"
17#include "X86CallingConv.h"
18#include "X86FrameLowering.h"
19#include "X86InstrBuilder.h"
20#include "X86IntrinsicsInfo.h"
21#include "X86MachineFunctionInfo.h"
22#include "X86ShuffleDecodeConstantPool.h"
23#include "X86TargetMachine.h"
24#include "X86TargetObjectFile.h"
25#include "llvm/ADT/SmallBitVector.h"
26#include "llvm/ADT/SmallSet.h"
27#include "llvm/ADT/Statistic.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/Analysis/EHPersonalities.h"
31#include "llvm/CodeGen/IntrinsicLowering.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineFunction.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
38#include "llvm/CodeGen/TargetLowering.h"
39#include "llvm/CodeGen/WinEHFuncInfo.h"
40#include "llvm/IR/CallSite.h"
41#include "llvm/IR/CallingConv.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/DerivedTypes.h"
44#include "llvm/IR/DiagnosticInfo.h"
45#include "llvm/IR/Function.h"
46#include "llvm/IR/GlobalAlias.h"
47#include "llvm/IR/GlobalVariable.h"
48#include "llvm/IR/Instructions.h"
49#include "llvm/IR/Intrinsics.h"
50#include "llvm/MC/MCAsmInfo.h"
51#include "llvm/MC/MCContext.h"
52#include "llvm/MC/MCExpr.h"
53#include "llvm/MC/MCSymbol.h"
54#include "llvm/Support/CommandLine.h"
55#include "llvm/Support/Debug.h"
56#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/KnownBits.h"
58#include "llvm/Support/MathExtras.h"
59#include "llvm/Target/TargetOptions.h"
60#include <algorithm>
61#include <bitset>
62#include <cctype>
63#include <numeric>
64using namespace llvm;
65
66#define DEBUG_TYPE"x86-isel" "x86-isel"
67
68STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"x86-isel", "NumTailCalls"
, "Number of tail calls", {0}, false}
;
69
70static cl::opt<bool> ExperimentalVectorWideningLegalization(
71 "x86-experimental-vector-widening-legalization", cl::init(false),
72 cl::desc("Enable an experimental vector type legalization through widening "
73 "rather than promotion."),
74 cl::Hidden);
75
76static cl::opt<int> ExperimentalPrefLoopAlignment(
77 "x86-experimental-pref-loop-alignment", cl::init(4),
78 cl::desc("Sets the preferable loop alignment for experiments "
79 "(the last x86-experimental-pref-loop-alignment bits"
80 " of the loop header PC will be 0)."),
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
89/// Call this when the user attempts to do something unsupported, like
90/// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
91/// report_fatal_error, so calling code should attempt to recover without
92/// crashing.
93static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
94 const char *Msg) {
95 MachineFunction &MF = DAG.getMachineFunction();
96 DAG.getContext()->diagnose(
97 DiagnosticInfoUnsupported(*MF.getFunction(), Msg, dl.getDebugLoc()));
98}
99
100X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
101 const X86Subtarget &STI)
102 : TargetLowering(TM), Subtarget(STI) {
103 bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
104 X86ScalarSSEf64 = Subtarget.hasSSE2();
105 X86ScalarSSEf32 = Subtarget.hasSSE1();
106 MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
107
108 // Set up the TargetLowering object.
109
110 // X86 is weird. It always uses i8 for shift amounts and setcc results.
111 setBooleanContents(ZeroOrOneBooleanContent);
112 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
113 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
114
115 // For 64-bit, since we have so many registers, use the ILP scheduler.
116 // For 32-bit, use the register pressure specific scheduling.
117 // For Atom, always use ILP scheduling.
118 if (Subtarget.isAtom())
119 setSchedulingPreference(Sched::ILP);
120 else if (Subtarget.is64Bit())
121 setSchedulingPreference(Sched::ILP);
122 else
123 setSchedulingPreference(Sched::RegPressure);
124 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
125 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
126
127 // Bypass expensive divides and use cheaper ones.
128 if (TM.getOptLevel() >= CodeGenOpt::Default) {
129 if (Subtarget.hasSlowDivide32())
130 addBypassSlowDiv(32, 8);
131 if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
132 addBypassSlowDiv(64, 32);
133 }
134
135 if (Subtarget.isTargetKnownWindowsMSVC() ||
136 Subtarget.isTargetWindowsItanium()) {
137 // Setup Windows compiler runtime calls.
138 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
139 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
140 setLibcallName(RTLIB::SREM_I64, "_allrem");
141 setLibcallName(RTLIB::UREM_I64, "_aullrem");
142 setLibcallName(RTLIB::MUL_I64, "_allmul");
143 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
144 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
145 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
146 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
147 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
148 }
149
150 if (Subtarget.isTargetDarwin()) {
151 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
152 setUseUnderscoreSetJmp(false);
153 setUseUnderscoreLongJmp(false);
154 } else if (Subtarget.isTargetWindowsGNU()) {
155 // MS runtime is weird: it exports _setjmp, but longjmp!
156 setUseUnderscoreSetJmp(true);
157 setUseUnderscoreLongJmp(false);
158 } else {
159 setUseUnderscoreSetJmp(true);
160 setUseUnderscoreLongJmp(true);
161 }
162
163 // Set up the register classes.
164 addRegisterClass(MVT::i8, &X86::GR8RegClass);
165 addRegisterClass(MVT::i16, &X86::GR16RegClass);
166 addRegisterClass(MVT::i32, &X86::GR32RegClass);
167 if (Subtarget.is64Bit())
168 addRegisterClass(MVT::i64, &X86::GR64RegClass);
169
170 for (MVT VT : MVT::integer_valuetypes())
171 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
172
173 // We don't accept any truncstore of integer registers.
174 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
175 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
176 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
177 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
178 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
179 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
180
181 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
182
183 // SETOEQ and SETUNE require checking two conditions.
184 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
185 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
186 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
187 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
188 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
189 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
190
191 // Integer absolute.
192 if (Subtarget.hasCMov()) {
193 setOperationAction(ISD::ABS , MVT::i16 , Custom);
194 setOperationAction(ISD::ABS , MVT::i32 , Custom);
195 if (Subtarget.is64Bit())
196 setOperationAction(ISD::ABS , MVT::i64 , Custom);
197 }
198
199 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
200 // operation.
201 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
202 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
203 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
204
205 if (Subtarget.is64Bit()) {
206 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
207 // f32/f64 are legal, f80 is custom.
208 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
209 else
210 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
211 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
212 } else if (!Subtarget.useSoftFloat()) {
213 // We have an algorithm for SSE2->double, and we turn this into a
214 // 64-bit FILD followed by conditional FADD for other targets.
215 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
216 // We have an algorithm for SSE2, and we turn this into a 64-bit
217 // FILD or VCVTUSI2SS/SD for other targets.
218 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
219 }
220
221 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
222 // this operation.
223 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
224 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
225
226 if (!Subtarget.useSoftFloat()) {
227 // SSE has no i16 to fp conversion, only i32.
228 if (X86ScalarSSEf32) {
229 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
230 // f32 and f64 cases are Legal, f80 case is not
231 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
232 } else {
233 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
234 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
235 }
236 } else {
237 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
238 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
239 }
240
241 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
242 // this operation.
243 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
244 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
245
246 if (!Subtarget.useSoftFloat()) {
247 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
248 // are Legal, f80 is custom lowered.
249 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
250 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
251
252 if (X86ScalarSSEf32) {
253 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
254 // f32 and f64 cases are Legal, f80 case is not
255 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
256 } else {
257 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
258 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
259 }
260 } else {
261 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
262 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Expand);
263 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Expand);
264 }
265
266 // Handle FP_TO_UINT by promoting the destination to a larger signed
267 // conversion.
268 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
269 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
270 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
271
272 if (Subtarget.is64Bit()) {
273 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
274 // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
275 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
276 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
277 } else {
278 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
279 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
280 }
281 } else if (!Subtarget.useSoftFloat()) {
282 // Since AVX is a superset of SSE3, only check for SSE here.
283 if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
284 // Expand FP_TO_UINT into a select.
285 // FIXME: We would like to use a Custom expander here eventually to do
286 // the optimal thing for SSE vs. the default expansion in the legalizer.
287 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
288 else
289 // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
290 // With SSE3 we can use fisttpll to convert to a signed i64; without
291 // SSE, we're stuck with a fistpll.
292 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
293
294 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
295 }
296
297 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
298 if (!X86ScalarSSEf64) {
299 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
300 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
301 if (Subtarget.is64Bit()) {
302 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
303 // Without SSE, i64->f64 goes through memory.
304 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
305 }
306 } else if (!Subtarget.is64Bit())
307 setOperationAction(ISD::BITCAST , MVT::i64 , Custom);
308
309 // Scalar integer divide and remainder are lowered to use operations that
310 // produce two results, to match the available instructions. This exposes
311 // the two-result form to trivial CSE, which is able to combine x/y and x%y
312 // into a single instruction.
313 //
314 // Scalar integer multiply-high is also lowered to use two-result
315 // operations, to match the available instructions. However, plain multiply
316 // (low) operations are left as Legal, as there are single-result
317 // instructions for this in x86. Using the two-result multiply instructions
318 // when both high and low results are needed must be arranged by dagcombine.
319 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
320 setOperationAction(ISD::MULHS, VT, Expand);
321 setOperationAction(ISD::MULHU, VT, Expand);
322 setOperationAction(ISD::SDIV, VT, Expand);
323 setOperationAction(ISD::UDIV, VT, Expand);
324 setOperationAction(ISD::SREM, VT, Expand);
325 setOperationAction(ISD::UREM, VT, Expand);
326 }
327
328 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
329 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
330 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
331 MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
332 setOperationAction(ISD::BR_CC, VT, Expand);
333 setOperationAction(ISD::SELECT_CC, VT, Expand);
334 }
335 if (Subtarget.is64Bit())
336 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
337 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
338 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
339 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
340 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
341
342 setOperationAction(ISD::FREM , MVT::f32 , Expand);
343 setOperationAction(ISD::FREM , MVT::f64 , Expand);
344 setOperationAction(ISD::FREM , MVT::f80 , Expand);
345 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
346
347 // Promote the i8 variants and force them on up to i32 which has a shorter
348 // encoding.
349 setOperationPromotedToType(ISD::CTTZ , MVT::i8 , MVT::i32);
350 setOperationPromotedToType(ISD::CTTZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
351 if (!Subtarget.hasBMI()) {
352 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
353 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
354 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Legal);
355 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Legal);
356 if (Subtarget.is64Bit()) {
357 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
358 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Legal);
359 }
360 }
361
362 if (Subtarget.hasLZCNT()) {
363 // When promoting the i8 variants, force them to i32 for a shorter
364 // encoding.
365 setOperationPromotedToType(ISD::CTLZ , MVT::i8 , MVT::i32);
366 setOperationPromotedToType(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
367 } else {
368 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
369 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
370 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
371 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
372 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
373 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
374 if (Subtarget.is64Bit()) {
375 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
376 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
377 }
378 }
379
380 // Special handling for half-precision floating point conversions.
381 // If we don't have F16C support, then lower half float conversions
382 // into library calls.
383 if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
384 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
385 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
386 }
387
388 // There's never any support for operations beyond MVT::f32.
389 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
390 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
391 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
392 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
393
394 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
395 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
396 setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
397 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
398 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
399 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
400
401 if (Subtarget.hasPOPCNT()) {
402 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
403 } else {
404 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
405 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
406 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
407 if (Subtarget.is64Bit())
408 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
409 }
410
411 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
412
413 if (!Subtarget.hasMOVBE())
414 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
415
416 // These should be promoted to a larger select which is supported.
417 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
418 // X86 wants to expand cmov itself.
419 for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
420 setOperationAction(ISD::SELECT, VT, Custom);
421 setOperationAction(ISD::SETCC, VT, Custom);
422 }
423 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
424 if (VT == MVT::i64 && !Subtarget.is64Bit())
425 continue;
426 setOperationAction(ISD::SELECT, VT, Custom);
427 setOperationAction(ISD::SETCC, VT, Custom);
428 }
429
430 // Custom action for SELECT MMX and expand action for SELECT_CC MMX
431 setOperationAction(ISD::SELECT, MVT::x86mmx, Custom);
432 setOperationAction(ISD::SELECT_CC, MVT::x86mmx, Expand);
433
434 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
435 // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
436 // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
437 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
438 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
439 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
440 if (TM.Options.ExceptionModel == ExceptionHandling::SjLj)
441 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
442
443 // Darwin ABI issue.
444 for (auto VT : { MVT::i32, MVT::i64 }) {
445 if (VT == MVT::i64 && !Subtarget.is64Bit())
446 continue;
447 setOperationAction(ISD::ConstantPool , VT, Custom);
448 setOperationAction(ISD::JumpTable , VT, Custom);
449 setOperationAction(ISD::GlobalAddress , VT, Custom);
450 setOperationAction(ISD::GlobalTLSAddress, VT, Custom);
451 setOperationAction(ISD::ExternalSymbol , VT, Custom);
452 setOperationAction(ISD::BlockAddress , VT, Custom);
453 }
454
455 // 64-bit shl, sra, srl (iff 32-bit x86)
456 for (auto VT : { MVT::i32, MVT::i64 }) {
457 if (VT == MVT::i64 && !Subtarget.is64Bit())
458 continue;
459 setOperationAction(ISD::SHL_PARTS, VT, Custom);
460 setOperationAction(ISD::SRA_PARTS, VT, Custom);
461 setOperationAction(ISD::SRL_PARTS, VT, Custom);
462 }
463
464 if (Subtarget.hasSSE1())
465 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
466
467 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
468
469 // Expand certain atomics
470 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
471 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
472 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
473 setOperationAction(ISD::ATOMIC_LOAD_ADD, VT, Custom);
474 setOperationAction(ISD::ATOMIC_LOAD_OR, VT, Custom);
475 setOperationAction(ISD::ATOMIC_LOAD_XOR, VT, Custom);
476 setOperationAction(ISD::ATOMIC_LOAD_AND, VT, Custom);
477 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
478 }
479
480 if (Subtarget.hasCmpxchg16b()) {
481 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
482 }
483
484 // FIXME - use subtarget debug flags
485 if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
486 !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
487 TM.Options.ExceptionModel != ExceptionHandling::SjLj) {
488 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
489 }
490
491 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
492 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
493
494 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
495 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
496
497 setOperationAction(ISD::TRAP, MVT::Other, Legal);
498 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
499
500 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
501 setOperationAction(ISD::VASTART , MVT::Other, Custom);
502 setOperationAction(ISD::VAEND , MVT::Other, Expand);
503 bool Is64Bit = Subtarget.is64Bit();
504 setOperationAction(ISD::VAARG, MVT::Other, Is64Bit ? Custom : Expand);
505 setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
506
507 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
508 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
509
510 setOperationAction(ISD::DYNAMIC_STACKALLOC, PtrVT, Custom);
511
512 // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
513 setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
514 setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
515
516 if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
517 // f32 and f64 use SSE.
518 // Set up the FP register classes.
519 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
520 : &X86::FR32RegClass);
521 addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
522 : &X86::FR64RegClass);
523
524 for (auto VT : { MVT::f32, MVT::f64 }) {
525 // Use ANDPD to simulate FABS.
526 setOperationAction(ISD::FABS, VT, Custom);
527
528 // Use XORP to simulate FNEG.
529 setOperationAction(ISD::FNEG, VT, Custom);
530
531 // Use ANDPD and ORPD to simulate FCOPYSIGN.
532 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
533
534 // We don't support sin/cos/fmod
535 setOperationAction(ISD::FSIN , VT, Expand);
536 setOperationAction(ISD::FCOS , VT, Expand);
537 setOperationAction(ISD::FSINCOS, VT, Expand);
538 }
539
540 // Lower this to MOVMSK plus an AND.
541 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
542 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
543
544 // Expand FP immediates into loads from the stack, except for the special
545 // cases we handle.
546 addLegalFPImmediate(APFloat(+0.0)); // xorpd
547 addLegalFPImmediate(APFloat(+0.0f)); // xorps
548 } else if (UseX87 && X86ScalarSSEf32) {
549 // Use SSE for f32, x87 for f64.
550 // Set up the FP register classes.
551 addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
552 : &X86::FR32RegClass);
553 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
554
555 // Use ANDPS to simulate FABS.
556 setOperationAction(ISD::FABS , MVT::f32, Custom);
557
558 // Use XORP to simulate FNEG.
559 setOperationAction(ISD::FNEG , MVT::f32, Custom);
560
561 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
562
563 // Use ANDPS and ORPS to simulate FCOPYSIGN.
564 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
565 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
566
567 // We don't support sin/cos/fmod
568 setOperationAction(ISD::FSIN , MVT::f32, Expand);
569 setOperationAction(ISD::FCOS , MVT::f32, Expand);
570 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
571
572 // Special cases we handle for FP constants.
573 addLegalFPImmediate(APFloat(+0.0f)); // xorps
574 addLegalFPImmediate(APFloat(+0.0)); // FLD0
575 addLegalFPImmediate(APFloat(+1.0)); // FLD1
576 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
577 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
578
579 // Always expand sin/cos functions even though x87 has an instruction.
580 setOperationAction(ISD::FSIN , MVT::f64, Expand);
581 setOperationAction(ISD::FCOS , MVT::f64, Expand);
582 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
583 } else if (UseX87) {
584 // f32 and f64 in x87.
585 // Set up the FP register classes.
586 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589 for (auto VT : { MVT::f32, MVT::f64 }) {
590 setOperationAction(ISD::UNDEF, VT, Expand);
591 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
592
593 // Always expand sin/cos functions even though x87 has an instruction.
594 setOperationAction(ISD::FSIN , VT, Expand);
595 setOperationAction(ISD::FCOS , VT, Expand);
596 setOperationAction(ISD::FSINCOS, VT, Expand);
597 }
598 addLegalFPImmediate(APFloat(+0.0)); // FLD0
599 addLegalFPImmediate(APFloat(+1.0)); // FLD1
600 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
601 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
602 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
603 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
604 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
605 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
606 }
607
608 // We don't support FMA.
609 setOperationAction(ISD::FMA, MVT::f64, Expand);
610 setOperationAction(ISD::FMA, MVT::f32, Expand);
611
612 // Long double always uses X87, except f128 in MMX.
613 if (UseX87) {
614 if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
615 addRegisterClass(MVT::f128, &X86::FR128RegClass);
616 ValueTypeActions.setTypeAction(MVT::f128, TypeSoftenFloat);
617 setOperationAction(ISD::FABS , MVT::f128, Custom);
618 setOperationAction(ISD::FNEG , MVT::f128, Custom);
619 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Custom);
620 }
621
622 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
623 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
624 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
625 {
626 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended());
627 addLegalFPImmediate(TmpFlt); // FLD0
628 TmpFlt.changeSign();
629 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
630
631 bool ignored;
632 APFloat TmpFlt2(+1.0);
633 TmpFlt2.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven,
634 &ignored);
635 addLegalFPImmediate(TmpFlt2); // FLD1
636 TmpFlt2.changeSign();
637 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
638 }
639
640 // Always expand sin/cos functions even though x87 has an instruction.
641 setOperationAction(ISD::FSIN , MVT::f80, Expand);
642 setOperationAction(ISD::FCOS , MVT::f80, Expand);
643 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
644
645 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
646 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
647 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
648 setOperationAction(ISD::FRINT, MVT::f80, Expand);
649 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
650 setOperationAction(ISD::FMA, MVT::f80, Expand);
651 }
652
653 // Always use a library call for pow.
654 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
655 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
656 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
657
658 setOperationAction(ISD::FLOG, MVT::f80, Expand);
659 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
660 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
661 setOperationAction(ISD::FEXP, MVT::f80, Expand);
662 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
663 setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
664 setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
665
666 // Some FP actions are always expanded for vector types.
667 for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
668 MVT::v2f64, MVT::v4f64, MVT::v8f64 }) {
669 setOperationAction(ISD::FSIN, VT, Expand);
670 setOperationAction(ISD::FSINCOS, VT, Expand);
671 setOperationAction(ISD::FCOS, VT, Expand);
672 setOperationAction(ISD::FREM, VT, Expand);
673 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
674 setOperationAction(ISD::FPOW, VT, Expand);
675 setOperationAction(ISD::FLOG, VT, Expand);
676 setOperationAction(ISD::FLOG2, VT, Expand);
677 setOperationAction(ISD::FLOG10, VT, Expand);
678 setOperationAction(ISD::FEXP, VT, Expand);
679 setOperationAction(ISD::FEXP2, VT, Expand);
680 }
681
682 // First set operation action for all vector types to either promote
683 // (for widening) or expand (for scalarization). Then we will selectively
684 // turn on ones that can be effectively codegen'd.
685 for (MVT VT : MVT::vector_valuetypes()) {
686 setOperationAction(ISD::SDIV, VT, Expand);
687 setOperationAction(ISD::UDIV, VT, Expand);
688 setOperationAction(ISD::SREM, VT, Expand);
689 setOperationAction(ISD::UREM, VT, Expand);
690 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
691 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
692 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
693 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
694 setOperationAction(ISD::FMA, VT, Expand);
695 setOperationAction(ISD::FFLOOR, VT, Expand);
696 setOperationAction(ISD::FCEIL, VT, Expand);
697 setOperationAction(ISD::FTRUNC, VT, Expand);
698 setOperationAction(ISD::FRINT, VT, Expand);
699 setOperationAction(ISD::FNEARBYINT, VT, Expand);
700 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701 setOperationAction(ISD::MULHS, VT, Expand);
702 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703 setOperationAction(ISD::MULHU, VT, Expand);
704 setOperationAction(ISD::SDIVREM, VT, Expand);
705 setOperationAction(ISD::UDIVREM, VT, Expand);
706 setOperationAction(ISD::CTPOP, VT, Expand);
707 setOperationAction(ISD::CTTZ, VT, Expand);
708 setOperationAction(ISD::CTLZ, VT, Expand);
709 setOperationAction(ISD::ROTL, VT, Expand);
710 setOperationAction(ISD::ROTR, VT, Expand);
711 setOperationAction(ISD::BSWAP, VT, Expand);
712 setOperationAction(ISD::SETCC, VT, Expand);
713 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
714 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
715 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
716 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
717 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
718 setOperationAction(ISD::TRUNCATE, VT, Expand);
719 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
720 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
721 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
722 setOperationAction(ISD::SELECT_CC, VT, Expand);
723 for (MVT InnerVT : MVT::vector_valuetypes()) {
724 setTruncStoreAction(InnerVT, VT, Expand);
725
726 setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
727 setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
728
729 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
730 // types, we have to deal with them whether we ask for Expansion or not.
731 // Setting Expand causes its own optimisation problems though, so leave
732 // them legal.
733 if (VT.getVectorElementType() == MVT::i1)
734 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
735
736 // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
737 // split/scalarized right now.
738 if (VT.getVectorElementType() == MVT::f16)
739 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
740 }
741 }
742
743 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
744 // with -msoft-float, disable use of MMX as well.
745 if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
746 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
747 // No operations on x86mmx supported, everything uses intrinsics.
748 }
749
750 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
751 addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
752 : &X86::VR128RegClass);
753
754 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
755 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
756 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Custom);
757 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
758 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
759 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
760 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
761 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
762 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
763 }
764
765 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
766 addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
767 : &X86::VR128RegClass);
768
769 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
770 // registers cannot be used even for integer operations.
771 addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
772 : &X86::VR128RegClass);
773 addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
774 : &X86::VR128RegClass);
775 addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
776 : &X86::VR128RegClass);
777 addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
778 : &X86::VR128RegClass);
779
780 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
781 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
782 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
783 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
784 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
785 setOperationAction(ISD::MULHU, MVT::v16i8, Custom);
786 setOperationAction(ISD::MULHS, MVT::v16i8, Custom);
787 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
788 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
789 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
790 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
791 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
792 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Custom);
793
794 setOperationAction(ISD::SMAX, MVT::v8i16, Legal);
795 setOperationAction(ISD::UMAX, MVT::v16i8, Legal);
796 setOperationAction(ISD::SMIN, MVT::v8i16, Legal);
797 setOperationAction(ISD::UMIN, MVT::v16i8, Legal);
798
799 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
800 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
801 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
802
803 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
804 setOperationAction(ISD::SETCC, VT, Custom);
805 setOperationAction(ISD::CTPOP, VT, Custom);
806 setOperationAction(ISD::CTTZ, VT, Custom);
807 }
808
809 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
810 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
811 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
812 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
813 setOperationAction(ISD::VSELECT, VT, Custom);
814 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
815 }
816
817 // We support custom legalizing of sext and anyext loads for specific
818 // memory vector types which we can load as a scalar (or sequence of
819 // scalars) and extend in-register to a legal 128-bit vector type. For sext
820 // loads these must work with a single scalar load.
821 for (MVT VT : MVT::integer_vector_valuetypes()) {
822 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
823 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
824 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
825 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
826 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
827 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
828 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
829 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
830 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
831 }
832
833 for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
834 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
835 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
836 setOperationAction(ISD::VSELECT, VT, Custom);
837
838 if (VT == MVT::v2i64 && !Subtarget.is64Bit())
839 continue;
840
841 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
842 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
843 }
844
845 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
846 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
847 setOperationPromotedToType(ISD::AND, VT, MVT::v2i64);
848 setOperationPromotedToType(ISD::OR, VT, MVT::v2i64);
849 setOperationPromotedToType(ISD::XOR, VT, MVT::v2i64);
850 setOperationPromotedToType(ISD::LOAD, VT, MVT::v2i64);
851 setOperationPromotedToType(ISD::SELECT, VT, MVT::v2i64);
852 }
853
854 // Custom lower v2i64 and v2f64 selects.
855 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
856 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
857
858 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
859 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
860
861 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
862 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
863
864 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
865 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
866 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
867
868 // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
869 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
870
871 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
872 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
873
874 for (MVT VT : MVT::fp_vector_valuetypes())
875 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
876
877 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
878 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
879 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
880
881 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
882 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
883 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
884
885 // In the customized shift lowering, the legal v4i32/v2i64 cases
886 // in AVX2 will be recognized.
887 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
888 setOperationAction(ISD::SRL, VT, Custom);
889 setOperationAction(ISD::SHL, VT, Custom);
890 setOperationAction(ISD::SRA, VT, Custom);
891 }
892 }
893
894 if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
895 setOperationAction(ISD::ABS, MVT::v16i8, Legal);
896 setOperationAction(ISD::ABS, MVT::v8i16, Legal);
897 setOperationAction(ISD::ABS, MVT::v4i32, Legal);
898 setOperationAction(ISD::BITREVERSE, MVT::v16i8, Custom);
899 setOperationAction(ISD::CTLZ, MVT::v16i8, Custom);
900 setOperationAction(ISD::CTLZ, MVT::v8i16, Custom);
901 setOperationAction(ISD::CTLZ, MVT::v4i32, Custom);
902 setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
903 }
904
905 if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
906 for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
907 setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
908 setOperationAction(ISD::FCEIL, RoundedTy, Legal);
909 setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
910 setOperationAction(ISD::FRINT, RoundedTy, Legal);
911 setOperationAction(ISD::FNEARBYINT, RoundedTy, Legal);
912 }
913
914 setOperationAction(ISD::SMAX, MVT::v16i8, Legal);
915 setOperationAction(ISD::SMAX, MVT::v4i32, Legal);
916 setOperationAction(ISD::UMAX, MVT::v8i16, Legal);
917 setOperationAction(ISD::UMAX, MVT::v4i32, Legal);
918 setOperationAction(ISD::SMIN, MVT::v16i8, Legal);
919 setOperationAction(ISD::SMIN, MVT::v4i32, Legal);
920 setOperationAction(ISD::UMIN, MVT::v8i16, Legal);
921 setOperationAction(ISD::UMIN, MVT::v4i32, Legal);
922
923 // FIXME: Do we need to handle scalar-to-vector here?
924 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
925
926 // We directly match byte blends in the backend as they match the VSELECT
927 // condition form.
928 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
929
930 // SSE41 brings specific instructions for doing vector sign extend even in
931 // cases where we don't have SRA.
932 for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
933 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, VT, Legal);
934 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, VT, Legal);
935 }
936
937 for (MVT VT : MVT::integer_vector_valuetypes()) {
938 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
939 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
940 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
941 }
942
943 // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
944 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
945 setLoadExtAction(LoadExtOp, MVT::v8i16, MVT::v8i8, Legal);
946 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i8, Legal);
947 setLoadExtAction(LoadExtOp, MVT::v2i32, MVT::v2i8, Legal);
948 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i8, Legal);
949 setLoadExtAction(LoadExtOp, MVT::v4i32, MVT::v4i16, Legal);
950 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i16, Legal);
951 setLoadExtAction(LoadExtOp, MVT::v2i64, MVT::v2i32, Legal);
952 }
953
954 // i8 vectors are custom because the source register and source
955 // source memory operand types are not the same width.
956 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
957 }
958
959 if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
960 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
961 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
962 setOperationAction(ISD::ROTL, VT, Custom);
963
964 // XOP can efficiently perform BITREVERSE with VPPERM.
965 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
966 setOperationAction(ISD::BITREVERSE, VT, Custom);
967
968 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
969 MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 })
970 setOperationAction(ISD::BITREVERSE, VT, Custom);
971 }
972
973 if (!Subtarget.useSoftFloat() && Subtarget.hasFp256()) {
974 bool HasInt256 = Subtarget.hasInt256();
975
976 addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
977 : &X86::VR256RegClass);
978 addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
979 : &X86::VR256RegClass);
980 addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
981 : &X86::VR256RegClass);
982 addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
983 : &X86::VR256RegClass);
984 addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
985 : &X86::VR256RegClass);
986 addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
987 : &X86::VR256RegClass);
988
989 for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
990 setOperationAction(ISD::FFLOOR, VT, Legal);
991 setOperationAction(ISD::FCEIL, VT, Legal);
992 setOperationAction(ISD::FTRUNC, VT, Legal);
993 setOperationAction(ISD::FRINT, VT, Legal);
994 setOperationAction(ISD::FNEARBYINT, VT, Legal);
995 setOperationAction(ISD::FNEG, VT, Custom);
996 setOperationAction(ISD::FABS, VT, Custom);
997 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
998 }
999
1000 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1001 // even though v8i16 is a legal type.
1002 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1003 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1004 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1005
1006 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1007 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1008 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1009
1010 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1011 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1012
1013 for (MVT VT : MVT::fp_vector_valuetypes())
1014 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1015
1016 // In the customized shift lowering, the legal v8i32/v4i64 cases
1017 // in AVX2 will be recognized.
1018 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1019 setOperationAction(ISD::SRL, VT, Custom);
1020 setOperationAction(ISD::SHL, VT, Custom);
1021 setOperationAction(ISD::SRA, VT, Custom);
1022 }
1023
1024 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1025 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1026 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1027
1028 for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1029 setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
1030 setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
1031 setOperationAction(ISD::ANY_EXTEND, VT, Custom);
1032 }
1033
1034 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1035 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1036 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1037 setOperationAction(ISD::BITREVERSE, MVT::v32i8, Custom);
1038
1039 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1040 setOperationAction(ISD::SETCC, VT, Custom);
1041 setOperationAction(ISD::CTPOP, VT, Custom);
1042 setOperationAction(ISD::CTTZ, VT, Custom);
1043 setOperationAction(ISD::CTLZ, VT, Custom);
1044 }
1045
1046 if (Subtarget.hasAnyFMA()) {
1047 for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1048 MVT::v2f64, MVT::v4f64 })
1049 setOperationAction(ISD::FMA, VT, Legal);
1050 }
1051
1052 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1053 setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1054 setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1055 }
1056
1057 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1058 setOperationAction(ISD::MUL, MVT::v8i32, HasInt256 ? Legal : Custom);
1059 setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1060 setOperationAction(ISD::MUL, MVT::v32i8, Custom);
1061
1062 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1063 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1064
1065 setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1066 setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1067 setOperationAction(ISD::MULHU, MVT::v32i8, Custom);
1068 setOperationAction(ISD::MULHS, MVT::v32i8, Custom);
1069
1070 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1071 setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1072 setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1073 setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1074 setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1075 setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1076 }
1077
1078 if (HasInt256) {
1079 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i64, Custom);
1080 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i32, Custom);
1081 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v16i16, Custom);
1082
1083 // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1084 // when we have a 256bit-wide blend with immediate.
1085 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1086
1087 // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1088 for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1089 setLoadExtAction(LoadExtOp, MVT::v16i16, MVT::v16i8, Legal);
1090 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i8, Legal);
1091 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i8, Legal);
1092 setLoadExtAction(LoadExtOp, MVT::v8i32, MVT::v8i16, Legal);
1093 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i16, Legal);
1094 setLoadExtAction(LoadExtOp, MVT::v4i64, MVT::v4i32, Legal);
1095 }
1096 }
1097
1098 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1099 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 }) {
1100 setOperationAction(ISD::MLOAD, VT, Legal);
1101 setOperationAction(ISD::MSTORE, VT, Legal);
1102 }
1103
1104 // Extract subvector is special because the value type
1105 // (result) is 128-bit but the source is 256-bit wide.
1106 for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1107 MVT::v4f32, MVT::v2f64 }) {
1108 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1109 }
1110
1111 // Custom lower several nodes for 256-bit types.
1112 for (MVT VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1113 MVT::v8f32, MVT::v4f64 }) {
1114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1116 setOperationAction(ISD::VSELECT, VT, Custom);
1117 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1118 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1119 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1120 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1121 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1122 }
1123
1124 if (HasInt256)
1125 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1126
1127 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1128 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1129 setOperationPromotedToType(ISD::AND, VT, MVT::v4i64);
1130 setOperationPromotedToType(ISD::OR, VT, MVT::v4i64);
1131 setOperationPromotedToType(ISD::XOR, VT, MVT::v4i64);
1132 setOperationPromotedToType(ISD::LOAD, VT, MVT::v4i64);
1133 setOperationPromotedToType(ISD::SELECT, VT, MVT::v4i64);
1134 }
1135
1136 if (HasInt256) {
1137 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1138 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1139 setOperationAction(ISD::MGATHER, VT, Custom);
1140 }
1141 }
1142
1143 if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1144 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1145 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1146 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1147 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1148
1149 addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1150 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1151 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1152
1153 for (MVT VT : MVT::fp_vector_valuetypes())
1154 setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1155
1156 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1157 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i8, Legal);
1158 setLoadExtAction(ExtType, MVT::v16i32, MVT::v16i16, Legal);
1159 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i8, Legal);
1160 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i16, Legal);
1161 setLoadExtAction(ExtType, MVT::v8i64, MVT::v8i32, Legal);
1162 }
1163
1164 for (MVT VT : {MVT::v2i64, MVT::v4i32, MVT::v8i32, MVT::v4i64, MVT::v8i16,
1165 MVT::v16i8, MVT::v16i16, MVT::v32i8, MVT::v16i32,
1166 MVT::v8i64, MVT::v32i16, MVT::v64i8}) {
1167 MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorNumElements());
1168 setLoadExtAction(ISD::SEXTLOAD, VT, MaskVT, Custom);
1169 setLoadExtAction(ISD::ZEXTLOAD, VT, MaskVT, Custom);
1170 setLoadExtAction(ISD::EXTLOAD, VT, MaskVT, Custom);
1171 setTruncStoreAction(VT, MaskVT, Custom);
1172 }
1173
1174 for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1175 setOperationAction(ISD::FNEG, VT, Custom);
1176 setOperationAction(ISD::FABS, VT, Custom);
1177 setOperationAction(ISD::FMA, VT, Legal);
1178 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1179 }
1180
1181 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1182 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1183 setOperationAction(ISD::FP_TO_UINT, MVT::v16i8, Legal);
1184 setOperationAction(ISD::FP_TO_UINT, MVT::v16i16, Legal);
1185 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1186 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1187 setOperationAction(ISD::FP_TO_UINT, MVT::v2i32, Custom);
1188 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1189 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1190 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1191 setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Promote);
1192 setOperationAction(ISD::SINT_TO_FP, MVT::v16i16, Promote);
1193 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1194 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1195 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1196 setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
1197 setOperationAction(ISD::UINT_TO_FP, MVT::v16i16, Custom);
1198 setOperationAction(ISD::SINT_TO_FP, MVT::v16i1, Custom);
1199 setOperationAction(ISD::UINT_TO_FP, MVT::v16i1, Custom);
1200 setOperationAction(ISD::SINT_TO_FP, MVT::v8i1, Custom);
1201 setOperationAction(ISD::UINT_TO_FP, MVT::v8i1, Custom);
1202 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1203 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1204 setOperationAction(ISD::SINT_TO_FP, MVT::v2i1, Custom);
1205 setOperationAction(ISD::UINT_TO_FP, MVT::v2i1, Custom);
1206 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1207 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1208
1209 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Legal);
1210 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Legal);
1211 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Legal);
1212 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Legal);
1213 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Legal);
1214 if (Subtarget.hasVLX()){
1215 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Legal);
1216 setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1217 setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1218 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Legal);
1219 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1220
1221 setTruncStoreAction(MVT::v2i64, MVT::v2i8, Legal);
1222 setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1223 setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1224 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Legal);
1225 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1226 } else {
1227 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1228 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64}) {
1229 setOperationAction(ISD::MLOAD, VT, Custom);
1230 setOperationAction(ISD::MSTORE, VT, Custom);
1231 }
1232 }
1233
1234 if (Subtarget.hasDQI()) {
1235 for (auto VT : { MVT::v2i64, MVT::v4i64, MVT::v8i64 }) {
1236 setOperationAction(ISD::SINT_TO_FP, VT, Legal);
1237 setOperationAction(ISD::UINT_TO_FP, VT, Legal);
1238 setOperationAction(ISD::FP_TO_SINT, VT, Legal);
1239 setOperationAction(ISD::FP_TO_UINT, VT, Legal);
1240 }
1241 if (Subtarget.hasVLX()) {
1242 // Fast v2f32 SINT_TO_FP( v2i32 ) custom conversion.
1243 setOperationAction(ISD::SINT_TO_FP, MVT::v2f32, Custom);
1244 setOperationAction(ISD::FP_TO_SINT, MVT::v2f32, Custom);
1245 setOperationAction(ISD::FP_TO_UINT, MVT::v2f32, Custom);
1246 }
1247 }
1248 if (Subtarget.hasVLX()) {
1249 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1250 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1251 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1252 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1253 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1254 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1255 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1256 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Custom);
1257 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i64, Custom);
1258 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Custom);
1259 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i64, Custom);
1260 }
1261
1262 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1263 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1264 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1265 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1266 setOperationAction(ISD::ANY_EXTEND, MVT::v16i32, Custom);
1267 setOperationAction(ISD::ANY_EXTEND, MVT::v8i64, Custom);
1268 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1269 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1270 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1271 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1272 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1273
1274 for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1275 setOperationAction(ISD::FFLOOR, VT, Legal);
1276 setOperationAction(ISD::FCEIL, VT, Legal);
1277 setOperationAction(ISD::FTRUNC, VT, Legal);
1278 setOperationAction(ISD::FRINT, VT, Legal);
1279 setOperationAction(ISD::FNEARBYINT, VT, Legal);
1280 }
1281
1282 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i64, Custom);
1283 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v16i32, Custom);
1284
1285 // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1286 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v64i8, Custom);
1287 setOperationAction(ISD::ZERO_EXTEND_VECTOR_INREG, MVT::v64i8, Custom);
1288
1289 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1290 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1291 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1292 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1293 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Custom);
1294
1295 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1296 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1297
1298 setOperationAction(ISD::UMUL_LOHI, MVT::v16i32, Custom);
1299 setOperationAction(ISD::SMUL_LOHI, MVT::v16i32, Custom);
1300
1301 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v1i1, Custom);
1302 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v16i1, Custom);
1303 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i1, Custom);
1304 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1305 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1306 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1307
1308
1309 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1310 setOperationAction(ISD::ABS, MVT::v4i64, Legal);
1311 setOperationAction(ISD::ABS, MVT::v2i64, Legal);
1312
1313 for (auto VT : { MVT::v8i1, MVT::v16i1 }) {
1314 setOperationAction(ISD::ADD, VT, Custom);
1315 setOperationAction(ISD::SUB, VT, Custom);
1316 setOperationAction(ISD::MUL, VT, Custom);
1317 setOperationAction(ISD::SETCC, VT, Custom);
1318 setOperationAction(ISD::SELECT, VT, Custom);
1319 setOperationAction(ISD::TRUNCATE, VT, Custom);
1320
1321 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1323 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1324 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1325 setOperationAction(ISD::VSELECT, VT, Expand);
1326 }
1327
1328 for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1329 setOperationAction(ISD::SMAX, VT, Legal);
1330 setOperationAction(ISD::UMAX, VT, Legal);
1331 setOperationAction(ISD::SMIN, VT, Legal);
1332 setOperationAction(ISD::UMIN, VT, Legal);
1333 setOperationAction(ISD::ABS, VT, Legal);
1334 setOperationAction(ISD::SRL, VT, Custom);
1335 setOperationAction(ISD::SHL, VT, Custom);
1336 setOperationAction(ISD::SRA, VT, Custom);
1337 setOperationAction(ISD::CTPOP, VT, Custom);
1338 setOperationAction(ISD::CTTZ, VT, Custom);
1339 }
1340
1341 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1342 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v16i32, MVT::v2i64, MVT::v4i64,
1343 MVT::v8i64}) {
1344 setOperationAction(ISD::ROTL, VT, Custom);
1345 setOperationAction(ISD::ROTR, VT, Custom);
1346 }
1347
1348 // Need to promote to 64-bit even though we have 32-bit masked instructions
1349 // because the IR optimizers rearrange bitcasts around logic ops leaving
1350 // too many variations to handle if we don't promote them.
1351 setOperationPromotedToType(ISD::AND, MVT::v16i32, MVT::v8i64);
1352 setOperationPromotedToType(ISD::OR, MVT::v16i32, MVT::v8i64);
1353 setOperationPromotedToType(ISD::XOR, MVT::v16i32, MVT::v8i64);
1354
1355 if (Subtarget.hasCDI()) {
1356 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1357 for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v16i32, MVT::v2i64,
1358 MVT::v4i64, MVT::v8i64}) {
1359 setOperationAction(ISD::CTLZ, VT, Legal);
1360 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
1361 }
1362 } // Subtarget.hasCDI()
1363
1364 if (Subtarget.hasDQI()) {
1365 // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1366 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1367 setOperationAction(ISD::MUL, MVT::v4i64, Legal);
1368 setOperationAction(ISD::MUL, MVT::v8i64, Legal);
1369 }
1370
1371 if (Subtarget.hasVPOPCNTDQ()) {
1372 // VPOPCNTDQ sub-targets extend 128/256 vectors to use the avx512
1373 // version of popcntd/q.
1374 for (auto VT : {MVT::v16i32, MVT::v8i64, MVT::v8i32, MVT::v4i64,
1375 MVT::v4i32, MVT::v2i64})
1376 setOperationAction(ISD::CTPOP, VT, Legal);
1377 }
1378
1379 // Custom legalize 2x32 to get a little better code.
1380 if (Subtarget.hasVLX()) {
1381 setOperationAction(ISD::MGATHER, MVT::v2f32, Custom);
1382 }
1383
1384 // Custom lower several nodes.
1385 for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1386 MVT::v4f32, MVT::v8f32, MVT::v2f64, MVT::v4f64 })
1387 setOperationAction(ISD::MSCATTER, VT, Custom);
1388
1389 setOperationAction(ISD::EXTRACT_SUBVECTOR, MVT::v1i1, Legal);
1390
1391 // Extract subvector is special because the value type
1392 // (result) is 256-bit but the source is 512-bit wide.
1393 // 128-bit was made Legal under AVX1.
1394 for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1395 MVT::v8f32, MVT::v4f64 })
1396 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1397 for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1,
1398 MVT::v16i1, MVT::v32i1, MVT::v64i1 })
1399 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1400
1401 for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1402 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1403 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1404 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1405 setOperationAction(ISD::VSELECT, VT, Custom);
1406 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1407 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1408 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Legal);
1409 setOperationAction(ISD::MLOAD, VT, Legal);
1410 setOperationAction(ISD::MSTORE, VT, Legal);
1411 setOperationAction(ISD::MGATHER, VT, Custom);
1412 setOperationAction(ISD::MSCATTER, VT, Custom);
1413 }
1414 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1415 setOperationPromotedToType(ISD::LOAD, VT, MVT::v8i64);
1416 setOperationPromotedToType(ISD::SELECT, VT, MVT::v8i64);
1417 }
1418 }// has AVX-512
1419
1420 if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1421 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1422 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1423
1424 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1425 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1426
1427 setOperationAction(ISD::ADD, MVT::v32i1, Custom);
1428 setOperationAction(ISD::ADD, MVT::v64i1, Custom);
1429 setOperationAction(ISD::SUB, MVT::v32i1, Custom);
1430 setOperationAction(ISD::SUB, MVT::v64i1, Custom);
1431 setOperationAction(ISD::MUL, MVT::v32i1, Custom);
1432 setOperationAction(ISD::MUL, MVT::v64i1, Custom);
1433
1434 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1435 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1436 setOperationAction(ISD::MUL, MVT::v32i16, Legal);
1437 setOperationAction(ISD::MUL, MVT::v64i8, Custom);
1438 setOperationAction(ISD::MULHS, MVT::v32i16, Legal);
1439 setOperationAction(ISD::MULHU, MVT::v32i16, Legal);
1440 setOperationAction(ISD::MULHS, MVT::v64i8, Custom);
1441 setOperationAction(ISD::MULHU, MVT::v64i8, Custom);
1442 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i1, Custom);
1443 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i1, Custom);
1444 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i16, Custom);
1445 setOperationAction(ISD::CONCAT_VECTORS, MVT::v64i8, Custom);
1446 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i1, Custom);
1447 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i1, Custom);
1448 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v32i16, Legal);
1449 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v64i8, Legal);
1450 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i16, Custom);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i8, Custom);
1452 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v32i1, Custom);
1453 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v64i1, Custom);
1454 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i16, Custom);
1455 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v64i8, Custom);
1456 setOperationAction(ISD::SELECT, MVT::v32i1, Custom);
1457 setOperationAction(ISD::SELECT, MVT::v64i1, Custom);
1458 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i8, Custom);
1459 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i8, Custom);
1460 setOperationAction(ISD::SIGN_EXTEND, MVT::v32i16, Custom);
1461 setOperationAction(ISD::ZERO_EXTEND, MVT::v32i16, Custom);
1462 setOperationAction(ISD::ANY_EXTEND, MVT::v32i16, Custom);
1463 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i16, Custom);
1464 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i8, Custom);
1465 setOperationAction(ISD::SIGN_EXTEND, MVT::v64i8, Custom);
1466 setOperationAction(ISD::ZERO_EXTEND, MVT::v64i8, Custom);
1467 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i1, Custom);
1468 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i1, Custom);
1469 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v32i16, Custom);
1470 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v64i8, Custom);
1471 setOperationAction(ISD::TRUNCATE, MVT::v32i1, Custom);
1472 setOperationAction(ISD::TRUNCATE, MVT::v64i1, Custom);
1473 setOperationAction(ISD::TRUNCATE, MVT::v32i8, Custom);
1474 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v32i1, Custom);
1475 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v64i1, Custom);
1476 setOperationAction(ISD::BUILD_VECTOR, MVT::v32i1, Custom);
1477 setOperationAction(ISD::BUILD_VECTOR, MVT::v64i1, Custom);
1478 setOperationAction(ISD::VSELECT, MVT::v32i1, Expand);
1479 setOperationAction(ISD::VSELECT, MVT::v64i1, Expand);
1480 setOperationAction(ISD::BITREVERSE, MVT::v64i8, Custom);
1481
1482 setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v32i16, Custom);
1483
1484 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Legal);
1485 if (Subtarget.hasVLX()) {
1486 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Legal);
1487 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Legal);
1488 }
1489
1490 LegalizeAction Action = Subtarget.hasVLX() ? Legal : Custom;
1491 for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1492 setOperationAction(ISD::MLOAD, VT, Action);
1493 setOperationAction(ISD::MSTORE, VT, Action);
1494 }
1495
1496 for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1497 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1498 setOperationAction(ISD::VSELECT, VT, Custom);
1499 setOperationAction(ISD::ABS, VT, Legal);
1500 setOperationAction(ISD::SRL, VT, Custom);
1501 setOperationAction(ISD::SHL, VT, Custom);
1502 setOperationAction(ISD::SRA, VT, Custom);
1503 setOperationAction(ISD::MLOAD, VT, Legal);
1504 setOperationAction(ISD::MSTORE, VT, Legal);
1505 setOperationAction(ISD::CTPOP, VT, Custom);
1506 setOperationAction(ISD::CTTZ, VT, Custom);
1507 setOperationAction(ISD::CTLZ, VT, Custom);
1508 setOperationAction(ISD::SMAX, VT, Legal);
1509 setOperationAction(ISD::UMAX, VT, Legal);
1510 setOperationAction(ISD::SMIN, VT, Legal);
1511 setOperationAction(ISD::UMIN, VT, Legal);
1512
1513 setOperationPromotedToType(ISD::AND, VT, MVT::v8i64);
1514 setOperationPromotedToType(ISD::OR, VT, MVT::v8i64);
1515 setOperationPromotedToType(ISD::XOR, VT, MVT::v8i64);
1516 }
1517
1518 for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1519 setLoadExtAction(ExtType, MVT::v32i16, MVT::v32i8, Legal);
1520 }
1521
1522 if (Subtarget.hasBITALG()) {
1523 for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v32i8,
1524 MVT::v16i16, MVT::v16i8, MVT::v8i16 })
1525 setOperationAction(ISD::CTPOP, VT, Legal);
1526 }
1527 }
1528
1529 if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1530 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1531 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1532
1533 for (auto VT : { MVT::v2i1, MVT::v4i1 }) {
1534 setOperationAction(ISD::ADD, VT, Custom);
1535 setOperationAction(ISD::SUB, VT, Custom);
1536 setOperationAction(ISD::MUL, VT, Custom);
1537 setOperationAction(ISD::VSELECT, VT, Expand);
1538
1539 setOperationAction(ISD::TRUNCATE, VT, Custom);
1540 setOperationAction(ISD::SETCC, VT, Custom);
1541 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1542 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1543 setOperationAction(ISD::SELECT, VT, Custom);
1544 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1545 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1546 }
1547
1548 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1549 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i1, Custom);
1550 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i1, Custom);
1551 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i1, Custom);
1552
1553 for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1554 setOperationAction(ISD::SMAX, VT, Legal);
1555 setOperationAction(ISD::UMAX, VT, Legal);
1556 setOperationAction(ISD::SMIN, VT, Legal);
1557 setOperationAction(ISD::UMIN, VT, Legal);
1558 }
1559 }
1560
1561 // We want to custom lower some of our intrinsics.
1562 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1563 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1564 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1565 if (!Subtarget.is64Bit()) {
1566 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1567 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1568 }
1569
1570 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1571 // handle type legalization for these operations here.
1572 //
1573 // FIXME: We really should do custom legalization for addition and
1574 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1575 // than generic legalization for 64-bit multiplication-with-overflow, though.
1576 for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1577 if (VT == MVT::i64 && !Subtarget.is64Bit())
1578 continue;
1579 // Add/Sub/Mul with overflow operations are custom lowered.
1580 setOperationAction(ISD::SADDO, VT, Custom);
1581 setOperationAction(ISD::UADDO, VT, Custom);
1582 setOperationAction(ISD::SSUBO, VT, Custom);
1583 setOperationAction(ISD::USUBO, VT, Custom);
1584 setOperationAction(ISD::SMULO, VT, Custom);
1585 setOperationAction(ISD::UMULO, VT, Custom);
1586
1587 // Support carry in as value rather than glue.
1588 setOperationAction(ISD::ADDCARRY, VT, Custom);
1589 setOperationAction(ISD::SUBCARRY, VT, Custom);
1590 setOperationAction(ISD::SETCCCARRY, VT, Custom);
1591 }
1592
1593 if (!Subtarget.is64Bit()) {
1594 // These libcalls are not available in 32-bit.
1595 setLibcallName(RTLIB::SHL_I128, nullptr);
1596 setLibcallName(RTLIB::SRL_I128, nullptr);
1597 setLibcallName(RTLIB::SRA_I128, nullptr);
1598 setLibcallName(RTLIB::MUL_I128, nullptr);
1599 }
1600
1601 // Combine sin / cos into one node or libcall if possible.
1602 if (Subtarget.hasSinCos()) {
1603 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1604 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1605 if (Subtarget.isTargetDarwin()) {
1606 // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1607 // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1608 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1609 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1610 }
1611 }
1612
1613 if (Subtarget.isTargetWin64()) {
1614 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1615 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1616 setOperationAction(ISD::SREM, MVT::i128, Custom);
1617 setOperationAction(ISD::UREM, MVT::i128, Custom);
1618 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1619 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1620 }
1621
1622 // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1623 // is. We should promote the value to 64-bits to solve this.
1624 // This is what the CRT headers do - `fmodf` is an inline header
1625 // function casting to f64 and calling `fmod`.
1626 if (Subtarget.is32Bit() && (Subtarget.isTargetKnownWindowsMSVC() ||
1627 Subtarget.isTargetWindowsItanium()))
1628 for (ISD::NodeType Op :
1629 {ISD::FCEIL, ISD::FCOS, ISD::FEXP, ISD::FFLOOR, ISD::FREM, ISD::FLOG,
1630 ISD::FLOG10, ISD::FPOW, ISD::FSIN})
1631 if (isOperationExpand(Op, MVT::f32))
1632 setOperationAction(Op, MVT::f32, Promote);
1633
1634 // We have target-specific dag combine patterns for the following nodes:
1635 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1636 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1637 setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
1638 setTargetDAGCombine(ISD::EXTRACT_SUBVECTOR);
1639 setTargetDAGCombine(ISD::BITCAST);
1640 setTargetDAGCombine(ISD::VSELECT);
1641 setTargetDAGCombine(ISD::SELECT);
1642 setTargetDAGCombine(ISD::SHL);
1643 setTargetDAGCombine(ISD::SRA);
1644 setTargetDAGCombine(ISD::SRL);
1645 setTargetDAGCombine(ISD::OR);
1646 setTargetDAGCombine(ISD::AND);
1647 setTargetDAGCombine(ISD::ADD);
1648 setTargetDAGCombine(ISD::FADD);
1649 setTargetDAGCombine(ISD::FSUB);
1650 setTargetDAGCombine(ISD::FNEG);
1651 setTargetDAGCombine(ISD::FMA);
1652 setTargetDAGCombine(ISD::FMINNUM);
1653 setTargetDAGCombine(ISD::FMAXNUM);
1654 setTargetDAGCombine(ISD::SUB);
1655 setTargetDAGCombine(ISD::LOAD);
1656 setTargetDAGCombine(ISD::MLOAD);
1657 setTargetDAGCombine(ISD::STORE);
1658 setTargetDAGCombine(ISD::MSTORE);
1659 setTargetDAGCombine(ISD::TRUNCATE);
1660 setTargetDAGCombine(ISD::ZERO_EXTEND);
1661 setTargetDAGCombine(ISD::ANY_EXTEND);
1662 setTargetDAGCombine(ISD::SIGN_EXTEND);
1663 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1664 setTargetDAGCombine(ISD::SIGN_EXTEND_VECTOR_INREG);
1665 setTargetDAGCombine(ISD::ZERO_EXTEND_VECTOR_INREG);
1666 setTargetDAGCombine(ISD::SINT_TO_FP);
1667 setTargetDAGCombine(ISD::UINT_TO_FP);
1668 setTargetDAGCombine(ISD::SETCC);
1669 setTargetDAGCombine(ISD::MUL);
1670 setTargetDAGCombine(ISD::XOR);
1671 setTargetDAGCombine(ISD::MSCATTER);
1672 setTargetDAGCombine(ISD::MGATHER);
1673
1674 computeRegisterProperties(Subtarget.getRegisterInfo());
1675
1676 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1677 MaxStoresPerMemsetOptSize = 8;
1678 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1679 MaxStoresPerMemcpyOptSize = 4;
1680 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1681 MaxStoresPerMemmoveOptSize = 4;
1682
1683 // TODO: These control memcmp expansion in CGP and could be raised higher, but
1684 // that needs to benchmarked and balanced with the potential use of vector
1685 // load/store types (PR33329, PR33914).
1686 MaxLoadsPerMemcmp = 2;
1687 MaxLoadsPerMemcmpOptSize = 2;
1688
1689 // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1690 setPrefLoopAlignment(ExperimentalPrefLoopAlignment);
1691
1692 // An out-of-order CPU can speculatively execute past a predictable branch,
1693 // but a conditional move could be stalled by an expensive earlier operation.
1694 PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1695 EnableExtLdPromotion = true;
1696 setPrefFunctionAlignment(4); // 2^4 bytes.
1697
1698 verifyIntrinsicTables();
1699}
1700
1701// This has so far only been implemented for 64-bit MachO.
1702bool X86TargetLowering::useLoadStackGuardNode() const {
1703 return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1704}
1705
1706TargetLoweringBase::LegalizeTypeAction
1707X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1708 if (ExperimentalVectorWideningLegalization &&
1709 VT.getVectorNumElements() != 1 &&
1710 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1711 return TypeWidenVector;
1712
1713 return TargetLoweringBase::getPreferredVectorAction(VT);
1714}
1715
1716EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL,
1717 LLVMContext& Context,
1718 EVT VT) const {
1719 if (!VT.isVector())
1720 return MVT::i8;
1721
1722 if (VT.isSimple()) {
1723 MVT VVT = VT.getSimpleVT();
1724 const unsigned NumElts = VVT.getVectorNumElements();
1725 MVT EltVT = VVT.getVectorElementType();
1726 if (VVT.is512BitVector()) {
1727 if (Subtarget.hasAVX512())
1728 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1729 EltVT == MVT::f32 || EltVT == MVT::f64)
1730 switch(NumElts) {
1731 case 8: return MVT::v8i1;
1732 case 16: return MVT::v16i1;
1733 }
1734 if (Subtarget.hasBWI())
1735 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1736 switch(NumElts) {
1737 case 32: return MVT::v32i1;
1738 case 64: return MVT::v64i1;
1739 }
1740 }
1741
1742 if (Subtarget.hasBWI() && Subtarget.hasVLX())
1743 return MVT::getVectorVT(MVT::i1, NumElts);
1744
1745 if (!isTypeLegal(VT) && getTypeAction(Context, VT) == TypePromoteInteger) {
1746 EVT LegalVT = getTypeToTransformTo(Context, VT);
1747 EltVT = LegalVT.getVectorElementType().getSimpleVT();
1748 }
1749
1750 if (Subtarget.hasVLX() && EltVT.getSizeInBits() >= 32)
1751 switch(NumElts) {
1752 case 2: return MVT::v2i1;
1753 case 4: return MVT::v4i1;
1754 case 8: return MVT::v8i1;
1755 }
1756 }
1757
1758 return VT.changeVectorElementTypeToInteger();
1759}
1760
1761/// Helper for getByValTypeAlignment to determine
1762/// the desired ByVal argument alignment.
1763static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1764 if (MaxAlign == 16)
1765 return;
1766 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1767 if (VTy->getBitWidth() == 128)
1768 MaxAlign = 16;
1769 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1770 unsigned EltAlign = 0;
1771 getMaxByValAlign(ATy->getElementType(), EltAlign);
1772 if (EltAlign > MaxAlign)
1773 MaxAlign = EltAlign;
1774 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1775 for (auto *EltTy : STy->elements()) {
1776 unsigned EltAlign = 0;
1777 getMaxByValAlign(EltTy, EltAlign);
1778 if (EltAlign > MaxAlign)
1779 MaxAlign = EltAlign;
1780 if (MaxAlign == 16)
1781 break;
1782 }
1783 }
1784}
1785
1786/// Return the desired alignment for ByVal aggregate
1787/// function arguments in the caller parameter area. For X86, aggregates
1788/// that contain SSE vectors are placed at 16-byte boundaries while the rest
1789/// are at 4-byte boundaries.
1790unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1791 const DataLayout &DL) const {
1792 if (Subtarget.is64Bit()) {
1793 // Max of 8 and alignment of type.
1794 unsigned TyAlign = DL.getABITypeAlignment(Ty);
1795 if (TyAlign > 8)
1796 return TyAlign;
1797 return 8;
1798 }
1799
1800 unsigned Align = 4;
1801 if (Subtarget.hasSSE1())
1802 getMaxByValAlign(Ty, Align);
1803 return Align;
1804}
1805
1806/// Returns the target specific optimal type for load
1807/// and store operations as a result of memset, memcpy, and memmove
1808/// lowering. If DstAlign is zero that means it's safe to destination
1809/// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1810/// means there isn't a need to check it against alignment requirement,
1811/// probably because the source does not need to be loaded. If 'IsMemset' is
1812/// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1813/// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1814/// source is constant so it does not need to be loaded.
1815/// It returns EVT::Other if the type should be determined using generic
1816/// target-independent logic.
1817EVT
1818X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1819 unsigned DstAlign, unsigned SrcAlign,
1820 bool IsMemset, bool ZeroMemset,
1821 bool MemcpyStrSrc,
1822 MachineFunction &MF) const {
1823 const Function *F = MF.getFunction();
1824 if (!F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1825 if (Size >= 16 &&
1826 (!Subtarget.isUnalignedMem16Slow() ||
1827 ((DstAlign == 0 || DstAlign >= 16) &&
1828 (SrcAlign == 0 || SrcAlign >= 16)))) {
1829 // FIXME: Check if unaligned 32-byte accesses are slow.
1830 if (Size >= 32 && Subtarget.hasAVX()) {
1831 // Although this isn't a well-supported type for AVX1, we'll let
1832 // legalization and shuffle lowering produce the optimal codegen. If we
1833 // choose an optimal type with a vector element larger than a byte,
1834 // getMemsetStores() may create an intermediate splat (using an integer
1835 // multiply) before we splat as a vector.
1836 return MVT::v32i8;
1837 }
1838 if (Subtarget.hasSSE2())
1839 return MVT::v16i8;
1840 // TODO: Can SSE1 handle a byte vector?
1841 if (Subtarget.hasSSE1())
1842 return MVT::v4f32;
1843 } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
1844 !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
1845 // Do not use f64 to lower memcpy if source is string constant. It's
1846 // better to use i32 to avoid the loads.
1847 // Also, do not use f64 to lower memset unless this is a memset of zeros.
1848 // The gymnastics of splatting a byte value into an XMM register and then
1849 // only using 8-byte stores (because this is a CPU with slow unaligned
1850 // 16-byte accesses) makes that a loser.
1851 return MVT::f64;
1852 }
1853 }
1854 // This is a compromise. If we reach here, unaligned accesses may be slow on
1855 // this target. However, creating smaller, aligned accesses could be even
1856 // slower and would certainly be a lot more code.
1857 if (Subtarget.is64Bit() && Size >= 8)
1858 return MVT::i64;
1859 return MVT::i32;
1860}
1861
1862bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1863 if (VT == MVT::f32)
1864 return X86ScalarSSEf32;
1865 else if (VT == MVT::f64)
1866 return X86ScalarSSEf64;
1867 return true;
1868}
1869
1870bool
1871X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1872 unsigned,
1873 unsigned,
1874 bool *Fast) const {
1875 if (Fast) {
1876 switch (VT.getSizeInBits()) {
1877 default:
1878 // 8-byte and under are always assumed to be fast.
1879 *Fast = true;
1880 break;
1881 case 128:
1882 *Fast = !Subtarget.isUnalignedMem16Slow();
1883 break;
1884 case 256:
1885 *Fast = !Subtarget.isUnalignedMem32Slow();
1886 break;
1887 // TODO: What about AVX-512 (512-bit) accesses?
1888 }
1889 }
1890 // Misaligned accesses of any size are always allowed.
1891 return true;
1892}
1893
1894/// Return the entry encoding for a jump table in the
1895/// current function. The returned value is a member of the
1896/// MachineJumpTableInfo::JTEntryKind enum.
1897unsigned X86TargetLowering::getJumpTableEncoding() const {
1898 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1899 // symbol.
1900 if (isPositionIndependent() && Subtarget.isPICStyleGOT())
1901 return MachineJumpTableInfo::EK_Custom32;
1902
1903 // Otherwise, use the normal jump table encoding heuristics.
1904 return TargetLowering::getJumpTableEncoding();
1905}
1906
1907bool X86TargetLowering::useSoftFloat() const {
1908 return Subtarget.useSoftFloat();
1909}
1910
1911void X86TargetLowering::markLibCallAttributes(MachineFunction *MF, unsigned CC,
1912 ArgListTy &Args) const {
1913
1914 // Only relabel X86-32 for C / Stdcall CCs.
1915 if (Subtarget.is64Bit())
1916 return;
1917 if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
1918 return;
1919 unsigned ParamRegs = 0;
1920 if (auto *M = MF->getFunction()->getParent())
1921 ParamRegs = M->getNumberRegisterParameters();
1922
1923 // Mark the first N int arguments as having reg
1924 for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
1925 Type *T = Args[Idx].Ty;
1926 if (T->isPointerTy() || T->isIntegerTy())
1927 if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
1928 unsigned numRegs = 1;
1929 if (MF->getDataLayout().getTypeAllocSize(T) > 4)
1930 numRegs = 2;
1931 if (ParamRegs < numRegs)
1932 return;
1933 ParamRegs -= numRegs;
1934 Args[Idx].IsInReg = true;
1935 }
1936 }
1937}
1938
1939const MCExpr *
1940X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1941 const MachineBasicBlock *MBB,
1942 unsigned uid,MCContext &Ctx) const{
1943 assert(isPositionIndependent() && Subtarget.isPICStyleGOT())(static_cast <bool> (isPositionIndependent() &&
Subtarget.isPICStyleGOT()) ? void (0) : __assert_fail ("isPositionIndependent() && Subtarget.isPICStyleGOT()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 1943, __extension__ __PRETTY_FUNCTION__))
;
1944 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1945 // entries.
1946 return MCSymbolRefExpr::create(MBB->getSymbol(),
1947 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1948}
1949
1950/// Returns relocation base for the given PIC jumptable.
1951SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1952 SelectionDAG &DAG) const {
1953 if (!Subtarget.is64Bit())
1954 // This doesn't have SDLoc associated with it, but is not really the
1955 // same as a Register.
1956 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1957 getPointerTy(DAG.getDataLayout()));
1958 return Table;
1959}
1960
1961/// This returns the relocation base for the given PIC jumptable,
1962/// the same as getPICJumpTableRelocBase, but as an MCExpr.
1963const MCExpr *X86TargetLowering::
1964getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1965 MCContext &Ctx) const {
1966 // X86-64 uses RIP relative addressing based on the jump table label.
1967 if (Subtarget.isPICStyleRIPRel())
1968 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1969
1970 // Otherwise, the reference is relative to the PIC base.
1971 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1972}
1973
1974std::pair<const TargetRegisterClass *, uint8_t>
1975X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1976 MVT VT) const {
1977 const TargetRegisterClass *RRC = nullptr;
1978 uint8_t Cost = 1;
1979 switch (VT.SimpleTy) {
1980 default:
1981 return TargetLowering::findRepresentativeClass(TRI, VT);
1982 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1983 RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1984 break;
1985 case MVT::x86mmx:
1986 RRC = &X86::VR64RegClass;
1987 break;
1988 case MVT::f32: case MVT::f64:
1989 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1990 case MVT::v4f32: case MVT::v2f64:
1991 case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
1992 case MVT::v8f32: case MVT::v4f64:
1993 case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
1994 case MVT::v16f32: case MVT::v8f64:
1995 RRC = &X86::VR128XRegClass;
1996 break;
1997 }
1998 return std::make_pair(RRC, Cost);
1999}
2000
2001unsigned X86TargetLowering::getAddressSpace() const {
2002 if (Subtarget.is64Bit())
2003 return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2004 return 256;
2005}
2006
2007static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2008 return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2009 (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2010}
2011
2012static Constant* SegmentOffset(IRBuilder<> &IRB,
2013 unsigned Offset, unsigned AddressSpace) {
2014 return ConstantExpr::getIntToPtr(
2015 ConstantInt::get(Type::getInt32Ty(IRB.getContext()), Offset),
2016 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2017}
2018
2019Value *X86TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
2020 // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2021 // tcbhead_t; use it instead of the usual global variable (see
2022 // sysdeps/{i386,x86_64}/nptl/tls.h)
2023 if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2024 if (Subtarget.isTargetFuchsia()) {
2025 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2026 return SegmentOffset(IRB, 0x10, getAddressSpace());
2027 } else {
2028 // %fs:0x28, unless we're using a Kernel code model, in which case
2029 // it's %gs:0x28. gs:0x14 on i386.
2030 unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2031 return SegmentOffset(IRB, Offset, getAddressSpace());
2032 }
2033 }
2034
2035 return TargetLowering::getIRStackGuard(IRB);
2036}
2037
2038void X86TargetLowering::insertSSPDeclarations(Module &M) const {
2039 // MSVC CRT provides functionalities for stack protection.
2040 if (Subtarget.getTargetTriple().isOSMSVCRT()) {
2041 // MSVC CRT has a global variable holding security cookie.
2042 M.getOrInsertGlobal("__security_cookie",
2043 Type::getInt8PtrTy(M.getContext()));
2044
2045 // MSVC CRT has a function to validate security cookie.
2046 auto *SecurityCheckCookie = cast<Function>(
2047 M.getOrInsertFunction("__security_check_cookie",
2048 Type::getVoidTy(M.getContext()),
2049 Type::getInt8PtrTy(M.getContext())));
2050 SecurityCheckCookie->setCallingConv(CallingConv::X86_FastCall);
2051 SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
2052 return;
2053 }
2054 // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2055 if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2056 return;
2057 TargetLowering::insertSSPDeclarations(M);
2058}
2059
2060Value *X86TargetLowering::getSDagStackGuard(const Module &M) const {
2061 // MSVC CRT has a global variable holding security cookie.
2062 if (Subtarget.getTargetTriple().isOSMSVCRT())
2063 return M.getGlobalVariable("__security_cookie");
2064 return TargetLowering::getSDagStackGuard(M);
2065}
2066
2067Value *X86TargetLowering::getSSPStackGuardCheck(const Module &M) const {
2068 // MSVC CRT has a function to validate security cookie.
2069 if (Subtarget.getTargetTriple().isOSMSVCRT())
2070 return M.getFunction("__security_check_cookie");
2071 return TargetLowering::getSSPStackGuardCheck(M);
2072}
2073
2074Value *X86TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
2075 if (Subtarget.getTargetTriple().isOSContiki())
2076 return getDefaultSafeStackPointerLocation(IRB, false);
2077
2078 // Android provides a fixed TLS slot for the SafeStack pointer. See the
2079 // definition of TLS_SLOT_SAFESTACK in
2080 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2081 if (Subtarget.isTargetAndroid()) {
2082 // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2083 // %gs:0x24 on i386
2084 unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2085 return SegmentOffset(IRB, Offset, getAddressSpace());
2086 }
2087
2088 // Fuchsia is similar.
2089 if (Subtarget.isTargetFuchsia()) {
2090 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2091 return SegmentOffset(IRB, 0x18, getAddressSpace());
2092 }
2093
2094 return TargetLowering::getSafeStackPointerLocation(IRB);
2095}
2096
2097bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2098 unsigned DestAS) const {
2099 assert(SrcAS != DestAS && "Expected different address spaces!")(static_cast <bool> (SrcAS != DestAS && "Expected different address spaces!"
) ? void (0) : __assert_fail ("SrcAS != DestAS && \"Expected different address spaces!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2099, __extension__ __PRETTY_FUNCTION__))
;
2100
2101 return SrcAS < 256 && DestAS < 256;
2102}
2103
2104//===----------------------------------------------------------------------===//
2105// Return Value Calling Convention Implementation
2106//===----------------------------------------------------------------------===//
2107
2108#include "X86GenCallingConv.inc"
2109
2110bool X86TargetLowering::CanLowerReturn(
2111 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2112 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2113 SmallVector<CCValAssign, 16> RVLocs;
2114 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2115 return CCInfo.CheckReturn(Outs, RetCC_X86);
2116}
2117
2118const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2119 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2120 return ScratchRegs;
2121}
2122
2123/// Lowers masks values (v*i1) to the local register values
2124/// \returns DAG node after lowering to register type
2125static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2126 const SDLoc &Dl, SelectionDAG &DAG) {
2127 EVT ValVT = ValArg.getValueType();
2128
2129 if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2130 (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2131 // Two stage lowering might be required
2132 // bitcast: v8i1 -> i8 / v16i1 -> i16
2133 // anyextend: i8 -> i32 / i16 -> i32
2134 EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2135 SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2136 if (ValLoc == MVT::i32)
2137 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2138 return ValToCopy;
2139 } else if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2140 (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2141 // One stage lowering is required
2142 // bitcast: v32i1 -> i32 / v64i1 -> i64
2143 return DAG.getBitcast(ValLoc, ValArg);
2144 } else
2145 return DAG.getNode(ISD::SIGN_EXTEND, Dl, ValLoc, ValArg);
2146}
2147
2148/// Breaks v64i1 value into two registers and adds the new node to the DAG
2149static void Passv64i1ArgInRegs(
2150 const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2151 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2152 CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2153 assert((Subtarget.hasBWI() || Subtarget.hasBMI()) &&(static_cast <bool> ((Subtarget.hasBWI() || Subtarget.hasBMI
()) && "Expected AVX512BW or AVX512BMI target!") ? void
(0) : __assert_fail ("(Subtarget.hasBWI() || Subtarget.hasBMI()) && \"Expected AVX512BW or AVX512BMI target!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2154, __extension__ __PRETTY_FUNCTION__))
2154 "Expected AVX512BW or AVX512BMI target!")(static_cast <bool> ((Subtarget.hasBWI() || Subtarget.hasBMI
()) && "Expected AVX512BW or AVX512BMI target!") ? void
(0) : __assert_fail ("(Subtarget.hasBWI() || Subtarget.hasBMI()) && \"Expected AVX512BW or AVX512BMI target!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2154, __extension__ __PRETTY_FUNCTION__))
;
2155 assert(Subtarget.is32Bit() && "Expecting 32 bit target")(static_cast <bool> (Subtarget.is32Bit() && "Expecting 32 bit target"
) ? void (0) : __assert_fail ("Subtarget.is32Bit() && \"Expecting 32 bit target\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2155, __extension__ __PRETTY_FUNCTION__))
;
2156 assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value")(static_cast <bool> (Arg.getValueType() == MVT::i64 &&
"Expecting 64 bit value") ? void (0) : __assert_fail ("Arg.getValueType() == MVT::i64 && \"Expecting 64 bit value\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2156, __extension__ __PRETTY_FUNCTION__))
;
2157 assert(VA.isRegLoc() && NextVA.isRegLoc() &&(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The value should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The value should reside in two registers\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2158, __extension__ __PRETTY_FUNCTION__))
2158 "The value should reside in two registers")(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The value should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The value should reside in two registers\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2158, __extension__ __PRETTY_FUNCTION__))
;
2159
2160 // Before splitting the value we cast it to i64
2161 Arg = DAG.getBitcast(MVT::i64, Arg);
2162
2163 // Splitting the value into two i32 types
2164 SDValue Lo, Hi;
2165 Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2166 DAG.getConstant(0, Dl, MVT::i32));
2167 Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2168 DAG.getConstant(1, Dl, MVT::i32));
2169
2170 // Attach the two i32 types into corresponding registers
2171 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2172 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2173}
2174
2175SDValue
2176X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2177 bool isVarArg,
2178 const SmallVectorImpl<ISD::OutputArg> &Outs,
2179 const SmallVectorImpl<SDValue> &OutVals,
2180 const SDLoc &dl, SelectionDAG &DAG) const {
2181 MachineFunction &MF = DAG.getMachineFunction();
2182 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2183
2184 // In some cases we need to disable registers from the default CSR list.
2185 // For example, when they are used for argument passing.
2186 bool ShouldDisableCalleeSavedRegister =
2187 CallConv == CallingConv::X86_RegCall ||
2188 MF.getFunction()->hasFnAttribute("no_caller_saved_registers");
2189
2190 if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2191 report_fatal_error("X86 interrupts may not return any value");
2192
2193 SmallVector<CCValAssign, 16> RVLocs;
2194 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2195 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2196
2197 SDValue Flag;
2198 SmallVector<SDValue, 6> RetOps;
2199 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2200 // Operand #1 = Bytes To Pop
2201 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2202 MVT::i32));
2203
2204 // Copy the result values into the output registers.
2205 for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2206 ++I, ++OutsIndex) {
2207 CCValAssign &VA = RVLocs[I];
2208 assert(VA.isRegLoc() && "Can only return in registers!")(static_cast <bool> (VA.isRegLoc() && "Can only return in registers!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2208, __extension__ __PRETTY_FUNCTION__))
;
2209
2210 // Add the register to the CalleeSaveDisableRegs list.
2211 if (ShouldDisableCalleeSavedRegister)
2212 MF.getRegInfo().disableCalleeSavedRegister(VA.getLocReg());
2213
2214 SDValue ValToCopy = OutVals[OutsIndex];
2215 EVT ValVT = ValToCopy.getValueType();
2216
2217 // Promote values to the appropriate types.
2218 if (VA.getLocInfo() == CCValAssign::SExt)
2219 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2220 else if (VA.getLocInfo() == CCValAssign::ZExt)
2221 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2222 else if (VA.getLocInfo() == CCValAssign::AExt) {
2223 if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2224 ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2225 else
2226 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2227 }
2228 else if (VA.getLocInfo() == CCValAssign::BCvt)
2229 ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2230
2231 assert(VA.getLocInfo() != CCValAssign::FPExt &&(static_cast <bool> (VA.getLocInfo() != CCValAssign::FPExt
&& "Unexpected FP-extend for return value.") ? void (
0) : __assert_fail ("VA.getLocInfo() != CCValAssign::FPExt && \"Unexpected FP-extend for return value.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2232, __extension__ __PRETTY_FUNCTION__))
2232 "Unexpected FP-extend for return value.")(static_cast <bool> (VA.getLocInfo() != CCValAssign::FPExt
&& "Unexpected FP-extend for return value.") ? void (
0) : __assert_fail ("VA.getLocInfo() != CCValAssign::FPExt && \"Unexpected FP-extend for return value.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2232, __extension__ __PRETTY_FUNCTION__))
;
2233
2234 // If this is x86-64, and we disabled SSE, we can't return FP values,
2235 // or SSE or MMX vectors.
2236 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2237 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2238 (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2239 errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2240 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2241 } else if (ValVT == MVT::f64 &&
2242 (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2243 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2244 // llvm-gcc has never done it right and no one has noticed, so this
2245 // should be OK for now.
2246 errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2247 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2248 }
2249
2250 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2251 // the RET instruction and handled by the FP Stackifier.
2252 if (VA.getLocReg() == X86::FP0 ||
2253 VA.getLocReg() == X86::FP1) {
2254 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2255 // change the value to the FP stack register class.
2256 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2257 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2258 RetOps.push_back(ValToCopy);
2259 // Don't emit a copytoreg.
2260 continue;
2261 }
2262
2263 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2264 // which is returned in RAX / RDX.
2265 if (Subtarget.is64Bit()) {
2266 if (ValVT == MVT::x86mmx) {
2267 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2268 ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2269 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2270 ValToCopy);
2271 // If we don't have SSE2 available, convert to v4f32 so the generated
2272 // register is legal.
2273 if (!Subtarget.hasSSE2())
2274 ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2275 }
2276 }
2277 }
2278
2279 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2280
2281 if (VA.needsCustom()) {
2282 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? 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-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2283, __extension__ __PRETTY_FUNCTION__))
2283 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? 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-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2283, __extension__ __PRETTY_FUNCTION__))
;
2284
2285 Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2286 Subtarget);
2287
2288 assert(2 == RegsToPass.size() &&(static_cast <bool> (2 == RegsToPass.size() && "Expecting two registers after Pass64BitArgInRegs"
) ? void (0) : __assert_fail ("2 == RegsToPass.size() && \"Expecting two registers after Pass64BitArgInRegs\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2289, __extension__ __PRETTY_FUNCTION__))
2289 "Expecting two registers after Pass64BitArgInRegs")(static_cast <bool> (2 == RegsToPass.size() && "Expecting two registers after Pass64BitArgInRegs"
) ? void (0) : __assert_fail ("2 == RegsToPass.size() && \"Expecting two registers after Pass64BitArgInRegs\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2289, __extension__ __PRETTY_FUNCTION__))
;
2290
2291 // Add the second register to the CalleeSaveDisableRegs list.
2292 if (ShouldDisableCalleeSavedRegister)
2293 MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2294 } else {
2295 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2296 }
2297
2298 // Add nodes to the DAG and add the values into the RetOps list
2299 for (auto &Reg : RegsToPass) {
2300 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2301 Flag = Chain.getValue(1);
2302 RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2303 }
2304 }
2305
2306 // Swift calling convention does not require we copy the sret argument
2307 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2308
2309 // All x86 ABIs require that for returning structs by value we copy
2310 // the sret argument into %rax/%eax (depending on ABI) for the return.
2311 // We saved the argument into a virtual register in the entry block,
2312 // so now we copy the value out and into %rax/%eax.
2313 //
2314 // Checking Function.hasStructRetAttr() here is insufficient because the IR
2315 // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2316 // false, then an sret argument may be implicitly inserted in the SelDAG. In
2317 // either case FuncInfo->setSRetReturnReg() will have been called.
2318 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2319 // When we have both sret and another return value, we should use the
2320 // original Chain stored in RetOps[0], instead of the current Chain updated
2321 // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2322
2323 // For the case of sret and another return value, we have
2324 // Chain_0 at the function entry
2325 // Chain_1 = getCopyToReg(Chain_0) in the above loop
2326 // If we use Chain_1 in getCopyFromReg, we will have
2327 // Val = getCopyFromReg(Chain_1)
2328 // Chain_2 = getCopyToReg(Chain_1, Val) from below
2329
2330 // getCopyToReg(Chain_0) will be glued together with
2331 // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2332 // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2333 // Data dependency from Unit B to Unit A due to usage of Val in
2334 // getCopyToReg(Chain_1, Val)
2335 // Chain dependency from Unit A to Unit B
2336
2337 // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2338 SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2339 getPointerTy(MF.getDataLayout()));
2340
2341 unsigned RetValReg
2342 = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2343 X86::RAX : X86::EAX;
2344 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2345 Flag = Chain.getValue(1);
2346
2347 // RAX/EAX now acts like a return value.
2348 RetOps.push_back(
2349 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2350
2351 // Add the returned register to the CalleeSaveDisableRegs list.
2352 if (ShouldDisableCalleeSavedRegister)
2353 MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2354 }
2355
2356 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2357 const MCPhysReg *I =
2358 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2359 if (I) {
2360 for (; *I; ++I) {
2361 if (X86::GR64RegClass.contains(*I))
2362 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2363 else
2364 llvm_unreachable("Unexpected register class in CSRsViaCopy!")::llvm::llvm_unreachable_internal("Unexpected register class in CSRsViaCopy!"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2364)
;
2365 }
2366 }
2367
2368 RetOps[0] = Chain; // Update chain.
2369
2370 // Add the flag if we have it.
2371 if (Flag.getNode())
2372 RetOps.push_back(Flag);
2373
2374 X86ISD::NodeType opcode = X86ISD::RET_FLAG;
2375 if (CallConv == CallingConv::X86_INTR)
2376 opcode = X86ISD::IRET;
2377 return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2378}
2379
2380bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2381 if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2382 return false;
2383
2384 SDValue TCChain = Chain;
2385 SDNode *Copy = *N->use_begin();
2386 if (Copy->getOpcode() == ISD::CopyToReg) {
2387 // If the copy has a glue operand, we conservatively assume it isn't safe to
2388 // perform a tail call.
2389 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2390 return false;
2391 TCChain = Copy->getOperand(0);
2392 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2393 return false;
2394
2395 bool HasRet = false;
2396 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2397 UI != UE; ++UI) {
2398 if (UI->getOpcode() != X86ISD::RET_FLAG)
2399 return false;
2400 // If we are returning more than one value, we can definitely
2401 // not make a tail call see PR19530
2402 if (UI->getNumOperands() > 4)
2403 return false;
2404 if (UI->getNumOperands() == 4 &&
2405 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2406 return false;
2407 HasRet = true;
2408 }
2409
2410 if (!HasRet)
2411 return false;
2412
2413 Chain = TCChain;
2414 return true;
2415}
2416
2417EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2418 ISD::NodeType ExtendKind) const {
2419 MVT ReturnMVT = MVT::i32;
2420
2421 bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2422 if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2423 // The ABI does not require i1, i8 or i16 to be extended.
2424 //
2425 // On Darwin, there is code in the wild relying on Clang's old behaviour of
2426 // always extending i8/i16 return values, so keep doing that for now.
2427 // (PR26665).
2428 ReturnMVT = MVT::i8;
2429 }
2430
2431 EVT MinVT = getRegisterType(Context, ReturnMVT);
2432 return VT.bitsLT(MinVT) ? MinVT : VT;
2433}
2434
2435/// Reads two 32 bit registers and creates a 64 bit mask value.
2436/// \param VA The current 32 bit value that need to be assigned.
2437/// \param NextVA The next 32 bit value that need to be assigned.
2438/// \param Root The parent DAG node.
2439/// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2440/// glue purposes. In the case the DAG is already using
2441/// physical register instead of virtual, we should glue
2442/// our new SDValue to InFlag SDvalue.
2443/// \return a new SDvalue of size 64bit.
2444static SDValue getv64i1Argument(CCValAssign &VA, CCValAssign &NextVA,
2445 SDValue &Root, SelectionDAG &DAG,
2446 const SDLoc &Dl, const X86Subtarget &Subtarget,
2447 SDValue *InFlag = nullptr) {
2448 assert((Subtarget.hasBWI()) && "Expected AVX512BW target!")(static_cast <bool> ((Subtarget.hasBWI()) && "Expected AVX512BW target!"
) ? void (0) : __assert_fail ("(Subtarget.hasBWI()) && \"Expected AVX512BW target!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2448, __extension__ __PRETTY_FUNCTION__))
;
2449 assert(Subtarget.is32Bit() && "Expecting 32 bit target")(static_cast <bool> (Subtarget.is32Bit() && "Expecting 32 bit target"
) ? void (0) : __assert_fail ("Subtarget.is32Bit() && \"Expecting 32 bit target\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2449, __extension__ __PRETTY_FUNCTION__))
;
2450 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Expecting first location of 64 bit width type") ? void (0) :
__assert_fail ("VA.getValVT() == MVT::v64i1 && \"Expecting first location of 64 bit width type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2451, __extension__ __PRETTY_FUNCTION__))
2451 "Expecting first location of 64 bit width type")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Expecting first location of 64 bit width type") ? void (0) :
__assert_fail ("VA.getValVT() == MVT::v64i1 && \"Expecting first location of 64 bit width type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2451, __extension__ __PRETTY_FUNCTION__))
;
2452 assert(NextVA.getValVT() == VA.getValVT() &&(static_cast <bool> (NextVA.getValVT() == VA.getValVT()
&& "The locations should have the same type") ? void
(0) : __assert_fail ("NextVA.getValVT() == VA.getValVT() && \"The locations should have the same type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2453, __extension__ __PRETTY_FUNCTION__))
2453 "The locations should have the same type")(static_cast <bool> (NextVA.getValVT() == VA.getValVT()
&& "The locations should have the same type") ? void
(0) : __assert_fail ("NextVA.getValVT() == VA.getValVT() && \"The locations should have the same type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2453, __extension__ __PRETTY_FUNCTION__))
;
2454 assert(VA.isRegLoc() && NextVA.isRegLoc() &&(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The values should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The values should reside in two registers\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2455, __extension__ __PRETTY_FUNCTION__))
2455 "The values should reside in two registers")(static_cast <bool> (VA.isRegLoc() && NextVA.isRegLoc
() && "The values should reside in two registers") ? void
(0) : __assert_fail ("VA.isRegLoc() && NextVA.isRegLoc() && \"The values should reside in two registers\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2455, __extension__ __PRETTY_FUNCTION__))
;
2456
2457 SDValue Lo, Hi;
2458 unsigned Reg;
2459 SDValue ArgValueLo, ArgValueHi;
2460
2461 MachineFunction &MF = DAG.getMachineFunction();
2462 const TargetRegisterClass *RC = &X86::GR32RegClass;
2463
2464 // Read a 32 bit value from the registers
2465 if (nullptr == InFlag) {
2466 // When no physical register is present,
2467 // create an intermediate virtual register
2468 Reg = MF.addLiveIn(VA.getLocReg(), RC);
2469 ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2470 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2471 ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2472 } else {
2473 // When a physical register is available read the value from it and glue
2474 // the reads together.
2475 ArgValueLo =
2476 DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2477 *InFlag = ArgValueLo.getValue(2);
2478 ArgValueHi =
2479 DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2480 *InFlag = ArgValueHi.getValue(2);
2481 }
2482
2483 // Convert the i32 type into v32i1 type
2484 Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2485
2486 // Convert the i32 type into v32i1 type
2487 Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2488
2489 // Concatenate the two values together
2490 return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2491}
2492
2493/// The function will lower a register of various sizes (8/16/32/64)
2494/// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2495/// \returns a DAG node contains the operand after lowering to mask type.
2496static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2497 const EVT &ValLoc, const SDLoc &Dl,
2498 SelectionDAG &DAG) {
2499 SDValue ValReturned = ValArg;
2500
2501 if (ValVT == MVT::v1i1)
2502 return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2503
2504 if (ValVT == MVT::v64i1) {
2505 // In 32 bit machine, this case is handled by getv64i1Argument
2506 assert(ValLoc == MVT::i64 && "Expecting only i64 locations")(static_cast <bool> (ValLoc == MVT::i64 && "Expecting only i64 locations"
) ? void (0) : __assert_fail ("ValLoc == MVT::i64 && \"Expecting only i64 locations\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2506, __extension__ __PRETTY_FUNCTION__))
;
2507 // In 64 bit machine, There is no need to truncate the value only bitcast
2508 } else {
2509 MVT maskLen;
2510 switch (ValVT.getSimpleVT().SimpleTy) {
2511 case MVT::v8i1:
2512 maskLen = MVT::i8;
2513 break;
2514 case MVT::v16i1:
2515 maskLen = MVT::i16;
2516 break;
2517 case MVT::v32i1:
2518 maskLen = MVT::i32;
2519 break;
2520 default:
2521 llvm_unreachable("Expecting a vector of i1 types")::llvm::llvm_unreachable_internal("Expecting a vector of i1 types"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2521)
;
2522 }
2523
2524 ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2525 }
2526 return DAG.getBitcast(ValVT, ValReturned);
2527}
2528
2529/// Lower the result values of a call into the
2530/// appropriate copies out of appropriate physical registers.
2531///
2532SDValue X86TargetLowering::LowerCallResult(
2533 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2534 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2535 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2536 uint32_t *RegMask) const {
2537
2538 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2539 // Assign locations to each value returned by this call.
2540 SmallVector<CCValAssign, 16> RVLocs;
2541 bool Is64Bit = Subtarget.is64Bit();
2542 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2543 *DAG.getContext());
2544 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2545
2546 // Copy all of the result registers out of their specified physreg.
2547 for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2548 ++I, ++InsIndex) {
2549 CCValAssign &VA = RVLocs[I];
2550 EVT CopyVT = VA.getLocVT();
2551
2552 // In some calling conventions we need to remove the used registers
2553 // from the register mask.
2554 if (RegMask) {
2555 for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2556 SubRegs.isValid(); ++SubRegs)
2557 RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2558 }
2559
2560 // If this is x86-64, and we disabled SSE, we can't return FP values
2561 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2562 ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2563 errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2564 VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2565 }
2566
2567 // If we prefer to use the value in xmm registers, copy it out as f80 and
2568 // use a truncate to move it from fp stack reg to xmm reg.
2569 bool RoundAfterCopy = false;
2570 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2571 isScalarFPTypeInSSEReg(VA.getValVT())) {
2572 if (!Subtarget.hasX87())
2573 report_fatal_error("X87 register return with X87 disabled");
2574 CopyVT = MVT::f80;
2575 RoundAfterCopy = (CopyVT != VA.getLocVT());
2576 }
2577
2578 SDValue Val;
2579 if (VA.needsCustom()) {
2580 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? 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-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2581, __extension__ __PRETTY_FUNCTION__))
2581 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? 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-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2581, __extension__ __PRETTY_FUNCTION__))
;
2582 Val =
2583 getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2584 } else {
2585 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2586 .getValue(1);
2587 Val = Chain.getValue(0);
2588 InFlag = Chain.getValue(2);
2589 }
2590
2591 if (RoundAfterCopy)
2592 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2593 // This truncation won't change the value.
2594 DAG.getIntPtrConstant(1, dl));
2595
2596 if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2597 if (VA.getValVT().isVector() &&
2598 ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2599 (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2600 // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2601 Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2602 } else
2603 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2604 }
2605
2606 InVals.push_back(Val);
2607 }
2608
2609 return Chain;
2610}
2611
2612//===----------------------------------------------------------------------===//
2613// C & StdCall & Fast Calling Convention implementation
2614//===----------------------------------------------------------------------===//
2615// StdCall calling convention seems to be standard for many Windows' API
2616// routines and around. It differs from C calling convention just a little:
2617// callee should clean up the stack, not caller. Symbols should be also
2618// decorated in some fancy way :) It doesn't support any vector arguments.
2619// For info on fast calling convention see Fast Calling Convention (tail call)
2620// implementation LowerX86_32FastCCCallTo.
2621
2622/// CallIsStructReturn - Determines whether a call uses struct return
2623/// semantics.
2624enum StructReturnType {
2625 NotStructReturn,
2626 RegStructReturn,
2627 StackStructReturn
2628};
2629static StructReturnType
2630callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsMCU) {
2631 if (Outs.empty())
2632 return NotStructReturn;
2633
2634 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2635 if (!Flags.isSRet())
2636 return NotStructReturn;
2637 if (Flags.isInReg() || IsMCU)
2638 return RegStructReturn;
2639 return StackStructReturn;
2640}
2641
2642/// Determines whether a function uses struct return semantics.
2643static StructReturnType
2644argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsMCU) {
2645 if (Ins.empty())
2646 return NotStructReturn;
2647
2648 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2649 if (!Flags.isSRet())
2650 return NotStructReturn;
2651 if (Flags.isInReg() || IsMCU)
2652 return RegStructReturn;
2653 return StackStructReturn;
2654}
2655
2656/// Make a copy of an aggregate at address specified by "Src" to address
2657/// "Dst" with size and alignment information specified by the specific
2658/// parameter attribute. The copy will be passed as a byval function parameter.
2659static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
2660 SDValue Chain, ISD::ArgFlagsTy Flags,
2661 SelectionDAG &DAG, const SDLoc &dl) {
2662 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2663
2664 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2665 /*isVolatile*/false, /*AlwaysInline=*/true,
2666 /*isTailCall*/false,
2667 MachinePointerInfo(), MachinePointerInfo());
2668}
2669
2670/// Return true if the calling convention is one that we can guarantee TCO for.
2671static bool canGuaranteeTCO(CallingConv::ID CC) {
2672 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2673 CC == CallingConv::X86_RegCall || CC == CallingConv::HiPE ||
2674 CC == CallingConv::HHVM);
2675}
2676
2677/// Return true if we might ever do TCO for calls with this calling convention.
2678static bool mayTailCallThisCC(CallingConv::ID CC) {
2679 switch (CC) {
2680 // C calling conventions:
2681 case CallingConv::C:
2682 case CallingConv::Win64:
2683 case CallingConv::X86_64_SysV:
2684 // Callee pop conventions:
2685 case CallingConv::X86_ThisCall:
2686 case CallingConv::X86_StdCall:
2687 case CallingConv::X86_VectorCall:
2688 case CallingConv::X86_FastCall:
2689 return true;
2690 default:
2691 return canGuaranteeTCO(CC);
2692 }
2693}
2694
2695/// Return true if the function is being made into a tailcall target by
2696/// changing its ABI.
2697static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2698 return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2699}
2700
2701bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2702 auto Attr =
2703 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2704 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2705 return false;
2706
2707 ImmutableCallSite CS(CI);
2708 CallingConv::ID CalleeCC = CS.getCallingConv();
2709 if (!mayTailCallThisCC(CalleeCC))
2710 return false;
2711
2712 return true;
2713}
2714
2715SDValue
2716X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2717 const SmallVectorImpl<ISD::InputArg> &Ins,
2718 const SDLoc &dl, SelectionDAG &DAG,
2719 const CCValAssign &VA,
2720 MachineFrameInfo &MFI, unsigned i) const {
2721 // Create the nodes corresponding to a load from this parameter slot.
2722 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2723 bool AlwaysUseMutable = shouldGuaranteeTCO(
2724 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2725 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2726 EVT ValVT;
2727 MVT PtrVT = getPointerTy(DAG.getDataLayout());
2728
2729 // If value is passed by pointer we have address passed instead of the value
2730 // itself. No need to extend if the mask value and location share the same
2731 // absolute size.
2732 bool ExtendedInMem =
2733 VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2734 VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2735
2736 if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2737 ValVT = VA.getLocVT();
2738 else
2739 ValVT = VA.getValVT();
2740
2741 // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2742 // taken by a return address.
2743 int Offset = 0;
2744 if (CallConv == CallingConv::X86_INTR) {
2745 // X86 interrupts may take one or two arguments.
2746 // On the stack there will be no return address as in regular call.
2747 // Offset of last argument need to be set to -4/-8 bytes.
2748 // Where offset of the first argument out of two, should be set to 0 bytes.
2749 Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2750 if (Subtarget.is64Bit() && Ins.size() == 2) {
2751 // The stack pointer needs to be realigned for 64 bit handlers with error
2752 // code, so the argument offset changes by 8 bytes.
2753 Offset += 8;
2754 }
2755 }
2756
2757 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2758 // changed with more analysis.
2759 // In case of tail call optimization mark all arguments mutable. Since they
2760 // could be overwritten by lowering of arguments in case of a tail call.
2761 if (Flags.isByVal()) {
2762 unsigned Bytes = Flags.getByValSize();
2763 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2764 int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2765 // Adjust SP offset of interrupt parameter.
2766 if (CallConv == CallingConv::X86_INTR) {
2767 MFI.setObjectOffset(FI, Offset);
2768 }
2769 return DAG.getFrameIndex(FI, PtrVT);
2770 }
2771
2772 // This is an argument in memory. We might be able to perform copy elision.
2773 if (Flags.isCopyElisionCandidate()) {
2774 EVT ArgVT = Ins[i].ArgVT;
2775 SDValue PartAddr;
2776 if (Ins[i].PartOffset == 0) {
2777 // If this is a one-part value or the first part of a multi-part value,
2778 // create a stack object for the entire argument value type and return a
2779 // load from our portion of it. This assumes that if the first part of an
2780 // argument is in memory, the rest will also be in memory.
2781 int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
2782 /*Immutable=*/false);
2783 PartAddr = DAG.getFrameIndex(FI, PtrVT);
2784 return DAG.getLoad(
2785 ValVT, dl, Chain, PartAddr,
2786 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
2787 } else {
2788 // This is not the first piece of an argument in memory. See if there is
2789 // already a fixed stack object including this offset. If so, assume it
2790 // was created by the PartOffset == 0 branch above and create a load from
2791 // the appropriate offset into it.
2792 int64_t PartBegin = VA.getLocMemOffset();
2793 int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
2794 int FI = MFI.getObjectIndexBegin();
2795 for (; MFI.isFixedObjectIndex(FI); ++FI) {
2796 int64_t ObjBegin = MFI.getObjectOffset(FI);
2797 int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
2798 if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
2799 break;
2800 }
2801 if (MFI.isFixedObjectIndex(FI)) {
2802 SDValue Addr =
2803 DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
2804 DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
2805 return DAG.getLoad(
2806 ValVT, dl, Chain, Addr,
2807 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI,
2808 Ins[i].PartOffset));
2809 }
2810 }
2811 }
2812
2813 int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
2814 VA.getLocMemOffset(), isImmutable);
2815
2816 // Set SExt or ZExt flag.
2817 if (VA.getLocInfo() == CCValAssign::ZExt) {
2818 MFI.setObjectZExt(FI, true);
2819 } else if (VA.getLocInfo() == CCValAssign::SExt) {
2820 MFI.setObjectSExt(FI, true);
2821 }
2822
2823 // Adjust SP offset of interrupt parameter.
2824 if (CallConv == CallingConv::X86_INTR) {
2825 MFI.setObjectOffset(FI, Offset);
2826 }
2827
2828 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2829 SDValue Val = DAG.getLoad(
2830 ValVT, dl, Chain, FIN,
2831 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
2832 return ExtendedInMem
2833 ? (VA.getValVT().isVector()
2834 ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
2835 : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
2836 : Val;
2837}
2838
2839// FIXME: Get this from tablegen.
2840static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2841 const X86Subtarget &Subtarget) {
2842 assert(Subtarget.is64Bit())(static_cast <bool> (Subtarget.is64Bit()) ? void (0) : __assert_fail
("Subtarget.is64Bit()", "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2842, __extension__ __PRETTY_FUNCTION__))
;
2843
2844 if (Subtarget.isCallingConvWin64(CallConv)) {
2845 static const MCPhysReg GPR64ArgRegsWin64[] = {
2846 X86::RCX, X86::RDX, X86::R8, X86::R9
2847 };
2848 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2849 }
2850
2851 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2852 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2853 };
2854 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2855}
2856
2857// FIXME: Get this from tablegen.
2858static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2859 CallingConv::ID CallConv,
2860 const X86Subtarget &Subtarget) {
2861 assert(Subtarget.is64Bit())(static_cast <bool> (Subtarget.is64Bit()) ? void (0) : __assert_fail
("Subtarget.is64Bit()", "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2861, __extension__ __PRETTY_FUNCTION__))
;
2862 if (Subtarget.isCallingConvWin64(CallConv)) {
2863 // The XMM registers which might contain var arg parameters are shadowed
2864 // in their paired GPR. So we only need to save the GPR to their home
2865 // slots.
2866 // TODO: __vectorcall will change this.
2867 return None;
2868 }
2869
2870 const Function *Fn = MF.getFunction();
2871 bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2872 bool isSoftFloat = Subtarget.useSoftFloat();
2873 assert(!(isSoftFloat && NoImplicitFloatOps) &&(static_cast <bool> (!(isSoftFloat && NoImplicitFloatOps
) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(isSoftFloat && NoImplicitFloatOps) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2874, __extension__ __PRETTY_FUNCTION__))
2874 "SSE register cannot be used when SSE is disabled!")(static_cast <bool> (!(isSoftFloat && NoImplicitFloatOps
) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(isSoftFloat && NoImplicitFloatOps) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2874, __extension__ __PRETTY_FUNCTION__))
;
2875 if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
2876 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2877 // registers.
2878 return None;
2879
2880 static const MCPhysReg XMMArgRegs64Bit[] = {
2881 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2882 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2883 };
2884 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2885}
2886
2887#ifndef NDEBUG
2888static bool isSortedByValueNo(const SmallVectorImpl<CCValAssign> &ArgLocs) {
2889 return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
2890 [](const CCValAssign &A, const CCValAssign &B) -> bool {
2891 return A.getValNo() < B.getValNo();
2892 });
2893}
2894#endif
2895
2896SDValue X86TargetLowering::LowerFormalArguments(
2897 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2898 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2899 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2900 MachineFunction &MF = DAG.getMachineFunction();
2901 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2902 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
2903
2904 const Function *Fn = MF.getFunction();
2905 if (Fn->hasExternalLinkage() &&
2906 Subtarget.isTargetCygMing() &&
2907 Fn->getName() == "main")
2908 FuncInfo->setForceFramePointer(true);
2909
2910 MachineFrameInfo &MFI = MF.getFrameInfo();
2911 bool Is64Bit = Subtarget.is64Bit();
2912 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
2913
2914 assert((static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2916, __extension__ __PRETTY_FUNCTION__))
2915 !(isVarArg && canGuaranteeTCO(CallConv)) &&(static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2916, __extension__ __PRETTY_FUNCTION__))
2916 "Var args not supported with calling conv' regcall, fastcc, ghc or hipe")(static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling conv' regcall, fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling conv' regcall, fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2916, __extension__ __PRETTY_FUNCTION__))
;
2917
2918 if (CallConv == CallingConv::X86_INTR) {
2919 bool isLegal = Ins.size() == 1 ||
2920 (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
2921 (!Is64Bit && Ins[1].VT == MVT::i32)));
2922 if (!isLegal)
2923 report_fatal_error("X86 interrupts may take one or two arguments");
2924 }
2925
2926 // Assign locations to all of the incoming arguments.
2927 SmallVector<CCValAssign, 16> ArgLocs;
2928 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2929
2930 // Allocate shadow area for Win64.
2931 if (IsWin64)
2932 CCInfo.AllocateStack(32, 8);
2933
2934 CCInfo.AnalyzeArguments(Ins, CC_X86);
2935
2936 // In vectorcall calling convention a second pass is required for the HVA
2937 // types.
2938 if (CallingConv::X86_VectorCall == CallConv) {
2939 CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
2940 }
2941
2942 // The next loop assumes that the locations are in the same order of the
2943 // input arguments.
2944 assert(isSortedByValueNo(ArgLocs) &&(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2945, __extension__ __PRETTY_FUNCTION__))
2945 "Argument Location list must be sorted before lowering")(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2945, __extension__ __PRETTY_FUNCTION__))
;
2946
2947 SDValue ArgValue;
2948 for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
2949 ++I, ++InsIndex) {
2950 assert(InsIndex < Ins.size() && "Invalid Ins index")(static_cast <bool> (InsIndex < Ins.size() &&
"Invalid Ins index") ? void (0) : __assert_fail ("InsIndex < Ins.size() && \"Invalid Ins index\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2950, __extension__ __PRETTY_FUNCTION__))
;
2951 CCValAssign &VA = ArgLocs[I];
2952
2953 if (VA.isRegLoc()) {
2954 EVT RegVT = VA.getLocVT();
2955 if (VA.needsCustom()) {
2956 assert((static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? 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-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2958, __extension__ __PRETTY_FUNCTION__))
2957 VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? 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-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2958, __extension__ __PRETTY_FUNCTION__))
2958 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? 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-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2958, __extension__ __PRETTY_FUNCTION__))
;
2959
2960 // v64i1 values, in regcall calling convention, that are
2961 // compiled to 32 bit arch, are split up into two registers.
2962 ArgValue =
2963 getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
2964 } else {
2965 const TargetRegisterClass *RC;
2966 if (RegVT == MVT::i32)
2967 RC = &X86::GR32RegClass;
2968 else if (Is64Bit && RegVT == MVT::i64)
2969 RC = &X86::GR64RegClass;
2970 else if (RegVT == MVT::f32)
2971 RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
2972 else if (RegVT == MVT::f64)
2973 RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
2974 else if (RegVT == MVT::f80)
2975 RC = &X86::RFP80RegClass;
2976 else if (RegVT == MVT::f128)
2977 RC = &X86::FR128RegClass;
2978 else if (RegVT.is512BitVector())
2979 RC = &X86::VR512RegClass;
2980 else if (RegVT.is256BitVector())
2981 RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
2982 else if (RegVT.is128BitVector())
2983 RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
2984 else if (RegVT == MVT::x86mmx)
2985 RC = &X86::VR64RegClass;
2986 else if (RegVT == MVT::v1i1)
2987 RC = &X86::VK1RegClass;
2988 else if (RegVT == MVT::v8i1)
2989 RC = &X86::VK8RegClass;
2990 else if (RegVT == MVT::v16i1)
2991 RC = &X86::VK16RegClass;
2992 else if (RegVT == MVT::v32i1)
2993 RC = &X86::VK32RegClass;
2994 else if (RegVT == MVT::v64i1)
2995 RC = &X86::VK64RegClass;
2996 else
2997 llvm_unreachable("Unknown argument type!")::llvm::llvm_unreachable_internal("Unknown argument type!", "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 2997)
;
2998
2999 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3000 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3001 }
3002
3003 // If this is an 8 or 16-bit value, it is really passed promoted to 32
3004 // bits. Insert an assert[sz]ext to capture this, then truncate to the
3005 // right size.
3006 if (VA.getLocInfo() == CCValAssign::SExt)
3007 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3008 DAG.getValueType(VA.getValVT()));
3009 else if (VA.getLocInfo() == CCValAssign::ZExt)
3010 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3011 DAG.getValueType(VA.getValVT()));
3012 else if (VA.getLocInfo() == CCValAssign::BCvt)
3013 ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3014
3015 if (VA.isExtInLoc()) {
3016 // Handle MMX values passed in XMM regs.
3017 if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3018 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3019 else if (VA.getValVT().isVector() &&
3020 VA.getValVT().getScalarType() == MVT::i1 &&
3021 ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3022 (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3023 // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3024 ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3025 } else
3026 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3027 }
3028 } else {
3029 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3029, __extension__ __PRETTY_FUNCTION__))
;
3030 ArgValue =
3031 LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3032 }
3033
3034 // If value is passed via pointer - do a load.
3035 if (VA.getLocInfo() == CCValAssign::Indirect)
3036 ArgValue =
3037 DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3038
3039 InVals.push_back(ArgValue);
3040 }
3041
3042 for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3043 // Swift calling convention does not require we copy the sret argument
3044 // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3045 if (CallConv == CallingConv::Swift)
3046 continue;
3047
3048 // All x86 ABIs require that for returning structs by value we copy the
3049 // sret argument into %rax/%eax (depending on ABI) for the return. Save
3050 // the argument into a virtual register so that we can access it from the
3051 // return points.
3052 if (Ins[I].Flags.isSRet()) {
3053 unsigned Reg = FuncInfo->getSRetReturnReg();
3054 if (!Reg) {
3055 MVT PtrTy = getPointerTy(DAG.getDataLayout());
3056 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3057 FuncInfo->setSRetReturnReg(Reg);
3058 }
3059 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3060 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3061 break;
3062 }
3063 }
3064
3065 unsigned StackSize = CCInfo.getNextStackOffset();
3066 // Align stack specially for tail calls.
3067 if (shouldGuaranteeTCO(CallConv,
3068 MF.getTarget().Options.GuaranteedTailCallOpt))
3069 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3070
3071 // If the function takes variable number of arguments, make a frame index for
3072 // the start of the first vararg value... for expansion of llvm.va_start. We
3073 // can skip this if there are no va_start calls.
3074 if (MFI.hasVAStart() &&
3075 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3076 CallConv != CallingConv::X86_ThisCall))) {
3077 FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3078 }
3079
3080 // Figure out if XMM registers are in use.
3081 assert(!(Subtarget.useSoftFloat() &&(static_cast <bool> (!(Subtarget.useSoftFloat() &&
Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
"SSE register cannot be used when SSE is disabled!") ? void (
0) : __assert_fail ("!(Subtarget.useSoftFloat() && Fn->hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3083, __extension__ __PRETTY_FUNCTION__))
3082 Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&(static_cast <bool> (!(Subtarget.useSoftFloat() &&
Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
"SSE register cannot be used when SSE is disabled!") ? void (
0) : __assert_fail ("!(Subtarget.useSoftFloat() && Fn->hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3083, __extension__ __PRETTY_FUNCTION__))
3083 "SSE register cannot be used when SSE is disabled!")(static_cast <bool> (!(Subtarget.useSoftFloat() &&
Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
"SSE register cannot be used when SSE is disabled!") ? void (
0) : __assert_fail ("!(Subtarget.useSoftFloat() && Fn->hasFnAttribute(Attribute::NoImplicitFloat)) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3083, __extension__ __PRETTY_FUNCTION__))
;
3084
3085 // 64-bit calling conventions support varargs and register parameters, so we
3086 // have to do extra work to spill them in the prologue.
3087 if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3088 // Find the first unallocated argument registers.
3089 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3090 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3091 unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3092 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3093 assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&(static_cast <bool> (!(NumXMMRegs && !Subtarget
.hasSSE1()) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(NumXMMRegs && !Subtarget.hasSSE1()) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3094, __extension__ __PRETTY_FUNCTION__))
3094 "SSE register cannot be used when SSE is disabled!")(static_cast <bool> (!(NumXMMRegs && !Subtarget
.hasSSE1()) && "SSE register cannot be used when SSE is disabled!"
) ? void (0) : __assert_fail ("!(NumXMMRegs && !Subtarget.hasSSE1()) && \"SSE register cannot be used when SSE is disabled!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3094, __extension__ __PRETTY_FUNCTION__))
;
3095
3096 // Gather all the live in physical registers.
3097 SmallVector<SDValue, 6> LiveGPRs;
3098 SmallVector<SDValue, 8> LiveXMMRegs;
3099 SDValue ALVal;
3100 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3101 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3102 LiveGPRs.push_back(
3103 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3104 }
3105 if (!ArgXMMs.empty()) {
3106 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3107 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3108 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3109 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3110 LiveXMMRegs.push_back(
3111 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3112 }
3113 }
3114
3115 if (IsWin64) {
3116 // Get to the caller-allocated home save location. Add 8 to account
3117 // for the return address.
3118 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3119 FuncInfo->setRegSaveFrameIndex(
3120 MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3121 // Fixup to set vararg frame on shadow area (4 x i64).
3122 if (NumIntRegs < 4)
3123 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3124 } else {
3125 // For X86-64, if there are vararg parameters that are passed via
3126 // registers, then we must store them to their spots on the stack so
3127 // they may be loaded by dereferencing the result of va_next.
3128 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3129 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3130 FuncInfo->setRegSaveFrameIndex(MFI.CreateStackObject(
3131 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3132 }
3133
3134 // Store the integer parameter registers.
3135 SmallVector<SDValue, 8> MemOps;
3136 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3137 getPointerTy(DAG.getDataLayout()));
3138 unsigned Offset = FuncInfo->getVarArgsGPOffset();
3139 for (SDValue Val : LiveGPRs) {
3140 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3141 RSFIN, DAG.getIntPtrConstant(Offset, dl));
3142 SDValue Store =
3143 DAG.getStore(Val.getValue(1), dl, Val, FIN,
3144 MachinePointerInfo::getFixedStack(
3145 DAG.getMachineFunction(),
3146 FuncInfo->getRegSaveFrameIndex(), Offset));
3147 MemOps.push_back(Store);
3148 Offset += 8;
3149 }
3150
3151 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3152 // Now store the XMM (fp + vector) parameter registers.
3153 SmallVector<SDValue, 12> SaveXMMOps;
3154 SaveXMMOps.push_back(Chain);
3155 SaveXMMOps.push_back(ALVal);
3156 SaveXMMOps.push_back(DAG.getIntPtrConstant(
3157 FuncInfo->getRegSaveFrameIndex(), dl));
3158 SaveXMMOps.push_back(DAG.getIntPtrConstant(
3159 FuncInfo->getVarArgsFPOffset(), dl));
3160 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3161 LiveXMMRegs.end());
3162 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
3163 MVT::Other, SaveXMMOps));
3164 }
3165
3166 if (!MemOps.empty())
3167 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3168 }
3169
3170 if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3171 // Find the largest legal vector type.
3172 MVT VecVT = MVT::Other;
3173 // FIXME: Only some x86_32 calling conventions support AVX512.
3174 if (Subtarget.hasAVX512() &&
3175 (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3176 CallConv == CallingConv::Intel_OCL_BI)))
3177 VecVT = MVT::v16f32;
3178 else if (Subtarget.hasAVX())
3179 VecVT = MVT::v8f32;
3180 else if (Subtarget.hasSSE2())
3181 VecVT = MVT::v4f32;
3182
3183 // We forward some GPRs and some vector types.
3184 SmallVector<MVT, 2> RegParmTypes;
3185 MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3186 RegParmTypes.push_back(IntVT);
3187 if (VecVT != MVT::Other)
3188 RegParmTypes.push_back(VecVT);
3189
3190 // Compute the set of forwarded registers. The rest are scratch.
3191 SmallVectorImpl<ForwardedRegister> &Forwards =
3192 FuncInfo->getForwardedMustTailRegParms();
3193 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3194
3195 // Conservatively forward AL on x86_64, since it might be used for varargs.
3196 if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3197 unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3198 Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3199 }
3200
3201 // Copy all forwards from physical to virtual registers.
3202 for (ForwardedRegister &F : Forwards) {
3203 // FIXME: Can we use a less constrained schedule?
3204 SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3205 F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
3206 Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
3207 }
3208 }
3209
3210 // Some CCs need callee pop.
3211 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3212 MF.getTarget().Options.GuaranteedTailCallOpt)) {
3213 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3214 } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3215 // X86 interrupts must pop the error code (and the alignment padding) if
3216 // present.
3217 FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3218 } else {
3219 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3220 // If this is an sret function, the return should pop the hidden pointer.
3221 if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3222 !Subtarget.getTargetTriple().isOSMSVCRT() &&
3223 argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3224 FuncInfo->setBytesToPopOnReturn(4);
3225 }
3226
3227 if (!Is64Bit) {
3228 // RegSaveFrameIndex is X86-64 only.
3229 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3230 if (CallConv == CallingConv::X86_FastCall ||
3231 CallConv == CallingConv::X86_ThisCall)
3232 // fastcc functions can't have varargs.
3233 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3234 }
3235
3236 FuncInfo->setArgumentStackSize(StackSize);
3237
3238 if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3239 EHPersonality Personality = classifyEHPersonality(Fn->getPersonalityFn());
3240 if (Personality == EHPersonality::CoreCLR) {
3241 assert(Is64Bit)(static_cast <bool> (Is64Bit) ? void (0) : __assert_fail
("Is64Bit", "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3241, __extension__ __PRETTY_FUNCTION__))
;
3242 // TODO: Add a mechanism to frame lowering that will allow us to indicate
3243 // that we'd prefer this slot be allocated towards the bottom of the frame
3244 // (i.e. near the stack pointer after allocating the frame). Every
3245 // funclet needs a copy of this slot in its (mostly empty) frame, and the
3246 // offset from the bottom of this and each funclet's frame must be the
3247 // same, so the size of funclets' (mostly empty) frames is dictated by
3248 // how far this slot is from the bottom (since they allocate just enough
3249 // space to accommodate holding this slot at the correct offset).
3250 int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3251 EHInfo->PSPSymFrameIdx = PSPSymFI;
3252 }
3253 }
3254
3255 if (CallConv == CallingConv::X86_RegCall ||
3256 Fn->hasFnAttribute("no_caller_saved_registers")) {
3257 MachineRegisterInfo &MRI = MF.getRegInfo();
3258 for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3259 MRI.disableCalleeSavedRegister(Pair.first);
3260 }
3261
3262 return Chain;
3263}
3264
3265SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3266 SDValue Arg, const SDLoc &dl,
3267 SelectionDAG &DAG,
3268 const CCValAssign &VA,
3269 ISD::ArgFlagsTy Flags) const {
3270 unsigned LocMemOffset = VA.getLocMemOffset();
3271 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3272 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3273 StackPtr, PtrOff);
3274 if (Flags.isByVal())
3275 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3276
3277 return DAG.getStore(
3278 Chain, dl, Arg, PtrOff,
3279 MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3280}
3281
3282/// Emit a load of return address if tail call
3283/// optimization is performed and it is required.
3284SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3285 SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3286 bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3287 // Adjust the Return address stack slot.
3288 EVT VT = getPointerTy(DAG.getDataLayout());
3289 OutRetAddr = getReturnAddressFrameIndex(DAG);
3290
3291 // Load the "old" Return address.
3292 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3293 return SDValue(OutRetAddr.getNode(), 1);
3294}
3295
3296/// Emit a store of the return address if tail call
3297/// optimization is performed and it is required (FPDiff!=0).
3298static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
3299 SDValue Chain, SDValue RetAddrFrIdx,
3300 EVT PtrVT, unsigned SlotSize,
3301 int FPDiff, const SDLoc &dl) {
3302 // Store the return address to the appropriate stack slot.
3303 if (!FPDiff) return Chain;
3304 // Calculate the new stack slot for the return address.
3305 int NewReturnAddrFI =
3306 MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3307 false);
3308 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3309 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3310 MachinePointerInfo::getFixedStack(
3311 DAG.getMachineFunction(), NewReturnAddrFI));
3312 return Chain;
3313}
3314
3315/// Returns a vector_shuffle mask for an movs{s|d}, movd
3316/// operation of specified width.
3317static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3318 SDValue V2) {
3319 unsigned NumElems = VT.getVectorNumElements();
3320 SmallVector<int, 8> Mask;
3321 Mask.push_back(NumElems);
3322 for (unsigned i = 1; i != NumElems; ++i)
3323 Mask.push_back(i);
3324 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3325}
3326
3327SDValue
3328X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3329 SmallVectorImpl<SDValue> &InVals) const {
3330 SelectionDAG &DAG = CLI.DAG;
3331 SDLoc &dl = CLI.DL;
3332 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3333 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3334 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3335 SDValue Chain = CLI.Chain;
3336 SDValue Callee = CLI.Callee;
3337 CallingConv::ID CallConv = CLI.CallConv;
3338 bool &isTailCall = CLI.IsTailCall;
3339 bool isVarArg = CLI.IsVarArg;
3340
3341 MachineFunction &MF = DAG.getMachineFunction();
3342 bool Is64Bit = Subtarget.is64Bit();
3343 bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3344 StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3345 bool IsSibcall = false;
3346 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
3347 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
3348 const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3349 const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3350 bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3351 (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3352
3353 if (CallConv == CallingConv::X86_INTR)
3354 report_fatal_error("X86 interrupts may not be called directly");
3355
3356 if (Attr.getValueAsString() == "true")
3357 isTailCall = false;
3358
3359 if (Subtarget.isPICStyleGOT() &&
3360 !MF.getTarget().Options.GuaranteedTailCallOpt) {
3361 // If we are using a GOT, disable tail calls to external symbols with
3362 // default visibility. Tail calling such a symbol requires using a GOT
3363 // relocation, which forces early binding of the symbol. This breaks code
3364 // that require lazy function symbol resolution. Using musttail or
3365 // GuaranteedTailCallOpt will override this.
3366 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3367 if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3368 G->getGlobal()->hasDefaultVisibility()))
3369 isTailCall = false;
3370 }
3371
3372 bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3373 if (IsMustTail) {
3374 // Force this to be a tail call. The verifier rules are enough to ensure
3375 // that we can lower this successfully without moving the return address
3376 // around.
3377 isTailCall = true;
3378 } else if (isTailCall) {
3379 // Check if it's really possible to do a tail call.
3380 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3381 isVarArg, SR != NotStructReturn,
3382 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
3383 Outs, OutVals, Ins, DAG);
3384
3385 // Sibcalls are automatically detected tailcalls which do not require
3386 // ABI changes.
3387 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3388 IsSibcall = true;
3389
3390 if (isTailCall)
3391 ++NumTailCalls;
3392 }
3393
3394 assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&(static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling convention fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling convention fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3395, __extension__ __PRETTY_FUNCTION__))
3395 "Var args not supported with calling convention fastcc, ghc or hipe")(static_cast <bool> (!(isVarArg && canGuaranteeTCO
(CallConv)) && "Var args not supported with calling convention fastcc, ghc or hipe"
) ? void (0) : __assert_fail ("!(isVarArg && canGuaranteeTCO(CallConv)) && \"Var args not supported with calling convention fastcc, ghc or hipe\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3395, __extension__ __PRETTY_FUNCTION__))
;
3396
3397 // Analyze operands of the call, assigning locations to each operand.
3398 SmallVector<CCValAssign, 16> ArgLocs;
3399 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3400
3401 // Allocate shadow area for Win64.
3402 if (IsWin64)
3403 CCInfo.AllocateStack(32, 8);
3404
3405 CCInfo.AnalyzeArguments(Outs, CC_X86);
3406
3407 // In vectorcall calling convention a second pass is required for the HVA
3408 // types.
3409 if (CallingConv::X86_VectorCall == CallConv) {
3410 CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3411 }
3412
3413 // Get a count of how many bytes are to be pushed on the stack.
3414 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3415 if (IsSibcall)
3416 // This is a sibcall. The memory operands are available in caller's
3417 // own caller's stack.
3418 NumBytes = 0;
3419 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3420 canGuaranteeTCO(CallConv))
3421 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3422
3423 int FPDiff = 0;
3424 if (isTailCall && !IsSibcall && !IsMustTail) {
3425 // Lower arguments at fp - stackoffset + fpdiff.
3426 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3427
3428 FPDiff = NumBytesCallerPushed - NumBytes;
3429
3430 // Set the delta of movement of the returnaddr stackslot.
3431 // But only set if delta is greater than previous delta.
3432 if (FPDiff < X86Info->getTCReturnAddrDelta())
3433 X86Info->setTCReturnAddrDelta(FPDiff);
3434 }
3435
3436 unsigned NumBytesToPush = NumBytes;
3437 unsigned NumBytesToPop = NumBytes;
3438
3439 // If we have an inalloca argument, all stack space has already been allocated
3440 // for us and be right at the top of the stack. We don't support multiple
3441 // arguments passed in memory when using inalloca.
3442 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3443 NumBytesToPush = 0;
3444 if (!ArgLocs.back().isMemLoc())
3445 report_fatal_error("cannot use inalloca attribute on a register "
3446 "parameter");
3447 if (ArgLocs.back().getLocMemOffset() != 0)
3448 report_fatal_error("any parameter with the inalloca attribute must be "
3449 "the only memory argument");
3450 }
3451
3452 if (!IsSibcall)
3453 Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3454 NumBytes - NumBytesToPush, dl);
3455
3456 SDValue RetAddrFrIdx;
3457 // Load return address for tail calls.
3458 if (isTailCall && FPDiff)
3459 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3460 Is64Bit, FPDiff, dl);
3461
3462 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3463 SmallVector<SDValue, 8> MemOpChains;
3464 SDValue StackPtr;
3465
3466 // The next loop assumes that the locations are in the same order of the
3467 // input arguments.
3468 assert(isSortedByValueNo(ArgLocs) &&(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3469, __extension__ __PRETTY_FUNCTION__))
3469 "Argument Location list must be sorted before lowering")(static_cast <bool> (isSortedByValueNo(ArgLocs) &&
"Argument Location list must be sorted before lowering") ? void
(0) : __assert_fail ("isSortedByValueNo(ArgLocs) && \"Argument Location list must be sorted before lowering\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3469, __extension__ __PRETTY_FUNCTION__))
;
3470
3471 // Walk the register/memloc assignments, inserting copies/loads. In the case
3472 // of tail call optimization arguments are handle later.
3473 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3474 for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3475 ++I, ++OutIndex) {
3476 assert(OutIndex < Outs.size() && "Invalid Out index")(static_cast <bool> (OutIndex < Outs.size() &&
"Invalid Out index") ? void (0) : __assert_fail ("OutIndex < Outs.size() && \"Invalid Out index\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3476, __extension__ __PRETTY_FUNCTION__))
;
3477 // Skip inalloca arguments, they have already been written.
3478 ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3479 if (Flags.isInAlloca())
3480 continue;
3481
3482 CCValAssign &VA = ArgLocs[I];
3483 EVT RegVT = VA.getLocVT();
3484 SDValue Arg = OutVals[OutIndex];
3485 bool isByVal = Flags.isByVal();
3486
3487 // Promote the value if needed.
3488 switch (VA.getLocInfo()) {
3489 default: llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3489)
;
3490 case CCValAssign::Full: break;
3491 case CCValAssign::SExt:
3492 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3493 break;
3494 case CCValAssign::ZExt:
3495 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3496 break;
3497 case CCValAssign::AExt:
3498 if (Arg.getValueType().isVector() &&
3499 Arg.getValueType().getVectorElementType() == MVT::i1)
3500 Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
3501 else if (RegVT.is128BitVector()) {
3502 // Special case: passing MMX values in XMM registers.
3503 Arg = DAG.getBitcast(MVT::i64, Arg);
3504 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3505 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3506 } else
3507 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3508 break;
3509 case CCValAssign::BCvt:
3510 Arg = DAG.getBitcast(RegVT, Arg);
3511 break;
3512 case CCValAssign::Indirect: {
3513 // Store the argument.
3514 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3515 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3516 Chain = DAG.getStore(
3517 Chain, dl, Arg, SpillSlot,
3518 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3519 Arg = SpillSlot;
3520 break;
3521 }
3522 }
3523
3524 if (VA.needsCustom()) {
3525 assert(VA.getValVT() == MVT::v64i1 &&(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? 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-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3526, __extension__ __PRETTY_FUNCTION__))
3526 "Currently the only custom case is when we split v64i1 to 2 regs")(static_cast <bool> (VA.getValVT() == MVT::v64i1 &&
"Currently the only custom case is when we split v64i1 to 2 regs"
) ? 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-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3526, __extension__ __PRETTY_FUNCTION__))
;
3527 // Split v64i1 value into two registers
3528 Passv64i1ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++I],
3529 Subtarget);
3530 } else if (VA.isRegLoc()) {
3531 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3532 if (isVarArg && IsWin64) {
3533 // Win64 ABI requires argument XMM reg to be copied to the corresponding
3534 // shadow reg if callee is a varargs function.
3535 unsigned ShadowReg = 0;
3536 switch (VA.getLocReg()) {
3537 case X86::XMM0: ShadowReg = X86::RCX; break;
3538 case X86::XMM1: ShadowReg = X86::RDX; break;
3539 case X86::XMM2: ShadowReg = X86::R8; break;
3540 case X86::XMM3: ShadowReg = X86::R9; break;
3541 }
3542 if (ShadowReg)
3543 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3544 }
3545 } else if (!IsSibcall && (!isTailCall || isByVal)) {
3546 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3546, __extension__ __PRETTY_FUNCTION__))
;
3547 if (!StackPtr.getNode())
3548 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3549 getPointerTy(DAG.getDataLayout()));
3550 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3551 dl, DAG, VA, Flags));
3552 }
3553 }
3554
3555 if (!MemOpChains.empty())
3556 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3557
3558 if (Subtarget.isPICStyleGOT()) {
3559 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3560 // GOT pointer.
3561 if (!isTailCall) {
3562 RegsToPass.push_back(std::make_pair(
3563 unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3564 getPointerTy(DAG.getDataLayout()))));
3565 } else {
3566 // If we are tail calling and generating PIC/GOT style code load the
3567 // address of the callee into ECX. The value in ecx is used as target of
3568 // the tail jump. This is done to circumvent the ebx/callee-saved problem
3569 // for tail calls on PIC/GOT architectures. Normally we would just put the
3570 // address of GOT into ebx and then call target@PLT. But for tail calls
3571 // ebx would be restored (since ebx is callee saved) before jumping to the
3572 // target@PLT.
3573
3574 // Note: The actual moving to ECX is done further down.
3575 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3576 if (G && !G->getGlobal()->hasLocalLinkage() &&
3577 G->getGlobal()->hasDefaultVisibility())
3578 Callee = LowerGlobalAddress(Callee, DAG);
3579 else if (isa<ExternalSymbolSDNode>(Callee))
3580 Callee = LowerExternalSymbol(Callee, DAG);
3581 }
3582 }
3583
3584 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3585 // From AMD64 ABI document:
3586 // For calls that may call functions that use varargs or stdargs
3587 // (prototype-less calls or calls to functions containing ellipsis (...) in
3588 // the declaration) %al is used as hidden argument to specify the number
3589 // of SSE registers used. The contents of %al do not need to match exactly
3590 // the number of registers, but must be an ubound on the number of SSE
3591 // registers used and is in the range 0 - 8 inclusive.
3592
3593 // Count the number of XMM registers allocated.
3594 static const MCPhysReg XMMArgRegs[] = {
3595 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3596 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3597 };
3598 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3599 assert((Subtarget.hasSSE1() || !NumXMMRegs)(static_cast <bool> ((Subtarget.hasSSE1() || !NumXMMRegs
) && "SSE registers cannot be used when SSE is disabled"
) ? void (0) : __assert_fail ("(Subtarget.hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3600, __extension__ __PRETTY_FUNCTION__))
3600 && "SSE registers cannot be used when SSE is disabled")(static_cast <bool> ((Subtarget.hasSSE1() || !NumXMMRegs
) && "SSE registers cannot be used when SSE is disabled"
) ? void (0) : __assert_fail ("(Subtarget.hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3600, __extension__ __PRETTY_FUNCTION__))
;
3601
3602 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3603 DAG.getConstant(NumXMMRegs, dl,
3604 MVT::i8)));
3605 }
3606
3607 if (isVarArg && IsMustTail) {
3608 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3609 for (const auto &F : Forwards) {
3610 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3611 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3612 }
3613 }
3614
3615 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
3616 // don't need this because the eligibility check rejects calls that require
3617 // shuffling arguments passed in memory.
3618 if (!IsSibcall && isTailCall) {
3619 // Force all the incoming stack arguments to be loaded from the stack
3620 // before any new outgoing arguments are stored to the stack, because the
3621 // outgoing stack slots may alias the incoming argument stack slots, and
3622 // the alias isn't otherwise explicit. This is slightly more conservative
3623 // than necessary, because it means that each store effectively depends
3624 // on every argument instead of just those arguments it would clobber.
3625 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3626
3627 SmallVector<SDValue, 8> MemOpChains2;
3628 SDValue FIN;
3629 int FI = 0;
3630 for (unsigned I = 0, OutsIndex = 0, E = ArgLocs.size(); I != E;
3631 ++I, ++OutsIndex) {
3632 CCValAssign &VA = ArgLocs[I];
3633
3634 if (VA.isRegLoc()) {
3635 if (VA.needsCustom()) {
3636 assert((CallConv == CallingConv::X86_RegCall) &&(static_cast <bool> ((CallConv == CallingConv::X86_RegCall
) && "Expecting custom case only in regcall calling convention"
) ? void (0) : __assert_fail ("(CallConv == CallingConv::X86_RegCall) && \"Expecting custom case only in regcall calling convention\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3637, __extension__ __PRETTY_FUNCTION__))
3637 "Expecting custom case only in regcall calling convention")(static_cast <bool> ((CallConv == CallingConv::X86_RegCall
) && "Expecting custom case only in regcall calling convention"
) ? void (0) : __assert_fail ("(CallConv == CallingConv::X86_RegCall) && \"Expecting custom case only in regcall calling convention\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3637, __extension__ __PRETTY_FUNCTION__))
;
3638 // This means that we are in special case where one argument was
3639 // passed through two register locations - Skip the next location
3640 ++I;
3641 }
3642
3643 continue;
3644 }
3645
3646 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3646, __extension__ __PRETTY_FUNCTION__))
;
3647 SDValue Arg = OutVals[OutsIndex];
3648 ISD::ArgFlagsTy Flags = Outs[OutsIndex].Flags;
3649 // Skip inalloca arguments. They don't require any work.
3650 if (Flags.isInAlloca())
3651 continue;
3652 // Create frame index.
3653 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3654 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3655 FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3656 FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3657
3658 if (Flags.isByVal()) {
3659 // Copy relative to framepointer.
3660 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3661 if (!StackPtr.getNode())
3662 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3663 getPointerTy(DAG.getDataLayout()));
3664 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3665 StackPtr, Source);
3666
3667 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3668 ArgChain,
3669 Flags, DAG, dl));
3670 } else {
3671 // Store relative to framepointer.
3672 MemOpChains2.push_back(DAG.getStore(
3673 ArgChain, dl, Arg, FIN,
3674 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
3675 }
3676 }
3677
3678 if (!MemOpChains2.empty())
3679 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3680
3681 // Store the return address to the appropriate stack slot.
3682 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3683 getPointerTy(DAG.getDataLayout()),
3684 RegInfo->getSlotSize(), FPDiff, dl);
3685 }
3686
3687 // Build a sequence of copy-to-reg nodes chained together with token chain
3688 // and flag operands which copy the outgoing args into registers.
3689 SDValue InFlag;
3690 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3691 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3692 RegsToPass[i].second, InFlag);
3693 InFlag = Chain.getValue(1);
3694 }
3695
3696 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3697 assert(Is64Bit && "Large code model is only legal in 64-bit mode.")(static_cast <bool> (Is64Bit && "Large code model is only legal in 64-bit mode."
) ? void (0) : __assert_fail ("Is64Bit && \"Large code model is only legal in 64-bit mode.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3697, __extension__ __PRETTY_FUNCTION__))
;
3698 // In the 64-bit large code model, we have to make all calls
3699 // through a register, since the call instruction's 32-bit
3700 // pc-relative offset may not be large enough to hold the whole
3701 // address.
3702 } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3703 // If the callee is a GlobalAddress node (quite common, every direct call
3704 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3705 // it.
3706 GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3707
3708 // We should use extra load for direct calls to dllimported functions in
3709 // non-JIT mode.
3710 const GlobalValue *GV = G->getGlobal();
3711 if (!GV->hasDLLImportStorageClass()) {
3712 unsigned char OpFlags = Subtarget.classifyGlobalFunctionReference(GV);
3713
3714 Callee = DAG.getTargetGlobalAddress(
3715 GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3716
3717 if (OpFlags == X86II::MO_GOTPCREL) {
3718 // Add a wrapper.
3719 Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3720 getPointerTy(DAG.getDataLayout()), Callee);
3721 // Add extra indirection
3722 Callee = DAG.getLoad(
3723 getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3724 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3725 }
3726 }
3727 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3728 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
3729 unsigned char OpFlags =
3730 Subtarget.classifyGlobalFunctionReference(nullptr, *Mod);
3731
3732 Callee = DAG.getTargetExternalSymbol(
3733 S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3734 } else if (Subtarget.isTarget64BitILP32() &&
3735 Callee->getValueType(0) == MVT::i32) {
3736 // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3737 Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3738 }
3739
3740 // Returns a chain & a flag for retval copy to use.
3741 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3742 SmallVector<SDValue, 8> Ops;
3743
3744 if (!IsSibcall && isTailCall) {
3745 Chain = DAG.getCALLSEQ_END(Chain,
3746 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3747 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3748 InFlag = Chain.getValue(1);
3749 }
3750
3751 Ops.push_back(Chain);
3752 Ops.push_back(Callee);
3753
3754 if (isTailCall)
3755 Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3756
3757 // Add argument registers to the end of the list so that they are known live
3758 // into the call.
3759 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3760 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3761 RegsToPass[i].second.getValueType()));
3762
3763 // Add a register mask operand representing the call-preserved registers.
3764 // If HasNCSR is asserted (attribute NoCallerSavedRegisters exists) then we
3765 // set X86_INTR calling convention because it has the same CSR mask
3766 // (same preserved registers).
3767 const uint32_t *Mask = RegInfo->getCallPreservedMask(
3768 MF, HasNCSR ? (CallingConv::ID)CallingConv::X86_INTR : CallConv);
3769 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3769, __extension__ __PRETTY_FUNCTION__))
;
3770
3771 // If this is an invoke in a 32-bit function using a funclet-based
3772 // personality, assume the function clobbers all registers. If an exception
3773 // is thrown, the runtime will not restore CSRs.
3774 // FIXME: Model this more precisely so that we can register allocate across
3775 // the normal edge and spill and fill across the exceptional edge.
3776 if (!Is64Bit && CLI.CS && CLI.CS.isInvoke()) {
3777 const Function *CallerFn = MF.getFunction();
3778 EHPersonality Pers =
3779 CallerFn->hasPersonalityFn()
3780 ? classifyEHPersonality(CallerFn->getPersonalityFn())
3781 : EHPersonality::Unknown;
3782 if (isFuncletEHPersonality(Pers))
3783 Mask = RegInfo->getNoPreservedMask();
3784 }
3785
3786 // Define a new register mask from the existing mask.
3787 uint32_t *RegMask = nullptr;
3788
3789 // In some calling conventions we need to remove the used physical registers
3790 // from the reg mask.
3791 if (CallConv == CallingConv::X86_RegCall || HasNCSR) {
3792 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3793
3794 // Allocate a new Reg Mask and copy Mask.
3795 RegMask = MF.allocateRegisterMask(TRI->getNumRegs());
3796 unsigned RegMaskSize = (TRI->getNumRegs() + 31) / 32;
3797 memcpy(RegMask, Mask, sizeof(uint32_t) * RegMaskSize);
3798
3799 // Make sure all sub registers of the argument registers are reset
3800 // in the RegMask.
3801 for (auto const &RegPair : RegsToPass)
3802 for (MCSubRegIterator SubRegs(RegPair.first, TRI, /*IncludeSelf=*/true);
3803 SubRegs.isValid(); ++SubRegs)
3804 RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
3805
3806 // Create the RegMask Operand according to our updated mask.
3807 Ops.push_back(DAG.getRegisterMask(RegMask));
3808 } else {
3809 // Create the RegMask Operand according to the static mask.
3810 Ops.push_back(DAG.getRegisterMask(Mask));
3811 }
3812
3813 if (InFlag.getNode())
3814 Ops.push_back(InFlag);
3815
3816 if (isTailCall) {
3817 // We used to do:
3818 //// If this is the first return lowered for this function, add the regs
3819 //// to the liveout set for the function.
3820 // This isn't right, although it's probably harmless on x86; liveouts
3821 // should be computed from returns not tail calls. Consider a void
3822 // function making a tail call to a function returning int.
3823 MF.getFrameInfo().setHasTailCall();
3824 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3825 }
3826
3827 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3828 InFlag = Chain.getValue(1);
3829
3830 // Create the CALLSEQ_END node.
3831 unsigned NumBytesForCalleeToPop;
3832 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3833 DAG.getTarget().Options.GuaranteedTailCallOpt))
3834 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3835 else if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3836 !Subtarget.getTargetTriple().isOSMSVCRT() &&
3837 SR == StackStructReturn)
3838 // If this is a call to a struct-return function, the callee
3839 // pops the hidden struct pointer, so we have to push it back.
3840 // This is common for Darwin/X86, Linux & Mingw32 targets.
3841 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3842 NumBytesForCalleeToPop = 4;
3843 else
3844 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3845
3846 if (CLI.DoesNotReturn && !getTargetMachine().Options.TrapUnreachable) {
3847 // No need to reset the stack after the call if the call doesn't return. To
3848 // make the MI verify, we'll pretend the callee does it for us.
3849 NumBytesForCalleeToPop = NumBytes;
3850 }
3851
3852 // Returns a flag for retval copy to use.
3853 if (!IsSibcall) {
3854 Chain = DAG.getCALLSEQ_END(Chain,
3855 DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3856 DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3857 true),
3858 InFlag, dl);
3859 InFlag = Chain.getValue(1);
3860 }
3861
3862 // Handle result values, copying them out of physregs into vregs that we
3863 // return.
3864 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
3865 InVals, RegMask);
3866}
3867
3868//===----------------------------------------------------------------------===//
3869// Fast Calling Convention (tail call) implementation
3870//===----------------------------------------------------------------------===//
3871
3872// Like std call, callee cleans arguments, convention except that ECX is
3873// reserved for storing the tail called function address. Only 2 registers are
3874// free for argument passing (inreg). Tail call optimization is performed
3875// provided:
3876// * tailcallopt is enabled
3877// * caller/callee are fastcc
3878// On X86_64 architecture with GOT-style position independent code only local
3879// (within module) calls are supported at the moment.
3880// To keep the stack aligned according to platform abi the function
3881// GetAlignedArgumentStackSize ensures that argument delta is always multiples
3882// of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3883// If a tail called function callee has more arguments than the caller the
3884// caller needs to make sure that there is room to move the RETADDR to. This is
3885// achieved by reserving an area the size of the argument delta right after the
3886// original RETADDR, but before the saved framepointer or the spilled registers
3887// e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3888// stack layout:
3889// arg1
3890// arg2
3891// RETADDR
3892// [ new RETADDR
3893// move area ]
3894// (possible EBP)
3895// ESI
3896// EDI
3897// local1 ..
3898
3899/// Make the stack size align e.g 16n + 12 aligned for a 16-byte align
3900/// requirement.
3901unsigned
3902X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3903 SelectionDAG& DAG) const {
3904 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3905 const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3906 unsigned StackAlignment = TFI.getStackAlignment();
3907 uint64_t AlignMask = StackAlignment - 1;
3908 int64_t Offset = StackSize;
3909 unsigned SlotSize = RegInfo->getSlotSize();
3910 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3911 // Number smaller than 12 so just add the difference.
3912 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3913 } else {
3914 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3915 Offset = ((~AlignMask) & Offset) + StackAlignment +
3916 (StackAlignment-SlotSize);
3917 }
3918 return Offset;
3919}
3920
3921/// Return true if the given stack call argument is already available in the
3922/// same position (relatively) of the caller's incoming argument stack.
3923static
3924bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3925 MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
3926 const X86InstrInfo *TII, const CCValAssign &VA) {
3927 unsigned Bytes = Arg.getValueSizeInBits() / 8;
3928
3929 for (;;) {
3930 // Look through nodes that don't alter the bits of the incoming value.
3931 unsigned Op = Arg.getOpcode();
3932 if (Op == ISD::ZERO_EXTEND || Op == ISD::ANY_EXTEND || Op == ISD::BITCAST) {
3933 Arg = Arg.getOperand(0);
3934 continue;
3935 }
3936 if (Op == ISD::TRUNCATE) {
3937 const SDValue &TruncInput = Arg.getOperand(0);
3938 if (TruncInput.getOpcode() == ISD::AssertZext &&
3939 cast<VTSDNode>(TruncInput.getOperand(1))->getVT() ==
3940 Arg.getValueType()) {
3941 Arg = TruncInput.getOperand(0);
3942 continue;
3943 }
3944 }
3945 break;
3946 }
3947
3948 int FI = INT_MAX2147483647;
3949 if (Arg.getOpcode() == ISD::CopyFromReg) {
3950 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3951 if (!TargetRegisterInfo::isVirtualRegister(VR))
3952 return false;
3953 MachineInstr *Def = MRI->getVRegDef(VR);
3954 if (!Def)
3955 return false;
3956 if (!Flags.isByVal()) {
3957 if (!TII->isLoadFromStackSlot(*Def, FI))
3958 return false;
3959 } else {
3960 unsigned Opcode = Def->getOpcode();
3961 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3962 Opcode == X86::LEA64_32r) &&
3963 Def->getOperand(1).isFI()) {
3964 FI = Def->getOperand(1).getIndex();
3965 Bytes = Flags.getByValSize();
3966 } else
3967 return false;
3968 }
3969 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3970 if (Flags.isByVal())
3971 // ByVal argument is passed in as a pointer but it's now being
3972 // dereferenced. e.g.
3973 // define @foo(%struct.X* %A) {
3974 // tail call @bar(%struct.X* byval %A)
3975 // }
3976 return false;
3977 SDValue Ptr = Ld->getBasePtr();
3978 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3979 if (!FINode)
3980 return false;
3981 FI = FINode->getIndex();
3982 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3983 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3984 FI = FINode->getIndex();
3985 Bytes = Flags.getByValSize();
3986 } else
3987 return false;
3988
3989 assert(FI != INT_MAX)(static_cast <bool> (FI != 2147483647) ? void (0) : __assert_fail
("FI != INT_MAX", "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 3989, __extension__ __PRETTY_FUNCTION__))
;
3990 if (!MFI.isFixedObjectIndex(FI))
3991 return false;
3992
3993 if (Offset != MFI.getObjectOffset(FI))
3994 return false;
3995
3996 // If this is not byval, check that the argument stack object is immutable.
3997 // inalloca and argument copy elision can create mutable argument stack
3998 // objects. Byval objects can be mutated, but a byval call intends to pass the
3999 // mutated memory.
4000 if (!Flags.isByVal() && !MFI.isImmutableObjectIndex(FI))
4001 return false;
4002
4003 if (VA.getLocVT().getSizeInBits() > Arg.getValueSizeInBits()) {
4004 // If the argument location is wider than the argument type, check that any
4005 // extension flags match.
4006 if (Flags.isZExt() != MFI.isObjectZExt(FI) ||
4007 Flags.isSExt() != MFI.isObjectSExt(FI)) {
4008 return false;
4009 }
4010 }
4011
4012 return Bytes == MFI.getObjectSize(FI);
4013}
4014
4015/// Check whether the call is eligible for tail call optimization. Targets
4016/// that want to do tail call optimization should implement this function.
4017bool X86TargetLowering::IsEligibleForTailCallOptimization(
4018 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
4019 bool isCalleeStructRet, bool isCallerStructRet, Type *RetTy,
4020 const SmallVectorImpl<ISD::OutputArg> &Outs,
4021 const SmallVectorImpl<SDValue> &OutVals,
4022 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4023 if (!mayTailCallThisCC(CalleeCC))
4024 return false;
4025
4026 // If -tailcallopt is specified, make fastcc functions tail-callable.
4027 MachineFunction &MF = DAG.getMachineFunction();
4028 const Function *CallerF = MF.getFunction();
4029
4030 // If the function return type is x86_fp80 and the callee return type is not,
4031 // then the FP_EXTEND of the call result is not a nop. It's not safe to
4032 // perform a tailcall optimization here.
4033 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
4034 return false;
4035
4036 CallingConv::ID CallerCC = CallerF->getCallingConv();
4037 bool CCMatch = CallerCC == CalleeCC;
4038 bool IsCalleeWin64 = Subtarget.isCallingConvWin64(CalleeCC);
4039 bool IsCallerWin64 = Subtarget.isCallingConvWin64(CallerCC);
4040
4041 // Win64 functions have extra shadow space for argument homing. Don't do the
4042 // sibcall if the caller and callee have mismatched expectations for this
4043 // space.
4044 if (IsCalleeWin64 != IsCallerWin64)
4045 return false;
4046
4047 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
4048 if (canGuaranteeTCO(CalleeCC) && CCMatch)
4049 return true;
4050 return false;
4051 }
4052
4053 // Look for obvious safe cases to perform tail call optimization that do not
4054 // require ABI changes. This is what gcc calls sibcall.
4055
4056 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
4057 // emit a special epilogue.
4058 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4059 if (RegInfo->needsStackRealignment(MF))
4060 return false;
4061
4062 // Also avoid sibcall optimization if either caller or callee uses struct
4063 // return semantics.
4064 if (isCalleeStructRet || isCallerStructRet)
4065 return false;
4066
4067 // Do not sibcall optimize vararg calls unless all arguments are passed via
4068 // registers.
4069 LLVMContext &C = *DAG.getContext();
4070 if (isVarArg && !Outs.empty()) {
4071 // Optimizing for varargs on Win64 is unlikely to be safe without
4072 // additional testing.
4073 if (IsCalleeWin64 || IsCallerWin64)
4074 return false;
4075
4076 SmallVector<CCValAssign, 16> ArgLocs;
4077 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4078
4079 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4080 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
4081 if (!ArgLocs[i].isRegLoc())
4082 return false;
4083 }
4084
4085 // If the call result is in ST0 / ST1, it needs to be popped off the x87
4086 // stack. Therefore, if it's not used by the call it is not safe to optimize
4087 // this into a sibcall.
4088 bool Unused = false;
4089 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4090 if (!Ins[i].Used) {
4091 Unused = true;
4092 break;
4093 }
4094 }
4095 if (Unused) {
4096 SmallVector<CCValAssign, 16> RVLocs;
4097 CCState CCInfo(CalleeCC, false, MF, RVLocs, C);
4098 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
4099 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4100 CCValAssign &VA = RVLocs[i];
4101 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
4102 return false;
4103 }
4104 }
4105
4106 // Check that the call results are passed in the same way.
4107 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
4108 RetCC_X86, RetCC_X86))
4109 return false;
4110 // The callee has to preserve all registers the caller needs to preserve.
4111 const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
4112 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
4113 if (!CCMatch) {
4114 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
4115 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
4116 return false;
4117 }
4118
4119 unsigned StackArgsSize = 0;
4120
4121 // If the callee takes no arguments then go on to check the results of the
4122 // call.
4123 if (!Outs.empty()) {
4124 // Check if stack adjustment is needed. For now, do not do this if any
4125 // argument is passed on the stack.
4126 SmallVector<CCValAssign, 16> ArgLocs;
4127 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
4128
4129 // Allocate shadow area for Win64
4130 if (IsCalleeWin64)
4131 CCInfo.AllocateStack(32, 8);
4132
4133 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
4134 StackArgsSize = CCInfo.getNextStackOffset();
4135
4136 if (CCInfo.getNextStackOffset()) {
4137 // Check if the arguments are already laid out in the right way as
4138 // the caller's fixed stack objects.
4139 MachineFrameInfo &MFI = MF.getFrameInfo();
4140 const MachineRegisterInfo *MRI = &MF.getRegInfo();
4141 const X86InstrInfo *TII = Subtarget.getInstrInfo();
4142 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4143 CCValAssign &VA = ArgLocs[i];
4144 SDValue Arg = OutVals[i];
4145 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4146 if (VA.getLocInfo() == CCValAssign::Indirect)
4147 return false;
4148 if (!VA.isRegLoc()) {
4149 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
4150 MFI, MRI, TII, VA))
4151 return false;
4152 }
4153 }
4154 }
4155
4156 bool PositionIndependent = isPositionIndependent();
4157 // If the tailcall address may be in a register, then make sure it's
4158 // possible to register allocate for it. In 32-bit, the call address can
4159 // only target EAX, EDX, or ECX since the tail call must be scheduled after
4160 // callee-saved registers are restored. These happen to be the same
4161 // registers used to pass 'inreg' arguments so watch out for those.
4162 if (!Subtarget.is64Bit() && ((!isa<GlobalAddressSDNode>(Callee) &&
4163 !isa<ExternalSymbolSDNode>(Callee)) ||
4164 PositionIndependent)) {
4165 unsigned NumInRegs = 0;
4166 // In PIC we need an extra register to formulate the address computation
4167 // for the callee.
4168 unsigned MaxInRegs = PositionIndependent ? 2 : 3;
4169
4170 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4171 CCValAssign &VA = ArgLocs[i];
4172 if (!VA.isRegLoc())
4173 continue;
4174 unsigned Reg = VA.getLocReg();
4175 switch (Reg) {
4176 default: break;
4177 case X86::EAX: case X86::EDX: case X86::ECX:
4178 if (++NumInRegs == MaxInRegs)
4179 return false;
4180 break;
4181 }
4182 }
4183 }
4184
4185 const MachineRegisterInfo &MRI = MF.getRegInfo();
4186 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
4187 return false;
4188 }
4189
4190 bool CalleeWillPop =
4191 X86::isCalleePop(CalleeCC, Subtarget.is64Bit(), isVarArg,
4192 MF.getTarget().Options.GuaranteedTailCallOpt);
4193
4194 if (unsigned BytesToPop =
4195 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn()) {
4196 // If we have bytes to pop, the callee must pop them.
4197 bool CalleePopMatches = CalleeWillPop && BytesToPop == StackArgsSize;
4198 if (!CalleePopMatches)
4199 return false;
4200 } else if (CalleeWillPop && StackArgsSize > 0) {
4201 // If we don't have bytes to pop, make sure the callee doesn't pop any.
4202 return false;
4203 }
4204
4205 return true;
4206}
4207
4208FastISel *
4209X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
4210 const TargetLibraryInfo *libInfo) const {
4211 return X86::createFastISel(funcInfo, libInfo);
4212}
4213
4214//===----------------------------------------------------------------------===//
4215// Other Lowering Hooks
4216//===----------------------------------------------------------------------===//
4217
4218static bool MayFoldLoad(SDValue Op) {
4219 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
4220}
4221
4222static bool MayFoldIntoStore(SDValue Op) {
4223 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
4224}
4225
4226static bool MayFoldIntoZeroExtend(SDValue Op) {
4227 if (Op.hasOneUse()) {
4228 unsigned Opcode = Op.getNode()->use_begin()->getOpcode();
4229 return (ISD::ZERO_EXTEND == Opcode);
4230 }
4231 return false;
4232}
4233
4234static bool isTargetShuffle(unsigned Opcode) {
4235 switch(Opcode) {
4236 default: return false;
4237 case X86ISD::BLENDI:
4238 case X86ISD::PSHUFB:
4239 case X86ISD::PSHUFD:
4240 case X86ISD::PSHUFHW:
4241 case X86ISD::PSHUFLW:
4242 case X86ISD::SHUFP:
4243 case X86ISD::INSERTPS:
4244 case X86ISD::EXTRQI:
4245 case X86ISD::INSERTQI:
4246 case X86ISD::PALIGNR:
4247 case X86ISD::VSHLDQ:
4248 case X86ISD::VSRLDQ:
4249 case X86ISD::MOVLHPS:
4250 case X86ISD::MOVHLPS:
4251 case X86ISD::MOVLPS:
4252 case X86ISD::MOVLPD:
4253 case X86ISD::MOVSHDUP:
4254 case X86ISD::MOVSLDUP:
4255 case X86ISD::MOVDDUP:
4256 case X86ISD::MOVSS:
4257 case X86ISD::MOVSD:
4258 case X86ISD::UNPCKL:
4259 case X86ISD::UNPCKH:
4260 case X86ISD::VBROADCAST:
4261 case X86ISD::VPERMILPI:
4262 case X86ISD::VPERMILPV:
4263 case X86ISD::VPERM2X128:
4264 case X86ISD::VPERMIL2:
4265 case X86ISD::VPERMI:
4266 case X86ISD::VPPERM:
4267 case X86ISD::VPERMV:
4268 case X86ISD::VPERMV3:
4269 case X86ISD::VPERMIV3:
4270 case X86ISD::VZEXT_MOVL:
4271 return true;
4272 }
4273}
4274
4275static bool isTargetShuffleVariableMask(unsigned Opcode) {
4276 switch (Opcode) {
4277 default: return false;
4278 // Target Shuffles.
4279 case X86ISD::PSHUFB:
4280 case X86ISD::VPERMILPV:
4281 case X86ISD::VPERMIL2:
4282 case X86ISD::VPPERM:
4283 case X86ISD::VPERMV:
4284 case X86ISD::VPERMV3:
4285 case X86ISD::VPERMIV3:
4286 return true;
4287 // 'Faux' Target Shuffles.
4288 case ISD::AND:
4289 case X86ISD::ANDNP:
4290 return true;
4291 }
4292}
4293
4294SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
4295 MachineFunction &MF = DAG.getMachineFunction();
4296 const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
4297 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
4298 int ReturnAddrIndex = FuncInfo->getRAIndex();
4299
4300 if (ReturnAddrIndex == 0) {
4301 // Set up a frame object for the return address.
4302 unsigned SlotSize = RegInfo->getSlotSize();
4303 ReturnAddrIndex = MF.getFrameInfo().CreateFixedObject(SlotSize,
4304 -(int64_t)SlotSize,
4305 false);
4306 FuncInfo->setRAIndex(ReturnAddrIndex);
4307 }
4308
4309 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
4310}
4311
4312bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
4313 bool hasSymbolicDisplacement) {
4314 // Offset should fit into 32 bit immediate field.
4315 if (!isInt<32>(Offset))
4316 return false;
4317
4318 // If we don't have a symbolic displacement - we don't have any extra
4319 // restrictions.
4320 if (!hasSymbolicDisplacement)
4321 return true;
4322
4323 // FIXME: Some tweaks might be needed for medium code model.
4324 if (M != CodeModel::Small && M != CodeModel::Kernel)
4325 return false;
4326
4327 // For small code model we assume that latest object is 16MB before end of 31
4328 // bits boundary. We may also accept pretty large negative constants knowing
4329 // that all objects are in the positive half of address space.
4330 if (M == CodeModel::Small && Offset < 16*1024*1024)
4331 return true;
4332
4333 // For kernel code model we know that all object resist in the negative half
4334 // of 32bits address space. We may not accept negative offsets, since they may
4335 // be just off and we may accept pretty large positive ones.
4336 if (M == CodeModel::Kernel && Offset >= 0)
4337 return true;
4338
4339 return false;
4340}
4341
4342/// Determines whether the callee is required to pop its own arguments.
4343/// Callee pop is necessary to support tail calls.
4344bool X86::isCalleePop(CallingConv::ID CallingConv,
4345 bool is64Bit, bool IsVarArg, bool GuaranteeTCO) {
4346 // If GuaranteeTCO is true, we force some calls to be callee pop so that we
4347 // can guarantee TCO.
4348 if (!IsVarArg && shouldGuaranteeTCO(CallingConv, GuaranteeTCO))
4349 return true;
4350
4351 switch (CallingConv) {
4352 default:
4353 return false;
4354 case CallingConv::X86_StdCall:
4355 case CallingConv::X86_FastCall:
4356 case CallingConv::X86_ThisCall:
4357 case CallingConv::X86_VectorCall:
4358 return !is64Bit;
4359 }
4360}
4361
4362/// \brief Return true if the condition is an unsigned comparison operation.
4363static bool isX86CCUnsigned(unsigned X86CC) {
4364 switch (X86CC) {
4365 default:
4366 llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4366)
;
4367 case X86::COND_E:
4368 case X86::COND_NE:
4369 case X86::COND_B:
4370 case X86::COND_A:
4371 case X86::COND_BE:
4372 case X86::COND_AE:
4373 return true;
4374 case X86::COND_G:
4375 case X86::COND_GE:
4376 case X86::COND_L:
4377 case X86::COND_LE:
4378 return false;
4379 }
4380}
4381
4382static X86::CondCode TranslateIntegerX86CC(ISD::CondCode SetCCOpcode) {
4383 switch (SetCCOpcode) {
4384 default: llvm_unreachable("Invalid integer condition!")::llvm::llvm_unreachable_internal("Invalid integer condition!"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4384)
;
4385 case ISD::SETEQ: return X86::COND_E;
4386 case ISD::SETGT: return X86::COND_G;
4387 case ISD::SETGE: return X86::COND_GE;
4388 case ISD::SETLT: return X86::COND_L;
4389 case ISD::SETLE: return X86::COND_LE;
4390 case ISD::SETNE: return X86::COND_NE;
4391 case ISD::SETULT: return X86::COND_B;
4392 case ISD::SETUGT: return X86::COND_A;
4393 case ISD::SETULE: return X86::COND_BE;
4394 case ISD::SETUGE: return X86::COND_AE;
4395 }
4396}
4397
4398/// Do a one-to-one translation of a ISD::CondCode to the X86-specific
4399/// condition code, returning the condition code and the LHS/RHS of the
4400/// comparison to make.
4401static X86::CondCode TranslateX86CC(ISD::CondCode SetCCOpcode, const SDLoc &DL,
4402 bool isFP, SDValue &LHS, SDValue &RHS,
4403 SelectionDAG &DAG) {
4404 if (!isFP) {
4405 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4406 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
4407 // X > -1 -> X == 0, jump !sign.
4408 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4409 return X86::COND_NS;
4410 }
4411 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
4412 // X < 0 -> X == 0, jump on sign.
4413 return X86::COND_S;
4414 }
4415 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
4416 // X < 1 -> X <= 0
4417 RHS = DAG.getConstant(0, DL, RHS.getValueType());
4418 return X86::COND_LE;
4419 }
4420 }
4421
4422 return TranslateIntegerX86CC(SetCCOpcode);
4423 }
4424
4425 // First determine if it is required or is profitable to flip the operands.
4426
4427 // If LHS is a foldable load, but RHS is not, flip the condition.
4428 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
4429 !ISD::isNON_EXTLoad(RHS.getNode())) {
4430 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
4431 std::swap(LHS, RHS);
4432 }
4433
4434 switch (SetCCOpcode) {
4435 default: break;
4436 case ISD::SETOLT:
4437 case ISD::SETOLE:
4438 case ISD::SETUGT:
4439 case ISD::SETUGE:
4440 std::swap(LHS, RHS);
4441 break;
4442 }
4443
4444 // On a floating point condition, the flags are set as follows:
4445 // ZF PF CF op
4446 // 0 | 0 | 0 | X > Y
4447 // 0 | 0 | 1 | X < Y
4448 // 1 | 0 | 0 | X == Y
4449 // 1 | 1 | 1 | unordered
4450 switch (SetCCOpcode) {
4451 default: llvm_unreachable("Condcode should be pre-legalized away")::llvm::llvm_unreachable_internal("Condcode should be pre-legalized away"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4451)
;
4452 case ISD::SETUEQ:
4453 case ISD::SETEQ: return X86::COND_E;
4454 case ISD::SETOLT: // flipped
4455 case ISD::SETOGT:
4456 case ISD::SETGT: return X86::COND_A;
4457 case ISD::SETOLE: // flipped
4458 case ISD::SETOGE:
4459 case ISD::SETGE: return X86::COND_AE;
4460 case ISD::SETUGT: // flipped
4461 case ISD::SETULT:
4462 case ISD::SETLT: return X86::COND_B;
4463 case ISD::SETUGE: // flipped
4464 case ISD::SETULE:
4465 case ISD::SETLE: return X86::COND_BE;
4466 case ISD::SETONE:
4467 case ISD::SETNE: return X86::COND_NE;
4468 case ISD::SETUO: return X86::COND_P;
4469 case ISD::SETO: return X86::COND_NP;
4470 case ISD::SETOEQ:
4471 case ISD::SETUNE: return X86::COND_INVALID;
4472 }
4473}
4474
4475/// Is there a floating point cmov for the specific X86 condition code?
4476/// Current x86 isa includes the following FP cmov instructions:
4477/// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
4478static bool hasFPCMov(unsigned X86CC) {
4479 switch (X86CC) {
4480 default:
4481 return false;
4482 case X86::COND_B:
4483 case X86::COND_BE:
4484 case X86::COND_E:
4485 case X86::COND_P:
4486 case X86::COND_A:
4487 case X86::COND_AE:
4488 case X86::COND_NE:
4489 case X86::COND_NP:
4490 return true;
4491 }
4492}
4493
4494
4495bool X86TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
4496 const CallInst &I,
4497 unsigned Intrinsic) const {
4498
4499 const IntrinsicData* IntrData = getIntrinsicWithChain(Intrinsic);
4500 if (!IntrData)
4501 return false;
4502
4503 Info.opc = ISD::INTRINSIC_W_CHAIN;
4504 Info.readMem = false;
4505 Info.writeMem = false;
4506 Info.vol = false;
4507 Info.offset = 0;
4508
4509 switch (IntrData->Type) {
4510 case EXPAND_FROM_MEM: {
4511 Info.ptrVal = I.getArgOperand(0);
4512 Info.memVT = MVT::getVT(I.getType());
4513 Info.align = 1;
4514 Info.readMem = true;
4515 break;
4516 }
4517 case COMPRESS_TO_MEM: {
4518 Info.ptrVal = I.getArgOperand(0);
4519 Info.memVT = MVT::getVT(I.getArgOperand(1)->getType());
4520 Info.align = 1;
4521 Info.writeMem = true;
4522 break;
4523 }
4524 case TRUNCATE_TO_MEM_VI8:
4525 case TRUNCATE_TO_MEM_VI16:
4526 case TRUNCATE_TO_MEM_VI32: {
4527 Info.ptrVal = I.getArgOperand(0);
4528 MVT VT = MVT::getVT(I.getArgOperand(1)->getType());
4529 MVT ScalarVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
4530 if (IntrData->Type == TRUNCATE_TO_MEM_VI8)
4531 ScalarVT = MVT::i8;
4532 else if (IntrData->Type == TRUNCATE_TO_MEM_VI16)
4533 ScalarVT = MVT::i16;
4534 else if (IntrData->Type == TRUNCATE_TO_MEM_VI32)
4535 ScalarVT = MVT::i32;
4536
4537 Info.memVT = MVT::getVectorVT(ScalarVT, VT.getVectorNumElements());
4538 Info.align = 1;
4539 Info.writeMem = true;
4540 break;
4541 }
4542 default:
4543 return false;
4544 }
4545
4546 return true;
4547}
4548
4549/// Returns true if the target can instruction select the
4550/// specified FP immediate natively. If false, the legalizer will
4551/// materialize the FP immediate as a load from a constant pool.
4552bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4553 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
4554 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
4555 return true;
4556 }
4557 return false;
4558}
4559
4560bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
4561 ISD::LoadExtType ExtTy,
4562 EVT NewVT) const {
4563 // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
4564 // relocation target a movq or addq instruction: don't let the load shrink.
4565 SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
4566 if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
4567 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
4568 return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
4569 return true;
4570}
4571
4572/// \brief Returns true if it is beneficial to convert a load of a constant
4573/// to just the constant itself.
4574bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
4575 Type *Ty) const {
4576 assert(Ty->isIntegerTy())(static_cast <bool> (Ty->isIntegerTy()) ? void (0) :
__assert_fail ("Ty->isIntegerTy()", "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4576, __extension__ __PRETTY_FUNCTION__))
;
4577
4578 unsigned BitSize = Ty->getPrimitiveSizeInBits();
4579 if (BitSize == 0 || BitSize > 64)
4580 return false;
4581 return true;
4582}
4583
4584bool X86TargetLowering::convertSelectOfConstantsToMath(EVT VT) const {
4585 // TODO: It might be a win to ease or lift this restriction, but the generic
4586 // folds in DAGCombiner conflict with vector folds for an AVX512 target.
4587 if (VT.isVector() && Subtarget.hasAVX512())
4588 return false;
4589
4590 return true;
4591}
4592
4593bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
4594 unsigned Index) const {
4595 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4596 return false;
4597
4598 // Mask vectors support all subregister combinations and operations that
4599 // extract half of vector.
4600 if (ResVT.getVectorElementType() == MVT::i1)
4601 return Index == 0 || ((ResVT.getSizeInBits() == SrcVT.getSizeInBits()*2) &&
4602 (Index == ResVT.getVectorNumElements()));
4603
4604 return (Index % ResVT.getVectorNumElements()) == 0;
4605}
4606
4607bool X86TargetLowering::isCheapToSpeculateCttz() const {
4608 // Speculate cttz only if we can directly use TZCNT.
4609 return Subtarget.hasBMI();
4610}
4611
4612bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4613 // Speculate ctlz only if we can directly use LZCNT.
4614 return Subtarget.hasLZCNT();
4615}
4616
4617bool X86TargetLowering::canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
4618 const SelectionDAG &DAG) const {
4619 // Do not merge to float value size (128 bytes) if no implicit
4620 // float attribute is set.
4621 bool NoFloat = DAG.getMachineFunction().getFunction()->hasFnAttribute(
4622 Attribute::NoImplicitFloat);
4623
4624 if (NoFloat) {
4625 unsigned MaxIntSize = Subtarget.is64Bit() ? 64 : 32;
4626 return (MemVT.getSizeInBits() <= MaxIntSize);
4627 }
4628 return true;
4629}
4630
4631bool X86TargetLowering::isCtlzFast() const {
4632 return Subtarget.hasFastLZCNT();
4633}
4634
4635bool X86TargetLowering::isMaskAndCmp0FoldingBeneficial(
4636 const Instruction &AndI) const {
4637 return true;
4638}
4639
4640bool X86TargetLowering::hasAndNotCompare(SDValue Y) const {
4641 if (!Subtarget.hasBMI())
4642 return false;
4643
4644 // There are only 32-bit and 64-bit forms for 'andn'.
4645 EVT VT = Y.getValueType();
4646 if (VT != MVT::i32 && VT != MVT::i64)
4647 return false;
4648
4649 return true;
4650}
4651
4652MVT X86TargetLowering::hasFastEqualityCompare(unsigned NumBits) const {
4653 MVT VT = MVT::getIntegerVT(NumBits);
4654 if (isTypeLegal(VT))
4655 return VT;
4656
4657 // PMOVMSKB can handle this.
4658 if (NumBits == 128 && isTypeLegal(MVT::v16i8))
4659 return MVT::v16i8;
4660
4661 // VPMOVMSKB can handle this.
4662 if (NumBits == 256 && isTypeLegal(MVT::v32i8))
4663 return MVT::v32i8;
4664
4665 // TODO: Allow 64-bit type for 32-bit target.
4666 // TODO: 512-bit types should be allowed, but make sure that those
4667 // cases are handled in combineVectorSizedSetCCEquality().
4668
4669 return MVT::INVALID_SIMPLE_VALUE_TYPE;
4670}
4671
4672/// Val is the undef sentinel value or equal to the specified value.
4673static bool isUndefOrEqual(int Val, int CmpVal) {
4674 return ((Val == SM_SentinelUndef) || (Val == CmpVal));
4675}
4676
4677/// Val is either the undef or zero sentinel value.
4678static bool isUndefOrZero(int Val) {
4679 return ((Val == SM_SentinelUndef) || (Val == SM_SentinelZero));
4680}
4681
4682/// Return true if every element in Mask, beginning
4683/// from position Pos and ending in Pos+Size is the undef sentinel value.
4684static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4685 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4686 if (Mask[i] != SM_SentinelUndef)
4687 return false;
4688 return true;
4689}
4690
4691/// Return true if Val is undef or if its value falls within the
4692/// specified range (L, H].
4693static bool isUndefOrInRange(int Val, int Low, int Hi) {
4694 return (Val == SM_SentinelUndef) || (Val >= Low && Val < Hi);
4695}
4696
4697/// Return true if every element in Mask is undef or if its value
4698/// falls within the specified range (L, H].
4699static bool isUndefOrInRange(ArrayRef<int> Mask,
4700 int Low, int Hi) {
4701 for (int M : Mask)
4702 if (!isUndefOrInRange(M, Low, Hi))
4703 return false;
4704 return true;
4705}
4706
4707/// Return true if Val is undef, zero or if its value falls within the
4708/// specified range (L, H].
4709static bool isUndefOrZeroOrInRange(int Val, int Low, int Hi) {
4710 return isUndefOrZero(Val) || (Val >= Low && Val < Hi);
4711}
4712
4713/// Return true if every element in Mask is undef, zero or if its value
4714/// falls within the specified range (L, H].
4715static bool isUndefOrZeroOrInRange(ArrayRef<int> Mask, int Low, int Hi) {
4716 for (int M : Mask)
4717 if (!isUndefOrZeroOrInRange(M, Low, Hi))
4718 return false;
4719 return true;
4720}
4721
4722/// Return true if every element in Mask, beginning
4723/// from position Pos and ending in Pos+Size, falls within the specified
4724/// sequential range (Low, Low+Size]. or is undef.
4725static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4726 unsigned Pos, unsigned Size, int Low) {
4727 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4728 if (!isUndefOrEqual(Mask[i], Low))
4729 return false;
4730 return true;
4731}
4732
4733/// Return true if every element in Mask, beginning
4734/// from position Pos and ending in Pos+Size, falls within the specified
4735/// sequential range (Low, Low+Size], or is undef or is zero.
4736static bool isSequentialOrUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
4737 unsigned Size, int Low) {
4738 for (unsigned i = Pos, e = Pos + Size; i != e; ++i, ++Low)
4739 if (!isUndefOrZero(Mask[i]) && Mask[i] != Low)
4740 return false;
4741 return true;
4742}
4743
4744/// Return true if every element in Mask, beginning
4745/// from position Pos and ending in Pos+Size is undef or is zero.
4746static bool isUndefOrZeroInRange(ArrayRef<int> Mask, unsigned Pos,
4747 unsigned Size) {
4748 for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4749 if (!isUndefOrZero(Mask[i]))
4750 return false;
4751 return true;
4752}
4753
4754/// \brief Helper function to test whether a shuffle mask could be
4755/// simplified by widening the elements being shuffled.
4756///
4757/// Appends the mask for wider elements in WidenedMask if valid. Otherwise
4758/// leaves it in an unspecified state.
4759///
4760/// NOTE: This must handle normal vector shuffle masks and *target* vector
4761/// shuffle masks. The latter have the special property of a '-2' representing
4762/// a zero-ed lane of a vector.
4763static bool canWidenShuffleElements(ArrayRef<int> Mask,
4764 SmallVectorImpl<int> &WidenedMask) {
4765 WidenedMask.assign(Mask.size() / 2, 0);
4766 for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
4767 int M0 = Mask[i];
4768 int M1 = Mask[i + 1];
4769
4770 // If both elements are undef, its trivial.
4771 if (M0 == SM_SentinelUndef && M1 == SM_SentinelUndef) {
4772 WidenedMask[i / 2] = SM_SentinelUndef;
4773 continue;
4774 }
4775
4776 // Check for an undef mask and a mask value properly aligned to fit with
4777 // a pair of values. If we find such a case, use the non-undef mask's value.
4778 if (M0 == SM_SentinelUndef && M1 >= 0 && (M1 % 2) == 1) {
4779 WidenedMask[i / 2] = M1 / 2;
4780 continue;
4781 }
4782 if (M1 == SM_SentinelUndef && M0 >= 0 && (M0 % 2) == 0) {
4783 WidenedMask[i / 2] = M0 / 2;
4784 continue;
4785 }
4786
4787 // When zeroing, we need to spread the zeroing across both lanes to widen.
4788 if (M0 == SM_SentinelZero || M1 == SM_SentinelZero) {
4789 if ((M0 == SM_SentinelZero || M0 == SM_SentinelUndef) &&
4790 (M1 == SM_SentinelZero || M1 == SM_SentinelUndef)) {
4791 WidenedMask[i / 2] = SM_SentinelZero;
4792 continue;
4793 }
4794 return false;
4795 }
4796
4797 // Finally check if the two mask values are adjacent and aligned with
4798 // a pair.
4799 if (M0 != SM_SentinelUndef && (M0 % 2) == 0 && (M0 + 1) == M1) {
4800 WidenedMask[i / 2] = M0 / 2;
4801 continue;
4802 }
4803
4804 // Otherwise we can't safely widen the elements used in this shuffle.
4805 return false;
4806 }
4807 assert(WidenedMask.size() == Mask.size() / 2 &&(static_cast <bool> (WidenedMask.size() == Mask.size() /
2 && "Incorrect size of mask after widening the elements!"
) ? void (0) : __assert_fail ("WidenedMask.size() == Mask.size() / 2 && \"Incorrect size of mask after widening the elements!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4808, __extension__ __PRETTY_FUNCTION__))
4808 "Incorrect size of mask after widening the elements!")(static_cast <bool> (WidenedMask.size() == Mask.size() /
2 && "Incorrect size of mask after widening the elements!"
) ? void (0) : __assert_fail ("WidenedMask.size() == Mask.size() / 2 && \"Incorrect size of mask after widening the elements!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4808, __extension__ __PRETTY_FUNCTION__))
;
4809
4810 return true;
4811}
4812
4813/// Returns true if Elt is a constant zero or a floating point constant +0.0.
4814bool X86::isZeroNode(SDValue Elt) {
4815 return isNullConstant(Elt) || isNullFPConstant(Elt);
4816}
4817
4818// Build a vector of constants.
4819// Use an UNDEF node if MaskElt == -1.
4820// Split 64-bit constants in the 32-bit mode.
4821static SDValue getConstVector(ArrayRef<int> Values, MVT VT, SelectionDAG &DAG,
4822 const SDLoc &dl, bool IsMask = false) {
4823
4824 SmallVector<SDValue, 32> Ops;
4825 bool Split = false;
4826
4827 MVT ConstVecVT = VT;
4828 unsigned NumElts = VT.getVectorNumElements();
4829 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4830 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4831 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4832 Split = true;
4833 }
4834
4835 MVT EltVT = ConstVecVT.getVectorElementType();
4836 for (unsigned i = 0; i < NumElts; ++i) {
4837 bool IsUndef = Values[i] < 0 && IsMask;
4838 SDValue OpNode = IsUndef ? DAG.getUNDEF(EltVT) :
4839 DAG.getConstant(Values[i], dl, EltVT);
4840 Ops.push_back(OpNode);
4841 if (Split)
4842 Ops.push_back(IsUndef ? DAG.getUNDEF(EltVT) :
4843 DAG.getConstant(0, dl, EltVT));
4844 }
4845 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4846 if (Split)
4847 ConstsNode = DAG.getBitcast(VT, ConstsNode);
4848 return ConstsNode;
4849}
4850
4851static SDValue getConstVector(ArrayRef<APInt> Bits, APInt &Undefs,
4852 MVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4853 assert(Bits.size() == Undefs.getBitWidth() &&(static_cast <bool> (Bits.size() == Undefs.getBitWidth(
) && "Unequal constant and undef arrays") ? void (0) :
__assert_fail ("Bits.size() == Undefs.getBitWidth() && \"Unequal constant and undef arrays\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4854, __extension__ __PRETTY_FUNCTION__))
4854 "Unequal constant and undef arrays")(static_cast <bool> (Bits.size() == Undefs.getBitWidth(
) && "Unequal constant and undef arrays") ? void (0) :
__assert_fail ("Bits.size() == Undefs.getBitWidth() && \"Unequal constant and undef arrays\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4854, __extension__ __PRETTY_FUNCTION__))
;
4855 SmallVector<SDValue, 32> Ops;
4856 bool Split = false;
4857
4858 MVT ConstVecVT = VT;
4859 unsigned NumElts = VT.getVectorNumElements();
4860 bool In64BitMode = DAG.getTargetLoweringInfo().isTypeLegal(MVT::i64);
4861 if (!In64BitMode && VT.getVectorElementType() == MVT::i64) {
4862 ConstVecVT = MVT::getVectorVT(MVT::i32, NumElts * 2);
4863 Split = true;
4864 }
4865
4866 MVT EltVT = ConstVecVT.getVectorElementType();
4867 for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
4868 if (Undefs[i]) {
4869 Ops.append(Split ? 2 : 1, DAG.getUNDEF(EltVT));
4870 continue;
4871 }
4872 const APInt &V = Bits[i];
4873 assert(V.getBitWidth() == VT.getScalarSizeInBits() && "Unexpected sizes")(static_cast <bool> (V.getBitWidth() == VT.getScalarSizeInBits
() && "Unexpected sizes") ? void (0) : __assert_fail (
"V.getBitWidth() == VT.getScalarSizeInBits() && \"Unexpected sizes\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4873, __extension__ __PRETTY_FUNCTION__))
;
4874 if (Split) {
4875 Ops.push_back(DAG.getConstant(V.trunc(32), dl, EltVT));
4876 Ops.push_back(DAG.getConstant(V.lshr(32).trunc(32), dl, EltVT));
4877 } else if (EltVT == MVT::f32) {
4878 APFloat FV(APFloat::IEEEsingle(), V);
4879 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
4880 } else if (EltVT == MVT::f64) {
4881 APFloat FV(APFloat::IEEEdouble(), V);
4882 Ops.push_back(DAG.getConstantFP(FV, dl, EltVT));
4883 } else {
4884 Ops.push_back(DAG.getConstant(V, dl, EltVT));
4885 }
4886 }
4887
4888 SDValue ConstsNode = DAG.getBuildVector(ConstVecVT, dl, Ops);
4889 return DAG.getBitcast(VT, ConstsNode);
4890}
4891
4892/// Returns a vector of specified type with all zero elements.
4893static SDValue getZeroVector(MVT VT, const X86Subtarget &Subtarget,
4894 SelectionDAG &DAG, const SDLoc &dl) {
4895 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() ||(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector() || VT.getVectorElementType() == MVT
::i1) && "Unexpected vector type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4897, __extension__ __PRETTY_FUNCTION__))
4896 VT.getVectorElementType() == MVT::i1) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector() || VT.getVectorElementType() == MVT
::i1) && "Unexpected vector type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4897, __extension__ __PRETTY_FUNCTION__))
4897 "Unexpected vector type")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector() || VT.getVectorElementType() == MVT
::i1) && "Unexpected vector type") ? void (0) : __assert_fail
("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector() || VT.getVectorElementType() == MVT::i1) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4897, __extension__ __PRETTY_FUNCTION__))
;
4898
4899 // Try to build SSE/AVX zero vectors as <N x i32> bitcasted to their dest
4900 // type. This ensures they get CSE'd. But if the integer type is not
4901 // available, use a floating-point +0.0 instead.
4902 SDValue Vec;
4903 if (!Subtarget.hasSSE2() && VT.is128BitVector()) {
4904 Vec = DAG.getConstantFP(+0.0, dl, MVT::v4f32);
4905 } else if (VT.getVectorElementType() == MVT::i1) {
4906 assert((Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) &&(static_cast <bool> ((Subtarget.hasBWI() || VT.getVectorNumElements
() <= 16) && "Unexpected vector type") ? void (0) :
__assert_fail ("(Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4907, __extension__ __PRETTY_FUNCTION__))
4907 "Unexpected vector type")(static_cast <bool> ((Subtarget.hasBWI() || VT.getVectorNumElements
() <= 16) && "Unexpected vector type") ? void (0) :
__assert_fail ("(Subtarget.hasBWI() || VT.getVectorNumElements() <= 16) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4907, __extension__ __PRETTY_FUNCTION__))
;
4908 assert((Subtarget.hasVLX() || VT.getVectorNumElements() >= 8) &&(static_cast <bool> ((Subtarget.hasVLX() || VT.getVectorNumElements
() >= 8) && "Unexpected vector type") ? void (0) :
__assert_fail ("(Subtarget.hasVLX() || VT.getVectorNumElements() >= 8) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4909, __extension__ __PRETTY_FUNCTION__))
4909 "Unexpected vector type")(static_cast <bool> ((Subtarget.hasVLX() || VT.getVectorNumElements
() >= 8) && "Unexpected vector type") ? void (0) :
__assert_fail ("(Subtarget.hasVLX() || VT.getVectorNumElements() >= 8) && \"Unexpected vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4909, __extension__ __PRETTY_FUNCTION__))
;
4910 Vec = DAG.getConstant(0, dl, VT);
4911 } else {
4912 unsigned Num32BitElts = VT.getSizeInBits() / 32;
4913 Vec = DAG.getConstant(0, dl, MVT::getVectorVT(MVT::i32, Num32BitElts));
4914 }
4915 return DAG.getBitcast(VT, Vec);
4916}
4917
4918static SDValue extractSubVector(SDValue Vec, unsigned IdxVal, SelectionDAG &DAG,
4919 const SDLoc &dl, unsigned vectorWidth) {
4920 EVT VT = Vec.getValueType();
4921 EVT ElVT = VT.getVectorElementType();
4922 unsigned Factor = VT.getSizeInBits()/vectorWidth;
4923 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4924 VT.getVectorNumElements()/Factor);
4925
4926 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
4927 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4928 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")(static_cast <bool> (isPowerOf2_32(ElemsPerChunk) &&
"Elements per chunk not power of 2") ? void (0) : __assert_fail
("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4928, __extension__ __PRETTY_FUNCTION__))
;
4929
4930 // This is the index of the first element of the vectorWidth-bit chunk
4931 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4932 IdxVal &= ~(ElemsPerChunk - 1);
4933
4934 // If the input is a buildvector just emit a smaller one.
4935 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4936 return DAG.getBuildVector(ResultVT, dl,
4937 Vec->ops().slice(IdxVal, ElemsPerChunk));
4938
4939 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4940 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4941}
4942
4943/// Generate a DAG to grab 128-bits from a vector > 128 bits. This
4944/// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4945/// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4946/// instructions or a simple subregister reference. Idx is an index in the
4947/// 128 bits we want. It need not be aligned to a 128-bit boundary. That makes
4948/// lowering EXTRACT_VECTOR_ELT operations easier.
4949static SDValue extract128BitVector(SDValue Vec, unsigned IdxVal,
4950 SelectionDAG &DAG, const SDLoc &dl) {
4951 assert((Vec.getValueType().is256BitVector() ||(static_cast <bool> ((Vec.getValueType().is256BitVector
() || Vec.getValueType().is512BitVector()) && "Unexpected vector size!"
) ? void (0) : __assert_fail ("(Vec.getValueType().is256BitVector() || Vec.getValueType().is512BitVector()) && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4952, __extension__ __PRETTY_FUNCTION__))
4952 Vec.getValueType().is512BitVector()) && "Unexpected vector size!")(static_cast <bool> ((Vec.getValueType().is256BitVector
() || Vec.getValueType().is512BitVector()) && "Unexpected vector size!"
) ? void (0) : __assert_fail ("(Vec.getValueType().is256BitVector() || Vec.getValueType().is512BitVector()) && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4952, __extension__ __PRETTY_FUNCTION__))
;
4953 return extractSubVector(Vec, IdxVal, DAG, dl, 128);
4954}
4955
4956/// Generate a DAG to grab 256-bits from a 512-bit vector.
4957static SDValue extract256BitVector(SDValue Vec, unsigned IdxVal,
4958 SelectionDAG &DAG, const SDLoc &dl) {
4959 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!")(static_cast <bool> (Vec.getValueType().is512BitVector(
) && "Unexpected vector size!") ? void (0) : __assert_fail
("Vec.getValueType().is512BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4959, __extension__ __PRETTY_FUNCTION__))
;
4960 return extractSubVector(Vec, IdxVal, DAG, dl, 256);
4961}
4962
4963static SDValue insertSubVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4964 SelectionDAG &DAG, const SDLoc &dl,
4965 unsigned vectorWidth) {
4966 assert((vectorWidth == 128 || vectorWidth == 256) &&(static_cast <bool> ((vectorWidth == 128 || vectorWidth
== 256) && "Unsupported vector width") ? void (0) : __assert_fail
("(vectorWidth == 128 || vectorWidth == 256) && \"Unsupported vector width\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4967, __extension__ __PRETTY_FUNCTION__))
4967 "Unsupported vector width")(static_cast <bool> ((vectorWidth == 128 || vectorWidth
== 256) && "Unsupported vector width") ? void (0) : __assert_fail
("(vectorWidth == 128 || vectorWidth == 256) && \"Unsupported vector width\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4967, __extension__ __PRETTY_FUNCTION__))
;
4968 // Inserting UNDEF is Result
4969 if (Vec.isUndef())
4970 return Result;
4971 EVT VT = Vec.getValueType();
4972 EVT ElVT = VT.getVectorElementType();
4973 EVT ResultVT = Result.getValueType();
4974
4975 // Insert the relevant vectorWidth bits.
4976 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4977 assert(isPowerOf2_32(ElemsPerChunk) && "Elements per chunk not power of 2")(static_cast <bool> (isPowerOf2_32(ElemsPerChunk) &&
"Elements per chunk not power of 2") ? void (0) : __assert_fail
("isPowerOf2_32(ElemsPerChunk) && \"Elements per chunk not power of 2\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4977, __extension__ __PRETTY_FUNCTION__))
;
4978
4979 // This is the index of the first element of the vectorWidth-bit chunk
4980 // we want. Since ElemsPerChunk is a power of 2 just need to clear bits.
4981 IdxVal &= ~(ElemsPerChunk - 1);
4982
4983 SDValue VecIdx = DAG.getIntPtrConstant(IdxVal, dl);
4984 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4985}
4986
4987/// Generate a DAG to put 128-bits into a vector > 128 bits. This
4988/// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4989/// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4990/// simple superregister reference. Idx is an index in the 128 bits
4991/// we want. It need not be aligned to a 128-bit boundary. That makes
4992/// lowering INSERT_VECTOR_ELT operations easier.
4993static SDValue insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4994 SelectionDAG &DAG, const SDLoc &dl) {
4995 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!")(static_cast <bool> (Vec.getValueType().is128BitVector(
) && "Unexpected vector size!") ? void (0) : __assert_fail
("Vec.getValueType().is128BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 4995, __extension__ __PRETTY_FUNCTION__))
;
4996 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4997}
4998
4999static SDValue insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
5000 SelectionDAG &DAG, const SDLoc &dl) {
5001 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!")(static_cast <bool> (Vec.getValueType().is256BitVector(
) && "Unexpected vector size!") ? void (0) : __assert_fail
("Vec.getValueType().is256BitVector() && \"Unexpected vector size!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5001, __extension__ __PRETTY_FUNCTION__))
;
5002 return insertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
5003}
5004
5005// Return true if the instruction zeroes the unused upper part of the
5006// destination and accepts mask.
5007static bool isMaskedZeroUpperBitsvXi1(unsigned int Opcode) {
5008 switch (Opcode) {
5009 default:
5010 return false;
5011 case X86ISD::TESTM:
5012 case X86ISD::TESTNM:
5013 case X86ISD::PCMPEQM:
5014 case X86ISD::PCMPGTM:
5015 case X86ISD::CMPM:
5016 case X86ISD::CMPMU:
5017 return true;
5018 }
5019}
5020
5021/// Insert i1-subvector to i1-vector.
5022static SDValue insert1BitVector(SDValue Op, SelectionDAG &DAG,
5023 const X86Subtarget &Subtarget) {
5024
5025 SDLoc dl(Op);
5026 SDValue Vec = Op.getOperand(0);
5027 SDValue SubVec = Op.getOperand(1);
5028 SDValue Idx = Op.getOperand(2);
5029
5030 if (!isa<ConstantSDNode>(Idx))
5031 return SDValue();
5032
5033 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5034 if (IdxVal == 0 && Vec.isUndef()) // the operation is legal
5035 return Op;
5036
5037 MVT OpVT = Op.getSimpleValueType();
5038 MVT SubVecVT = SubVec.getSimpleValueType();
5039 unsigned NumElems = OpVT.getVectorNumElements();
5040 unsigned SubVecNumElems = SubVecVT.getVectorNumElements();
5041
5042 assert(IdxVal + SubVecNumElems <= NumElems &&(static_cast <bool> (IdxVal + SubVecNumElems <= NumElems
&& IdxVal % SubVecVT.getSizeInBits() == 0 &&
"Unexpected index value in INSERT_SUBVECTOR") ? void (0) : __assert_fail
("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5044, __extension__ __PRETTY_FUNCTION__))
5043 IdxVal % SubVecVT.getSizeInBits() == 0 &&(static_cast <bool> (IdxVal + SubVecNumElems <= NumElems
&& IdxVal % SubVecVT.getSizeInBits() == 0 &&
"Unexpected index value in INSERT_SUBVECTOR") ? void (0) : __assert_fail
("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5044, __extension__ __PRETTY_FUNCTION__))
5044 "Unexpected index value in INSERT_SUBVECTOR")(static_cast <bool> (IdxVal + SubVecNumElems <= NumElems
&& IdxVal % SubVecVT.getSizeInBits() == 0 &&
"Unexpected index value in INSERT_SUBVECTOR") ? void (0) : __assert_fail
("IdxVal + SubVecNumElems <= NumElems && IdxVal % SubVecVT.getSizeInBits() == 0 && \"Unexpected index value in INSERT_SUBVECTOR\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5044, __extension__ __PRETTY_FUNCTION__))
;
5045
5046 // There are 3 possible cases:
5047 // 1. Subvector should be inserted in the lower part (IdxVal == 0)
5048 // 2. Subvector should be inserted in the upper part
5049 // (IdxVal + SubVecNumElems == NumElems)
5050 // 3. Subvector should be inserted in the middle (for example v2i1
5051 // to v16i1, index 2)
5052
5053 // If this node widens - by concatenating zeroes - the type of the result
5054 // of a node with instruction that zeroes all upper (irrelevant) bits of the
5055 // output register, mark this node as legal to enable replacing them with
5056 // the v8i1 version of the previous instruction during instruction selection.
5057 // For example, VPCMPEQDZ128rr instruction stores its v4i1 result in a k-reg,
5058 // while zeroing all the upper remaining 60 bits of the register. if the
5059 // result of such instruction is inserted into an allZeroVector, then we can
5060 // safely remove insert_vector (in instruction selection) as the cmp instr
5061 // already zeroed the rest of the register.
5062 if (ISD::isBuildVectorAllZeros(Vec.getNode()) && IdxVal == 0 &&
5063 (isMaskedZeroUpperBitsvXi1(SubVec.getOpcode()) ||
5064 (SubVec.getOpcode() == ISD::AND &&
5065 (isMaskedZeroUpperBitsvXi1(SubVec.getOperand(0).getOpcode()) ||
5066 isMaskedZeroUpperBitsvXi1(SubVec.getOperand(1).getOpcode())))))
5067 return Op;
5068
5069 // extend to natively supported kshift
5070 MVT MinVT = Subtarget.hasDQI() ? MVT::v8i1 : MVT::v16i1;
5071 MVT WideOpVT = OpVT;
5072 if (OpVT.getSizeInBits() < MinVT.getStoreSizeInBits())
5073 WideOpVT = MinVT;
5074
5075 SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
5076 SDValue Undef = DAG.getUNDEF(WideOpVT);
5077 SDValue WideSubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5078 Undef, SubVec, ZeroIdx);
5079
5080 // Extract sub-vector if require.
5081 auto ExtractSubVec = [&](SDValue V) {
5082 return (WideOpVT == OpVT) ? V : DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
5083 OpVT, V, ZeroIdx);
5084 };
5085
5086 if (Vec.isUndef()) {
5087 if (IdxVal != 0) {
5088 SDValue ShiftBits = DAG.getConstant(IdxVal, dl, MVT::i8);
5089 WideSubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, WideSubVec,
5090 ShiftBits);
5091 }
5092 return ExtractSubVec(WideSubVec);
5093 }
5094
5095 if (ISD::isBuildVectorAllZeros(Vec.getNode())) {
5096 NumElems = WideOpVT.getVectorNumElements();
5097 unsigned ShiftLeft = NumElems - SubVecNumElems;
5098 unsigned ShiftRight = NumElems - SubVecNumElems - IdxVal;
5099 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, WideSubVec,
5100 DAG.getConstant(ShiftLeft, dl, MVT::i8));
5101 Vec = ShiftRight ? DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec,
5102 DAG.getConstant(ShiftRight, dl, MVT::i8)) : Vec;
5103 return ExtractSubVec(Vec);
5104 }
5105
5106 if (IdxVal == 0) {
5107 // Zero lower bits of the Vec
5108 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
5109 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
5110 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5111 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5112 // Merge them together, SubVec should be zero extended.
5113 WideSubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT,
5114 getZeroVector(WideOpVT, Subtarget, DAG, dl),
5115 SubVec, ZeroIdx);
5116 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, WideSubVec);
5117 return ExtractSubVec(Vec);
5118 }
5119
5120 // Simple case when we put subvector in the upper part
5121 if (IdxVal + SubVecNumElems == NumElems) {
5122 // Zero upper bits of the Vec
5123 WideSubVec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, WideSubVec,
5124 DAG.getConstant(IdxVal, dl, MVT::i8));
5125 SDValue ShiftBits = DAG.getConstant(SubVecNumElems, dl, MVT::i8);
5126 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, WideOpVT, Undef, Vec, ZeroIdx);
5127 Vec = DAG.getNode(X86ISD::KSHIFTL, dl, WideOpVT, Vec, ShiftBits);
5128 Vec = DAG.getNode(X86ISD::KSHIFTR, dl, WideOpVT, Vec, ShiftBits);
5129 Vec = DAG.getNode(ISD::OR, dl, WideOpVT, Vec, WideSubVec);
5130 return ExtractSubVec(Vec);
5131 }
5132 // Subvector should be inserted in the middle - use shuffle
5133 WideSubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
5134 SubVec, ZeroIdx);
5135 SmallVector<int, 64> Mask;
5136 for (unsigned i = 0; i < NumElems; ++i)
5137 Mask.push_back(i >= IdxVal && i < IdxVal + SubVecNumElems ?
5138 i : i + NumElems);
5139 return DAG.getVectorShuffle(OpVT, dl, WideSubVec, Vec, Mask);
5140}
5141
5142/// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
5143/// instructions. This is used because creating CONCAT_VECTOR nodes of
5144/// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
5145/// large BUILD_VECTORS.
5146static SDValue concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
5147 unsigned NumElems, SelectionDAG &DAG,
5148 const SDLoc &dl) {
5149 SDValue V = insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
5150 return insert128BitVector(V, V2, NumElems / 2, DAG, dl);
5151}
5152
5153static SDValue concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
5154 unsigned NumElems, SelectionDAG &DAG,
5155 const SDLoc &dl) {
5156 SDValue V = insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
5157 return insert256BitVector(V, V2, NumElems / 2, DAG, dl);
5158}
5159
5160/// Returns a vector of specified type with all bits set.
5161/// Always build ones vectors as <4 x i32>, <8 x i32> or <16 x i32>.
5162/// Then bitcast to their original type, ensuring they get CSE'd.
5163static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5164 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Expected a 128/256/512-bit vector type"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected a 128/256/512-bit vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5165, __extension__ __PRETTY_FUNCTION__))
5165 "Expected a 128/256/512-bit vector type")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Expected a 128/256/512-bit vector type"
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Expected a 128/256/512-bit vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5165, __extension__ __PRETTY_FUNCTION__))
;
5166
5167 APInt Ones = APInt::getAllOnesValue(32);
5168 unsigned NumElts = VT.getSizeInBits() / 32;
5169 SDValue Vec = DAG.getConstant(Ones, dl, MVT::getVectorVT(MVT::i32, NumElts));
5170 return DAG.getBitcast(VT, Vec);
5171}
5172
5173static SDValue getExtendInVec(unsigned Opc, const SDLoc &DL, EVT VT, SDValue In,
5174 SelectionDAG &DAG) {
5175 EVT InVT = In.getValueType();
5176 assert((X86ISD::VSEXT == Opc || X86ISD::VZEXT == Opc) && "Unexpected opcode")(static_cast <bool> ((X86ISD::VSEXT == Opc || X86ISD::VZEXT
== Opc) && "Unexpected opcode") ? void (0) : __assert_fail
("(X86ISD::VSEXT == Opc || X86ISD::VZEXT == Opc) && \"Unexpected opcode\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5176, __extension__ __PRETTY_FUNCTION__))
;
5177
5178 if (VT.is128BitVector() && InVT.is128BitVector())
5179 return X86ISD::VSEXT == Opc ? DAG.getSignExtendVectorInReg(In, DL, VT)
5180 : DAG.getZeroExtendVectorInReg(In, DL, VT);
5181
5182 // For 256-bit vectors, we only need the lower (128-bit) input half.
5183 // For 512-bit vectors, we only need the lower input half or quarter.
5184 if (VT.getSizeInBits() > 128 && InVT.getSizeInBits() > 128) {
5185 int Scale = VT.getScalarSizeInBits() / InVT.getScalarSizeInBits();
5186 In = extractSubVector(In, 0, DAG, DL,
5187 std::max(128, (int)VT.getSizeInBits() / Scale));
5188 }
5189
5190 return DAG.getNode(Opc, DL, VT, In);
5191}
5192
5193/// Returns a vector_shuffle node for an unpackl operation.
5194static SDValue getUnpackl(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
5195 SDValue V1, SDValue V2) {
5196 SmallVector<int, 8> Mask;
5197 createUnpackShuffleMask(VT, Mask, /* Lo = */ true, /* Unary = */ false);
5198 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5199}
5200
5201/// Returns a vector_shuffle node for an unpackh operation.
5202static SDValue getUnpackh(SelectionDAG &DAG, const SDLoc &dl, MVT VT,
5203 SDValue V1, SDValue V2) {
5204 SmallVector<int, 8> Mask;
5205 createUnpackShuffleMask(VT, Mask, /* Lo = */ false, /* Unary = */ false);
5206 return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
5207}
5208
5209/// Return a vector_shuffle of the specified vector of zero or undef vector.
5210/// This produces a shuffle where the low element of V2 is swizzled into the
5211/// zero/undef vector, landing at element Idx.
5212/// This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5213static SDValue getShuffleVectorZeroOrUndef(SDValue V2, int Idx,
5214 bool IsZero,
5215 const X86Subtarget &Subtarget,
5216 SelectionDAG &DAG) {
5217 MVT VT = V2.getSimpleValueType();
5218 SDValue V1 = IsZero
5219 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5220 int NumElems = VT.getVectorNumElements();
5221 SmallVector<int, 16> MaskVec(NumElems);
5222 for (int i = 0; i != NumElems; ++i)
5223 // If this is the insertion idx, put the low elt of V2 here.
5224 MaskVec[i] = (i == Idx) ? NumElems : i;
5225 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, MaskVec);
5226}
5227
5228static SDValue peekThroughBitcasts(SDValue V) {
5229 while (V.getNode() && V.getOpcode() == ISD::BITCAST)
5230 V = V.getOperand(0);
5231 return V;
5232}
5233
5234static SDValue peekThroughOneUseBitcasts(SDValue V) {
5235 while (V.getNode() && V.getOpcode() == ISD::BITCAST &&
5236 V.getOperand(0).hasOneUse())
5237 V = V.getOperand(0);
5238 return V;
5239}
5240
5241static const Constant *getTargetConstantFromNode(SDValue Op) {
5242 Op = peekThroughBitcasts(Op);
5243
5244 auto *Load = dyn_cast<LoadSDNode>(Op);
5245 if (!Load)
5246 return nullptr;
5247
5248 SDValue Ptr = Load->getBasePtr();
5249 if (Ptr->getOpcode() == X86ISD::Wrapper ||
5250 Ptr->getOpcode() == X86ISD::WrapperRIP)
5251 Ptr = Ptr->getOperand(0);
5252
5253 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
5254 if (!CNode || CNode->isMachineConstantPoolEntry())
5255 return nullptr;
5256
5257 return dyn_cast<Constant>(CNode->getConstVal());
5258}
5259
5260// Extract raw constant bits from constant pools.
5261static bool getTargetConstantBitsFromNode(SDValue Op, unsigned EltSizeInBits,
5262 APInt &UndefElts,
5263 SmallVectorImpl<APInt> &EltBits,
5264 bool AllowWholeUndefs = true,
5265 bool AllowPartialUndefs = true) {
5266 assert(EltBits.empty() && "Expected an empty EltBits vector")(static_cast <bool> (EltBits.empty() && "Expected an empty EltBits vector"
) ? void (0) : __assert_fail ("EltBits.empty() && \"Expected an empty EltBits vector\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5266, __extension__ __PRETTY_FUNCTION__))
;
5267
5268 Op = peekThroughBitcasts(Op);
5269
5270 EVT VT = Op.getValueType();
5271 unsigned SizeInBits = VT.getSizeInBits();
5272 assert((SizeInBits % EltSizeInBits) == 0 && "Can't split constant!")(static_cast <bool> ((SizeInBits % EltSizeInBits) == 0 &&
"Can't split constant!") ? void (0) : __assert_fail ("(SizeInBits % EltSizeInBits) == 0 && \"Can't split constant!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5272, __extension__ __PRETTY_FUNCTION__))
;
5273 unsigned NumElts = SizeInBits / EltSizeInBits;
5274
5275 // Bitcast a source array of element bits to the target size.
5276 auto CastBitData = [&](APInt &UndefSrcElts, ArrayRef<APInt> SrcEltBits) {
5277 unsigned NumSrcElts = UndefSrcElts.getBitWidth();
5278 unsigned SrcEltSizeInBits = SrcEltBits[0].getBitWidth();
5279 assert((NumSrcElts * SrcEltSizeInBits) == SizeInBits &&(static_cast <bool> ((NumSrcElts * SrcEltSizeInBits) ==
SizeInBits && "Constant bit sizes don't match") ? void
(0) : __assert_fail ("(NumSrcElts * SrcEltSizeInBits) == SizeInBits && \"Constant bit sizes don't match\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5280, __extension__ __PRETTY_FUNCTION__))
5280 "Constant bit sizes don't match")(static_cast <bool> ((NumSrcElts * SrcEltSizeInBits) ==
SizeInBits && "Constant bit sizes don't match") ? void
(0) : __assert_fail ("(NumSrcElts * SrcEltSizeInBits) == SizeInBits && \"Constant bit sizes don't match\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5280, __extension__ __PRETTY_FUNCTION__))
;
5281
5282 // Don't split if we don't allow undef bits.
5283 bool AllowUndefs = AllowWholeUndefs || AllowPartialUndefs;
5284 if (UndefSrcElts.getBoolValue() && !AllowUndefs)
5285 return false;
5286
5287 // If we're already the right size, don't bother bitcasting.
5288 if (NumSrcElts == NumElts) {
5289 UndefElts = UndefSrcElts;
5290 EltBits.assign(SrcEltBits.begin(), SrcEltBits.end());
5291 return true;
5292 }
5293
5294 // Extract all the undef/constant element data and pack into single bitsets.
5295 APInt UndefBits(SizeInBits, 0);
5296 APInt MaskBits(SizeInBits, 0);
5297
5298 for (unsigned i = 0; i != NumSrcElts; ++i) {
5299 unsigned BitOffset = i * SrcEltSizeInBits;
5300 if (UndefSrcElts[i])
5301 UndefBits.setBits(BitOffset, BitOffset + SrcEltSizeInBits);
5302 MaskBits.insertBits(SrcEltBits[i], BitOffset);
5303 }
5304
5305 // Split the undef/constant single bitset data into the target elements.
5306 UndefElts = APInt(NumElts, 0);
5307 EltBits.resize(NumElts, APInt(EltSizeInBits, 0));
5308
5309 for (unsigned i = 0; i != NumElts; ++i) {
5310 unsigned BitOffset = i * EltSizeInBits;
5311 APInt UndefEltBits = UndefBits.extractBits(EltSizeInBits, BitOffset);
5312
5313 // Only treat an element as UNDEF if all bits are UNDEF.
5314 if (UndefEltBits.isAllOnesValue()) {
5315 if (!AllowWholeUndefs)
5316 return false;
5317 UndefElts.setBit(i);
5318 continue;
5319 }
5320
5321 // If only some bits are UNDEF then treat them as zero (or bail if not
5322 // supported).
5323 if (UndefEltBits.getBoolValue() && !AllowPartialUndefs)
5324 return false;
5325
5326 APInt Bits = MaskBits.extractBits(EltSizeInBits, BitOffset);
5327 EltBits[i] = Bits.getZExtValue();
5328 }
5329 return true;
5330 };
5331
5332 // Collect constant bits and insert into mask/undef bit masks.
5333 auto CollectConstantBits = [](const Constant *Cst, APInt &Mask, APInt &Undefs,
5334 unsigned UndefBitIndex) {
5335 if (!Cst)
5336 return false;
5337 if (isa<UndefValue>(Cst)) {
5338 Undefs.setBit(UndefBitIndex);
5339 return true;
5340 }
5341 if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
5342 Mask = CInt->getValue();
5343 return true;
5344 }
5345 if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
5346 Mask = CFP->getValueAPF().bitcastToAPInt();
5347 return true;
5348 }
5349 return false;
5350 };
5351
5352 // Handle UNDEFs.
5353 if (Op.isUndef()) {
5354 APInt UndefSrcElts = APInt::getAllOnesValue(NumElts);
5355 SmallVector<APInt, 64> SrcEltBits(NumElts, APInt(EltSizeInBits, 0));
5356 return CastBitData(UndefSrcElts, SrcEltBits);
5357 }
5358
5359 // Extract scalar constant bits.
5360 if (auto *Cst = dyn_cast<ConstantSDNode>(Op)) {
5361 APInt UndefSrcElts = APInt::getNullValue(1);
5362 SmallVector<APInt, 64> SrcEltBits(1, Cst->getAPIntValue());
5363 return CastBitData(UndefSrcElts, SrcEltBits);
5364 }
5365
5366 // Extract constant bits from build vector.
5367 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5368 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5369 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5370
5371 APInt UndefSrcElts(NumSrcElts, 0);
5372 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5373 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
5374 const SDValue &Src = Op.getOperand(i);
5375 if (Src.isUndef()) {
5376 UndefSrcElts.setBit(i);
5377 continue;
5378 }
5379 auto *Cst = cast<ConstantSDNode>(Src);
5380 SrcEltBits[i] = Cst->getAPIntValue().zextOrTrunc(SrcEltSizeInBits);
5381 }
5382 return CastBitData(UndefSrcElts, SrcEltBits);
5383 }
5384
5385 // Extract constant bits from constant pool vector.
5386 if (auto *Cst = getTargetConstantFromNode(Op)) {
5387 Type *CstTy = Cst->getType();
5388 if (!CstTy->isVectorTy() || (SizeInBits != CstTy->getPrimitiveSizeInBits()))
5389 return false;
5390
5391 unsigned SrcEltSizeInBits = CstTy->getScalarSizeInBits();
5392 unsigned NumSrcElts = CstTy->getVectorNumElements();
5393
5394 APInt UndefSrcElts(NumSrcElts, 0);
5395 SmallVector<APInt, 64> SrcEltBits(NumSrcElts, APInt(SrcEltSizeInBits, 0));
5396 for (unsigned i = 0; i != NumSrcElts; ++i)
5397 if (!CollectConstantBits(Cst->getAggregateElement(i), SrcEltBits[i],
5398 UndefSrcElts, i))
5399 return false;
5400
5401 return CastBitData(UndefSrcElts, SrcEltBits);
5402 }
5403
5404 // Extract constant bits from a broadcasted constant pool scalar.
5405 if (Op.getOpcode() == X86ISD::VBROADCAST &&
5406 EltSizeInBits <= VT.getScalarSizeInBits()) {
5407 if (auto *Broadcast = getTargetConstantFromNode(Op.getOperand(0))) {
5408 unsigned SrcEltSizeInBits = Broadcast->getType()->getScalarSizeInBits();
5409 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5410
5411 APInt UndefSrcElts(NumSrcElts, 0);
5412 SmallVector<APInt, 64> SrcEltBits(1, APInt(SrcEltSizeInBits, 0));
5413 if (CollectConstantBits(Broadcast, SrcEltBits[0], UndefSrcElts, 0)) {
5414 if (UndefSrcElts[0])
5415 UndefSrcElts.setBits(0, NumSrcElts);
5416 SrcEltBits.append(NumSrcElts - 1, SrcEltBits[0]);
5417 return CastBitData(UndefSrcElts, SrcEltBits);
5418 }
5419 }
5420 }
5421
5422 // Extract a rematerialized scalar constant insertion.
5423 if (Op.getOpcode() == X86ISD::VZEXT_MOVL &&
5424 Op.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
5425 isa<ConstantSDNode>(Op.getOperand(0).getOperand(0))) {
5426 unsigned SrcEltSizeInBits = VT.getScalarSizeInBits();
5427 unsigned NumSrcElts = SizeInBits / SrcEltSizeInBits;
5428
5429 APInt UndefSrcElts(NumSrcElts, 0);
5430 SmallVector<APInt, 64> SrcEltBits;
5431 auto *CN = cast<ConstantSDNode>(Op.getOperand(0).getOperand(0));
5432 SrcEltBits.push_back(CN->getAPIntValue().zextOrTrunc(SrcEltSizeInBits));
5433 SrcEltBits.append(NumSrcElts - 1, APInt(SrcEltSizeInBits, 0));
5434 return CastBitData(UndefSrcElts, SrcEltBits);
5435 }
5436
5437 return false;
5438}
5439
5440static bool getTargetShuffleMaskIndices(SDValue MaskNode,
5441 unsigned MaskEltSizeInBits,
5442 SmallVectorImpl<uint64_t> &RawMask) {
5443 APInt UndefElts;
5444 SmallVector<APInt, 64> EltBits;
5445
5446 // Extract the raw target constant bits.
5447 // FIXME: We currently don't support UNDEF bits or mask entries.
5448 if (!getTargetConstantBitsFromNode(MaskNode, MaskEltSizeInBits, UndefElts,
5449 EltBits, /* AllowWholeUndefs */ false,
5450 /* AllowPartialUndefs */ false))
5451 return false;
5452
5453 // Insert the extracted elements into the mask.
5454 for (APInt Elt : EltBits)
5455 RawMask.push_back(Elt.getZExtValue());
5456
5457 return true;
5458}
5459
5460/// Create a shuffle mask that matches the PACKSS/PACKUS truncation.
5461/// Note: This ignores saturation, so inputs must be checked first.
5462static void createPackShuffleMask(MVT VT, SmallVectorImpl<int> &Mask,
5463 bool Unary) {
5464 assert(Mask.empty() && "Expected an empty shuffle mask vector")(static_cast <bool> (Mask.empty() && "Expected an empty shuffle mask vector"
) ? void (0) : __assert_fail ("Mask.empty() && \"Expected an empty shuffle mask vector\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5464, __extension__ __PRETTY_FUNCTION__))
;
5465 unsigned NumElts = VT.getVectorNumElements();
5466 unsigned NumLanes = VT.getSizeInBits() / 128;
5467 unsigned NumEltsPerLane = 128 / VT.getScalarSizeInBits();
5468 unsigned Offset = Unary ? 0 : NumElts;
5469
5470 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
5471 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += 2)
5472 Mask.push_back(Elt + (Lane * NumEltsPerLane));
5473 for (unsigned Elt = 0; Elt != NumEltsPerLane; Elt += 2)
5474 Mask.push_back(Elt + (Lane * NumEltsPerLane) + Offset);
5475 }
5476}
5477
5478/// Calculates the shuffle mask corresponding to the target-specific opcode.
5479/// If the mask could be calculated, returns it in \p Mask, returns the shuffle
5480/// operands in \p Ops, and returns true.
5481/// Sets \p IsUnary to true if only one source is used. Note that this will set
5482/// IsUnary for shuffles which use a single input multiple times, and in those
5483/// cases it will adjust the mask to only have indices within that single input.
5484/// It is an error to call this with non-empty Mask/Ops vectors.
5485static bool getTargetShuffleMask(SDNode *N, MVT VT, bool AllowSentinelZero,
5486 SmallVectorImpl<SDValue> &Ops,
5487 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5488 unsigned NumElems = VT.getVectorNumElements();
5489 SDValue ImmN;
5490
5491 assert(Mask.empty() && "getTargetShuffleMask expects an empty Mask vector")(static_cast <bool> (Mask.empty() && "getTargetShuffleMask expects an empty Mask vector"
) ? void (0) : __assert_fail ("Mask.empty() && \"getTargetShuffleMask expects an empty Mask vector\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5491, __extension__ __PRETTY_FUNCTION__))
;
5492 assert(Ops.empty() && "getTargetShuffleMask expects an empty Ops vector")(static_cast <bool> (Ops.empty() && "getTargetShuffleMask expects an empty Ops vector"
) ? void (0) : __assert_fail ("Ops.empty() && \"getTargetShuffleMask expects an empty Ops vector\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5492, __extension__ __PRETTY_FUNCTION__))
;
5493
5494 IsUnary = false;
5495 bool IsFakeUnary = false;
5496 switch(N->getOpcode()) {
5497 case X86ISD::BLENDI:
5498 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5498, __extension__ __PRETTY_FUNCTION__))
;
5499 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5499, __extension__ __PRETTY_FUNCTION__))
;
5500 ImmN = N->getOperand(N->getNumOperands()-1);
5501 DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5502 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5503 break;
5504 case X86ISD::SHUFP:
5505 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5505, __extension__ __PRETTY_FUNCTION__))
;
5506 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5506, __extension__ __PRETTY_FUNCTION__))
;
5507 ImmN = N->getOperand(N->getNumOperands()-1);
5508 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5509 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5510 break;
5511 case X86ISD::INSERTPS:
5512 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5512, __extension__ __PRETTY_FUNCTION__))
;
5513 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5513, __extension__ __PRETTY_FUNCTION__))
;
5514 ImmN = N->getOperand(N->getNumOperands()-1);
5515 DecodeINSERTPSMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5516 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5517 break;
5518 case X86ISD::EXTRQI:
5519 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5519, __extension__ __PRETTY_FUNCTION__))
;
5520 if (isa<ConstantSDNode>(N->getOperand(1)) &&
5521 isa<ConstantSDNode>(N->getOperand(2))) {
5522 int BitLen = N->getConstantOperandVal(1);
5523 int BitIdx = N->getConstantOperandVal(2);
5524 DecodeEXTRQIMask(VT, BitLen, BitIdx, Mask);
5525 IsUnary = true;
5526 }
5527 break;
5528 case X86ISD::INSERTQI:
5529 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5529, __extension__ __PRETTY_FUNCTION__))
;
5530 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5530, __extension__ __PRETTY_FUNCTION__))
;
5531 if (isa<ConstantSDNode>(N->getOperand(2)) &&
5532 isa<ConstantSDNode>(N->getOperand(3))) {
5533 int BitLen = N->getConstantOperandVal(2);
5534 int BitIdx = N->getConstantOperandVal(3);
5535 DecodeINSERTQIMask(VT, BitLen, BitIdx, Mask);
5536 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5537 }
5538 break;
5539 case X86ISD::UNPCKH:
5540 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5540, __extension__ __PRETTY_FUNCTION__))
;
5541 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5541, __extension__ __PRETTY_FUNCTION__))
;
5542 DecodeUNPCKHMask(VT, Mask);
5543 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5544 break;
5545 case X86ISD::UNPCKL:
5546 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5546, __extension__ __PRETTY_FUNCTION__))
;
5547 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5547, __extension__ __PRETTY_FUNCTION__))
;
5548 DecodeUNPCKLMask(VT, Mask);
5549 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5550 break;
5551 case X86ISD::MOVHLPS:
5552 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5552, __extension__ __PRETTY_FUNCTION__))
;
5553 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5553, __extension__ __PRETTY_FUNCTION__))
;
5554 DecodeMOVHLPSMask(NumElems, Mask);
5555 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5556 break;
5557 case X86ISD::MOVLHPS:
5558 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5558, __extension__ __PRETTY_FUNCTION__))
;
5559 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5559, __extension__ __PRETTY_FUNCTION__))
;
5560 DecodeMOVLHPSMask(NumElems, Mask);
5561 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5562 break;
5563 case X86ISD::PALIGNR:
5564 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5564, __extension__ __PRETTY_FUNCTION__))
;
5565 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5565, __extension__ __PRETTY_FUNCTION__))
;
5566 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5566, __extension__ __PRETTY_FUNCTION__))
;
5567 ImmN = N->getOperand(N->getNumOperands()-1);
5568 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5569 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5570 Ops.push_back(N->getOperand(1));
5571 Ops.push_back(N->getOperand(0));
5572 break;
5573 case X86ISD::VSHLDQ:
5574 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5574, __extension__ __PRETTY_FUNCTION__))
;
5575 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5575, __extension__ __PRETTY_FUNCTION__))
;
5576 ImmN = N->getOperand(N->getNumOperands() - 1);
5577 DecodePSLLDQMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5578 IsUnary = true;
5579 break;
5580 case X86ISD::VSRLDQ:
5581 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5581, __extension__ __PRETTY_FUNCTION__))
;
5582 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5582, __extension__ __PRETTY_FUNCTION__))
;
5583 ImmN = N->getOperand(N->getNumOperands() - 1);
5584 DecodePSRLDQMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5585 IsUnary = true;
5586 break;
5587 case X86ISD::PSHUFD:
5588 case X86ISD::VPERMILPI:
5589 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5589, __extension__ __PRETTY_FUNCTION__))
;
5590 ImmN = N->getOperand(N->getNumOperands()-1);
5591 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5592 IsUnary = true;
5593 break;
5594 case X86ISD::PSHUFHW:
5595 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5595, __extension__ __PRETTY_FUNCTION__))
;
5596 ImmN = N->getOperand(N->getNumOperands()-1);
5597 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5598 IsUnary = true;
5599 break;
5600 case X86ISD::PSHUFLW:
5601 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5601, __extension__ __PRETTY_FUNCTION__))
;
5602 ImmN = N->getOperand(N->getNumOperands()-1);
5603 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5604 IsUnary = true;
5605 break;
5606 case X86ISD::VZEXT_MOVL:
5607 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5607, __extension__ __PRETTY_FUNCTION__))
;
5608 DecodeZeroMoveLowMask(VT, Mask);
5609 IsUnary = true;
5610 break;
5611 case X86ISD::VBROADCAST: {
5612 SDValue N0 = N->getOperand(0);
5613 // See if we're broadcasting from index 0 of an EXTRACT_SUBVECTOR. If so,
5614 // add the pre-extracted value to the Ops vector.
5615 if (N0.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5616 N0.getOperand(0).getValueType() == VT &&
5617 N0.getConstantOperandVal(1) == 0)
5618 Ops.push_back(N0.getOperand(0));
5619
5620 // We only decode broadcasts of same-sized vectors, unless the broadcast
5621 // came from an extract from the original width. If we found one, we
5622 // pushed it the Ops vector above.
5623 if (N0.getValueType() == VT || !Ops.empty()) {
5624 DecodeVectorBroadcast(VT, Mask);
5625 IsUnary = true;
5626 break;
5627 }
5628 return false;
5629 }
5630 case X86ISD::VPERMILPV: {
5631 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5631, __extension__ __PRETTY_FUNCTION__))
;
5632 IsUnary = true;
5633 SDValue MaskNode = N->getOperand(1);
5634 unsigned MaskEltSize = VT.getScalarSizeInBits();
5635 SmallVector<uint64_t, 32> RawMask;
5636 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask)) {
5637 DecodeVPERMILPMask(VT, RawMask, Mask);
5638 break;
5639 }
5640 if (auto *C = getTargetConstantFromNode(MaskNode)) {
5641 DecodeVPERMILPMask(C, MaskEltSize, Mask);
5642 break;
5643 }
5644 return false;
5645 }
5646 case X86ISD::PSHUFB: {
5647 assert(VT.getScalarType() == MVT::i8 && "Byte vector expected")(static_cast <bool> (VT.getScalarType() == MVT::i8 &&
"Byte vector expected") ? void (0) : __assert_fail ("VT.getScalarType() == MVT::i8 && \"Byte vector expected\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5647, __extension__ __PRETTY_FUNCTION__))
;
5648 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5648, __extension__ __PRETTY_FUNCTION__))
;
5649 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5649, __extension__ __PRETTY_FUNCTION__))
;
5650 IsUnary = true;
5651 SDValue MaskNode = N->getOperand(1);
5652 SmallVector<uint64_t, 32> RawMask;
5653 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask)) {
5654 DecodePSHUFBMask(RawMask, Mask);
5655 break;
5656 }
5657 if (auto *C = getTargetConstantFromNode(MaskNode)) {
5658 DecodePSHUFBMask(C, Mask);
5659 break;
5660 }
5661 return false;
5662 }
5663 case X86ISD::VPERMI:
5664 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5664, __extension__ __PRETTY_FUNCTION__))
;
5665 ImmN = N->getOperand(N->getNumOperands()-1);
5666 DecodeVPERMMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5667 IsUnary = true;
5668 break;
5669 case X86ISD::MOVSS:
5670 case X86ISD::MOVSD:
5671 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5671, __extension__ __PRETTY_FUNCTION__))
;
5672 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5672, __extension__ __PRETTY_FUNCTION__))
;
5673 DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
5674 break;
5675 case X86ISD::VPERM2X128:
5676 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5676, __extension__ __PRETTY_FUNCTION__))
;
5677 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5677, __extension__ __PRETTY_FUNCTION__))
;
5678 ImmN = N->getOperand(N->getNumOperands()-1);
5679 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5680 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5681 break;
5682 case X86ISD::MOVSLDUP:
5683 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5683, __extension__ __PRETTY_FUNCTION__))
;
5684 DecodeMOVSLDUPMask(VT, Mask);
5685 IsUnary = true;
5686 break;
5687 case X86ISD::MOVSHDUP:
5688 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5688, __extension__ __PRETTY_FUNCTION__))
;
5689 DecodeMOVSHDUPMask(VT, Mask);
5690 IsUnary = true;
5691 break;
5692 case X86ISD::MOVDDUP:
5693 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5693, __extension__ __PRETTY_FUNCTION__))
;
5694 DecodeMOVDDUPMask(VT, Mask);
5695 IsUnary = true;
5696 break;
5697 case X86ISD::MOVLPD:
5698 case X86ISD::MOVLPS:
5699 // Not yet implemented
5700 return false;
5701 case X86ISD::VPERMIL2: {
5702 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5702, __extension__ __PRETTY_FUNCTION__))
;
5703 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5703, __extension__ __PRETTY_FUNCTION__))
;
5704 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5705 unsigned MaskEltSize = VT.getScalarSizeInBits();
5706 SDValue MaskNode = N->getOperand(2);
5707 SDValue CtrlNode = N->getOperand(3);
5708 if (ConstantSDNode *CtrlOp = dyn_cast<ConstantSDNode>(CtrlNode)) {
5709 unsigned CtrlImm = CtrlOp->getZExtValue();
5710 SmallVector<uint64_t, 32> RawMask;
5711 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask)) {
5712 DecodeVPERMIL2PMask(VT, CtrlImm, RawMask, Mask);
5713 break;
5714 }
5715 if (auto *C = getTargetConstantFromNode(MaskNode)) {
5716 DecodeVPERMIL2PMask(C, CtrlImm, MaskEltSize, Mask);
5717 break;
5718 }
5719 }
5720 return false;
5721 }
5722 case X86ISD::VPPERM: {
5723 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5723, __extension__ __PRETTY_FUNCTION__))
;
5724 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5724, __extension__ __PRETTY_FUNCTION__))
;
5725 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5726 SDValue MaskNode = N->getOperand(2);
5727 SmallVector<uint64_t, 32> RawMask;
5728 if (getTargetShuffleMaskIndices(MaskNode, 8, RawMask)) {
5729 DecodeVPPERMMask(RawMask, Mask);
5730 break;
5731 }
5732 if (auto *C = getTargetConstantFromNode(MaskNode)) {
5733 DecodeVPPERMMask(C, Mask);
5734 break;
5735 }
5736 return false;
5737 }
5738 case X86ISD::VPERMV: {
5739 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5739, __extension__ __PRETTY_FUNCTION__))
;
5740 IsUnary = true;
5741 // Unlike most shuffle nodes, VPERMV's mask operand is operand 0.
5742 Ops.push_back(N->getOperand(1));
5743 SDValue MaskNode = N->getOperand(0);
5744 SmallVector<uint64_t, 32> RawMask;
5745 unsigned MaskEltSize = VT.getScalarSizeInBits();
5746 if (getTargetShuffleMaskIndices(MaskNode, MaskEltSize, RawMask)) {
5747 DecodeVPERMVMask(RawMask, Mask);
5748 break;
5749 }
5750 if (auto *C = getTargetConstantFromNode(MaskNode)) {
5751 DecodeVPERMVMask(C, MaskEltSize, Mask);
5752 break;
5753 }
5754 return false;
5755 }
5756 case X86ISD::VPERMV3: {
5757 assert(N->getOperand(0).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(0).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(0).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5757, __extension__ __PRETTY_FUNCTION__))
;
5758 assert(N->getOperand(2).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(2).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(2).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5758, __extension__ __PRETTY_FUNCTION__))
;
5759 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(2);
5760 // Unlike most shuffle nodes, VPERMV3's mask operand is the middle one.
5761 Ops.push_back(N->getOperand(0));
5762 Ops.push_back(N->getOperand(2));
5763 SDValue MaskNode = N->getOperand(1);
5764 unsigned MaskEltSize = VT.getScalarSizeInBits();
5765 if (auto *C = getTargetConstantFromNode(MaskNode)) {
5766 DecodeVPERMV3Mask(C, MaskEltSize, Mask);
5767 break;
5768 }
5769 return false;
5770 }
5771 case X86ISD::VPERMIV3: {
5772 assert(N->getOperand(1).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(1).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(1).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5772, __extension__ __PRETTY_FUNCTION__))
;
5773 assert(N->getOperand(2).getValueType() == VT && "Unexpected value type")(static_cast <bool> (N->getOperand(2).getValueType()
== VT && "Unexpected value type") ? void (0) : __assert_fail
("N->getOperand(2).getValueType() == VT && \"Unexpected value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5773, __extension__ __PRETTY_FUNCTION__))
;
5774 IsUnary = IsFakeUnary = N->getOperand(1) == N->getOperand(2);
5775 // Unlike most shuffle nodes, VPERMIV3's mask operand is the first one.
5776 Ops.push_back(N->getOperand(1));
5777 Ops.push_back(N->getOperand(2));
5778 SDValue MaskNode = N->getOperand(0);
5779 unsigned MaskEltSize = VT.getScalarSizeInBits();
5780 if (auto *C = getTargetConstantFromNode(MaskNode)) {
5781 DecodeVPERMV3Mask(C, MaskEltSize, Mask);
5782 break;
5783 }
5784 return false;
5785 }
5786 default: llvm_unreachable("unknown target shuffle node")::llvm::llvm_unreachable_internal("unknown target shuffle node"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5786)
;
5787 }
5788
5789 // Empty mask indicates the decode failed.
5790 if (Mask.empty())
5791 return false;
5792
5793 // Check if we're getting a shuffle mask with zero'd elements.
5794 if (!AllowSentinelZero)
5795 if (any_of(Mask, [](int M) { return M == SM_SentinelZero; }))
5796 return false;
5797
5798 // If we have a fake unary shuffle, the shuffle mask is spread across two
5799 // inputs that are actually the same node. Re-map the mask to always point
5800 // into the first input.
5801 if (IsFakeUnary)
5802 for (int &M : Mask)
5803 if (M >= (int)Mask.size())
5804 M -= Mask.size();
5805
5806 // If we didn't already add operands in the opcode-specific code, default to
5807 // adding 1 or 2 operands starting at 0.
5808 if (Ops.empty()) {
5809 Ops.push_back(N->getOperand(0));
5810 if (!IsUnary || IsFakeUnary)
5811 Ops.push_back(N->getOperand(1));
5812 }
5813
5814 return true;
5815}
5816
5817/// Check a target shuffle mask's inputs to see if we can set any values to
5818/// SM_SentinelZero - this is for elements that are known to be zero
5819/// (not just zeroable) from their inputs.
5820/// Returns true if the target shuffle mask was decoded.
5821static bool setTargetShuffleZeroElements(SDValue N,
5822 SmallVectorImpl<int> &Mask,
5823 SmallVectorImpl<SDValue> &Ops) {
5824 bool IsUnary;
5825 if (!isTargetShuffle(N.getOpcode()))
5826 return false;
5827
5828 MVT VT = N.getSimpleValueType();
5829 if (!getTargetShuffleMask(N.getNode(), VT, true, Ops, Mask, IsUnary))
5830 return false;
5831
5832 SDValue V1 = Ops[0];
5833 SDValue V2 = IsUnary ? V1 : Ops[1];
5834
5835 V1 = peekThroughBitcasts(V1);
5836 V2 = peekThroughBitcasts(V2);
5837
5838 assert((VT.getSizeInBits() % Mask.size()) == 0 &&(static_cast <bool> ((VT.getSizeInBits() % Mask.size())
== 0 && "Illegal split of shuffle value type") ? void
(0) : __assert_fail ("(VT.getSizeInBits() % Mask.size()) == 0 && \"Illegal split of shuffle value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5839, __extension__ __PRETTY_FUNCTION__))
5839 "Illegal split of shuffle value type")(static_cast <bool> ((VT.getSizeInBits() % Mask.size())
== 0 && "Illegal split of shuffle value type") ? void
(0) : __assert_fail ("(VT.getSizeInBits() % Mask.size()) == 0 && \"Illegal split of shuffle value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5839, __extension__ __PRETTY_FUNCTION__))
;
5840 unsigned EltSizeInBits = VT.getSizeInBits() / Mask.size();
5841
5842 // Extract known constant input data.
5843 APInt UndefSrcElts[2];
5844 SmallVector<APInt, 32> SrcEltBits[2];
5845 bool IsSrcConstant[2] = {
5846 getTargetConstantBitsFromNode(V1, EltSizeInBits, UndefSrcElts[0],
5847 SrcEltBits[0], true, false),
5848 getTargetConstantBitsFromNode(V2, EltSizeInBits, UndefSrcElts[1],
5849 SrcEltBits[1], true, false)};
5850
5851 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
5852 int M = Mask[i];
5853
5854 // Already decoded as SM_SentinelZero / SM_SentinelUndef.
5855 if (M < 0)
5856 continue;
5857
5858 // Determine shuffle input and normalize the mask.
5859 unsigned SrcIdx = M / Size;
5860 SDValue V = M < Size ? V1 : V2;
5861 M %= Size;
5862
5863 // We are referencing an UNDEF input.
5864 if (V.isUndef()) {
5865 Mask[i] = SM_SentinelUndef;
5866 continue;
5867 }
5868
5869 // SCALAR_TO_VECTOR - only the first element is defined, and the rest UNDEF.
5870 // TODO: We currently only set UNDEF for integer types - floats use the same
5871 // registers as vectors and many of the scalar folded loads rely on the
5872 // SCALAR_TO_VECTOR pattern.
5873 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5874 (Size % V.getValueType().getVectorNumElements()) == 0) {
5875 int Scale = Size / V.getValueType().getVectorNumElements();
5876 int Idx = M / Scale;
5877 if (Idx != 0 && !VT.isFloatingPoint())
5878 Mask[i] = SM_SentinelUndef;
5879 else if (Idx == 0 && X86::isZeroNode(V.getOperand(0)))
5880 Mask[i] = SM_SentinelZero;
5881 continue;
5882 }
5883
5884 // Attempt to extract from the source's constant bits.
5885 if (IsSrcConstant[SrcIdx]) {
5886 if (UndefSrcElts[SrcIdx][M])
5887 Mask[i] = SM_SentinelUndef;
5888 else if (SrcEltBits[SrcIdx][M] == 0)
5889 Mask[i] = SM_SentinelZero;
5890 }
5891 }
5892
5893 assert(VT.getVectorNumElements() == Mask.size() &&(static_cast <bool> (VT.getVectorNumElements() == Mask.
size() && "Different mask size from vector size!") ? void
(0) : __assert_fail ("VT.getVectorNumElements() == Mask.size() && \"Different mask size from vector size!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5894, __extension__ __PRETTY_FUNCTION__))
5894 "Different mask size from vector size!")(static_cast <bool> (VT.getVectorNumElements() == Mask.
size() && "Different mask size from vector size!") ? void
(0) : __assert_fail ("VT.getVectorNumElements() == Mask.size() && \"Different mask size from vector size!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5894, __extension__ __PRETTY_FUNCTION__))
;
5895 return true;
5896}
5897
5898// Attempt to decode ops that could be represented as a shuffle mask.
5899// The decoded shuffle mask may contain a different number of elements to the
5900// destination value type.
5901static bool getFauxShuffleMask(SDValue N, SmallVectorImpl<int> &Mask,
5902 SmallVectorImpl<SDValue> &Ops,
5903 SelectionDAG &DAG) {
5904 Mask.clear();
5905 Ops.clear();
5906
5907 MVT VT = N.getSimpleValueType();
5908 unsigned NumElts = VT.getVectorNumElements();
5909 unsigned NumSizeInBits = VT.getSizeInBits();
5910 unsigned NumBitsPerElt = VT.getScalarSizeInBits();
5911 assert((NumBitsPerElt % 8) == 0 && (NumSizeInBits % 8) == 0 &&(static_cast <bool> ((NumBitsPerElt % 8) == 0 &&
(NumSizeInBits % 8) == 0 && "Expected byte aligned value types"
) ? void (0) : __assert_fail ("(NumBitsPerElt % 8) == 0 && (NumSizeInBits % 8) == 0 && \"Expected byte aligned value types\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5912, __extension__ __PRETTY_FUNCTION__))
5912 "Expected byte aligned value types")(static_cast <bool> ((NumBitsPerElt % 8) == 0 &&
(NumSizeInBits % 8) == 0 && "Expected byte aligned value types"
) ? void (0) : __assert_fail ("(NumBitsPerElt % 8) == 0 && (NumSizeInBits % 8) == 0 && \"Expected byte aligned value types\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5912, __extension__ __PRETTY_FUNCTION__))
;
5913
5914 unsigned Opcode = N.getOpcode();
5915 switch (Opcode) {
5916 case ISD::AND:
5917 case X86ISD::ANDNP: {
5918 // Attempt to decode as a per-byte mask.
5919 APInt UndefElts;
5920 SmallVector<APInt, 32> EltBits;
5921 SDValue N0 = N.getOperand(0);
5922 SDValue N1 = N.getOperand(1);
5923 bool IsAndN = (X86ISD::ANDNP == Opcode);
5924 uint64_t ZeroMask = IsAndN ? 255 : 0;
5925 if (!getTargetConstantBitsFromNode(IsAndN ? N0 : N1, 8, UndefElts, EltBits))
5926 return false;
5927 for (int i = 0, e = (int)EltBits.size(); i != e; ++i) {
5928 if (UndefElts[i]) {
5929 Mask.push_back(SM_SentinelUndef);
5930 continue;
5931 }
5932 uint64_t ByteBits = EltBits[i].getZExtValue();
5933 if (ByteBits != 0 && ByteBits != 255)
5934 return false;
5935 Mask.push_back(ByteBits == ZeroMask ? SM_SentinelZero : i);
5936 }
5937 Ops.push_back(IsAndN ? N1 : N0);
5938 return true;
5939 }
5940 case ISD::SCALAR_TO_VECTOR: {
5941 // Match against a scalar_to_vector of an extract from a vector,
5942 // for PEXTRW/PEXTRB we must handle the implicit zext of the scalar.
5943 SDValue N0 = N.getOperand(0);
5944 SDValue SrcExtract;
5945
5946 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5947 N0.getOperand(0).getValueType() == VT) ||
5948 (N0.getOpcode() == X86ISD::PEXTRW &&
5949 N0.getOperand(0).getValueType() == MVT::v8i16) ||
5950 (N0.getOpcode() == X86ISD::PEXTRB &&
5951 N0.getOperand(0).getValueType() == MVT::v16i8)) {
5952 SrcExtract = N0;
5953 }
5954
5955 if (!SrcExtract || !isa<ConstantSDNode>(SrcExtract.getOperand(1)))
5956 return false;
5957
5958 SDValue SrcVec = SrcExtract.getOperand(0);
5959 EVT SrcVT = SrcVec.getValueType();
5960 unsigned NumSrcElts = SrcVT.getVectorNumElements();
5961 unsigned NumZeros = (NumBitsPerElt / SrcVT.getScalarSizeInBits()) - 1;
5962
5963 unsigned SrcIdx = SrcExtract.getConstantOperandVal(1);
5964 if (NumSrcElts <= SrcIdx)
5965 return false;
5966
5967 Ops.push_back(SrcVec);
5968 Mask.push_back(SrcIdx);
5969 Mask.append(NumZeros, SM_SentinelZero);
5970 Mask.append(NumSrcElts - Mask.size(), SM_SentinelUndef);
5971 return true;
5972 }
5973 case X86ISD::PINSRB:
5974 case X86ISD::PINSRW: {
5975 SDValue InVec = N.getOperand(0);
5976 SDValue InScl = N.getOperand(1);
5977 uint64_t InIdx = N.getConstantOperandVal(2);
5978 assert(InIdx < NumElts && "Illegal insertion index")(static_cast <bool> (InIdx < NumElts && "Illegal insertion index"
) ? void (0) : __assert_fail ("InIdx < NumElts && \"Illegal insertion index\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5978, __extension__ __PRETTY_FUNCTION__))
;
5979
5980 // Attempt to recognise a PINSR*(VEC, 0, Idx) shuffle pattern.
5981 if (X86::isZeroNode(InScl)) {
5982 Ops.push_back(InVec);
5983 for (unsigned i = 0; i != NumElts; ++i)
5984 Mask.push_back(i == InIdx ? SM_SentinelZero : (int)i);
5985 return true;
5986 }
5987
5988 // Attempt to recognise a PINSR*(PEXTR*) shuffle pattern.
5989 // TODO: Expand this to support INSERT_VECTOR_ELT/etc.
5990 unsigned ExOp =
5991 (X86ISD::PINSRB == Opcode ? X86ISD::PEXTRB : X86ISD::PEXTRW);
5992 if (InScl.getOpcode() != ExOp)
5993 return false;
5994
5995 SDValue ExVec = InScl.getOperand(0);
5996 uint64_t ExIdx = InScl.getConstantOperandVal(1);
5997 assert(ExIdx < NumElts && "Illegal extraction index")(static_cast <bool> (ExIdx < NumElts && "Illegal extraction index"
) ? void (0) : __assert_fail ("ExIdx < NumElts && \"Illegal extraction index\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 5997, __extension__ __PRETTY_FUNCTION__))
;
5998 Ops.push_back(InVec);
5999 Ops.push_back(ExVec);
6000 for (unsigned i = 0; i != NumElts; ++i)
6001 Mask.push_back(i == InIdx ? NumElts + ExIdx : i);
6002 return true;
6003 }
6004 case X86ISD::PACKSS:
6005 case X86ISD::PACKUS: {
6006 SDValue N0 = N.getOperand(0);
6007 SDValue N1 = N.getOperand(1);
6008 assert(N0.getValueType().getVectorNumElements() == (NumElts / 2) &&(static_cast <bool> (N0.getValueType().getVectorNumElements
() == (NumElts / 2) && N1.getValueType().getVectorNumElements
() == (NumElts / 2) && "Unexpected input value type")
? void (0) : __assert_fail ("N0.getValueType().getVectorNumElements() == (NumElts / 2) && N1.getValueType().getVectorNumElements() == (NumElts / 2) && \"Unexpected input value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6010, __extension__ __PRETTY_FUNCTION__))
6009 N1.getValueType().getVectorNumElements() == (NumElts / 2) &&(static_cast <bool> (N0.getValueType().getVectorNumElements
() == (NumElts / 2) && N1.getValueType().getVectorNumElements
() == (NumElts / 2) && "Unexpected input value type")
? void (0) : __assert_fail ("N0.getValueType().getVectorNumElements() == (NumElts / 2) && N1.getValueType().getVectorNumElements() == (NumElts / 2) && \"Unexpected input value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6010, __extension__ __PRETTY_FUNCTION__))
6010 "Unexpected input value type")(static_cast <bool> (N0.getValueType().getVectorNumElements
() == (NumElts / 2) && N1.getValueType().getVectorNumElements
() == (NumElts / 2) && "Unexpected input value type")
? void (0) : __assert_fail ("N0.getValueType().getVectorNumElements() == (NumElts / 2) && N1.getValueType().getVectorNumElements() == (NumElts / 2) && \"Unexpected input value type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6010, __extension__ __PRETTY_FUNCTION__))
;
6011
6012 // If we know input saturation won't happen we can treat this
6013 // as a truncation shuffle.
6014 if (Opcode == X86ISD::PACKSS) {
6015 if ((!N0.isUndef() && DAG.ComputeNumSignBits(N0) <= NumBitsPerElt) ||
6016 (!N1.isUndef() && DAG.ComputeNumSignBits(N1) <= NumBitsPerElt))
6017 return false;
6018 } else {
6019 APInt ZeroMask = APInt::getHighBitsSet(2 * NumBitsPerElt, NumBitsPerElt);
6020 if ((!N0.isUndef() && !DAG.MaskedValueIsZero(N0, ZeroMask)) ||
6021 (!N1.isUndef() && !DAG.MaskedValueIsZero(N1, ZeroMask)))
6022 return false;
6023 }
6024
6025 bool IsUnary = (N0 == N1);
6026
6027 Ops.push_back(N0);
6028 if (!IsUnary)
6029 Ops.push_back(N1);
6030
6031 createPackShuffleMask(VT, Mask, IsUnary);
6032 return true;
6033 }
6034 case X86ISD::VSHLI:
6035 case X86ISD::VSRLI: {
6036 uint64_t ShiftVal = N.getConstantOperandVal(1);
6037 // Out of range bit shifts are guaranteed to be zero.
6038 if (NumBitsPerElt <= ShiftVal) {
6039 Mask.append(NumElts, SM_SentinelZero);
6040 return true;
6041 }
6042
6043 // We can only decode 'whole byte' bit shifts as shuffles.
6044 if ((ShiftVal % 8) != 0)
6045 break;
6046
6047 uint64_t ByteShift = ShiftVal / 8;
6048 unsigned NumBytes = NumSizeInBits / 8;
6049 unsigned NumBytesPerElt = NumBitsPerElt / 8;
6050 Ops.push_back(N.getOperand(0));
6051
6052 // Clear mask to all zeros and insert the shifted byte indices.
6053 Mask.append(NumBytes, SM_SentinelZero);
6054
6055 if (X86ISD::VSHLI == Opcode) {
6056 for (unsigned i = 0; i != NumBytes; i += NumBytesPerElt)
6057 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6058 Mask[i + j] = i + j - ByteShift;
6059 } else {
6060 for (unsigned i = 0; i != NumBytes; i += NumBytesPerElt)
6061 for (unsigned j = ByteShift; j != NumBytesPerElt; ++j)
6062 Mask[i + j - ByteShift] = i + j;
6063 }
6064 return true;
6065 }
6066 case ISD::ZERO_EXTEND_VECTOR_INREG:
6067 case X86ISD::VZEXT: {
6068 // TODO - add support for VPMOVZX with smaller input vector types.
6069 SDValue Src = N.getOperand(0);
6070 MVT SrcVT = Src.getSimpleValueType();
6071 if (NumSizeInBits != SrcVT.getSizeInBits())
6072 break;
6073 DecodeZeroExtendMask(SrcVT.getScalarType(), VT, Mask);
6074 Ops.push_back(Src);
6075 return true;
6076 }
6077 }
6078
6079 return false;
6080}
6081
6082/// Removes unused shuffle source inputs and adjusts the shuffle mask accordingly.
6083static void resolveTargetShuffleInputsAndMask(SmallVectorImpl<SDValue> &Inputs,
6084 SmallVectorImpl<int> &Mask) {
6085 int MaskWidth = Mask.size();
6086 SmallVector<SDValue, 16> UsedInputs;
6087 for (int i = 0, e = Inputs.size(); i < e; ++i) {
6088 int lo = UsedInputs.size() * MaskWidth;
6089 int hi = lo + MaskWidth;
6090
6091 // Strip UNDEF input usage.
6092 if (Inputs[i].isUndef())
6093 for (int &M : Mask)
6094 if ((lo <= M) && (M < hi))
6095 M = SM_SentinelUndef;
6096
6097 // Check for unused inputs.
6098 if (any_of(Mask, [lo, hi](int i) { return (lo <= i) && (i < hi); })) {
6099 UsedInputs.push_back(Inputs[i]);
6100 continue;
6101 }
6102 for (int &M : Mask)
6103 if (lo <= M)
6104 M -= MaskWidth;
6105 }
6106 Inputs = UsedInputs;
6107}
6108
6109/// Calls setTargetShuffleZeroElements to resolve a target shuffle mask's inputs
6110/// and set the SM_SentinelUndef and SM_SentinelZero values. Then check the
6111/// remaining input indices in case we now have a unary shuffle and adjust the
6112/// inputs accordingly.
6113/// Returns true if the target shuffle mask was decoded.
6114static bool resolveTargetShuffleInputs(SDValue Op,
6115 SmallVectorImpl<SDValue> &Inputs,
6116 SmallVectorImpl<int> &Mask,
6117 SelectionDAG &DAG) {
6118 if (!setTargetShuffleZeroElements(Op, Mask, Inputs))
6119 if (!getFauxShuffleMask(Op, Mask, Inputs, DAG))
6120 return false;
6121
6122 resolveTargetShuffleInputsAndMask(Inputs, Mask);
6123 return true;
6124}
6125
6126/// Returns the scalar element that will make up the ith
6127/// element of the result of the vector shuffle.
6128static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
6129 unsigned Depth) {
6130 if (Depth == 6)
6131 return SDValue(); // Limit search depth.
6132
6133 SDValue V = SDValue(N, 0);
6134 EVT VT = V.getValueType();
6135 unsigned Opcode = V.getOpcode();
6136
6137 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
6138 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
6139 int Elt = SV->getMaskElt(Index);
6140
6141 if (Elt < 0)
6142 return DAG.getUNDEF(VT.getVectorElementType());
6143
6144 unsigned NumElems = VT.getVectorNumElements();
6145 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
6146 : SV->getOperand(1);
6147 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
6148 }
6149
6150 // Recurse into target specific vector shuffles to find scalars.
6151 if (isTargetShuffle(Opcode)) {
6152 MVT ShufVT = V.getSimpleValueType();
6153 MVT ShufSVT = ShufVT.getVectorElementType();
6154 int NumElems = (int)ShufVT.getVectorNumElements();
6155 SmallVector<int, 16> ShuffleMask;
6156 SmallVector<SDValue, 16> ShuffleOps;
6157 bool IsUnary;
6158
6159 if (!getTargetShuffleMask(N, ShufVT, true, ShuffleOps, ShuffleMask, IsUnary))
6160 return SDValue();
6161
6162 int Elt = ShuffleMask[Index];
6163 if (Elt == SM_SentinelZero)
6164 return ShufSVT.isInteger() ? DAG.getConstant(0, SDLoc(N), ShufSVT)
6165 : DAG.getConstantFP(+0.0, SDLoc(N), ShufSVT);
6166 if (Elt == SM_SentinelUndef)
6167 return DAG.getUNDEF(ShufSVT);
6168
6169 assert(0 <= Elt && Elt < (2*NumElems) && "Shuffle index out of range")(static_cast <bool> (0 <= Elt && Elt < (2
*NumElems) && "Shuffle index out of range") ? void (0
) : __assert_fail ("0 <= Elt && Elt < (2*NumElems) && \"Shuffle index out of range\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6169, __extension__ __PRETTY_FUNCTION__))
;
6170 SDValue NewV = (Elt < NumElems) ? ShuffleOps[0] : ShuffleOps[1];
6171 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
6172 Depth+1);
6173 }
6174
6175 // Actual nodes that may contain scalar elements
6176 if (Opcode == ISD::BITCAST) {
6177 V = V.getOperand(0);
6178 EVT SrcVT = V.getValueType();
6179 unsigned NumElems = VT.getVectorNumElements();
6180
6181 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
6182 return SDValue();
6183 }
6184
6185 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6186 return (Index == 0) ? V.getOperand(0)
6187 : DAG.getUNDEF(VT.getVectorElementType());
6188
6189 if (V.getOpcode() == ISD::BUILD_VECTOR)
6190 return V.getOperand(Index);
6191
6192 return SDValue();
6193}
6194
6195// Use PINSRB/PINSRW/PINSRD to create a build vector.
6196static SDValue LowerBuildVectorAsInsert(SDValue Op, unsigned NonZeros,
6197 unsigned NumNonZero, unsigned NumZero,
6198 SelectionDAG &DAG,
6199 const X86Subtarget &Subtarget) {
6200 MVT VT = Op.getSimpleValueType();
6201 unsigned NumElts = VT.getVectorNumElements();
6202 assert(((VT == MVT::v8i16 && Subtarget.hasSSE2()) ||(static_cast <bool> (((VT == MVT::v8i16 && Subtarget
.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) &&
Subtarget.hasSSE41())) && "Illegal vector insertion"
) ? void (0) : __assert_fail ("((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) && \"Illegal vector insertion\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6204, __extension__ __PRETTY_FUNCTION__))
6203 ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) &&(static_cast <bool> (((VT == MVT::v8i16 && Subtarget
.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) &&
Subtarget.hasSSE41())) && "Illegal vector insertion"
) ? void (0) : __assert_fail ("((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) && \"Illegal vector insertion\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6204, __extension__ __PRETTY_FUNCTION__))
6204 "Illegal vector insertion")(static_cast <bool> (((VT == MVT::v8i16 && Subtarget
.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) &&
Subtarget.hasSSE41())) && "Illegal vector insertion"
) ? void (0) : __assert_fail ("((VT == MVT::v8i16 && Subtarget.hasSSE2()) || ((VT == MVT::v16i8 || VT == MVT::v4i32) && Subtarget.hasSSE41())) && \"Illegal vector insertion\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6204, __extension__ __PRETTY_FUNCTION__))
;
6205
6206 SDLoc dl(Op);
6207 SDValue V;
6208 bool First = true;
6209
6210 for (unsigned i = 0; i < NumElts; ++i) {
6211 bool IsNonZero = (NonZeros & (1 << i)) != 0;
6212 if (!IsNonZero)
6213 continue;
6214
6215 // If the build vector contains zeros or our first insertion is not the
6216 // first index then insert into zero vector to break any register
6217 // dependency else use SCALAR_TO_VECTOR/VZEXT_MOVL.
6218 if (First) {
6219 First = false;
6220 if (NumZero || 0 != i)
6221 V = getZeroVector(VT, Subtarget, DAG, dl);
6222 else {
6223 assert(0 == i && "Expected insertion into zero-index")(static_cast <bool> (0 == i && "Expected insertion into zero-index"
) ? void (0) : __assert_fail ("0 == i && \"Expected insertion into zero-index\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6223, __extension__ __PRETTY_FUNCTION__))
;
6224 V = DAG.getAnyExtOrTrunc(Op.getOperand(i), dl, MVT::i32);
6225 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
6226 V = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, V);
6227 V = DAG.getBitcast(VT, V);
6228 continue;
6229 }
6230 }
6231 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V, Op.getOperand(i),
6232 DAG.getIntPtrConstant(i, dl));
6233 }
6234
6235 return V;
6236}
6237
6238/// Custom lower build_vector of v16i8.
6239static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
6240 unsigned NumNonZero, unsigned NumZero,
6241 SelectionDAG &DAG,
6242 const X86Subtarget &Subtarget) {
6243 if (NumNonZero > 8 && !Subtarget.hasSSE41())
6244 return SDValue();
6245
6246 // SSE4.1 - use PINSRB to insert each byte directly.
6247 if (Subtarget.hasSSE41())
6248 return LowerBuildVectorAsInsert(Op, NonZeros, NumNonZero, NumZero, DAG,
6249 Subtarget);
6250
6251 SDLoc dl(Op);
6252 SDValue V;
6253 bool First = true;
6254
6255 // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
6256 for (unsigned i = 0; i < 16; ++i) {
6257 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
6258 if (ThisIsNonZero && First) {
6259 if (NumZero)
6260 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
6261 else
6262 V = DAG.getUNDEF(MVT::v8i16);
6263 First = false;
6264 }
6265
6266 if ((i & 1) != 0) {
6267 // FIXME: Investigate extending to i32 instead of just i16.
6268 // FIXME: Investigate combining the first 4 bytes as a i32 instead.
6269 SDValue ThisElt, LastElt;
6270 bool LastIsNonZero = (NonZeros & (1 << (i - 1))) != 0;
6271 if (LastIsNonZero) {
6272 LastElt =
6273 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i - 1));
6274 }
6275 if (ThisIsNonZero) {
6276 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
6277 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16, ThisElt,
6278 DAG.getConstant(8, dl, MVT::i8));
6279 if (LastIsNonZero)
6280 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
6281 } else
6282 ThisElt = LastElt;
6283
6284 if (ThisElt) {
6285 if (1 == i) {
6286 V = NumZero ? DAG.getZExtOrTrunc(ThisElt, dl, MVT::i32)
6287 : DAG.getAnyExtOrTrunc(ThisElt, dl, MVT::i32);
6288 V = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, V);
6289 V = DAG.getNode(X86ISD::VZEXT_MOVL, dl, MVT::v4i32, V);
6290 V = DAG.getBitcast(MVT::v8i16, V);
6291 } else {
6292 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
6293 DAG.getIntPtrConstant(i / 2, dl));
6294 }
6295 }
6296 }
6297 }
6298
6299 return DAG.getBitcast(MVT::v16i8, V);
6300}
6301
6302/// Custom lower build_vector of v8i16.
6303static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
6304 unsigned NumNonZero, unsigned NumZero,
6305 SelectionDAG &DAG,
6306 const X86Subtarget &Subtarget) {
6307 if (NumNonZero > 4 && !Subtarget.hasSSE41())
6308 return SDValue();
6309
6310 // Use PINSRW to insert each byte directly.
6311 return LowerBuildVectorAsInsert(Op, NonZeros, NumNonZero, NumZero, DAG,
6312 Subtarget);
6313}
6314
6315/// Custom lower build_vector of v4i32 or v4f32.
6316static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
6317 const X86Subtarget &Subtarget) {
6318 // Find all zeroable elements.
6319 std::bitset<4> Zeroable;
6320 for (int i=0; i < 4; ++i) {
6321 SDValue Elt = Op->getOperand(i);
6322 Zeroable[i] = (Elt.isUndef() || X86::isZeroNode(Elt));
6323 }
6324 assert(Zeroable.size() - Zeroable.count() > 1 &&(static_cast <bool> (Zeroable.size() - Zeroable.count()
> 1 && "We expect at least two non-zero elements!"
) ? void (0) : __assert_fail ("Zeroable.size() - Zeroable.count() > 1 && \"We expect at least two non-zero elements!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6325, __extension__ __PRETTY_FUNCTION__))
6325 "We expect at least two non-zero elements!")(static_cast <bool> (Zeroable.size() - Zeroable.count()
> 1 && "We expect at least two non-zero elements!"
) ? void (0) : __assert_fail ("Zeroable.size() - Zeroable.count() > 1 && \"We expect at least two non-zero elements!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6325, __extension__ __PRETTY_FUNCTION__))
;
6326
6327 // We only know how to deal with build_vector nodes where elements are either
6328 // zeroable or extract_vector_elt with constant index.
6329 SDValue FirstNonZero;
6330 unsigned FirstNonZeroIdx;
6331 for (unsigned i=0; i < 4; ++i) {
6332 if (Zeroable[i])
6333 continue;
6334 SDValue Elt = Op->getOperand(i);
6335 if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6336 !isa<ConstantSDNode>(Elt.getOperand(1)))
6337 return SDValue();
6338 // Make sure that this node is extracting from a 128-bit vector.
6339 MVT VT = Elt.getOperand(0).getSimpleValueType();
6340 if (!VT.is128BitVector())
6341 return SDValue();
6342 if (!FirstNonZero.getNode()) {
6343 FirstNonZero = Elt;
6344 FirstNonZeroIdx = i;
6345 }
6346 }
6347
6348 assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!")(static_cast <bool> (FirstNonZero.getNode() && "Unexpected build vector of all zeros!"
) ? void (0) : __assert_fail ("FirstNonZero.getNode() && \"Unexpected build vector of all zeros!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6348, __extension__ __PRETTY_FUNCTION__))
;
6349 SDValue V1 = FirstNonZero.getOperand(0);
6350 MVT VT = V1.getSimpleValueType();
6351
6352 // See if this build_vector can be lowered as a blend with zero.
6353 SDValue Elt;
6354 unsigned EltMaskIdx, EltIdx;
6355 int Mask[4];
6356 for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
6357 if (Zeroable[EltIdx]) {
6358 // The zero vector will be on the right hand side.
6359 Mask[EltIdx] = EltIdx+4;
6360 continue;
6361 }
6362
6363 Elt = Op->getOperand(EltIdx);
6364 // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
6365 EltMaskIdx = Elt.getConstantOperandVal(1);
6366 if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
6367 break;
6368 Mask[EltIdx] = EltIdx;
6369 }
6370
6371 if (EltIdx == 4) {
6372 // Let the shuffle legalizer deal with blend operations.
6373 SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
6374 if (V1.getSimpleValueType() != VT)
6375 V1 = DAG.getBitcast(VT, V1);
6376 return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, Mask);
6377 }
6378
6379 // See if we can lower this build_vector to a INSERTPS.
6380 if (!Subtarget.hasSSE41())
6381 return SDValue();
6382
6383 SDValue V2 = Elt.getOperand(0);
6384 if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
6385 V1 = SDValue();
6386
6387 bool CanFold = true;
6388 for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
6389 if (Zeroable[i])
6390 continue;
6391
6392 SDValue Current = Op->getOperand(i);
6393 SDValue SrcVector = Current->getOperand(0);
6394 if (!V1.getNode())
6395 V1 = SrcVector;
6396 CanFold = (SrcVector == V1) && (Current.getConstantOperandVal(1) == i);
6397 }
6398
6399 if (!CanFold)
6400 return SDValue();
6401
6402 assert(V1.getNode() && "Expected at least two non-zero elements!")(static_cast <bool> (V1.getNode() && "Expected at least two non-zero elements!"
) ? void (0) : __assert_fail ("V1.getNode() && \"Expected at least two non-zero elements!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6402, __extension__ __PRETTY_FUNCTION__))
;
6403 if (V1.getSimpleValueType() != MVT::v4f32)
6404 V1 = DAG.getBitcast(MVT::v4f32, V1);
6405 if (V2.getSimpleValueType() != MVT::v4f32)
6406 V2 = DAG.getBitcast(MVT::v4f32, V2);
6407
6408 // Ok, we can emit an INSERTPS instruction.
6409 unsigned ZMask = Zeroable.to_ulong();
6410
6411 unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
6412 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!")(static_cast <bool> ((InsertPSMask & ~0xFFu) == 0 &&
"Invalid mask!") ? void (0) : __assert_fail ("(InsertPSMask & ~0xFFu) == 0 && \"Invalid mask!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6412, __extension__ __PRETTY_FUNCTION__))
;
6413 SDLoc DL(Op);
6414 SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
6415 DAG.getIntPtrConstant(InsertPSMask, DL));
6416 return DAG.getBitcast(VT, Result);
6417}
6418
6419/// Return a vector logical shift node.
6420static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp, unsigned NumBits,
6421 SelectionDAG &DAG, const TargetLowering &TLI,
6422 const SDLoc &dl) {
6423 assert(VT.is128BitVector() && "Unknown type for VShift")(static_cast <bool> (VT.is128BitVector() && "Unknown type for VShift"
) ? void (0) : __assert_fail ("VT.is128BitVector() && \"Unknown type for VShift\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6423, __extension__ __PRETTY_FUNCTION__))
;
6424 MVT ShVT = MVT::v16i8;
6425 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
6426 SrcOp = DAG.getBitcast(ShVT, SrcOp);
6427 MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
6428 assert(NumBits % 8 == 0 && "Only support byte sized shifts")(static_cast <bool> (NumBits % 8 == 0 && "Only support byte sized shifts"
) ? void (0) : __assert_fail ("NumBits % 8 == 0 && \"Only support byte sized shifts\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6428, __extension__ __PRETTY_FUNCTION__))
;
6429 SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
6430 return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
6431}
6432
6433static SDValue LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, const SDLoc &dl,
6434 SelectionDAG &DAG) {
6435
6436 // Check if the scalar load can be widened into a vector load. And if
6437 // the address is "base + cst" see if the cst can be "absorbed" into
6438 // the shuffle mask.
6439 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
6440 SDValue Ptr = LD->getBasePtr();
6441 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
6442 return SDValue();
6443 EVT PVT = LD->getValueType(0);
6444 if (PVT != MVT::i32 && PVT != MVT::f32)
6445 return SDValue();
6446
6447 int FI = -1;
6448 int64_t Offset = 0;
6449 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
6450 FI = FINode->getIndex();
6451 Offset = 0;
6452 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
6453 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6454 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6455 Offset = Ptr.getConstantOperandVal(1);
6456 Ptr = Ptr.getOperand(0);
6457 } else {
6458 return SDValue();
6459 }
6460
6461 // FIXME: 256-bit vector instructions don't require a strict alignment,
6462 // improve this code to support it better.
6463 unsigned RequiredAlign = VT.getSizeInBits()/8;
6464 SDValue Chain = LD->getChain();
6465 // Make sure the stack object alignment is at least 16 or 32.
6466 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6467 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
6468 if (MFI.isFixedObjectIndex(FI)) {
6469 // Can't change the alignment. FIXME: It's possible to compute
6470 // the exact stack offset and reference FI + adjust offset instead.
6471 // If someone *really* cares about this. That's the way to implement it.
6472 return SDValue();
6473 } else {
6474 MFI.setObjectAlignment(FI, RequiredAlign);
6475 }
6476 }
6477
6478 // (Offset % 16 or 32) must be multiple of 4. Then address is then
6479 // Ptr + (Offset & ~15).
6480 if (Offset < 0)
6481 return SDValue();
6482 if ((Offset % RequiredAlign) & 3)
6483 return SDValue();
6484 int64_t StartOffset = Offset & ~int64_t(RequiredAlign - 1);
6485 if (StartOffset) {
6486 SDLoc DL(Ptr);
6487 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
6488 DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
6489 }
6490
6491 int EltNo = (Offset - StartOffset) >> 2;
6492 unsigned NumElems = VT.getVectorNumElements();
6493
6494 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
6495 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
6496 LD->getPointerInfo().getWithOffset(StartOffset));
6497
6498 SmallVector<int, 8> Mask(NumElems, EltNo);
6499
6500 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), Mask);
6501 }
6502
6503 return SDValue();
6504}
6505
6506/// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
6507/// elements can be replaced by a single large load which has the same value as
6508/// a build_vector or insert_subvector whose loaded operands are 'Elts'.
6509///
6510/// Example: <load i32 *a, load i32 *a+4, zero, undef> -> zextload a
6511static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
6512 const SDLoc &DL, SelectionDAG &DAG,
6513 const X86Subtarget &Subtarget,
6514 bool isAfterLegalize) {
6515 unsigned NumElems = Elts.size();
6516
6517 int LastLoadedElt = -1;
6518 SmallBitVector LoadMask(NumElems, false);
6519 SmallBitVector ZeroMask(NumElems, false);
6
Calling constructor for 'SmallBitVector'
9
Returning from constructor for 'SmallBitVector'
6520 SmallBitVector UndefMask(NumElems, false);
6521
6522 // For each element in the initializer, see if we've found a load, zero or an
6523 // undef.
6524 for (unsigned i = 0; i < NumElems; ++i) {
10
Loop condition is true. Entering loop body
6525 SDValue Elt = peekThroughBitcasts(Elts[i]);
6526 if (!Elt.getNode())
11
Assuming the condition is false
12
Taking false branch
6527 return SDValue();
6528
6529 if (Elt.isUndef())
13
Taking false branch
6530 UndefMask[i] = true;
6531 else if (X86::isZeroNode(Elt) || ISD::isBuildVectorAllZeros(Elt.getNode()))
14
Assuming the condition is false
15
Assuming the condition is false
16
Taking false branch
6532 ZeroMask[i] = true;
6533 else if (ISD::isNON_EXTLoad(Elt.getNode())) {
17
Taking false branch
6534 LoadMask[i] = true;
6535 LastLoadedElt = i;
6536 // Each loaded element must be the correct fractional portion of the
6537 // requested vector load.
6538 if ((NumElems * Elt.getValueSizeInBits()) != VT.getSizeInBits())
6539 return SDValue();
6540 } else
6541 return SDValue();
6542 }
6543 assert((ZeroMask | UndefMask | LoadMask).count() == NumElems &&(static_cast <bool> ((ZeroMask | UndefMask | LoadMask).
count() == NumElems && "Incomplete element masks") ? void
(0) : __assert_fail ("(ZeroMask | UndefMask | LoadMask).count() == NumElems && \"Incomplete element masks\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6544, __extension__ __PRETTY_FUNCTION__))
6544 "Incomplete element masks")(static_cast <bool> ((ZeroMask | UndefMask | LoadMask).
count() == NumElems && "Incomplete element masks") ? void
(0) : __assert_fail ("(ZeroMask | UndefMask | LoadMask).count() == NumElems && \"Incomplete element masks\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6544, __extension__ __PRETTY_FUNCTION__))
;
6545
6546 // Handle Special Cases - all undef or undef/zero.
6547 if (UndefMask.count() == NumElems)
6548 return DAG.getUNDEF(VT);
6549
6550 // FIXME: Should we return this as a BUILD_VECTOR instead?
6551 if ((ZeroMask | UndefMask).count() == NumElems)
6552 return VT.isInteger() ? DAG.getConstant(0, DL, VT)
6553 : DAG.getConstantFP(0.0, DL, VT);
6554
6555 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6556 int FirstLoadedElt = LoadMask.find_first();
6557 SDValue EltBase = peekThroughBitcasts(Elts[FirstLoadedElt]);
6558 LoadSDNode *LDBase = cast<LoadSDNode>(EltBase);
6559 EVT LDBaseVT = EltBase.getValueType();
6560
6561 // Consecutive loads can contain UNDEFS but not ZERO elements.
6562 // Consecutive loads with UNDEFs and ZEROs elements require a
6563 // an additional shuffle stage to clear the ZERO elements.
6564 bool IsConsecutiveLoad = true;
6565 bool IsConsecutiveLoadWithZeros = true;
6566 for (int i = FirstLoadedElt + 1; i <= LastLoadedElt; ++i) {
6567 if (LoadMask[i]) {
6568 SDValue Elt = peekThroughBitcasts(Elts[i]);
6569 LoadSDNode *LD = cast<LoadSDNode>(Elt);
6570 if (!DAG.areNonVolatileConsecutiveLoads(
6571 LD, LDBase, Elt.getValueType().getStoreSizeInBits() / 8,
6572 i - FirstLoadedElt)) {
6573 IsConsecutiveLoad = false;
6574 IsConsecutiveLoadWithZeros = false;
6575 break;
6576 }
6577 } else if (ZeroMask[i]) {
6578 IsConsecutiveLoad = false;
6579 }
6580 }
6581
6582 SmallVector<LoadSDNode *, 8> Loads;
6583 for (int i = FirstLoadedElt; i <= LastLoadedElt; ++i)
6584 if (LoadMask[i])
6585 Loads.push_back(cast<LoadSDNode>(peekThroughBitcasts(Elts[i])));
6586
6587 auto CreateLoad = [&DAG, &DL, &Loads](EVT VT, LoadSDNode *LDBase) {
6588 auto MMOFlags = LDBase->getMemOperand()->getFlags();
6589 assert(!(MMOFlags & MachineMemOperand::MOVolatile) &&(static_cast <bool> (!(MMOFlags & MachineMemOperand
::MOVolatile) && "Cannot merge volatile loads.") ? void
(0) : __assert_fail ("!(MMOFlags & MachineMemOperand::MOVolatile) && \"Cannot merge volatile loads.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6590, __extension__ __PRETTY_FUNCTION__))
6590 "Cannot merge volatile loads.")(static_cast <bool> (!(MMOFlags & MachineMemOperand
::MOVolatile) && "Cannot merge volatile loads.") ? void
(0) : __assert_fail ("!(MMOFlags & MachineMemOperand::MOVolatile) && \"Cannot merge volatile loads.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6590, __extension__ __PRETTY_FUNCTION__))
;
6591 SDValue NewLd =
6592 DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
6593 LDBase->getPointerInfo(), LDBase->getAlignment(), MMOFlags);
6594 for (auto *LD : Loads)
6595 DAG.makeEquivalentMemoryOrdering(LD, NewLd);
6596 return NewLd;
6597 };
6598
6599 // LOAD - all consecutive load/undefs (must start/end with a load).
6600 // If we have found an entire vector of loads and undefs, then return a large
6601 // load of the entire vector width starting at the base pointer.
6602 // If the vector contains zeros, then attempt to shuffle those elements.
6603 if (FirstLoadedElt == 0 && LastLoadedElt == (int)(NumElems - 1) &&
6604 (IsConsecutiveLoad || IsConsecutiveLoadWithZeros)) {
6605 assert(LDBase && "Did not find base load for merging consecutive loads")(static_cast <bool> (LDBase && "Did not find base load for merging consecutive loads"
) ? void (0) : __assert_fail ("LDBase && \"Did not find base load for merging consecutive loads\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6605, __extension__ __PRETTY_FUNCTION__))
;
6606 EVT EltVT = LDBase->getValueType(0);
6607 // Ensure that the input vector size for the merged loads matches the
6608 // cumulative size of the input elements.
6609 if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
6610 return SDValue();
6611
6612 if (isAfterLegalize && !TLI.isOperationLegal(ISD::LOAD, VT))
6613 return SDValue();
6614
6615 // Don't create 256-bit non-temporal aligned loads without AVX2 as these
6616 // will lower to regular temporal loads and use the cache.
6617 if (LDBase->isNonTemporal() && LDBase->getAlignment() >= 32 &&
6618 VT.is256BitVector() && !Subtarget.hasInt256())
6619 return SDValue();
6620
6621 if (IsConsecutiveLoad)
6622 return CreateLoad(VT, LDBase);
6623
6624 // IsConsecutiveLoadWithZeros - we need to create a shuffle of the loaded
6625 // vector and a zero vector to clear out the zero elements.
6626 if (!isAfterLegalize && NumElems == VT.getVectorNumElements()) {
6627 SmallVector<int, 4> ClearMask(NumElems, -1);
6628 for (unsigned i = 0; i < NumElems; ++i) {
6629 if (ZeroMask[i])
6630 ClearMask[i] = i + NumElems;
6631 else if (LoadMask[i])
6632 ClearMask[i] = i;
6633 }
6634 SDValue V = CreateLoad(VT, LDBase);
6635 SDValue Z = VT.isInteger() ? DAG.getConstant(0, DL, VT)
6636 : DAG.getConstantFP(0.0, DL, VT);
6637 return DAG.getVectorShuffle(VT, DL, V, Z, ClearMask);
6638 }
6639 }
6640
6641 int LoadSize =
6642 (1 + LastLoadedElt - FirstLoadedElt) * LDBaseVT.getStoreSizeInBits();
6643
6644 // VZEXT_LOAD - consecutive 32/64-bit load/undefs followed by zeros/undefs.
6645 if (IsConsecutiveLoad && FirstLoadedElt == 0 &&
6646 (LoadSize == 32 || LoadSize == 64) &&
6647 ((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()))) {
6648 MVT VecSVT = VT.isFloatingPoint() ? MVT::getFloatingPointVT(LoadSize)
6649 : MVT::getIntegerVT(LoadSize);
6650 MVT VecVT = MVT::getVectorVT(VecSVT, VT.getSizeInBits() / LoadSize);
6651 if (TLI.isTypeLegal(VecVT)) {
6652 SDVTList Tys = DAG.getVTList(VecVT, MVT::Other);
6653 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
6654 SDValue ResNode =
6655 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, VecSVT,
6656 LDBase->getPointerInfo(),
6657 LDBase->getAlignment(),
6658 false/*isVolatile*/, true/*ReadMem*/,
6659 false/*WriteMem*/);
6660 for (auto *LD : Loads)
6661 DAG.makeEquivalentMemoryOrdering(LD, ResNode);
6662 return DAG.getBitcast(VT, ResNode);
6663 }
6664 }
6665
6666 return SDValue();
6667}
18
Potential leak of memory pointed to by 'ZeroMask.X'
6668
6669static Constant *getConstantVector(MVT VT, const APInt &SplatValue,
6670 unsigned SplatBitSize, LLVMContext &C) {
6671 unsigned ScalarSize = VT.getScalarSizeInBits();
6672 unsigned NumElm = SplatBitSize / ScalarSize;
6673
6674 SmallVector<Constant *, 32> ConstantVec;
6675 for (unsigned i = 0; i < NumElm; i++) {
6676 APInt Val = SplatValue.extractBits(ScalarSize, ScalarSize * i);
6677 Constant *Const;
6678 if (VT.isFloatingPoint()) {
6679 if (ScalarSize == 32) {
6680 Const = ConstantFP::get(C, APFloat(APFloat::IEEEsingle(), Val));
6681 } else {
6682 assert(ScalarSize == 64 && "Unsupported floating point scalar size")(static_cast <bool> (ScalarSize == 64 && "Unsupported floating point scalar size"
) ? void (0) : __assert_fail ("ScalarSize == 64 && \"Unsupported floating point scalar size\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6682, __extension__ __PRETTY_FUNCTION__))
;
6683 Const = ConstantFP::get(C, APFloat(APFloat::IEEEdouble(), Val));
6684 }
6685 } else
6686 Const = Constant::getIntegerValue(Type::getIntNTy(C, ScalarSize), Val);
6687 ConstantVec.push_back(Const);
6688 }
6689 return ConstantVector::get(ArrayRef<Constant *>(ConstantVec));
6690}
6691
6692static bool isUseOfShuffle(SDNode *N) {
6693 for (auto *U : N->uses()) {
6694 if (isTargetShuffle(U->getOpcode()))
6695 return true;
6696 if (U->getOpcode() == ISD::BITCAST) // Ignore bitcasts
6697 return isUseOfShuffle(U);
6698 }
6699 return false;
6700}
6701
6702// Check if the current node of build vector is a zero extended vector.
6703// // If so, return the value extended.
6704// // For example: (0,0,0,a,0,0,0,a,0,0,0,a,0,0,0,a) returns a.
6705// // NumElt - return the number of zero extended identical values.
6706// // EltType - return the type of the value include the zero extend.
6707static SDValue isSplatZeroExtended(const BuildVectorSDNode *Op,
6708 unsigned &NumElt, MVT &EltType) {
6709 SDValue ExtValue = Op->getOperand(0);
6710 unsigned NumElts = Op->getNumOperands();
6711 unsigned Delta = NumElts;
6712
6713 for (unsigned i = 1; i < NumElts; i++) {
6714 if (Op->getOperand(i) == ExtValue) {
6715 Delta = i;
6716 break;
6717 }
6718 if (!(Op->getOperand(i).isUndef() || isNullConstant(Op->getOperand(i))))
6719 return SDValue();
6720 }
6721 if (!isPowerOf2_32(Delta) || Delta == 1)
6722 return SDValue();
6723
6724 for (unsigned i = Delta; i < NumElts; i++) {
6725 if (i % Delta == 0) {
6726 if (Op->getOperand(i) != ExtValue)
6727 return SDValue();
6728 } else if (!(isNullConstant(Op->getOperand(i)) ||
6729 Op->getOperand(i).isUndef()))
6730 return SDValue();
6731 }
6732 unsigned EltSize = Op->getSimpleValueType(0).getScalarSizeInBits();
6733 unsigned ExtVTSize = EltSize * Delta;
6734 EltType = MVT::getIntegerVT(ExtVTSize);
6735 NumElt = NumElts / Delta;
6736 return ExtValue;
6737}
6738
6739/// Attempt to use the vbroadcast instruction to generate a splat value
6740/// from a splat BUILD_VECTOR which uses:
6741/// a. A single scalar load, or a constant.
6742/// b. Repeated pattern of constants (e.g. <0,1,0,1> or <0,1,2,3,0,1,2,3>).
6743///
6744/// The VBROADCAST node is returned when a pattern is found,
6745/// or SDValue() otherwise.
6746static SDValue lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
6747 const X86Subtarget &Subtarget,
6748 SelectionDAG &DAG) {
6749 // VBROADCAST requires AVX.
6750 // TODO: Splats could be generated for non-AVX CPUs using SSE
6751 // instructions, but there's less potential gain for only 128-bit vectors.
6752 if (!Subtarget.hasAVX())
6753 return SDValue();
6754
6755 MVT VT = BVOp->getSimpleValueType(0);
6756 SDLoc dl(BVOp);
6757
6758 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Unsupported vector type for broadcast."
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Unsupported vector type for broadcast.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6759, __extension__ __PRETTY_FUNCTION__))
6759 "Unsupported vector type for broadcast.")(static_cast <bool> ((VT.is128BitVector() || VT.is256BitVector
() || VT.is512BitVector()) && "Unsupported vector type for broadcast."
) ? void (0) : __assert_fail ("(VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) && \"Unsupported vector type for broadcast.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6759, __extension__ __PRETTY_FUNCTION__))
;
6760
6761 BitVector UndefElements;
6762 SDValue Ld = BVOp->getSplatValue(&UndefElements);
6763
6764 // Attempt to use VBROADCASTM
6765 // From this paterrn:
6766 // a. t0 = (zext_i64 (bitcast_i8 v2i1 X))
6767 // b. t1 = (build_vector t0 t0)
6768 //
6769 // Create (VBROADCASTM v2i1 X)
6770 if (Subtarget.hasCDI() && (VT.is512BitVector() || Subtarget.hasVLX())) {
6771 MVT EltType = VT.getScalarType();
6772 unsigned NumElts = VT.getVectorNumElements();
6773 SDValue BOperand;
6774 SDValue ZeroExtended = isSplatZeroExtended(BVOp, NumElts, EltType);
6775 if ((ZeroExtended && ZeroExtended.getOpcode() == ISD::BITCAST) ||
6776 (Ld && Ld.getOpcode() == ISD::ZERO_EXTEND &&
6777 Ld.getOperand(0).getOpcode() == ISD::BITCAST)) {
6778 if (ZeroExtended)
6779 BOperand = ZeroExtended.getOperand(0);
6780 else
6781 BOperand = Ld.getOperand(0).getOperand(0);
6782 if (BOperand.getValueType().isVector() &&
6783 BOperand.getSimpleValueType().getVectorElementType() == MVT::i1) {
6784 if ((EltType == MVT::i64 && (VT.getVectorElementType() == MVT::i8 ||
6785 NumElts == 8)) || // for broadcastmb2q
6786 (EltType == MVT::i32 && (VT.getVectorElementType() == MVT::i16 ||
6787 NumElts == 16))) { // for broadcastmw2d
6788 SDValue Brdcst =
6789 DAG.getNode(X86ISD::VBROADCASTM, dl,
6790 MVT::getVectorVT(EltType, NumElts), BOperand);
6791 return DAG.getBitcast(VT, Brdcst);
6792 }
6793 }
6794 }
6795 }
6796
6797 // We need a splat of a single value to use broadcast, and it doesn't
6798 // make any sense if the value is only in one element of the vector.
6799 if (!Ld || (VT.getVectorNumElements() - UndefElements.count()) <= 1) {
6800 APInt SplatValue, Undef;
6801 unsigned SplatBitSize;
6802 bool HasUndef;
6803 // Check if this is a repeated constant pattern suitable for broadcasting.
6804 if (BVOp->isConstantSplat(SplatValue, Undef, SplatBitSize, HasUndef) &&
6805 SplatBitSize > VT.getScalarSizeInBits() &&
6806 SplatBitSize < VT.getSizeInBits()) {
6807 // Avoid replacing with broadcast when it's a use of a shuffle
6808 // instruction to preserve the present custom lowering of shuffles.
6809 if (isUseOfShuffle(BVOp) || BVOp->hasOneUse())
6810 return SDValue();
6811 // replace BUILD_VECTOR with broadcast of the repeated constants.
6812 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6813 LLVMContext *Ctx = DAG.getContext();
6814 MVT PVT = TLI.getPointerTy(DAG.getDataLayout());
6815 if (Subtarget.hasAVX()) {
6816 if (SplatBitSize <= 64 && Subtarget.hasAVX2() &&
6817 !(SplatBitSize == 64 && Subtarget.is32Bit())) {
6818 // Splatted value can fit in one INTEGER constant in constant pool.
6819 // Load the constant and broadcast it.
6820 MVT CVT = MVT::getIntegerVT(SplatBitSize);
6821 Type *ScalarTy = Type::getIntNTy(*Ctx, SplatBitSize);
6822 Constant *C = Constant::getIntegerValue(ScalarTy, SplatValue);
6823 SDValue CP = DAG.getConstantPool(C, PVT);
6824 unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
6825
6826 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6827 Ld = DAG.getLoad(
6828 CVT, dl, DAG.getEntryNode(), CP,
6829 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
6830 Alignment);
6831 SDValue Brdcst = DAG.getNode(X86ISD::VBROADCAST, dl,
6832 MVT::getVectorVT(CVT, Repeat), Ld);
6833 return DAG.getBitcast(VT, Brdcst);
6834 } else if (SplatBitSize == 32 || SplatBitSize == 64) {
6835 // Splatted value can fit in one FLOAT constant in constant pool.
6836 // Load the constant and broadcast it.
6837 // AVX have support for 32 and 64 bit broadcast for floats only.
6838 // No 64bit integer in 32bit subtarget.
6839 MVT CVT = MVT::getFloatingPointVT(SplatBitSize);
6840 // Lower the splat via APFloat directly, to avoid any conversion.
6841 Constant *C =
6842 SplatBitSize == 32
6843 ? ConstantFP::get(*Ctx,
6844 APFloat(APFloat::IEEEsingle(), SplatValue))
6845 : ConstantFP::get(*Ctx,
6846 APFloat(APFloat::IEEEdouble(), SplatValue));
6847 SDValue CP = DAG.getConstantPool(C, PVT);
6848 unsigned Repeat = VT.getSizeInBits() / SplatBitSize;
6849
6850 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6851 Ld = DAG.getLoad(
6852 CVT, dl, DAG.getEntryNode(), CP,
6853 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
6854 Alignment);
6855 SDValue Brdcst = DAG.getNode(X86ISD::VBROADCAST, dl,
6856 MVT::getVectorVT(CVT, Repeat), Ld);
6857 return DAG.getBitcast(VT, Brdcst);
6858 } else if (SplatBitSize > 64) {
6859 // Load the vector of constants and broadcast it.
6860 MVT CVT = VT.getScalarType();
6861 Constant *VecC = getConstantVector(VT, SplatValue, SplatBitSize,
6862 *Ctx);
6863 SDValue VCP = DAG.getConstantPool(VecC, PVT);
6864 unsigned NumElm = SplatBitSize / VT.getScalarSizeInBits();
6865 unsigned Alignment = cast<ConstantPoolSDNode>(VCP)->getAlignment();
6866 Ld = DAG.getLoad(
6867 MVT::getVectorVT(CVT, NumElm), dl, DAG.getEntryNode(), VCP,
6868 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
6869 Alignment);
6870 SDValue Brdcst = DAG.getNode(X86ISD::SUBV_BROADCAST, dl, VT, Ld);
6871 return DAG.getBitcast(VT, Brdcst);
6872 }
6873 }
6874 }
6875 return SDValue();
6876 }
6877
6878 bool ConstSplatVal =
6879 (Ld.getOpcode() == ISD::Constant || Ld.getOpcode() == ISD::ConstantFP);
6880
6881 // Make sure that all of the users of a non-constant load are from the
6882 // BUILD_VECTOR node.
6883 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6884 return SDValue();
6885
6886 unsigned ScalarSize = Ld.getValueSizeInBits();
6887 bool IsGE256 = (VT.getSizeInBits() >= 256);
6888
6889 // When optimizing for size, generate up to 5 extra bytes for a broadcast
6890 // instruction to save 8 or more bytes of constant pool data.
6891 // TODO: If multiple splats are generated to load the same constant,
6892 // it may be detrimental to overall size. There needs to be a way to detect
6893 // that condition to know if this is truly a size win.
6894 bool OptForSize = DAG.getMachineFunction().getFunction()->optForSize();
6895
6896 // Handle broadcasting a single constant scalar from the constant pool
6897 // into a vector.
6898 // On Sandybridge (no AVX2), it is still better to load a constant vector
6899 // from the constant pool and not to broadcast it from a scalar.
6900 // But override that restriction when optimizing for size.
6901 // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6902 if (ConstSplatVal && (Subtarget.hasAVX2() || OptForSize)) {
6903 EVT CVT = Ld.getValueType();
6904 assert(!CVT.isVector() && "Must not broadcast a vector type")(static_cast <bool> (!CVT.isVector() && "Must not broadcast a vector type"
) ? void (0) : __assert_fail ("!CVT.isVector() && \"Must not broadcast a vector type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6904, __extension__ __PRETTY_FUNCTION__))
;
6905
6906 // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6907 // For size optimization, also splat v2f64 and v2i64, and for size opt
6908 // with AVX2, also splat i8 and i16.
6909 // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6910 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6911 (OptForSize && (ScalarSize == 64 || Subtarget.hasAVX2()))) {
6912 const Constant *C = nullptr;
6913 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6914 C = CI->getConstantIntValue();
6915 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6916 C = CF->getConstantFPValue();
6917
6918 assert(C && "Invalid constant type")(static_cast <bool> (C && "Invalid constant type"
) ? void (0) : __assert_fail ("C && \"Invalid constant type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6918, __extension__ __PRETTY_FUNCTION__))
;
6919
6920 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6921 SDValue CP =
6922 DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
6923 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6924 Ld = DAG.getLoad(
6925 CVT, dl, DAG.getEntryNode(), CP,
6926 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
6927 Alignment);
6928
6929 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6930 }
6931 }
6932
6933 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6934
6935 // Handle AVX2 in-register broadcasts.
6936 if (!IsLoad && Subtarget.hasInt256() &&
6937 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6938 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6939
6940 // The scalar source must be a normal load.
6941 if (!IsLoad)
6942 return SDValue();
6943
6944 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6945 (Subtarget.hasVLX() && ScalarSize == 64))
6946 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6947
6948 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6949 // double since there is no vbroadcastsd xmm
6950 if (Subtarget.hasInt256() && Ld.getValueType().isInteger()) {
6951 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6952 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6953 }
6954
6955 // Unsupported broadcast.
6956 return SDValue();
6957}
6958
6959/// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6960/// underlying vector and index.
6961///
6962/// Modifies \p ExtractedFromVec to the real vector and returns the real
6963/// index.
6964static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6965 SDValue ExtIdx) {
6966 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6967 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6968 return Idx;
6969
6970 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6971 // lowered this:
6972 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6973 // to:
6974 // (extract_vector_elt (vector_shuffle<2,u,u,u>
6975 // (extract_subvector (v8f32 %vreg0), Constant<4>),
6976 // undef)
6977 // Constant<0>)
6978 // In this case the vector is the extract_subvector expression and the index
6979 // is 2, as specified by the shuffle.
6980 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6981 SDValue ShuffleVec = SVOp->getOperand(0);
6982 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6983 assert(ShuffleVecVT.getVectorElementType() ==(static_cast <bool> (ShuffleVecVT.getVectorElementType(
) == ExtractedFromVec.getSimpleValueType().getVectorElementType
()) ? void (0) : __assert_fail ("ShuffleVecVT.getVectorElementType() == ExtractedFromVec.getSimpleValueType().getVectorElementType()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6984, __extension__ __PRETTY_FUNCTION__))
6984 ExtractedFromVec.getSimpleValueType().getVectorElementType())(static_cast <bool> (ShuffleVecVT.getVectorElementType(
) == ExtractedFromVec.getSimpleValueType().getVectorElementType
()) ? void (0) : __assert_fail ("ShuffleVecVT.getVectorElementType() == ExtractedFromVec.getSimpleValueType().getVectorElementType()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 6984, __extension__ __PRETTY_FUNCTION__))
;
6985
6986 int ShuffleIdx = SVOp->getMaskElt(Idx);
6987 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6988 ExtractedFromVec = ShuffleVec;
6989 return ShuffleIdx;
6990 }
6991 return Idx;
6992}
6993
6994static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6995 MVT VT = Op.getSimpleValueType();
6996
6997 // Skip if insert_vec_elt is not supported.
6998 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6999 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
7000 return SDValue();
7001
7002 SDLoc DL(Op);
7003 unsigned NumElems = Op.getNumOperands();
7004
7005 SDValue VecIn1;
7006 SDValue VecIn2;
7007 SmallVector<unsigned, 4> InsertIndices;
7008 SmallVector<int, 8> Mask(NumElems, -1);
7009
7010 for (unsigned i = 0; i != NumElems; ++i) {
7011 unsigned Opc = Op.getOperand(i).getOpcode();
7012
7013 if (Opc == ISD::UNDEF)
7014 continue;
7015
7016 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
7017 // Quit if more than 1 elements need inserting.
7018 if (InsertIndices.size() > 1)
7019 return SDValue();
7020
7021 InsertIndices.push_back(i);
7022 continue;
7023 }
7024
7025 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
7026 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
7027
7028 // Quit if non-constant index.
7029 if (!isa<ConstantSDNode>(ExtIdx))
7030 return SDValue();
7031 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
7032
7033 // Quit if extracted from vector of different type.
7034 if (ExtractedFromVec.getValueType() != VT)
7035 return SDValue();
7036
7037 if (!VecIn1.getNode())
7038 VecIn1 = ExtractedFromVec;
7039 else if (VecIn1 != ExtractedFromVec) {
7040 if (!VecIn2.getNode())
7041 VecIn2 = ExtractedFromVec;
7042 else if (VecIn2 != ExtractedFromVec)
7043 // Quit if more than 2 vectors to shuffle
7044 return SDValue();
7045 }
7046
7047 if (ExtractedFromVec == VecIn1)
7048 Mask[i] = Idx;
7049 else if (ExtractedFromVec == VecIn2)
7050 Mask[i] = Idx + NumElems;
7051 }
7052
7053 if (!VecIn1.getNode())
7054 return SDValue();
7055
7056 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
7057 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, Mask);
7058
7059 for (unsigned Idx : InsertIndices)
7060 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
7061 DAG.getIntPtrConstant(Idx, DL));
7062
7063 return NV;
7064}
7065
7066static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
7067 assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&(static_cast <bool> (ISD::isBuildVectorOfConstantSDNodes
(Op.getNode()) && Op.getScalarValueSizeInBits() == 1 &&
"Can not convert non-constant vector") ? void (0) : __assert_fail
("ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && Op.getScalarValueSizeInBits() == 1 && \"Can not convert non-constant vector\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 7069, __extension__ __PRETTY_FUNCTION__))
7068 Op.getScalarValueSizeInBits() == 1 &&(static_cast <bool> (ISD::isBuildVectorOfConstantSDNodes
(Op.getNode()) && Op.getScalarValueSizeInBits() == 1 &&
"Can not convert non-constant vector") ? void (0) : __assert_fail
("ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && Op.getScalarValueSizeInBits() == 1 && \"Can not convert non-constant vector\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 7069, __extension__ __PRETTY_FUNCTION__))
7069 "Can not convert non-constant vector")(static_cast <bool> (ISD::isBuildVectorOfConstantSDNodes
(Op.getNode()) && Op.getScalarValueSizeInBits() == 1 &&
"Can not convert non-constant vector") ? void (0) : __assert_fail
("ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && Op.getScalarValueSizeInBits() == 1 && \"Can not convert non-constant vector\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 7069, __extension__ __PRETTY_FUNCTION__))
;
7070 uint64_t Immediate = 0;
7071 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
7072 SDValue In = Op.getOperand(idx);
7073 if (!In.isUndef())
7074 Immediate |= (cast<ConstantSDNode>(In)->getZExtValue() & 0x1) << idx;
7075 }
7076 SDLoc dl(Op);
7077 MVT VT = MVT::getIntegerVT(std::max((int)Op.getValueSizeInBits(), 8));
7078 return DAG.getConstant(Immediate, dl, VT);
7079}
7080// Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
7081SDValue
7082X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
7083
7084 MVT VT = Op.getSimpleValueType();
7085 assert((VT.getVectorElementType() == MVT::i1) &&(static_cast <bool> ((VT.getVectorElementType() == MVT::
i1) && "Unexpected type in LowerBUILD_VECTORvXi1!") ?
void (0) : __assert_fail ("(VT.getVectorElementType() == MVT::i1) && \"Unexpected type in LowerBUILD_VECTORvXi1!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 7086, __extension__ __PRETTY_FUNCTION__))
7086 "Unexpected type in LowerBUILD_VECTORvXi1!")(static_cast <bool> ((VT.getVectorElementType() == MVT::
i1) && "Unexpected type in LowerBUILD_VECTORvXi1!") ?
void (0) : __assert_fail ("(VT.getVectorElementType() == MVT::i1) && \"Unexpected type in LowerBUILD_VECTORvXi1!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 7086, __extension__ __PRETTY_FUNCTION__))
;
7087
7088 SDLoc dl(Op);
7089 if (ISD::isBuildVectorAllZeros(Op.getNode()))
7090 return DAG.getTargetConstant(0, dl, VT);
7091
7092 if (ISD::isBuildVectorAllOnes(Op.getNode()))
7093 return DAG.getTargetConstant(1, dl, VT);
7094
7095 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
7096 if (VT == MVT::v64i1 && !Subtarget.is64Bit()) {
7097 // Split the pieces.
7098 SDValue Lower =
7099 DAG.getBuildVector(MVT::v32i1, dl, Op.getNode()->ops().slice(0, 32));
7100 SDValue Upper =
7101 DAG.getBuildVector(MVT::v32i1, dl, Op.getNode()->ops().slice(32, 32));
7102 // We have to manually lower both halves so getNode doesn't try to
7103 // reassemble the build_vector.
7104 Lower = LowerBUILD_VECTORvXi1(Lower, DAG);
7105 Upper = LowerBUILD_VECTORvXi1(Upper, DAG);
7106 return DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v64i1, Lower, Upper);
7107 }
7108 SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
7109 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
7110 return DAG.getBitcast(VT, Imm);
7111 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
7112 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
7113 DAG.getIntPtrConstant(0, dl));
7114 }
7115
7116 // Vector has one or more non-const elements
7117 uint64_t Immediate = 0;
7118 SmallVector<unsigned, 16> NonConstIdx;
7119 bool IsSplat = true;
7120 bool HasConstElts = false;
7121 int SplatIdx = -1;
7122 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
7123 SDValue In = Op.getOperand(idx);
7124 if (In.isUndef())
7125 continue;
7126 if (!isa<ConstantSDNode>(In))
7127 NonConstIdx.push_back(idx);
7128 else {
7129 Immediate |= (cast<ConstantSDNode>(In)->getZExtValue() & 0x1) << idx;
7130 HasConstElts = true;
7131 }
7132 if (SplatIdx < 0)
7133 SplatIdx = idx;
7134 else if (In != Op.getOperand(SplatIdx))
7135 IsSplat = false;
7136 }
7137
7138 // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
7139 if (IsSplat)
7140 return DAG.getSelect(dl, VT, Op.getOperand(SplatIdx),
7141 DAG.getConstant(1, dl, VT),
7142 DAG.getConstant(0, dl, VT));
7143
7144 // insert elements one by one
7145 SDValue DstVec;
7146 SDValue Imm;
7147 if (Immediate) {
7148 MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
7149 Imm = DAG.getConstant(Immediate, dl, ImmVT);
7150 }
7151 else if (HasConstElts)
7152 Imm = DAG.getConstant(0, dl, VT);
7153 else
7154 Imm = DAG.getUNDEF(VT);
7155 if (Imm.getValueSizeInBits() == VT.getSizeInBits())
7156 DstVec = DAG.getBitcast(VT, Imm);
7157 else {
7158 SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
7159 DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
7160 DAG.getIntPtrConstant(0, dl));
7161 }
7162
7163 for (unsigned i = 0, e = NonConstIdx.size(); i != e; ++i) {
7164 unsigned InsertIdx = NonConstIdx[i];
7165 DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
7166 Op.getOperand(InsertIdx),
7167 DAG.getIntPtrConstant(InsertIdx, dl));
7168 }
7169 return DstVec;
7170}
7171
7172/// \brief Return true if \p N implements a horizontal binop and return the
7173/// operands for the horizontal binop into V0 and V1.
7174///
7175/// This is a helper function of LowerToHorizontalOp().
7176/// This function checks that the build_vector \p N in input implements a
7177/// horizontal operation. Parameter \p Opcode defines the kind of horizontal
7178/// operation to match.
7179/// For example, if \p Opcode is equal to ISD::ADD, then this function
7180/// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
7181/// is equal to ISD::SUB, then this function checks if this is a horizontal
7182/// arithmetic sub.
7183///
7184/// This function only analyzes elements of \p N whose indices are
7185/// in range [BaseIdx, LastIdx).
7186static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
7187 SelectionDAG &DAG,
7188 unsigned BaseIdx, unsigned LastIdx,
7189 SDValue &V0, SDValue &V1) {
7190 EVT VT = N->getValueType(0);
7191
7192 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!")(static_cast <bool> (BaseIdx * 2 <= LastIdx &&
"Invalid Indices in input!") ? void (0) : __assert_fail ("BaseIdx * 2 <= LastIdx && \"Invalid Indices in input!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 7192, __extension__ __PRETTY_FUNCTION__))
;
7193 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&(static_cast <bool> (VT.isVector() && VT.getVectorNumElements
() >= LastIdx && "Invalid Vector in input!") ? void
(0) : __assert_fail ("VT.isVector() && VT.getVectorNumElements() >= LastIdx && \"Invalid Vector in input!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 7194, __extension__ __PRETTY_FUNCTION__))
7194 "Invalid Vector in input!")(static_cast <bool> (VT.isVector() && VT.getVectorNumElements
() >= LastIdx && "Invalid Vector in input!") ? void
(0) : __assert_fail ("VT.isVector() && VT.getVectorNumElements() >= LastIdx && \"Invalid Vector in input!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 7194, __extension__ __PRETTY_FUNCTION__))
;
7195
7196 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
7197 bool CanFold = true;
7198 unsigned ExpectedVExtractIdx = BaseIdx;
7199 unsigned NumElts = LastIdx - BaseIdx;
7200 V0 = DAG.getUNDEF(VT);
7201 V1 = DAG.getUNDEF(VT);
7202
7203 // Check if N implements a horizontal binop.
7204 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
7205 SDValue Op = N->getOperand(i + BaseIdx);
7206
7207 // Skip UNDEFs.
7208 if (Op->isUndef()) {
7209 // Update the expected vector extract index.
7210 if (i * 2 == NumElts)
7211 ExpectedVExtractIdx = BaseIdx;
7212 ExpectedVExtractIdx += 2;
7213 continue;
7214 }
7215
7216 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
7217
7218 if (!CanFold)
7219 break;
7220
7221 SDValue Op0 = Op.getOperand(0);
7222 SDValue Op1 = Op.getOperand(1);
7223
7224 // Try to match the following pattern:
7225 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
7226 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7227 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7228 Op0.getOperand(0) == Op1.getOperand(0) &&
7229 isa<ConstantSDNode>(Op0.getOperand(1)) &&
7230 isa<ConstantSDNode>(Op1.getOperand(1)));
7231 if (!CanFold)
7232 break;
7233
7234 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
7235 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
7236
7237 if (i * 2 < NumElts) {
7238 if (V0.isUndef()) {
7239 V0 = Op0.getOperand(0);
7240 if (V0.getValueType() != VT)
7241 return false;
7242 }
7243 } else {
7244 if (V1.isUndef()) {
7245 V1 = Op0.getOperand(0);
7246 if (V1.getValueType() != VT)
7247 return false;
7248 }
7249 if (i * 2 == NumElts)
7250 ExpectedVExtractIdx = BaseIdx;
7251 }
7252
7253 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
7254 if (I0 == ExpectedVExtractIdx)
7255 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
7256 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
7257 // Try to match the following dag sequence:
7258 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
7259 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
7260 } else
7261 CanFold = false;
7262
7263 ExpectedVExtractIdx += 2;
7264 }
7265
7266 return CanFold;
7267}
7268
7269/// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
7270/// a concat_vector.
7271///
7272/// This is a helper function of LowerToHorizontalOp().
7273/// This function expects two 256-bit vectors called V0 and V1.
7274/// At first, each vector is split into two separate 128-bit vectors.
7275/// Then, the resulting 128-bit vectors are used to implement two
7276/// horizontal binary operations.
7277///
7278/// The kind of horizontal binary operation is defined by \p X86Opcode.
7279///
7280/// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
7281/// the two new horizontal binop.
7282/// When Mode is set, the first horizontal binop dag node would take as input
7283/// the lower 128-bit of V0 and the upper 128-bit of V0. The second
7284/// horizontal binop dag node would take as input the lower 128-bit of V1
7285/// and the upper 128-bit of V1.
7286/// Example:
7287/// HADD V0_LO, V0_HI
7288/// HADD V1_LO, V1_HI
7289///
7290/// Otherwise, the first horizontal binop dag node takes as input the lower
7291/// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
7292/// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
7293/// Example:
7294/// HADD V0_LO, V1_LO
7295/// HADD V0_HI, V1_HI
7296///
7297/// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
7298/// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
7299/// the upper 128-bits of the result.
7300static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
7301 const SDLoc &DL, SelectionDAG &DAG,
7302 unsigned X86Opcode, bool Mode,
7303 bool isUndefLO, bool isUndefHI) {
7304 MVT VT = V0.getSimpleValueType();
7305 assert(VT.is256BitVector() && VT == V1.getSimpleValueType() &&(static_cast <bool> (VT.is256BitVector() && VT ==
V1.getSimpleValueType() && "Invalid nodes in input!"
) ? void (0) : __assert_fail ("VT.is256BitVector() && VT == V1.getSimpleValueType() && \"Invalid nodes in input!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 7306, __extension__ __PRETTY_FUNCTION__))
7306 "Invalid nodes in input!")(static_cast <bool> (VT.is256BitVector() && VT ==
V1.getSimpleValueType() && "Invalid nodes in input!"
) ? void (0) : __assert_fail ("VT.is256BitVector() && VT == V1.getSimpleValueType() && \"Invalid nodes in input!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/lib/Target/X86/X86ISelLowering.cpp"
, 7306, __extension__ __PRETTY_FUNCTION__))
;
7307
7308 unsigned NumElts = VT.getVectorNumElements();
7309 SDValue V0_LO = extract128BitVector(V0, 0, DAG, DL);
7310 SDValue V0_HI = extract128BitVector(V0, NumElts/2, DAG, DL);
7311 SDValue V1_LO = extract128BitVector(V1, 0, DAG, DL);
7312 SDValue V1_HI = extract128BitVector(V1, NumElts/2, DAG, DL);
7313 MVT NewVT = V0_LO.getSimpleValueType();
7314
7315 SDValue LO = DAG.getUNDEF(NewVT);
7316 SDValue HI = DAG.getUNDEF(NewVT);
7317
7318 if (Mode) {
7319 // Don't emit a horizontal binop if the result is expected to be UNDEF.
7320 if (!isUndefLO && !V0->isUndef())
7321 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
7322 if (!isUndefHI && !V1->isUndef())
7323 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
7324 } else {
7325 // Don't emit a horizontal binop if the result is expected to be UNDEF.
7326 if (!isUndefLO && (!V0_LO->isUndef() || !V1_LO->isUndef()))
7327 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
7328
7329 if (!isUndefHI && (!V0_HI->isUndef() || !V1_HI->isUndef()))
7330 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
7331 }
7332
7333 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
7334}
7335
7336/// Returns true iff \p BV builds a vector with the result equivalent to
7337/// the result of ADDSUB operation.
7338/// If true is returned then the operands of ADDSUB = Opnd0 +- Opnd1 operation
7339/// are written to the parameters \p Opnd0 and \p Opnd1.
7340static bool isAddSub(const BuildVectorSDNode *BV,
7341 const X86Subtarget &Subtarget, SelectionDAG &DAG,
7342 SDValue &Opnd0, SDValue &Opnd1) {
7343
7344 MVT VT = BV->getSimpleValueType(0);
7345 if ((!Subtarget.hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
7346 (!Subtarget.hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)) &&
7347 (!Subtarget.hasAVX512() || (VT != MVT::v16f32 && VT != MVT::v8f64)))
7348 return false;
7349
7350 unsigned NumElts = VT.getVectorNumElements();
7351 SDValue InVec0 = DAG.getUNDEF(VT);
7352 SDValue InVec1 = DAG.getUNDEF(VT);
7353
7354 // Odd-numbered elements in the input build vector are obtained from
7355 // adding two integer/float elements.
7356 // Even-numbered elements in the input build vector are obtained from
7357 // subtracting two integer/float elements.
7358 unsigned ExpectedOpcode = ISD::FSUB;
7359 unsigned NextExpectedOpcode = ISD::FADD;
7360 bool AddFound = false;
7361 bool SubFound = false;
7362
7363 for (unsigned i = 0, e = NumElts; i != e; ++i) {
7364 SDValue Op = BV->getOperand(i);
7365
7366 // Skip 'undef' values.
7367 unsigned Opcode = Op.getOpcode();
7368 if (Opcode == ISD::UNDEF) {
7369 std::swap(ExpectedOpcode, NextExpectedOpcode);
7370 continue;
7371 }
7372
7373 // Early exit if we found an unexpected opcode.
7374 if (Opcode != ExpectedOpcode)
7375 return false;
7376
7377 SDValue Op0 = Op.getOperand(0);
7378 SDValue Op1 = Op.getOperand(1);
7379
7380 // Try to match the following pattern:
7381 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
7382 // Early exit if we cannot match that sequence.
7383 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7384 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7385 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
7386 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
7387 Op0.getOperand(1) != Op1.getOperand(1))
7388 return false;
7389
7390 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
7391 if (I0 != i)
7392 return false;
7393
7394 // We found a valid add/sub node. Update the information accordingly.
7395 if (i & 1)
7396 AddFound = true;
7397 else
7398 SubFound = true;
7399
7400 // Update InVec0 and InVec1.
7401 if (InVec0.isUndef()) {
7402 InVec0 = Op0.getOperand(0);
7403 if (InVec0.getSimpleValueType() != VT)
7404 return false;
7405 }
7406 if (InVec1.isUndef()) {
7407 InVec1 = Op1.getOperand(0);
7408 if (InVec1.getSimpleValueType() != VT)
7409 return false;
7410 }
7411
7412 // Make sure that operands in input to each add/sub node always
7413 // come from a same pair of vectors.
7414 if (InVec0 != Op0.getOperand(0)) {
7415 if (ExpectedOpcode == ISD::FSUB)
7416 return false;
7417
7418 // FADD is commutable. Try to commute the operands
7419 // and then test again.
7420 std::swap(Op0, Op1);
7421 if (InVec0 != Op0.getOperand(0))
7422 return false;
7423 }
7424
7425 if (InVec1 != Op1.getOperand(0))
7426 return false;
7427
7428 // Update the pair of expected opcodes.
7429 std::swap(ExpectedOpcode, NextExpectedOpcode);
7430 }
7431
7432 // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
7433 if (!AddFound || !SubFound || InVec0.isUndef() || InVec1.isUndef())
7434 return false;
7435
7436 Opnd0 = InVec0;
7437 Opnd1 = InVec1;
7438 return true;
7439}
7440
7441/// Returns true if is possible to fold MUL and an idiom that has already been
7442/// recognized as ADDSUB(\p Opnd0, \p Opnd1) into FMADDSUB(x, y, \p Opnd1).
7443/// If (and only if) true is returned, the operands of FMADDSUB are written to
7444/// parameters \p Opnd0, \p Opnd1, \p Opnd2.
7445///
7446/// Prior to calling this function it should be known that there is some
7447/// SDNode that potentially can be replaced with an X86ISD::ADDSUB operation
7448/// using \p Opnd0 and \p Opnd1 as operands. Also, this method is called
7449/// before replacement of such SDNode with ADDSUB operation. Thus the number
7450/// of \p Opnd0 uses is expected to be equal to 2.
7451/// For example, this function may be called for the following IR:
7452/// %AB = fmul fast <2 x double> %A, %B
7453/// %Sub = fsub fast <2 x double> %AB, %C
7454/// %Add = fadd fast <2 x double> %AB, %C
7455/// %Addsub = shufflevector <2 x double> %Sub, <2 x double> %Add,
7456/// <2 x i32> <i32 0, i32 3>
7457/// There is a def for %Addsub here, which potentially can be replaced by
7458/// X86ISD::ADDSUB operation:
7459/// %Addsub = X86ISD::ADDSUB %AB, %C
7460/// and such ADDSUB can further be replaced with FMADDSUB:
7461/// %Addsub = FMADDSUB %A, %B, %C.
7462///
7463/// The main reason why this method is called before the replacement of the
7464/// recognized ADDSUB idiom with ADDSUB operation is that such replacement
7465/// is illegal sometimes. E.g. 512-bit ADDSUB is not available, while 512-bit
7466/// FMADDSUB is.
7467static bool isFMAddSub(const X86Subtarget &Subtarget, SelectionDAG &DAG,
7468 SDValue &Opnd0, SDValue &Opnd1, SDValue &Opnd2) {
7469 if (Opnd0.getOpcode() != ISD::FMUL || Opnd0->use_size() != 2 ||
7470 !Subtarget.hasAnyFMA())
7471 return false;
7472
7473 // FIXME: These checks must match the similar ones in
7474 // DAGCombiner::visitFADDForFMACombine. It would be good to have one
7475 // function that would answer if it is Ok to fuse MUL + ADD to FMADD
7476 // or MUL + ADDSUB to FMADDSUB.
7477 const TargetOptions &Options = DAG.getTarget().Options;
7478 bool AllowFusion =
7479 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7480 if (!AllowFusion)
7481 return false;
7482
7483 Opnd2 = Opnd1;
7484 Opnd1 = Opnd0.getOperand(1);
7485 Opnd0 = Opnd0.getOperand(0);
7486
7487 return true;
7488}
7489
7490/// Try to fold a build_vector that performs an 'addsub' or 'fmaddsub' operation
7491/// accordingly to X86ISD::ADDSUB or X86ISD::FMADDSUB node.
7492static SDValue lowerToAddSubOrFMAddSub(const BuildVectorSDNode *BV,
7493 const X86Subtarget &Subtarget,
7494 SelectionDAG &DAG) {
7495 SDValue Opnd0, Opnd1;
7496 if (!isAddSub(BV, Subtarget, DAG, Opnd0, Opnd1))
7497 return SDValue();
7498
7499 MVT VT = BV->getSimpleValueType(0);
7500 SDLoc DL(BV);
7501
7502 // Try to generate X86ISD::FMADDSUB node here.
7503 SDValue Opnd2;
7504 if (isFMAddSub(Subtarget, DAG, Opnd0, Opnd1, Opnd2))
7505 return DAG.getNode(X86ISD::FMADDSUB, DL, VT, Opnd0, Opnd1, Opnd2);
7506
7507