Bug Summary

File:lib/Target/X86/X86ISelLowering.cpp
Warning:line 27192, column 5
Value stored to 'AllowIntDomain' is never read

Annotated Source Code

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