Bug Summary

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

Annotated Source Code

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