Bug Summary

File:lib/Target/X86/X86FastISel.cpp
Warning:line 2503, column 5
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name X86FastISel.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/lib/Target/X86 -I /build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86 -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/lib/Target/X86 -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp -faddrsig
1//===-- X86FastISel.cpp - X86 FastISel 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 X86-specific support for the FastISel class. Much
11// of the target-specific code is generated by tablegen in the file
12// X86GenFastISel.inc, which is #included here.
13//
14//===----------------------------------------------------------------------===//
15
16#include "X86.h"
17#include "X86CallingConv.h"
18#include "X86InstrBuilder.h"
19#include "X86InstrInfo.h"
20#include "X86MachineFunctionInfo.h"
21#include "X86RegisterInfo.h"
22#include "X86Subtarget.h"
23#include "X86TargetMachine.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
25#include "llvm/CodeGen/FastISel.h"
26#include "llvm/CodeGen/FunctionLoweringInfo.h"
27#include "llvm/CodeGen/MachineConstantPool.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/IR/CallSite.h"
31#include "llvm/IR/CallingConv.h"
32#include "llvm/IR/DebugInfo.h"
33#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/GetElementPtrTypeIterator.h"
35#include "llvm/IR/GlobalAlias.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/Operator.h"
40#include "llvm/MC/MCAsmInfo.h"
41#include "llvm/MC/MCSymbol.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Target/TargetOptions.h"
44using namespace llvm;
45
46namespace {
47
48class X86FastISel final : public FastISel {
49 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
50 /// make the right decision when generating code for different targets.
51 const X86Subtarget *Subtarget;
52
53 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
54 /// floating point ops.
55 /// When SSE is available, use it for f32 operations.
56 /// When SSE2 is available, use it for f64 operations.
57 bool X86ScalarSSEf64;
58 bool X86ScalarSSEf32;
59
60public:
61 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
62 const TargetLibraryInfo *libInfo)
63 : FastISel(funcInfo, libInfo) {
64 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
65 X86ScalarSSEf64 = Subtarget->hasSSE2();
66 X86ScalarSSEf32 = Subtarget->hasSSE1();
67 }
68
69 bool fastSelectInstruction(const Instruction *I) override;
70
71 /// The specified machine instr operand is a vreg, and that
72 /// vreg is being provided by the specified load instruction. If possible,
73 /// try to fold the load as an operand to the instruction, returning true if
74 /// possible.
75 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
76 const LoadInst *LI) override;
77
78 bool fastLowerArguments() override;
79 bool fastLowerCall(CallLoweringInfo &CLI) override;
80 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
81
82#include "X86GenFastISel.inc"
83
84private:
85 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
86 const DebugLoc &DL);
87
88 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
89 unsigned &ResultReg, unsigned Alignment = 1);
90
91 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
92 MachineMemOperand *MMO = nullptr, bool Aligned = false);
93 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
94 X86AddressMode &AM,
95 MachineMemOperand *MMO = nullptr, bool Aligned = false);
96
97 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
98 unsigned &ResultReg);
99
100 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
101 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
102
103 bool X86SelectLoad(const Instruction *I);
104
105 bool X86SelectStore(const Instruction *I);
106
107 bool X86SelectRet(const Instruction *I);
108
109 bool X86SelectCmp(const Instruction *I);
110
111 bool X86SelectZExt(const Instruction *I);
112
113 bool X86SelectSExt(const Instruction *I);
114
115 bool X86SelectBranch(const Instruction *I);
116
117 bool X86SelectShift(const Instruction *I);
118
119 bool X86SelectDivRem(const Instruction *I);
120
121 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
122
123 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
124
125 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
126
127 bool X86SelectSelect(const Instruction *I);
128
129 bool X86SelectTrunc(const Instruction *I);
130
131 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
132 const TargetRegisterClass *RC);
133
134 bool X86SelectFPExt(const Instruction *I);
135 bool X86SelectFPTrunc(const Instruction *I);
136 bool X86SelectSIToFP(const Instruction *I);
137 bool X86SelectUIToFP(const Instruction *I);
138 bool X86SelectIntToFP(const Instruction *I, bool IsSigned);
139
140 const X86InstrInfo *getInstrInfo() const {
141 return Subtarget->getInstrInfo();
142 }
143 const X86TargetMachine *getTargetMachine() const {
144 return static_cast<const X86TargetMachine *>(&TM);
145 }
146
147 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
148
149 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
150 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
151 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
152 unsigned fastMaterializeConstant(const Constant *C) override;
153
154 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
155
156 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
157
158 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
159 /// computed in an SSE register, not on the X87 floating point stack.
160 bool isScalarFPTypeInSSEReg(EVT VT) const {
161 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
162 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
163 }
164
165 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
166
167 bool IsMemcpySmall(uint64_t Len);
168
169 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
170 X86AddressMode SrcAM, uint64_t Len);
171
172 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
173 const Value *Cond);
174
175 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
176 X86AddressMode &AM);
177
178 unsigned fastEmitInst_rrrr(unsigned MachineInstOpcode,
179 const TargetRegisterClass *RC, unsigned Op0,
180 bool Op0IsKill, unsigned Op1, bool Op1IsKill,
181 unsigned Op2, bool Op2IsKill, unsigned Op3,
182 bool Op3IsKill);
183};
184
185} // end anonymous namespace.
186
187static std::pair<unsigned, bool>
188getX86SSEConditionCode(CmpInst::Predicate Predicate) {
189 unsigned CC;
190 bool NeedSwap = false;
191
192 // SSE Condition code mapping:
193 // 0 - EQ
194 // 1 - LT
195 // 2 - LE
196 // 3 - UNORD
197 // 4 - NEQ
198 // 5 - NLT
199 // 6 - NLE
200 // 7 - ORD
201 switch (Predicate) {
202 default: llvm_unreachable("Unexpected predicate")::llvm::llvm_unreachable_internal("Unexpected predicate", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 202)
;
203 case CmpInst::FCMP_OEQ: CC = 0; break;
204 case CmpInst::FCMP_OGT: NeedSwap = true; LLVM_FALLTHROUGH[[clang::fallthrough]];
205 case CmpInst::FCMP_OLT: CC = 1; break;
206 case CmpInst::FCMP_OGE: NeedSwap = true; LLVM_FALLTHROUGH[[clang::fallthrough]];
207 case CmpInst::FCMP_OLE: CC = 2; break;
208 case CmpInst::FCMP_UNO: CC = 3; break;
209 case CmpInst::FCMP_UNE: CC = 4; break;
210 case CmpInst::FCMP_ULE: NeedSwap = true; LLVM_FALLTHROUGH[[clang::fallthrough]];
211 case CmpInst::FCMP_UGE: CC = 5; break;
212 case CmpInst::FCMP_ULT: NeedSwap = true; LLVM_FALLTHROUGH[[clang::fallthrough]];
213 case CmpInst::FCMP_UGT: CC = 6; break;
214 case CmpInst::FCMP_ORD: CC = 7; break;
215 case CmpInst::FCMP_UEQ: CC = 8; break;
216 case CmpInst::FCMP_ONE: CC = 12; break;
217 }
218
219 return std::make_pair(CC, NeedSwap);
220}
221
222/// Adds a complex addressing mode to the given machine instr builder.
223/// Note, this will constrain the index register. If its not possible to
224/// constrain the given index register, then a new one will be created. The
225/// IndexReg field of the addressing mode will be updated to match in this case.
226const MachineInstrBuilder &
227X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
228 X86AddressMode &AM) {
229 // First constrain the index register. It needs to be a GR64_NOSP.
230 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
231 MIB->getNumOperands() +
232 X86::AddrIndexReg);
233 return ::addFullAddress(MIB, AM);
234}
235
236/// Check if it is possible to fold the condition from the XALU intrinsic
237/// into the user. The condition code will only be updated on success.
238bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
239 const Value *Cond) {
240 if (!isa<ExtractValueInst>(Cond))
241 return false;
242
243 const auto *EV = cast<ExtractValueInst>(Cond);
244 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
245 return false;
246
247 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
248 MVT RetVT;
249 const Function *Callee = II->getCalledFunction();
250 Type *RetTy =
251 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
252 if (!isTypeLegal(RetTy, RetVT))
253 return false;
254
255 if (RetVT != MVT::i32 && RetVT != MVT::i64)
256 return false;
257
258 X86::CondCode TmpCC;
259 switch (II->getIntrinsicID()) {
260 default: return false;
261 case Intrinsic::sadd_with_overflow:
262 case Intrinsic::ssub_with_overflow:
263 case Intrinsic::smul_with_overflow:
264 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
265 case Intrinsic::uadd_with_overflow:
266 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
267 }
268
269 // Check if both instructions are in the same basic block.
270 if (II->getParent() != I->getParent())
271 return false;
272
273 // Make sure nothing is in the way
274 BasicBlock::const_iterator Start(I);
275 BasicBlock::const_iterator End(II);
276 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
277 // We only expect extractvalue instructions between the intrinsic and the
278 // instruction to be selected.
279 if (!isa<ExtractValueInst>(Itr))
280 return false;
281
282 // Check that the extractvalue operand comes from the intrinsic.
283 const auto *EVI = cast<ExtractValueInst>(Itr);
284 if (EVI->getAggregateOperand() != II)
285 return false;
286 }
287
288 CC = TmpCC;
289 return true;
290}
291
292bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
293 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
294 if (evt == MVT::Other || !evt.isSimple())
295 // Unhandled type. Halt "fast" selection and bail.
296 return false;
297
298 VT = evt.getSimpleVT();
299 // For now, require SSE/SSE2 for performing floating-point operations,
300 // since x87 requires additional work.
301 if (VT == MVT::f64 && !X86ScalarSSEf64)
302 return false;
303 if (VT == MVT::f32 && !X86ScalarSSEf32)
304 return false;
305 // Similarly, no f80 support yet.
306 if (VT == MVT::f80)
307 return false;
308 // We only handle legal types. For example, on x86-32 the instruction
309 // selector contains all of the 64-bit instructions from x86-64,
310 // under the assumption that i64 won't be used if the target doesn't
311 // support it.
312 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
313}
314
315#include "X86GenCallingConv.inc"
316
317/// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
318/// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
319/// Return true and the result register by reference if it is possible.
320bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
321 MachineMemOperand *MMO, unsigned &ResultReg,
322 unsigned Alignment) {
323 bool HasSSE41 = Subtarget->hasSSE41();
324 bool HasAVX = Subtarget->hasAVX();
325 bool HasAVX2 = Subtarget->hasAVX2();
326 bool HasAVX512 = Subtarget->hasAVX512();
327 bool HasVLX = Subtarget->hasVLX();
328 bool IsNonTemporal = MMO && MMO->isNonTemporal();
329
330 // Get opcode and regclass of the output for the given load instruction.
331 unsigned Opc = 0;
332 const TargetRegisterClass *RC = nullptr;
333 switch (VT.getSimpleVT().SimpleTy) {
334 default: return false;
335 case MVT::i1:
336 case MVT::i8:
337 Opc = X86::MOV8rm;
338 RC = &X86::GR8RegClass;
339 break;
340 case MVT::i16:
341 Opc = X86::MOV16rm;
342 RC = &X86::GR16RegClass;
343 break;
344 case MVT::i32:
345 Opc = X86::MOV32rm;
346 RC = &X86::GR32RegClass;
347 break;
348 case MVT::i64:
349 // Must be in x86-64 mode.
350 Opc = X86::MOV64rm;
351 RC = &X86::GR64RegClass;
352 break;
353 case MVT::f32:
354 if (X86ScalarSSEf32) {
355 Opc = HasAVX512 ? X86::VMOVSSZrm : HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
356 RC = HasAVX512 ? &X86::FR32XRegClass : &X86::FR32RegClass;
357 } else {
358 Opc = X86::LD_Fp32m;
359 RC = &X86::RFP32RegClass;
360 }
361 break;
362 case MVT::f64:
363 if (X86ScalarSSEf64) {
364 Opc = HasAVX512 ? X86::VMOVSDZrm : HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
365 RC = HasAVX512 ? &X86::FR64XRegClass : &X86::FR64RegClass;
366 } else {
367 Opc = X86::LD_Fp64m;
368 RC = &X86::RFP64RegClass;
369 }
370 break;
371 case MVT::f80:
372 // No f80 support yet.
373 return false;
374 case MVT::v4f32:
375 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
376 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
377 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
378 else if (Alignment >= 16)
379 Opc = HasVLX ? X86::VMOVAPSZ128rm :
380 HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
381 else
382 Opc = HasVLX ? X86::VMOVUPSZ128rm :
383 HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
384 RC = HasVLX ? &X86::VR128XRegClass : &X86::VR128RegClass;
385 break;
386 case MVT::v2f64:
387 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
388 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
389 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
390 else if (Alignment >= 16)
391 Opc = HasVLX ? X86::VMOVAPDZ128rm :
392 HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
393 else
394 Opc = HasVLX ? X86::VMOVUPDZ128rm :
395 HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
396 RC = HasVLX ? &X86::VR128XRegClass : &X86::VR128RegClass;
397 break;
398 case MVT::v4i32:
399 case MVT::v2i64:
400 case MVT::v8i16:
401 case MVT::v16i8:
402 if (IsNonTemporal && Alignment >= 16)
403 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
404 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
405 else if (Alignment >= 16)
406 Opc = HasVLX ? X86::VMOVDQA64Z128rm :
407 HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
408 else
409 Opc = HasVLX ? X86::VMOVDQU64Z128rm :
410 HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
411 RC = HasVLX ? &X86::VR128XRegClass : &X86::VR128RegClass;
412 break;
413 case MVT::v8f32:
414 assert(HasAVX)(static_cast <bool> (HasAVX) ? void (0) : __assert_fail
("HasAVX", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 414, __extension__ __PRETTY_FUNCTION__))
;
415 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
416 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
417 else if (IsNonTemporal && Alignment >= 16)
418 return false; // Force split for X86::VMOVNTDQArm
419 else if (Alignment >= 32)
420 Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
421 else
422 Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
423 RC = HasVLX ? &X86::VR256XRegClass : &X86::VR256RegClass;
424 break;
425 case MVT::v4f64:
426 assert(HasAVX)(static_cast <bool> (HasAVX) ? void (0) : __assert_fail
("HasAVX", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 426, __extension__ __PRETTY_FUNCTION__))
;
427 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
428 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
429 else if (IsNonTemporal && Alignment >= 16)
430 return false; // Force split for X86::VMOVNTDQArm
431 else if (Alignment >= 32)
432 Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
433 else
434 Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
435 RC = HasVLX ? &X86::VR256XRegClass : &X86::VR256RegClass;
436 break;
437 case MVT::v8i32:
438 case MVT::v4i64:
439 case MVT::v16i16:
440 case MVT::v32i8:
441 assert(HasAVX)(static_cast <bool> (HasAVX) ? void (0) : __assert_fail
("HasAVX", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 441, __extension__ __PRETTY_FUNCTION__))
;
442 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
443 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
444 else if (IsNonTemporal && Alignment >= 16)
445 return false; // Force split for X86::VMOVNTDQArm
446 else if (Alignment >= 32)
447 Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
448 else
449 Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
450 RC = HasVLX ? &X86::VR256XRegClass : &X86::VR256RegClass;
451 break;
452 case MVT::v16f32:
453 assert(HasAVX512)(static_cast <bool> (HasAVX512) ? void (0) : __assert_fail
("HasAVX512", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 453, __extension__ __PRETTY_FUNCTION__))
;
454 if (IsNonTemporal && Alignment >= 64)
455 Opc = X86::VMOVNTDQAZrm;
456 else
457 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
458 RC = &X86::VR512RegClass;
459 break;
460 case MVT::v8f64:
461 assert(HasAVX512)(static_cast <bool> (HasAVX512) ? void (0) : __assert_fail
("HasAVX512", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 461, __extension__ __PRETTY_FUNCTION__))
;
462 if (IsNonTemporal && Alignment >= 64)
463 Opc = X86::VMOVNTDQAZrm;
464 else
465 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
466 RC = &X86::VR512RegClass;
467 break;
468 case MVT::v8i64:
469 case MVT::v16i32:
470 case MVT::v32i16:
471 case MVT::v64i8:
472 assert(HasAVX512)(static_cast <bool> (HasAVX512) ? void (0) : __assert_fail
("HasAVX512", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 472, __extension__ __PRETTY_FUNCTION__))
;
473 // Note: There are a lot more choices based on type with AVX-512, but
474 // there's really no advantage when the load isn't masked.
475 if (IsNonTemporal && Alignment >= 64)
476 Opc = X86::VMOVNTDQAZrm;
477 else
478 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
479 RC = &X86::VR512RegClass;
480 break;
481 }
482
483 ResultReg = createResultReg(RC);
484 MachineInstrBuilder MIB =
485 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
486 addFullAddress(MIB, AM);
487 if (MMO)
488 MIB->addMemOperand(*FuncInfo.MF, MMO);
489 return true;
490}
491
492/// X86FastEmitStore - Emit a machine instruction to store a value Val of
493/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
494/// and a displacement offset, or a GlobalAddress,
495/// i.e. V. Return true if it is possible.
496bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
497 X86AddressMode &AM,
498 MachineMemOperand *MMO, bool Aligned) {
499 bool HasSSE1 = Subtarget->hasSSE1();
500 bool HasSSE2 = Subtarget->hasSSE2();
501 bool HasSSE4A = Subtarget->hasSSE4A();
502 bool HasAVX = Subtarget->hasAVX();
503 bool HasAVX512 = Subtarget->hasAVX512();
504 bool HasVLX = Subtarget->hasVLX();
505 bool IsNonTemporal = MMO && MMO->isNonTemporal();
506
507 // Get opcode and regclass of the output for the given store instruction.
508 unsigned Opc = 0;
509 switch (VT.getSimpleVT().SimpleTy) {
510 case MVT::f80: // No f80 support yet.
511 default: return false;
512 case MVT::i1: {
513 // Mask out all but lowest bit.
514 unsigned AndResult = createResultReg(&X86::GR8RegClass);
515 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
516 TII.get(X86::AND8ri), AndResult)
517 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
518 ValReg = AndResult;
519 LLVM_FALLTHROUGH[[clang::fallthrough]]; // handle i1 as i8.
520 }
521 case MVT::i8: Opc = X86::MOV8mr; break;
522 case MVT::i16: Opc = X86::MOV16mr; break;
523 case MVT::i32:
524 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
525 break;
526 case MVT::i64:
527 // Must be in x86-64 mode.
528 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
529 break;
530 case MVT::f32:
531 if (X86ScalarSSEf32) {
532 if (IsNonTemporal && HasSSE4A)
533 Opc = X86::MOVNTSS;
534 else
535 Opc = HasAVX512 ? X86::VMOVSSZmr :
536 HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
537 } else
538 Opc = X86::ST_Fp32m;
539 break;
540 case MVT::f64:
541 if (X86ScalarSSEf32) {
542 if (IsNonTemporal && HasSSE4A)
543 Opc = X86::MOVNTSD;
544 else
545 Opc = HasAVX512 ? X86::VMOVSDZmr :
546 HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
547 } else
548 Opc = X86::ST_Fp64m;
549 break;
550 case MVT::x86mmx:
551 Opc = (IsNonTemporal && HasSSE1) ? X86::MMX_MOVNTQmr : X86::MMX_MOVQ64mr;
552 break;
553 case MVT::v4f32:
554 if (Aligned) {
555 if (IsNonTemporal)
556 Opc = HasVLX ? X86::VMOVNTPSZ128mr :
557 HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
558 else
559 Opc = HasVLX ? X86::VMOVAPSZ128mr :
560 HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
561 } else
562 Opc = HasVLX ? X86::VMOVUPSZ128mr :
563 HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
564 break;
565 case MVT::v2f64:
566 if (Aligned) {
567 if (IsNonTemporal)
568 Opc = HasVLX ? X86::VMOVNTPDZ128mr :
569 HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
570 else
571 Opc = HasVLX ? X86::VMOVAPDZ128mr :
572 HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
573 } else
574 Opc = HasVLX ? X86::VMOVUPDZ128mr :
575 HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
576 break;
577 case MVT::v4i32:
578 case MVT::v2i64:
579 case MVT::v8i16:
580 case MVT::v16i8:
581 if (Aligned) {
582 if (IsNonTemporal)
583 Opc = HasVLX ? X86::VMOVNTDQZ128mr :
584 HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
585 else
586 Opc = HasVLX ? X86::VMOVDQA64Z128mr :
587 HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
588 } else
589 Opc = HasVLX ? X86::VMOVDQU64Z128mr :
590 HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
591 break;
592 case MVT::v8f32:
593 assert(HasAVX)(static_cast <bool> (HasAVX) ? void (0) : __assert_fail
("HasAVX", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 593, __extension__ __PRETTY_FUNCTION__))
;
594 if (Aligned) {
595 if (IsNonTemporal)
596 Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
597 else
598 Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
599 } else
600 Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
601 break;
602 case MVT::v4f64:
603 assert(HasAVX)(static_cast <bool> (HasAVX) ? void (0) : __assert_fail
("HasAVX", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 603, __extension__ __PRETTY_FUNCTION__))
;
604 if (Aligned) {
605 if (IsNonTemporal)
606 Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
607 else
608 Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
609 } else
610 Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
611 break;
612 case MVT::v8i32:
613 case MVT::v4i64:
614 case MVT::v16i16:
615 case MVT::v32i8:
616 assert(HasAVX)(static_cast <bool> (HasAVX) ? void (0) : __assert_fail
("HasAVX", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 616, __extension__ __PRETTY_FUNCTION__))
;
617 if (Aligned) {
618 if (IsNonTemporal)
619 Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
620 else
621 Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
622 } else
623 Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
624 break;
625 case MVT::v16f32:
626 assert(HasAVX512)(static_cast <bool> (HasAVX512) ? void (0) : __assert_fail
("HasAVX512", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 626, __extension__ __PRETTY_FUNCTION__))
;
627 if (Aligned)
628 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
629 else
630 Opc = X86::VMOVUPSZmr;
631 break;
632 case MVT::v8f64:
633 assert(HasAVX512)(static_cast <bool> (HasAVX512) ? void (0) : __assert_fail
("HasAVX512", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 633, __extension__ __PRETTY_FUNCTION__))
;
634 if (Aligned) {
635 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
636 } else
637 Opc = X86::VMOVUPDZmr;
638 break;
639 case MVT::v8i64:
640 case MVT::v16i32:
641 case MVT::v32i16:
642 case MVT::v64i8:
643 assert(HasAVX512)(static_cast <bool> (HasAVX512) ? void (0) : __assert_fail
("HasAVX512", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 643, __extension__ __PRETTY_FUNCTION__))
;
644 // Note: There are a lot more choices based on type with AVX-512, but
645 // there's really no advantage when the store isn't masked.
646 if (Aligned)
647 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
648 else
649 Opc = X86::VMOVDQU64Zmr;
650 break;
651 }
652
653 const MCInstrDesc &Desc = TII.get(Opc);
654 // Some of the instructions in the previous switch use FR128 instead
655 // of FR32 for ValReg. Make sure the register we feed the instruction
656 // matches its register class constraints.
657 // Note: This is fine to do a copy from FR32 to FR128, this is the
658 // same registers behind the scene and actually why it did not trigger
659 // any bugs before.
660 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
661 MachineInstrBuilder MIB =
662 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
663 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
664 if (MMO)
665 MIB->addMemOperand(*FuncInfo.MF, MMO);
666
667 return true;
668}
669
670bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
671 X86AddressMode &AM,
672 MachineMemOperand *MMO, bool Aligned) {
673 // Handle 'null' like i32/i64 0.
674 if (isa<ConstantPointerNull>(Val))
675 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
676
677 // If this is a store of a simple constant, fold the constant into the store.
678 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
679 unsigned Opc = 0;
680 bool Signed = true;
681 switch (VT.getSimpleVT().SimpleTy) {
682 default: break;
683 case MVT::i1:
684 Signed = false;
685 LLVM_FALLTHROUGH[[clang::fallthrough]]; // Handle as i8.
686 case MVT::i8: Opc = X86::MOV8mi; break;
687 case MVT::i16: Opc = X86::MOV16mi; break;
688 case MVT::i32: Opc = X86::MOV32mi; break;
689 case MVT::i64:
690 // Must be a 32-bit sign extended value.
691 if (isInt<32>(CI->getSExtValue()))
692 Opc = X86::MOV64mi32;
693 break;
694 }
695
696 if (Opc) {
697 MachineInstrBuilder MIB =
698 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
699 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
700 : CI->getZExtValue());
701 if (MMO)
702 MIB->addMemOperand(*FuncInfo.MF, MMO);
703 return true;
704 }
705 }
706
707 unsigned ValReg = getRegForValue(Val);
708 if (ValReg == 0)
709 return false;
710
711 bool ValKill = hasTrivialKill(Val);
712 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
713}
714
715/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
716/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
717/// ISD::SIGN_EXTEND).
718bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
719 unsigned Src, EVT SrcVT,
720 unsigned &ResultReg) {
721 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
722 Src, /*TODO: Kill=*/false);
723 if (RR == 0)
724 return false;
725
726 ResultReg = RR;
727 return true;
728}
729
730bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
731 // Handle constant address.
732 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
733 // Can't handle alternate code models yet.
734 if (TM.getCodeModel() != CodeModel::Small)
735 return false;
736
737 // Can't handle TLS yet.
738 if (GV->isThreadLocal())
739 return false;
740
741 // RIP-relative addresses can't have additional register operands, so if
742 // we've already folded stuff into the addressing mode, just force the
743 // global value into its own register, which we can use as the basereg.
744 if (!Subtarget->isPICStyleRIPRel() ||
745 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
746 // Okay, we've committed to selecting this global. Set up the address.
747 AM.GV = GV;
748
749 // Allow the subtarget to classify the global.
750 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
751
752 // If this reference is relative to the pic base, set it now.
753 if (isGlobalRelativeToPICBase(GVFlags)) {
754 // FIXME: How do we know Base.Reg is free??
755 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
756 }
757
758 // Unless the ABI requires an extra load, return a direct reference to
759 // the global.
760 if (!isGlobalStubReference(GVFlags)) {
761 if (Subtarget->isPICStyleRIPRel()) {
762 // Use rip-relative addressing if we can. Above we verified that the
763 // base and index registers are unused.
764 assert(AM.Base.Reg == 0 && AM.IndexReg == 0)(static_cast <bool> (AM.Base.Reg == 0 && AM.IndexReg
== 0) ? void (0) : __assert_fail ("AM.Base.Reg == 0 && AM.IndexReg == 0"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 764, __extension__ __PRETTY_FUNCTION__))
;
765 AM.Base.Reg = X86::RIP;
766 }
767 AM.GVOpFlags = GVFlags;
768 return true;
769 }
770
771 // Ok, we need to do a load from a stub. If we've already loaded from
772 // this stub, reuse the loaded pointer, otherwise emit the load now.
773 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
774 unsigned LoadReg;
775 if (I != LocalValueMap.end() && I->second != 0) {
776 LoadReg = I->second;
777 } else {
778 // Issue load from stub.
779 unsigned Opc = 0;
780 const TargetRegisterClass *RC = nullptr;
781 X86AddressMode StubAM;
782 StubAM.Base.Reg = AM.Base.Reg;
783 StubAM.GV = GV;
784 StubAM.GVOpFlags = GVFlags;
785
786 // Prepare for inserting code in the local-value area.
787 SavePoint SaveInsertPt = enterLocalValueArea();
788
789 if (TLI.getPointerTy(DL) == MVT::i64) {
790 Opc = X86::MOV64rm;
791 RC = &X86::GR64RegClass;
792
793 if (Subtarget->isPICStyleRIPRel())
794 StubAM.Base.Reg = X86::RIP;
795 } else {
796 Opc = X86::MOV32rm;
797 RC = &X86::GR32RegClass;
798 }
799
800 LoadReg = createResultReg(RC);
801 MachineInstrBuilder LoadMI =
802 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
803 addFullAddress(LoadMI, StubAM);
804
805 // Ok, back to normal mode.
806 leaveLocalValueArea(SaveInsertPt);
807
808 // Prevent loading GV stub multiple times in same MBB.
809 LocalValueMap[V] = LoadReg;
810 }
811
812 // Now construct the final address. Note that the Disp, Scale,
813 // and Index values may already be set here.
814 AM.Base.Reg = LoadReg;
815 AM.GV = nullptr;
816 return true;
817 }
818 }
819
820 // If all else fails, try to materialize the value in a register.
821 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
822 if (AM.Base.Reg == 0) {
823 AM.Base.Reg = getRegForValue(V);
824 return AM.Base.Reg != 0;
825 }
826 if (AM.IndexReg == 0) {
827 assert(AM.Scale == 1 && "Scale with no index!")(static_cast <bool> (AM.Scale == 1 && "Scale with no index!"
) ? void (0) : __assert_fail ("AM.Scale == 1 && \"Scale with no index!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 827, __extension__ __PRETTY_FUNCTION__))
;
828 AM.IndexReg = getRegForValue(V);
829 return AM.IndexReg != 0;
830 }
831 }
832
833 return false;
834}
835
836/// X86SelectAddress - Attempt to fill in an address from the given value.
837///
838bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
839 SmallVector<const Value *, 32> GEPs;
840redo_gep:
841 const User *U = nullptr;
842 unsigned Opcode = Instruction::UserOp1;
843 if (const Instruction *I = dyn_cast<Instruction>(V)) {
844 // Don't walk into other basic blocks; it's possible we haven't
845 // visited them yet, so the instructions may not yet be assigned
846 // virtual registers.
847 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
848 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
849 Opcode = I->getOpcode();
850 U = I;
851 }
852 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
853 Opcode = C->getOpcode();
854 U = C;
855 }
856
857 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
858 if (Ty->getAddressSpace() > 255)
859 // Fast instruction selection doesn't support the special
860 // address spaces.
861 return false;
862
863 switch (Opcode) {
864 default: break;
865 case Instruction::BitCast:
866 // Look past bitcasts.
867 return X86SelectAddress(U->getOperand(0), AM);
868
869 case Instruction::IntToPtr:
870 // Look past no-op inttoptrs.
871 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
872 TLI.getPointerTy(DL))
873 return X86SelectAddress(U->getOperand(0), AM);
874 break;
875
876 case Instruction::PtrToInt:
877 // Look past no-op ptrtoints.
878 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
879 return X86SelectAddress(U->getOperand(0), AM);
880 break;
881
882 case Instruction::Alloca: {
883 // Do static allocas.
884 const AllocaInst *A = cast<AllocaInst>(V);
885 DenseMap<const AllocaInst *, int>::iterator SI =
886 FuncInfo.StaticAllocaMap.find(A);
887 if (SI != FuncInfo.StaticAllocaMap.end()) {
888 AM.BaseType = X86AddressMode::FrameIndexBase;
889 AM.Base.FrameIndex = SI->second;
890 return true;
891 }
892 break;
893 }
894
895 case Instruction::Add: {
896 // Adds of constants are common and easy enough.
897 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
898 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
899 // They have to fit in the 32-bit signed displacement field though.
900 if (isInt<32>(Disp)) {
901 AM.Disp = (uint32_t)Disp;
902 return X86SelectAddress(U->getOperand(0), AM);
903 }
904 }
905 break;
906 }
907
908 case Instruction::GetElementPtr: {
909 X86AddressMode SavedAM = AM;
910
911 // Pattern-match simple GEPs.
912 uint64_t Disp = (int32_t)AM.Disp;
913 unsigned IndexReg = AM.IndexReg;
914 unsigned Scale = AM.Scale;
915 gep_type_iterator GTI = gep_type_begin(U);
916 // Iterate through the indices, folding what we can. Constants can be
917 // folded, and one dynamic index can be handled, if the scale is supported.
918 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
919 i != e; ++i, ++GTI) {
920 const Value *Op = *i;
921 if (StructType *STy = GTI.getStructTypeOrNull()) {
922 const StructLayout *SL = DL.getStructLayout(STy);
923 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
924 continue;
925 }
926
927 // A array/variable index is always of the form i*S where S is the
928 // constant scale size. See if we can push the scale into immediates.
929 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
930 for (;;) {
931 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
932 // Constant-offset addressing.
933 Disp += CI->getSExtValue() * S;
934 break;
935 }
936 if (canFoldAddIntoGEP(U, Op)) {
937 // A compatible add with a constant operand. Fold the constant.
938 ConstantInt *CI =
939 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
940 Disp += CI->getSExtValue() * S;
941 // Iterate on the other operand.
942 Op = cast<AddOperator>(Op)->getOperand(0);
943 continue;
944 }
945 if (IndexReg == 0 &&
946 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
947 (S == 1 || S == 2 || S == 4 || S == 8)) {
948 // Scaled-index addressing.
949 Scale = S;
950 IndexReg = getRegForGEPIndex(Op).first;
951 if (IndexReg == 0)
952 return false;
953 break;
954 }
955 // Unsupported.
956 goto unsupported_gep;
957 }
958 }
959
960 // Check for displacement overflow.
961 if (!isInt<32>(Disp))
962 break;
963
964 AM.IndexReg = IndexReg;
965 AM.Scale = Scale;
966 AM.Disp = (uint32_t)Disp;
967 GEPs.push_back(V);
968
969 if (const GetElementPtrInst *GEP =
970 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
971 // Ok, the GEP indices were covered by constant-offset and scaled-index
972 // addressing. Update the address state and move on to examining the base.
973 V = GEP;
974 goto redo_gep;
975 } else if (X86SelectAddress(U->getOperand(0), AM)) {
976 return true;
977 }
978
979 // If we couldn't merge the gep value into this addr mode, revert back to
980 // our address and just match the value instead of completely failing.
981 AM = SavedAM;
982
983 for (const Value *I : reverse(GEPs))
984 if (handleConstantAddresses(I, AM))
985 return true;
986
987 return false;
988 unsupported_gep:
989 // Ok, the GEP indices weren't all covered.
990 break;
991 }
992 }
993
994 return handleConstantAddresses(V, AM);
995}
996
997/// X86SelectCallAddress - Attempt to fill in an address from the given value.
998///
999bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
1000 const User *U = nullptr;
1001 unsigned Opcode = Instruction::UserOp1;
1002 const Instruction *I = dyn_cast<Instruction>(V);
1003 // Record if the value is defined in the same basic block.
1004 //
1005 // This information is crucial to know whether or not folding an
1006 // operand is valid.
1007 // Indeed, FastISel generates or reuses a virtual register for all
1008 // operands of all instructions it selects. Obviously, the definition and
1009 // its uses must use the same virtual register otherwise the produced
1010 // code is incorrect.
1011 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
1012 // registers for values that are alive across basic blocks. This ensures
1013 // that the values are consistently set between across basic block, even
1014 // if different instruction selection mechanisms are used (e.g., a mix of
1015 // SDISel and FastISel).
1016 // For values local to a basic block, the instruction selection process
1017 // generates these virtual registers with whatever method is appropriate
1018 // for its needs. In particular, FastISel and SDISel do not share the way
1019 // local virtual registers are set.
1020 // Therefore, this is impossible (or at least unsafe) to share values
1021 // between basic blocks unless they use the same instruction selection
1022 // method, which is not guarantee for X86.
1023 // Moreover, things like hasOneUse could not be used accurately, if we
1024 // allow to reference values across basic blocks whereas they are not
1025 // alive across basic blocks initially.
1026 bool InMBB = true;
1027 if (I) {
1028 Opcode = I->getOpcode();
1029 U = I;
1030 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1031 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1032 Opcode = C->getOpcode();
1033 U = C;
1034 }
1035
1036 switch (Opcode) {
1037 default: break;
1038 case Instruction::BitCast:
1039 // Look past bitcasts if its operand is in the same BB.
1040 if (InMBB)
1041 return X86SelectCallAddress(U->getOperand(0), AM);
1042 break;
1043
1044 case Instruction::IntToPtr:
1045 // Look past no-op inttoptrs if its operand is in the same BB.
1046 if (InMBB &&
1047 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1048 TLI.getPointerTy(DL))
1049 return X86SelectCallAddress(U->getOperand(0), AM);
1050 break;
1051
1052 case Instruction::PtrToInt:
1053 // Look past no-op ptrtoints if its operand is in the same BB.
1054 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
1055 return X86SelectCallAddress(U->getOperand(0), AM);
1056 break;
1057 }
1058
1059 // Handle constant address.
1060 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1061 // Can't handle alternate code models yet.
1062 if (TM.getCodeModel() != CodeModel::Small)
1063 return false;
1064
1065 // RIP-relative addresses can't have additional register operands.
1066 if (Subtarget->isPICStyleRIPRel() &&
1067 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1068 return false;
1069
1070 // Can't handle TLS.
1071 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1072 if (GVar->isThreadLocal())
1073 return false;
1074
1075 // Okay, we've committed to selecting this global. Set up the basic address.
1076 AM.GV = GV;
1077
1078 // Return a direct reference to the global. Fastisel can handle calls to
1079 // functions that require loads, such as dllimport and nonlazybind
1080 // functions.
1081 if (Subtarget->isPICStyleRIPRel()) {
1082 // Use rip-relative addressing if we can. Above we verified that the
1083 // base and index registers are unused.
1084 assert(AM.Base.Reg == 0 && AM.IndexReg == 0)(static_cast <bool> (AM.Base.Reg == 0 && AM.IndexReg
== 0) ? void (0) : __assert_fail ("AM.Base.Reg == 0 && AM.IndexReg == 0"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1084, __extension__ __PRETTY_FUNCTION__))
;
1085 AM.Base.Reg = X86::RIP;
1086 } else {
1087 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
1088 }
1089
1090 return true;
1091 }
1092
1093 // If all else fails, try to materialize the value in a register.
1094 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1095 if (AM.Base.Reg == 0) {
1096 AM.Base.Reg = getRegForValue(V);
1097 return AM.Base.Reg != 0;
1098 }
1099 if (AM.IndexReg == 0) {
1100 assert(AM.Scale == 1 && "Scale with no index!")(static_cast <bool> (AM.Scale == 1 && "Scale with no index!"
) ? void (0) : __assert_fail ("AM.Scale == 1 && \"Scale with no index!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1100, __extension__ __PRETTY_FUNCTION__))
;
1101 AM.IndexReg = getRegForValue(V);
1102 return AM.IndexReg != 0;
1103 }
1104 }
1105
1106 return false;
1107}
1108
1109
1110/// X86SelectStore - Select and emit code to implement store instructions.
1111bool X86FastISel::X86SelectStore(const Instruction *I) {
1112 // Atomic stores need special handling.
1113 const StoreInst *S = cast<StoreInst>(I);
1114
1115 if (S->isAtomic())
1116 return false;
1117
1118 const Value *PtrV = I->getOperand(1);
1119 if (TLI.supportSwiftError()) {
1120 // Swifterror values can come from either a function parameter with
1121 // swifterror attribute or an alloca with swifterror attribute.
1122 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1123 if (Arg->hasSwiftErrorAttr())
1124 return false;
1125 }
1126
1127 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1128 if (Alloca->isSwiftError())
1129 return false;
1130 }
1131 }
1132
1133 const Value *Val = S->getValueOperand();
1134 const Value *Ptr = S->getPointerOperand();
1135
1136 MVT VT;
1137 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1138 return false;
1139
1140 unsigned Alignment = S->getAlignment();
1141 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1142 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1143 Alignment = ABIAlignment;
1144 bool Aligned = Alignment >= ABIAlignment;
1145
1146 X86AddressMode AM;
1147 if (!X86SelectAddress(Ptr, AM))
1148 return false;
1149
1150 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1151}
1152
1153/// X86SelectRet - Select and emit code to implement ret instructions.
1154bool X86FastISel::X86SelectRet(const Instruction *I) {
1155 const ReturnInst *Ret = cast<ReturnInst>(I);
1156 const Function &F = *I->getParent()->getParent();
1157 const X86MachineFunctionInfo *X86MFInfo =
1158 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1159
1160 if (!FuncInfo.CanLowerReturn)
1161 return false;
1162
1163 if (TLI.supportSwiftError() &&
1164 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1165 return false;
1166
1167 if (TLI.supportSplitCSR(FuncInfo.MF))
1168 return false;
1169
1170 CallingConv::ID CC = F.getCallingConv();
1171 if (CC != CallingConv::C &&
1172 CC != CallingConv::Fast &&
1173 CC != CallingConv::X86_FastCall &&
1174 CC != CallingConv::X86_StdCall &&
1175 CC != CallingConv::X86_ThisCall &&
1176 CC != CallingConv::X86_64_SysV &&
1177 CC != CallingConv::Win64)
1178 return false;
1179
1180 // Don't handle popping bytes if they don't fit the ret's immediate.
1181 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
1182 return false;
1183
1184 // fastcc with -tailcallopt is intended to provide a guaranteed
1185 // tail call optimization. Fastisel doesn't know how to do that.
1186 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1187 return false;
1188
1189 // Let SDISel handle vararg functions.
1190 if (F.isVarArg())
1191 return false;
1192
1193 // Build a list of return value registers.
1194 SmallVector<unsigned, 4> RetRegs;
1195
1196 if (Ret->getNumOperands() > 0) {
1197 SmallVector<ISD::OutputArg, 4> Outs;
1198 GetReturnInfo(CC, F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
1199
1200 // Analyze operands of the call, assigning locations to each operand.
1201 SmallVector<CCValAssign, 16> ValLocs;
1202 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1203 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1204
1205 const Value *RV = Ret->getOperand(0);
1206 unsigned Reg = getRegForValue(RV);
1207 if (Reg == 0)
1208 return false;
1209
1210 // Only handle a single return value for now.
1211 if (ValLocs.size() != 1)
1212 return false;
1213
1214 CCValAssign &VA = ValLocs[0];
1215
1216 // Don't bother handling odd stuff for now.
1217 if (VA.getLocInfo() != CCValAssign::Full)
1218 return false;
1219 // Only handle register returns for now.
1220 if (!VA.isRegLoc())
1221 return false;
1222
1223 // The calling-convention tables for x87 returns don't tell
1224 // the whole story.
1225 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1226 return false;
1227
1228 unsigned SrcReg = Reg + VA.getValNo();
1229 EVT SrcVT = TLI.getValueType(DL, RV->getType());
1230 EVT DstVT = VA.getValVT();
1231 // Special handling for extended integers.
1232 if (SrcVT != DstVT) {
1233 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1234 return false;
1235
1236 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1237 return false;
1238
1239 assert(DstVT == MVT::i32 && "X86 should always ext to i32")(static_cast <bool> (DstVT == MVT::i32 && "X86 should always ext to i32"
) ? void (0) : __assert_fail ("DstVT == MVT::i32 && \"X86 should always ext to i32\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1239, __extension__ __PRETTY_FUNCTION__))
;
1240
1241 if (SrcVT == MVT::i1) {
1242 if (Outs[0].Flags.isSExt())
1243 return false;
1244 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1245 SrcVT = MVT::i8;
1246 }
1247 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1248 ISD::SIGN_EXTEND;
1249 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1250 SrcReg, /*TODO: Kill=*/false);
1251 }
1252
1253 // Make the copy.
1254 unsigned DstReg = VA.getLocReg();
1255 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1256 // Avoid a cross-class copy. This is very unlikely.
1257 if (!SrcRC->contains(DstReg))
1258 return false;
1259 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1260 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1261
1262 // Add register to return instruction.
1263 RetRegs.push_back(VA.getLocReg());
1264 }
1265
1266 // Swift calling convention does not require we copy the sret argument
1267 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1268
1269 // All x86 ABIs require that for returning structs by value we copy
1270 // the sret argument into %rax/%eax (depending on ABI) for the return.
1271 // We saved the argument into a virtual register in the entry block,
1272 // so now we copy the value out and into %rax/%eax.
1273 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
1274 unsigned Reg = X86MFInfo->getSRetReturnReg();
1275 assert(Reg &&(static_cast <bool> (Reg && "SRetReturnReg should have been set in LowerFormalArguments()!"
) ? void (0) : __assert_fail ("Reg && \"SRetReturnReg should have been set in LowerFormalArguments()!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1276, __extension__ __PRETTY_FUNCTION__))
1276 "SRetReturnReg should have been set in LowerFormalArguments()!")(static_cast <bool> (Reg && "SRetReturnReg should have been set in LowerFormalArguments()!"
) ? void (0) : __assert_fail ("Reg && \"SRetReturnReg should have been set in LowerFormalArguments()!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1276, __extension__ __PRETTY_FUNCTION__))
;
1277 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1278 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1279 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1280 RetRegs.push_back(RetReg);
1281 }
1282
1283 // Now emit the RET.
1284 MachineInstrBuilder MIB;
1285 if (X86MFInfo->getBytesToPopOnReturn()) {
1286 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1287 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1288 .addImm(X86MFInfo->getBytesToPopOnReturn());
1289 } else {
1290 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1291 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1292 }
1293 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1294 MIB.addReg(RetRegs[i], RegState::Implicit);
1295 return true;
1296}
1297
1298/// X86SelectLoad - Select and emit code to implement load instructions.
1299///
1300bool X86FastISel::X86SelectLoad(const Instruction *I) {
1301 const LoadInst *LI = cast<LoadInst>(I);
1302
1303 // Atomic loads need special handling.
1304 if (LI->isAtomic())
1305 return false;
1306
1307 const Value *SV = I->getOperand(0);
1308 if (TLI.supportSwiftError()) {
1309 // Swifterror values can come from either a function parameter with
1310 // swifterror attribute or an alloca with swifterror attribute.
1311 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1312 if (Arg->hasSwiftErrorAttr())
1313 return false;
1314 }
1315
1316 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1317 if (Alloca->isSwiftError())
1318 return false;
1319 }
1320 }
1321
1322 MVT VT;
1323 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1324 return false;
1325
1326 const Value *Ptr = LI->getPointerOperand();
1327
1328 X86AddressMode AM;
1329 if (!X86SelectAddress(Ptr, AM))
1330 return false;
1331
1332 unsigned Alignment = LI->getAlignment();
1333 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1334 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1335 Alignment = ABIAlignment;
1336
1337 unsigned ResultReg = 0;
1338 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1339 Alignment))
1340 return false;
1341
1342 updateValueMap(I, ResultReg);
1343 return true;
1344}
1345
1346static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1347 bool HasAVX512 = Subtarget->hasAVX512();
1348 bool HasAVX = Subtarget->hasAVX();
1349 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1350 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1351
1352 switch (VT.getSimpleVT().SimpleTy) {
1353 default: return 0;
1354 case MVT::i8: return X86::CMP8rr;
1355 case MVT::i16: return X86::CMP16rr;
1356 case MVT::i32: return X86::CMP32rr;
1357 case MVT::i64: return X86::CMP64rr;
1358 case MVT::f32:
1359 return X86ScalarSSEf32
1360 ? (HasAVX512 ? X86::VUCOMISSZrr
1361 : HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr)
1362 : 0;
1363 case MVT::f64:
1364 return X86ScalarSSEf64
1365 ? (HasAVX512 ? X86::VUCOMISDZrr
1366 : HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr)
1367 : 0;
1368 }
1369}
1370
1371/// If we have a comparison with RHS as the RHS of the comparison, return an
1372/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1373static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1374 int64_t Val = RHSC->getSExtValue();
1375 switch (VT.getSimpleVT().SimpleTy) {
1376 // Otherwise, we can't fold the immediate into this comparison.
1377 default:
1378 return 0;
1379 case MVT::i8:
1380 return X86::CMP8ri;
1381 case MVT::i16:
1382 if (isInt<8>(Val))
1383 return X86::CMP16ri8;
1384 return X86::CMP16ri;
1385 case MVT::i32:
1386 if (isInt<8>(Val))
1387 return X86::CMP32ri8;
1388 return X86::CMP32ri;
1389 case MVT::i64:
1390 if (isInt<8>(Val))
1391 return X86::CMP64ri8;
1392 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1393 // field.
1394 if (isInt<32>(Val))
1395 return X86::CMP64ri32;
1396 return 0;
1397 }
1398}
1399
1400bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1401 const DebugLoc &CurDbgLoc) {
1402 unsigned Op0Reg = getRegForValue(Op0);
1403 if (Op0Reg == 0) return false;
1404
1405 // Handle 'null' like i32/i64 0.
1406 if (isa<ConstantPointerNull>(Op1))
1407 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1408
1409 // We have two options: compare with register or immediate. If the RHS of
1410 // the compare is an immediate that we can fold into this compare, use
1411 // CMPri, otherwise use CMPrr.
1412 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1413 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1415 .addReg(Op0Reg)
1416 .addImm(Op1C->getSExtValue());
1417 return true;
1418 }
1419 }
1420
1421 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1422 if (CompareOpc == 0) return false;
1423
1424 unsigned Op1Reg = getRegForValue(Op1);
1425 if (Op1Reg == 0) return false;
1426 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1427 .addReg(Op0Reg)
1428 .addReg(Op1Reg);
1429
1430 return true;
1431}
1432
1433bool X86FastISel::X86SelectCmp(const Instruction *I) {
1434 const CmpInst *CI = cast<CmpInst>(I);
1435
1436 MVT VT;
1437 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1438 return false;
1439
1440 // Try to optimize or fold the cmp.
1441 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1442 unsigned ResultReg = 0;
1443 switch (Predicate) {
1444 default: break;
1445 case CmpInst::FCMP_FALSE: {
1446 ResultReg = createResultReg(&X86::GR32RegClass);
1447 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1448 ResultReg);
1449 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1450 X86::sub_8bit);
1451 if (!ResultReg)
1452 return false;
1453 break;
1454 }
1455 case CmpInst::FCMP_TRUE: {
1456 ResultReg = createResultReg(&X86::GR8RegClass);
1457 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1458 ResultReg).addImm(1);
1459 break;
1460 }
1461 }
1462
1463 if (ResultReg) {
1464 updateValueMap(I, ResultReg);
1465 return true;
1466 }
1467
1468 const Value *LHS = CI->getOperand(0);
1469 const Value *RHS = CI->getOperand(1);
1470
1471 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1472 // We don't have to materialize a zero constant for this case and can just use
1473 // %x again on the RHS.
1474 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1475 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1476 if (RHSC && RHSC->isNullValue())
1477 RHS = LHS;
1478 }
1479
1480 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1481 static const uint16_t SETFOpcTable[2][3] = {
1482 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1483 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1484 };
1485 const uint16_t *SETFOpc = nullptr;
1486 switch (Predicate) {
1487 default: break;
1488 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1489 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1490 }
1491
1492 ResultReg = createResultReg(&X86::GR8RegClass);
1493 if (SETFOpc) {
1494 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1495 return false;
1496
1497 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1498 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1499 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1500 FlagReg1);
1501 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1502 FlagReg2);
1503 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1504 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1505 updateValueMap(I, ResultReg);
1506 return true;
1507 }
1508
1509 X86::CondCode CC;
1510 bool SwapArgs;
1511 std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
1512 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.")(static_cast <bool> (CC <= X86::LAST_VALID_COND &&
"Unexpected condition code.") ? void (0) : __assert_fail ("CC <= X86::LAST_VALID_COND && \"Unexpected condition code.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1512, __extension__ __PRETTY_FUNCTION__))
;
1513 unsigned Opc = X86::getSETFromCond(CC);
1514
1515 if (SwapArgs)
1516 std::swap(LHS, RHS);
1517
1518 // Emit a compare of LHS/RHS.
1519 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1520 return false;
1521
1522 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1523 updateValueMap(I, ResultReg);
1524 return true;
1525}
1526
1527bool X86FastISel::X86SelectZExt(const Instruction *I) {
1528 EVT DstVT = TLI.getValueType(DL, I->getType());
1529 if (!TLI.isTypeLegal(DstVT))
1530 return false;
1531
1532 unsigned ResultReg = getRegForValue(I->getOperand(0));
1533 if (ResultReg == 0)
1534 return false;
1535
1536 // Handle zero-extension from i1 to i8, which is common.
1537 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1538 if (SrcVT == MVT::i1) {
1539 // Set the high bits to zero.
1540 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1541 SrcVT = MVT::i8;
1542
1543 if (ResultReg == 0)
1544 return false;
1545 }
1546
1547 if (DstVT == MVT::i64) {
1548 // Handle extension to 64-bits via sub-register shenanigans.
1549 unsigned MovInst;
1550
1551 switch (SrcVT.SimpleTy) {
1552 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1553 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1554 case MVT::i32: MovInst = X86::MOV32rr; break;
1555 default: llvm_unreachable("Unexpected zext to i64 source type")::llvm::llvm_unreachable_internal("Unexpected zext to i64 source type"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1555)
;
1556 }
1557
1558 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1559 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1560 .addReg(ResultReg);
1561
1562 ResultReg = createResultReg(&X86::GR64RegClass);
1563 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1564 ResultReg)
1565 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1566 } else if (DstVT == MVT::i16) {
1567 // i8->i16 doesn't exist in the autogenerated isel table. Need to zero
1568 // extend to 32-bits and then extract down to 16-bits.
1569 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1570 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOVZX32rr8),
1571 Result32).addReg(ResultReg);
1572
1573 ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, /*Kill=*/true,
1574 X86::sub_16bit);
1575 } else if (DstVT != MVT::i8) {
1576 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1577 ResultReg, /*Kill=*/true);
1578 if (ResultReg == 0)
1579 return false;
1580 }
1581
1582 updateValueMap(I, ResultReg);
1583 return true;
1584}
1585
1586bool X86FastISel::X86SelectSExt(const Instruction *I) {
1587 EVT DstVT = TLI.getValueType(DL, I->getType());
1588 if (!TLI.isTypeLegal(DstVT))
1589 return false;
1590
1591 unsigned ResultReg = getRegForValue(I->getOperand(0));
1592 if (ResultReg == 0)
1593 return false;
1594
1595 // Handle sign-extension from i1 to i8.
1596 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1597 if (SrcVT == MVT::i1) {
1598 // Set the high bits to zero.
1599 unsigned ZExtReg = fastEmitZExtFromI1(MVT::i8, ResultReg,
1600 /*TODO: Kill=*/false);
1601 if (ZExtReg == 0)
1602 return false;
1603
1604 // Negate the result to make an 8-bit sign extended value.
1605 ResultReg = createResultReg(&X86::GR8RegClass);
1606 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::NEG8r),
1607 ResultReg).addReg(ZExtReg);
1608
1609 SrcVT = MVT::i8;
1610 }
1611
1612 if (DstVT == MVT::i16) {
1613 // i8->i16 doesn't exist in the autogenerated isel table. Need to sign
1614 // extend to 32-bits and then extract down to 16-bits.
1615 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1616 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOVSX32rr8),
1617 Result32).addReg(ResultReg);
1618
1619 ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, /*Kill=*/true,
1620 X86::sub_16bit);
1621 } else if (DstVT != MVT::i8) {
1622 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::SIGN_EXTEND,
1623 ResultReg, /*Kill=*/true);
1624 if (ResultReg == 0)
1625 return false;
1626 }
1627
1628 updateValueMap(I, ResultReg);
1629 return true;
1630}
1631
1632bool X86FastISel::X86SelectBranch(const Instruction *I) {
1633 // Unconditional branches are selected by tablegen-generated code.
1634 // Handle a conditional branch.
1635 const BranchInst *BI = cast<BranchInst>(I);
1636 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1637 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1638
1639 // Fold the common case of a conditional branch with a comparison
1640 // in the same block (values defined on other blocks may not have
1641 // initialized registers).
1642 X86::CondCode CC;
1643 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1644 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1645 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1646
1647 // Try to optimize or fold the cmp.
1648 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1649 switch (Predicate) {
1650 default: break;
1651 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1652 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1653 }
1654
1655 const Value *CmpLHS = CI->getOperand(0);
1656 const Value *CmpRHS = CI->getOperand(1);
1657
1658 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1659 // 0.0.
1660 // We don't have to materialize a zero constant for this case and can just
1661 // use %x again on the RHS.
1662 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1663 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1664 if (CmpRHSC && CmpRHSC->isNullValue())
1665 CmpRHS = CmpLHS;
1666 }
1667
1668 // Try to take advantage of fallthrough opportunities.
1669 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1670 std::swap(TrueMBB, FalseMBB);
1671 Predicate = CmpInst::getInversePredicate(Predicate);
1672 }
1673
1674 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1675 // code check. Instead two branch instructions are required to check all
1676 // the flags. First we change the predicate to a supported condition code,
1677 // which will be the first branch. Later one we will emit the second
1678 // branch.
1679 bool NeedExtraBranch = false;
1680 switch (Predicate) {
1681 default: break;
1682 case CmpInst::FCMP_OEQ:
1683 std::swap(TrueMBB, FalseMBB);
1684 LLVM_FALLTHROUGH[[clang::fallthrough]];
1685 case CmpInst::FCMP_UNE:
1686 NeedExtraBranch = true;
1687 Predicate = CmpInst::FCMP_ONE;
1688 break;
1689 }
1690
1691 bool SwapArgs;
1692 unsigned BranchOpc;
1693 std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
1694 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.")(static_cast <bool> (CC <= X86::LAST_VALID_COND &&
"Unexpected condition code.") ? void (0) : __assert_fail ("CC <= X86::LAST_VALID_COND && \"Unexpected condition code.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1694, __extension__ __PRETTY_FUNCTION__))
;
1695
1696 BranchOpc = X86::GetCondBranchFromCond(CC);
1697 if (SwapArgs)
1698 std::swap(CmpLHS, CmpRHS);
1699
1700 // Emit a compare of the LHS and RHS, setting the flags.
1701 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1702 return false;
1703
1704 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1705 .addMBB(TrueMBB);
1706
1707 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1708 // to UNE above).
1709 if (NeedExtraBranch) {
1710 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1711 .addMBB(TrueMBB);
1712 }
1713
1714 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1715 return true;
1716 }
1717 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1718 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1719 // typically happen for _Bool and C++ bools.
1720 MVT SourceVT;
1721 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1722 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1723 unsigned TestOpc = 0;
1724 switch (SourceVT.SimpleTy) {
1725 default: break;
1726 case MVT::i8: TestOpc = X86::TEST8ri; break;
1727 case MVT::i16: TestOpc = X86::TEST16ri; break;
1728 case MVT::i32: TestOpc = X86::TEST32ri; break;
1729 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1730 }
1731 if (TestOpc) {
1732 unsigned OpReg = getRegForValue(TI->getOperand(0));
1733 if (OpReg == 0) return false;
1734
1735 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1736 .addReg(OpReg).addImm(1);
1737
1738 unsigned JmpOpc = X86::JNE_1;
1739 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1740 std::swap(TrueMBB, FalseMBB);
1741 JmpOpc = X86::JE_1;
1742 }
1743
1744 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1745 .addMBB(TrueMBB);
1746
1747 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1748 return true;
1749 }
1750 }
1751 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1752 // Fake request the condition, otherwise the intrinsic might be completely
1753 // optimized away.
1754 unsigned TmpReg = getRegForValue(BI->getCondition());
1755 if (TmpReg == 0)
1756 return false;
1757
1758 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1759
1760 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1761 .addMBB(TrueMBB);
1762 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1763 return true;
1764 }
1765
1766 // Otherwise do a clumsy setcc and re-test it.
1767 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1768 // in an explicit cast, so make sure to handle that correctly.
1769 unsigned OpReg = getRegForValue(BI->getCondition());
1770 if (OpReg == 0) return false;
1771
1772 // In case OpReg is a K register, COPY to a GPR
1773 if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) {
1774 unsigned KOpReg = OpReg;
1775 OpReg = createResultReg(&X86::GR32RegClass);
1776 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1777 TII.get(TargetOpcode::COPY), OpReg)
1778 .addReg(KOpReg);
1779 OpReg = fastEmitInst_extractsubreg(MVT::i8, OpReg, /*Kill=*/true,
1780 X86::sub_8bit);
1781 }
1782 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1783 .addReg(OpReg)
1784 .addImm(1);
1785 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1786 .addMBB(TrueMBB);
1787 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1788 return true;
1789}
1790
1791bool X86FastISel::X86SelectShift(const Instruction *I) {
1792 unsigned CReg = 0, OpReg = 0;
1793 const TargetRegisterClass *RC = nullptr;
1794 if (I->getType()->isIntegerTy(8)) {
1795 CReg = X86::CL;
1796 RC = &X86::GR8RegClass;
1797 switch (I->getOpcode()) {
1798 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1799 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1800 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1801 default: return false;
1802 }
1803 } else if (I->getType()->isIntegerTy(16)) {
1804 CReg = X86::CX;
1805 RC = &X86::GR16RegClass;
1806 switch (I->getOpcode()) {
1807 default: llvm_unreachable("Unexpected shift opcode")::llvm::llvm_unreachable_internal("Unexpected shift opcode", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1807)
;
1808 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1809 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1810 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1811 }
1812 } else if (I->getType()->isIntegerTy(32)) {
1813 CReg = X86::ECX;
1814 RC = &X86::GR32RegClass;
1815 switch (I->getOpcode()) {
1816 default: llvm_unreachable("Unexpected shift opcode")::llvm::llvm_unreachable_internal("Unexpected shift opcode", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1816)
;
1817 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1818 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1819 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1820 }
1821 } else if (I->getType()->isIntegerTy(64)) {
1822 CReg = X86::RCX;
1823 RC = &X86::GR64RegClass;
1824 switch (I->getOpcode()) {
1825 default: llvm_unreachable("Unexpected shift opcode")::llvm::llvm_unreachable_internal("Unexpected shift opcode", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1825)
;
1826 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1827 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1828 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1829 }
1830 } else {
1831 return false;
1832 }
1833
1834 MVT VT;
1835 if (!isTypeLegal(I->getType(), VT))
1836 return false;
1837
1838 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1839 if (Op0Reg == 0) return false;
1840
1841 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1842 if (Op1Reg == 0) return false;
1843 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1844 CReg).addReg(Op1Reg);
1845
1846 // The shift instruction uses X86::CL. If we defined a super-register
1847 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1848 if (CReg != X86::CL)
1849 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1850 TII.get(TargetOpcode::KILL), X86::CL)
1851 .addReg(CReg, RegState::Kill);
1852
1853 unsigned ResultReg = createResultReg(RC);
1854 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1855 .addReg(Op0Reg);
1856 updateValueMap(I, ResultReg);
1857 return true;
1858}
1859
1860bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1861 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1862 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1863 const static bool S = true; // IsSigned
1864 const static bool U = false; // !IsSigned
1865 const static unsigned Copy = TargetOpcode::COPY;
1866 // For the X86 DIV/IDIV instruction, in most cases the dividend
1867 // (numerator) must be in a specific register pair highreg:lowreg,
1868 // producing the quotient in lowreg and the remainder in highreg.
1869 // For most data types, to set up the instruction, the dividend is
1870 // copied into lowreg, and lowreg is sign-extended or zero-extended
1871 // into highreg. The exception is i8, where the dividend is defined
1872 // as a single register rather than a register pair, and we
1873 // therefore directly sign-extend or zero-extend the dividend into
1874 // lowreg, instead of copying, and ignore the highreg.
1875 const static struct DivRemEntry {
1876 // The following portion depends only on the data type.
1877 const TargetRegisterClass *RC;
1878 unsigned LowInReg; // low part of the register pair
1879 unsigned HighInReg; // high part of the register pair
1880 // The following portion depends on both the data type and the operation.
1881 struct DivRemResult {
1882 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1883 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1884 // highreg, or copying a zero into highreg.
1885 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1886 // zero/sign-extending into lowreg for i8.
1887 unsigned DivRemResultReg; // Register containing the desired result.
1888 bool IsOpSigned; // Whether to use signed or unsigned form.
1889 } ResultTable[NumOps];
1890 } OpTable[NumTypes] = {
1891 { &X86::GR8RegClass, X86::AX, 0, {
1892 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1893 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1894 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1895 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1896 }
1897 }, // i8
1898 { &X86::GR16RegClass, X86::AX, X86::DX, {
1899 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1900 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1901 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1902 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1903 }
1904 }, // i16
1905 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1906 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1907 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1908 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1909 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1910 }
1911 }, // i32
1912 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1913 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1914 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1915 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1916 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1917 }
1918 }, // i64
1919 };
1920
1921 MVT VT;
1922 if (!isTypeLegal(I->getType(), VT))
1923 return false;
1924
1925 unsigned TypeIndex, OpIndex;
1926 switch (VT.SimpleTy) {
1927 default: return false;
1928 case MVT::i8: TypeIndex = 0; break;
1929 case MVT::i16: TypeIndex = 1; break;
1930 case MVT::i32: TypeIndex = 2; break;
1931 case MVT::i64: TypeIndex = 3;
1932 if (!Subtarget->is64Bit())
1933 return false;
1934 break;
1935 }
1936
1937 switch (I->getOpcode()) {
1938 default: llvm_unreachable("Unexpected div/rem opcode")::llvm::llvm_unreachable_internal("Unexpected div/rem opcode"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 1938)
;
1939 case Instruction::SDiv: OpIndex = 0; break;
1940 case Instruction::SRem: OpIndex = 1; break;
1941 case Instruction::UDiv: OpIndex = 2; break;
1942 case Instruction::URem: OpIndex = 3; break;
1943 }
1944
1945 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1946 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1947 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1948 if (Op0Reg == 0)
1949 return false;
1950 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1951 if (Op1Reg == 0)
1952 return false;
1953
1954 // Move op0 into low-order input register.
1955 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1956 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1957 // Zero-extend or sign-extend into high-order input register.
1958 if (OpEntry.OpSignExtend) {
1959 if (OpEntry.IsOpSigned)
1960 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1961 TII.get(OpEntry.OpSignExtend));
1962 else {
1963 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1964 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1965 TII.get(X86::MOV32r0), Zero32);
1966
1967 // Copy the zero into the appropriate sub/super/identical physical
1968 // register. Unfortunately the operations needed are not uniform enough
1969 // to fit neatly into the table above.
1970 if (VT == MVT::i16) {
1971 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1972 TII.get(Copy), TypeEntry.HighInReg)
1973 .addReg(Zero32, 0, X86::sub_16bit);
1974 } else if (VT == MVT::i32) {
1975 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1976 TII.get(Copy), TypeEntry.HighInReg)
1977 .addReg(Zero32);
1978 } else if (VT == MVT::i64) {
1979 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1980 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1981 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1982 }
1983 }
1984 }
1985 // Generate the DIV/IDIV instruction.
1986 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1987 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1988 // For i8 remainder, we can't reference ah directly, as we'll end
1989 // up with bogus copies like %r9b = COPY %ah. Reference ax
1990 // instead to prevent ah references in a rex instruction.
1991 //
1992 // The current assumption of the fast register allocator is that isel
1993 // won't generate explicit references to the GR8_NOREX registers. If
1994 // the allocator and/or the backend get enhanced to be more robust in
1995 // that regard, this can be, and should be, removed.
1996 unsigned ResultReg = 0;
1997 if ((I->getOpcode() == Instruction::SRem ||
1998 I->getOpcode() == Instruction::URem) &&
1999 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
2000 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
2001 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
2002 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2003 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
2004
2005 // Shift AX right by 8 bits instead of using AH.
2006 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
2007 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
2008
2009 // Now reference the 8-bit subreg of the result.
2010 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
2011 /*Kill=*/true, X86::sub_8bit);
2012 }
2013 // Copy the result out of the physreg if we haven't already.
2014 if (!ResultReg) {
2015 ResultReg = createResultReg(TypeEntry.RC);
2016 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
2017 .addReg(OpEntry.DivRemResultReg);
2018 }
2019 updateValueMap(I, ResultReg);
2020
2021 return true;
2022}
2023
2024/// Emit a conditional move instruction (if the are supported) to lower
2025/// the select.
2026bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
2027 // Check if the subtarget supports these instructions.
2028 if (!Subtarget->hasCMov())
2029 return false;
2030
2031 // FIXME: Add support for i8.
2032 if (RetVT < MVT::i16 || RetVT > MVT::i64)
2033 return false;
2034
2035 const Value *Cond = I->getOperand(0);
2036 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2037 bool NeedTest = true;
2038 X86::CondCode CC = X86::COND_NE;
2039
2040 // Optimize conditions coming from a compare if both instructions are in the
2041 // same basic block (values defined in other basic blocks may not have
2042 // initialized registers).
2043 const auto *CI = dyn_cast<CmpInst>(Cond);
2044 if (CI && (CI->getParent() == I->getParent())) {
2045 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2046
2047 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
2048 static const uint16_t SETFOpcTable[2][3] = {
2049 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
2050 { X86::SETPr, X86::SETNEr, X86::OR8rr }
2051 };
2052 const uint16_t *SETFOpc = nullptr;
2053 switch (Predicate) {
2054 default: break;
2055 case CmpInst::FCMP_OEQ:
2056 SETFOpc = &SETFOpcTable[0][0];
2057 Predicate = CmpInst::ICMP_NE;
2058 break;
2059 case CmpInst::FCMP_UNE:
2060 SETFOpc = &SETFOpcTable[1][0];
2061 Predicate = CmpInst::ICMP_NE;
2062 break;
2063 }
2064
2065 bool NeedSwap;
2066 std::tie(CC, NeedSwap) = X86::getX86ConditionCode(Predicate);
2067 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.")(static_cast <bool> (CC <= X86::LAST_VALID_COND &&
"Unexpected condition code.") ? void (0) : __assert_fail ("CC <= X86::LAST_VALID_COND && \"Unexpected condition code.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2067, __extension__ __PRETTY_FUNCTION__))
;
2068
2069 const Value *CmpLHS = CI->getOperand(0);
2070 const Value *CmpRHS = CI->getOperand(1);
2071 if (NeedSwap)
2072 std::swap(CmpLHS, CmpRHS);
2073
2074 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2075 // Emit a compare of the LHS and RHS, setting the flags.
2076 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2077 return false;
2078
2079 if (SETFOpc) {
2080 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
2081 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
2082 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
2083 FlagReg1);
2084 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
2085 FlagReg2);
2086 auto const &II = TII.get(SETFOpc[2]);
2087 if (II.getNumDefs()) {
2088 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
2089 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
2090 .addReg(FlagReg2).addReg(FlagReg1);
2091 } else {
2092 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2093 .addReg(FlagReg2).addReg(FlagReg1);
2094 }
2095 }
2096 NeedTest = false;
2097 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2098 // Fake request the condition, otherwise the intrinsic might be completely
2099 // optimized away.
2100 unsigned TmpReg = getRegForValue(Cond);
2101 if (TmpReg == 0)
2102 return false;
2103
2104 NeedTest = false;
2105 }
2106
2107 if (NeedTest) {
2108 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2109 // garbage. Indeed, only the less significant bit is supposed to be
2110 // accurate. If we read more than the lsb, we may see non-zero values
2111 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2112 // the select. This is achieved by performing TEST against 1.
2113 unsigned CondReg = getRegForValue(Cond);
2114 if (CondReg == 0)
2115 return false;
2116 bool CondIsKill = hasTrivialKill(Cond);
2117
2118 // In case OpReg is a K register, COPY to a GPR
2119 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2120 unsigned KCondReg = CondReg;
2121 CondReg = createResultReg(&X86::GR32RegClass);
2122 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2123 TII.get(TargetOpcode::COPY), CondReg)
2124 .addReg(KCondReg, getKillRegState(CondIsKill));
2125 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, /*Kill=*/true,
2126 X86::sub_8bit);
2127 }
2128 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2129 .addReg(CondReg, getKillRegState(CondIsKill))
2130 .addImm(1);
2131 }
2132
2133 const Value *LHS = I->getOperand(1);
2134 const Value *RHS = I->getOperand(2);
2135
2136 unsigned RHSReg = getRegForValue(RHS);
2137 bool RHSIsKill = hasTrivialKill(RHS);
2138
2139 unsigned LHSReg = getRegForValue(LHS);
2140 bool LHSIsKill = hasTrivialKill(LHS);
2141
2142 if (!LHSReg || !RHSReg)
2143 return false;
2144
2145 const TargetRegisterInfo &TRI = *Subtarget->getRegisterInfo();
2146 unsigned Opc = X86::getCMovFromCond(CC, TRI.getRegSizeInBits(*RC)/8);
2147 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2148 LHSReg, LHSIsKill);
2149 updateValueMap(I, ResultReg);
2150 return true;
2151}
2152
2153/// Emit SSE or AVX instructions to lower the select.
2154///
2155/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2156/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
2157/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
2158bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2159 // Optimize conditions coming from a compare if both instructions are in the
2160 // same basic block (values defined in other basic blocks may not have
2161 // initialized registers).
2162 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2163 if (!CI || (CI->getParent() != I->getParent()))
2164 return false;
2165
2166 if (I->getType() != CI->getOperand(0)->getType() ||
2167 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2168 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2169 return false;
2170
2171 const Value *CmpLHS = CI->getOperand(0);
2172 const Value *CmpRHS = CI->getOperand(1);
2173 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2174
2175 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2176 // We don't have to materialize a zero constant for this case and can just use
2177 // %x again on the RHS.
2178 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2179 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2180 if (CmpRHSC && CmpRHSC->isNullValue())
2181 CmpRHS = CmpLHS;
2182 }
2183
2184 unsigned CC;
2185 bool NeedSwap;
2186 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2187 if (CC > 7 && !Subtarget->hasAVX())
2188 return false;
2189
2190 if (NeedSwap)
2191 std::swap(CmpLHS, CmpRHS);
2192
2193 // Choose the SSE instruction sequence based on data type (float or double).
2194 static const uint16_t OpcTable[2][4] = {
2195 { X86::CMPSSrr, X86::ANDPSrr, X86::ANDNPSrr, X86::ORPSrr },
2196 { X86::CMPSDrr, X86::ANDPDrr, X86::ANDNPDrr, X86::ORPDrr }
2197 };
2198
2199 const uint16_t *Opc = nullptr;
2200 switch (RetVT.SimpleTy) {
2201 default: return false;
2202 case MVT::f32: Opc = &OpcTable[0][0]; break;
2203 case MVT::f64: Opc = &OpcTable[1][0]; break;
2204 }
2205
2206 const Value *LHS = I->getOperand(1);
2207 const Value *RHS = I->getOperand(2);
2208
2209 unsigned LHSReg = getRegForValue(LHS);
2210 bool LHSIsKill = hasTrivialKill(LHS);
2211
2212 unsigned RHSReg = getRegForValue(RHS);
2213 bool RHSIsKill = hasTrivialKill(RHS);
2214
2215 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2216 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2217
2218 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2219 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2220
2221 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2222 return false;
2223
2224 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2225 unsigned ResultReg;
2226
2227 if (Subtarget->hasAVX512()) {
2228 // If we have AVX512 we can use a mask compare and masked movss/sd.
2229 const TargetRegisterClass *VR128X = &X86::VR128XRegClass;
2230 const TargetRegisterClass *VK1 = &X86::VK1RegClass;
2231
2232 unsigned CmpOpcode =
2233 (RetVT == MVT::f32) ? X86::VCMPSSZrr : X86::VCMPSDZrr;
2234 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, VK1, CmpLHSReg, CmpLHSIsKill,
2235 CmpRHSReg, CmpRHSIsKill, CC);
2236
2237 // Need an IMPLICIT_DEF for the input that is used to generate the upper
2238 // bits of the result register since its not based on any of the inputs.
2239 unsigned ImplicitDefReg = createResultReg(VR128X);
2240 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2241 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2242
2243 // Place RHSReg is the passthru of the masked movss/sd operation and put
2244 // LHS in the input. The mask input comes from the compare.
2245 unsigned MovOpcode =
2246 (RetVT == MVT::f32) ? X86::VMOVSSZrrk : X86::VMOVSDZrrk;
2247 unsigned MovReg = fastEmitInst_rrrr(MovOpcode, VR128X, RHSReg, RHSIsKill,
2248 CmpReg, true, ImplicitDefReg, true,
2249 LHSReg, LHSIsKill);
2250
2251 ResultReg = createResultReg(RC);
2252 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2253 TII.get(TargetOpcode::COPY), ResultReg).addReg(MovReg);
2254
2255 } else if (Subtarget->hasAVX()) {
2256 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2257
2258 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2259 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2260 // uses XMM0 as the selection register. That may need just as many
2261 // instructions as the AND/ANDN/OR sequence due to register moves, so
2262 // don't bother.
2263 unsigned CmpOpcode =
2264 (RetVT == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2265 unsigned BlendOpcode =
2266 (RetVT == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2267
2268 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpLHSIsKill,
2269 CmpRHSReg, CmpRHSIsKill, CC);
2270 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2271 LHSReg, LHSIsKill, CmpReg, true);
2272 ResultReg = createResultReg(RC);
2273 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2274 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
2275 } else {
2276 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2277 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2278 CmpRHSReg, CmpRHSIsKill, CC);
2279 unsigned AndReg = fastEmitInst_rr(Opc[1], VR128, CmpReg, /*IsKill=*/false,
2280 LHSReg, LHSIsKill);
2281 unsigned AndNReg = fastEmitInst_rr(Opc[2], VR128, CmpReg, /*IsKill=*/true,
2282 RHSReg, RHSIsKill);
2283 unsigned OrReg = fastEmitInst_rr(Opc[3], VR128, AndNReg, /*IsKill=*/true,
2284 AndReg, /*IsKill=*/true);
2285 ResultReg = createResultReg(RC);
2286 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2287 TII.get(TargetOpcode::COPY), ResultReg).addReg(OrReg);
2288 }
2289 updateValueMap(I, ResultReg);
2290 return true;
2291}
2292
2293bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2294 // These are pseudo CMOV instructions and will be later expanded into control-
2295 // flow.
2296 unsigned Opc;
2297 switch (RetVT.SimpleTy) {
2298 default: return false;
2299 case MVT::i8: Opc = X86::CMOV_GR8; break;
2300 case MVT::i16: Opc = X86::CMOV_GR16; break;
2301 case MVT::i32: Opc = X86::CMOV_GR32; break;
2302 case MVT::f32: Opc = X86::CMOV_FR32; break;
2303 case MVT::f64: Opc = X86::CMOV_FR64; break;
2304 }
2305
2306 const Value *Cond = I->getOperand(0);
2307 X86::CondCode CC = X86::COND_NE;
2308
2309 // Optimize conditions coming from a compare if both instructions are in the
2310 // same basic block (values defined in other basic blocks may not have
2311 // initialized registers).
2312 const auto *CI = dyn_cast<CmpInst>(Cond);
2313 if (CI && (CI->getParent() == I->getParent())) {
2314 bool NeedSwap;
2315 std::tie(CC, NeedSwap) = X86::getX86ConditionCode(CI->getPredicate());
2316 if (CC > X86::LAST_VALID_COND)
2317 return false;
2318
2319 const Value *CmpLHS = CI->getOperand(0);
2320 const Value *CmpRHS = CI->getOperand(1);
2321
2322 if (NeedSwap)
2323 std::swap(CmpLHS, CmpRHS);
2324
2325 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2326 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2327 return false;
2328 } else {
2329 unsigned CondReg = getRegForValue(Cond);
2330 if (CondReg == 0)
2331 return false;
2332 bool CondIsKill = hasTrivialKill(Cond);
2333
2334 // In case OpReg is a K register, COPY to a GPR
2335 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2336 unsigned KCondReg = CondReg;
2337 CondReg = createResultReg(&X86::GR32RegClass);
2338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2339 TII.get(TargetOpcode::COPY), CondReg)
2340 .addReg(KCondReg, getKillRegState(CondIsKill));
2341 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, /*Kill=*/true,
2342 X86::sub_8bit);
2343 }
2344 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2345 .addReg(CondReg, getKillRegState(CondIsKill))
2346 .addImm(1);
2347 }
2348
2349 const Value *LHS = I->getOperand(1);
2350 const Value *RHS = I->getOperand(2);
2351
2352 unsigned LHSReg = getRegForValue(LHS);
2353 bool LHSIsKill = hasTrivialKill(LHS);
2354
2355 unsigned RHSReg = getRegForValue(RHS);
2356 bool RHSIsKill = hasTrivialKill(RHS);
2357
2358 if (!LHSReg || !RHSReg)
2359 return false;
2360
2361 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2362
2363 unsigned ResultReg =
2364 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2365 updateValueMap(I, ResultReg);
2366 return true;
2367}
2368
2369bool X86FastISel::X86SelectSelect(const Instruction *I) {
2370 MVT RetVT;
2371 if (!isTypeLegal(I->getType(), RetVT))
2372 return false;
2373
2374 // Check if we can fold the select.
2375 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2376 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2377 const Value *Opnd = nullptr;
2378 switch (Predicate) {
2379 default: break;
2380 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2381 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2382 }
2383 // No need for a select anymore - this is an unconditional move.
2384 if (Opnd) {
2385 unsigned OpReg = getRegForValue(Opnd);
2386 if (OpReg == 0)
2387 return false;
2388 bool OpIsKill = hasTrivialKill(Opnd);
2389 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2390 unsigned ResultReg = createResultReg(RC);
2391 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2392 TII.get(TargetOpcode::COPY), ResultReg)
2393 .addReg(OpReg, getKillRegState(OpIsKill));
2394 updateValueMap(I, ResultReg);
2395 return true;
2396 }
2397 }
2398
2399 // First try to use real conditional move instructions.
2400 if (X86FastEmitCMoveSelect(RetVT, I))
2401 return true;
2402
2403 // Try to use a sequence of SSE instructions to simulate a conditional move.
2404 if (X86FastEmitSSESelect(RetVT, I))
2405 return true;
2406
2407 // Fall-back to pseudo conditional move instructions, which will be later
2408 // converted to control-flow.
2409 if (X86FastEmitPseudoSelect(RetVT, I))
2410 return true;
2411
2412 return false;
2413}
2414
2415// Common code for X86SelectSIToFP and X86SelectUIToFP.
2416bool X86FastISel::X86SelectIntToFP(const Instruction *I, bool IsSigned) {
2417 // The target-independent selection algorithm in FastISel already knows how
2418 // to select a SINT_TO_FP if the target is SSE but not AVX.
2419 // Early exit if the subtarget doesn't have AVX.
2420 // Unsigned conversion requires avx512.
2421 bool HasAVX512 = Subtarget->hasAVX512();
2422 if (!Subtarget->hasAVX() || (!IsSigned && !HasAVX512))
2423 return false;
2424
2425 // TODO: We could sign extend narrower types.
2426 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
2427 if (SrcVT != MVT::i32 && SrcVT != MVT::i64)
2428 return false;
2429
2430 // Select integer to float/double conversion.
2431 unsigned OpReg = getRegForValue(I->getOperand(0));
2432 if (OpReg == 0)
2433 return false;
2434
2435 unsigned Opcode;
2436
2437 static const uint16_t SCvtOpc[2][2][2] = {
2438 { { X86::VCVTSI2SSrr, X86::VCVTSI642SSrr },
2439 { X86::VCVTSI2SDrr, X86::VCVTSI642SDrr } },
2440 { { X86::VCVTSI2SSZrr, X86::VCVTSI642SSZrr },
2441 { X86::VCVTSI2SDZrr, X86::VCVTSI642SDZrr } },
2442 };
2443 static const uint16_t UCvtOpc[2][2] = {
2444 { X86::VCVTUSI2SSZrr, X86::VCVTUSI642SSZrr },
2445 { X86::VCVTUSI2SDZrr, X86::VCVTUSI642SDZrr },
2446 };
2447 bool Is64Bit = SrcVT == MVT::i64;
2448
2449 if (I->getType()->isDoubleTy()) {
2450 // s/uitofp int -> double
2451 Opcode = IsSigned ? SCvtOpc[HasAVX512][1][Is64Bit] : UCvtOpc[1][Is64Bit];
2452 } else if (I->getType()->isFloatTy()) {
2453 // s/uitofp int -> float
2454 Opcode = IsSigned ? SCvtOpc[HasAVX512][0][Is64Bit] : UCvtOpc[0][Is64Bit];
2455 } else
2456 return false;
2457
2458 MVT DstVT = TLI.getValueType(DL, I->getType()).getSimpleVT();
2459 const TargetRegisterClass *RC = TLI.getRegClassFor(DstVT);
2460 unsigned ImplicitDefReg = createResultReg(RC);
2461 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2462 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2463 unsigned ResultReg =
2464 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
2465 updateValueMap(I, ResultReg);
2466 return true;
2467}
2468
2469bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2470 return X86SelectIntToFP(I, /*IsSigned*/true);
2471}
2472
2473bool X86FastISel::X86SelectUIToFP(const Instruction *I) {
2474 return X86SelectIntToFP(I, /*IsSigned*/false);
2475}
2476
2477// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2478bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2479 unsigned TargetOpc,
2480 const TargetRegisterClass *RC) {
2481 assert((I->getOpcode() == Instruction::FPExt ||(static_cast <bool> ((I->getOpcode() == Instruction::
FPExt || I->getOpcode() == Instruction::FPTrunc) &&
"Instruction must be an FPExt or FPTrunc!") ? void (0) : __assert_fail
("(I->getOpcode() == Instruction::FPExt || I->getOpcode() == Instruction::FPTrunc) && \"Instruction must be an FPExt or FPTrunc!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2483, __extension__ __PRETTY_FUNCTION__))
2482 I->getOpcode() == Instruction::FPTrunc) &&(static_cast <bool> ((I->getOpcode() == Instruction::
FPExt || I->getOpcode() == Instruction::FPTrunc) &&
"Instruction must be an FPExt or FPTrunc!") ? void (0) : __assert_fail
("(I->getOpcode() == Instruction::FPExt || I->getOpcode() == Instruction::FPTrunc) && \"Instruction must be an FPExt or FPTrunc!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2483, __extension__ __PRETTY_FUNCTION__))
2483 "Instruction must be an FPExt or FPTrunc!")(static_cast <bool> ((I->getOpcode() == Instruction::
FPExt || I->getOpcode() == Instruction::FPTrunc) &&
"Instruction must be an FPExt or FPTrunc!") ? void (0) : __assert_fail
("(I->getOpcode() == Instruction::FPExt || I->getOpcode() == Instruction::FPTrunc) && \"Instruction must be an FPExt or FPTrunc!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2483, __extension__ __PRETTY_FUNCTION__))
;
2484
2485 unsigned OpReg = getRegForValue(I->getOperand(0));
2486 if (OpReg == 0)
8
Assuming 'OpReg' is not equal to 0
9
Taking false branch
2487 return false;
2488
2489 unsigned ImplicitDefReg;
10
'ImplicitDefReg' declared without an initial value
2490 if (Subtarget->hasAVX()) {
11
Taking false branch
2491 ImplicitDefReg = createResultReg(RC);
2492 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2493 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2494
2495 }
2496
2497 unsigned ResultReg = createResultReg(RC);
2498 MachineInstrBuilder MIB;
2499 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2500 ResultReg);
2501
2502 if (Subtarget->hasAVX())
12
Taking true branch
2503 MIB.addReg(ImplicitDefReg);
13
1st function call argument is an uninitialized value
2504
2505 MIB.addReg(OpReg);
2506 updateValueMap(I, ResultReg);
2507 return true;
2508}
2509
2510bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2511 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
3
Assuming the condition is true
4
Taking true branch
2512 I->getOperand(0)->getType()->isFloatTy()) {
2513 bool HasAVX512 = Subtarget->hasAVX512();
2514 // fpext from float to double.
2515 unsigned Opc =
2516 HasAVX512 ? X86::VCVTSS2SDZrr
5
'?' condition is true
2517 : Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2518 return X86SelectFPExtOrFPTrunc(
7
Calling 'X86FastISel::X86SelectFPExtOrFPTrunc'
2519 I, Opc, HasAVX512 ? &X86::FR64XRegClass : &X86::FR64RegClass);
6
'?' condition is true
2520 }
2521
2522 return false;
2523}
2524
2525bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2526 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2527 I->getOperand(0)->getType()->isDoubleTy()) {
2528 bool HasAVX512 = Subtarget->hasAVX512();
2529 // fptrunc from double to float.
2530 unsigned Opc =
2531 HasAVX512 ? X86::VCVTSD2SSZrr
2532 : Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2533 return X86SelectFPExtOrFPTrunc(
2534 I, Opc, HasAVX512 ? &X86::FR32XRegClass : &X86::FR32RegClass);
2535 }
2536
2537 return false;
2538}
2539
2540bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2541 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2542 EVT DstVT = TLI.getValueType(DL, I->getType());
2543
2544 // This code only handles truncation to byte.
2545 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2546 return false;
2547 if (!TLI.isTypeLegal(SrcVT))
2548 return false;
2549
2550 unsigned InputReg = getRegForValue(I->getOperand(0));
2551 if (!InputReg)
2552 // Unhandled operand. Halt "fast" selection and bail.
2553 return false;
2554
2555 if (SrcVT == MVT::i8) {
2556 // Truncate from i8 to i1; no code needed.
2557 updateValueMap(I, InputReg);
2558 return true;
2559 }
2560
2561 // Issue an extract_subreg.
2562 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
2563 InputReg, false,
2564 X86::sub_8bit);
2565 if (!ResultReg)
2566 return false;
2567
2568 updateValueMap(I, ResultReg);
2569 return true;
2570}
2571
2572bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2573 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2574}
2575
2576bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2577 X86AddressMode SrcAM, uint64_t Len) {
2578
2579 // Make sure we don't bloat code by inlining very large memcpy's.
2580 if (!IsMemcpySmall(Len))
2581 return false;
2582
2583 bool i64Legal = Subtarget->is64Bit();
2584
2585 // We don't care about alignment here since we just emit integer accesses.
2586 while (Len) {
2587 MVT VT;
2588 if (Len >= 8 && i64Legal)
2589 VT = MVT::i64;
2590 else if (Len >= 4)
2591 VT = MVT::i32;
2592 else if (Len >= 2)
2593 VT = MVT::i16;
2594 else
2595 VT = MVT::i8;
2596
2597 unsigned Reg;
2598 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2599 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2600 assert(RV && "Failed to emit load or store??")(static_cast <bool> (RV && "Failed to emit load or store??"
) ? void (0) : __assert_fail ("RV && \"Failed to emit load or store??\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2600, __extension__ __PRETTY_FUNCTION__))
;
2601
2602 unsigned Size = VT.getSizeInBits()/8;
2603 Len -= Size;
2604 DestAM.Disp += Size;
2605 SrcAM.Disp += Size;
2606 }
2607
2608 return true;
2609}
2610
2611bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2612 // FIXME: Handle more intrinsics.
2613 switch (II->getIntrinsicID()) {
2614 default: return false;
2615 case Intrinsic::convert_from_fp16:
2616 case Intrinsic::convert_to_fp16: {
2617 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
2618 return false;
2619
2620 const Value *Op = II->getArgOperand(0);
2621 unsigned InputReg = getRegForValue(Op);
2622 if (InputReg == 0)
2623 return false;
2624
2625 // F16C only allows converting from float to half and from half to float.
2626 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2627 if (IsFloatToHalf) {
2628 if (!Op->getType()->isFloatTy())
2629 return false;
2630 } else {
2631 if (!II->getType()->isFloatTy())
2632 return false;
2633 }
2634
2635 unsigned ResultReg = 0;
2636 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2637 if (IsFloatToHalf) {
2638 // 'InputReg' is implicitly promoted from register class FR32 to
2639 // register class VR128 by method 'constrainOperandRegClass' which is
2640 // directly called by 'fastEmitInst_ri'.
2641 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2642 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2643 // It's consistent with the other FP instructions, which are usually
2644 // controlled by MXCSR.
2645 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
2646
2647 // Move the lower 32-bits of ResultReg to another register of class GR32.
2648 ResultReg = createResultReg(&X86::GR32RegClass);
2649 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2650 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2651 .addReg(InputReg, RegState::Kill);
2652
2653 // The result value is in the lower 16-bits of ResultReg.
2654 unsigned RegIdx = X86::sub_16bit;
2655 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2656 } else {
2657 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!")(static_cast <bool> (Op->getType()->isIntegerTy(16
) && "Expected a 16-bit integer!") ? void (0) : __assert_fail
("Op->getType()->isIntegerTy(16) && \"Expected a 16-bit integer!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2657, __extension__ __PRETTY_FUNCTION__))
;
2658 // Explicitly sign-extend the input to 32-bit.
2659 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2660 /*Kill=*/false);
2661
2662 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2663 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2664 InputReg, /*Kill=*/true);
2665
2666 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2667
2668 // The result value is in the lower 32-bits of ResultReg.
2669 // Emit an explicit copy from register class VR128 to register class FR32.
2670 ResultReg = createResultReg(&X86::FR32RegClass);
2671 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2672 TII.get(TargetOpcode::COPY), ResultReg)
2673 .addReg(InputReg, RegState::Kill);
2674 }
2675
2676 updateValueMap(II, ResultReg);
2677 return true;
2678 }
2679 case Intrinsic::frameaddress: {
2680 MachineFunction *MF = FuncInfo.MF;
2681 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2682 return false;
2683
2684 Type *RetTy = II->getCalledFunction()->getReturnType();
2685
2686 MVT VT;
2687 if (!isTypeLegal(RetTy, VT))
2688 return false;
2689
2690 unsigned Opc;
2691 const TargetRegisterClass *RC = nullptr;
2692
2693 switch (VT.SimpleTy) {
2694 default: llvm_unreachable("Invalid result type for frameaddress.")::llvm::llvm_unreachable_internal("Invalid result type for frameaddress."
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2694)
;
2695 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2696 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2697 }
2698
2699 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2700 // we get the wrong frame register.
2701 MachineFrameInfo &MFI = MF->getFrameInfo();
2702 MFI.setFrameAddressIsTaken(true);
2703
2704 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2705 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2706 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||(static_cast <bool> (((FrameReg == X86::RBP && VT
== MVT::i64) || (FrameReg == X86::EBP && VT == MVT::
i32)) && "Invalid Frame Register!") ? void (0) : __assert_fail
("((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg == X86::EBP && VT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2708, __extension__ __PRETTY_FUNCTION__))
2707 (FrameReg == X86::EBP && VT == MVT::i32)) &&(static_cast <bool> (((FrameReg == X86::RBP && VT
== MVT::i64) || (FrameReg == X86::EBP && VT == MVT::
i32)) && "Invalid Frame Register!") ? void (0) : __assert_fail
("((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg == X86::EBP && VT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2708, __extension__ __PRETTY_FUNCTION__))
2708 "Invalid Frame Register!")(static_cast <bool> (((FrameReg == X86::RBP && VT
== MVT::i64) || (FrameReg == X86::EBP && VT == MVT::
i32)) && "Invalid Frame Register!") ? void (0) : __assert_fail
("((FrameReg == X86::RBP && VT == MVT::i64) || (FrameReg == X86::EBP && VT == MVT::i32)) && \"Invalid Frame Register!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2708, __extension__ __PRETTY_FUNCTION__))
;
2709
2710 // Always make a copy of the frame register to a vreg first, so that we
2711 // never directly reference the frame register (the TwoAddressInstruction-
2712 // Pass doesn't like that).
2713 unsigned SrcReg = createResultReg(RC);
2714 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2715 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2716
2717 // Now recursively load from the frame address.
2718 // movq (%rbp), %rax
2719 // movq (%rax), %rax
2720 // movq (%rax), %rax
2721 // ...
2722 unsigned DestReg;
2723 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2724 while (Depth--) {
2725 DestReg = createResultReg(RC);
2726 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2727 TII.get(Opc), DestReg), SrcReg);
2728 SrcReg = DestReg;
2729 }
2730
2731 updateValueMap(II, SrcReg);
2732 return true;
2733 }
2734 case Intrinsic::memcpy: {
2735 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2736 // Don't handle volatile or variable length memcpys.
2737 if (MCI->isVolatile())
2738 return false;
2739
2740 if (isa<ConstantInt>(MCI->getLength())) {
2741 // Small memcpy's are common enough that we want to do them
2742 // without a call if possible.
2743 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2744 if (IsMemcpySmall(Len)) {
2745 X86AddressMode DestAM, SrcAM;
2746 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2747 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2748 return false;
2749 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2750 return true;
2751 }
2752 }
2753
2754 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2755 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2756 return false;
2757
2758 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2759 return false;
2760
2761 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 1);
2762 }
2763 case Intrinsic::memset: {
2764 const MemSetInst *MSI = cast<MemSetInst>(II);
2765
2766 if (MSI->isVolatile())
2767 return false;
2768
2769 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2770 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2771 return false;
2772
2773 if (MSI->getDestAddressSpace() > 255)
2774 return false;
2775
2776 return lowerCallTo(II, "memset", II->getNumArgOperands() - 1);
2777 }
2778 case Intrinsic::stackprotector: {
2779 // Emit code to store the stack guard onto the stack.
2780 EVT PtrTy = TLI.getPointerTy(DL);
2781
2782 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2783 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2784
2785 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2786
2787 // Grab the frame index.
2788 X86AddressMode AM;
2789 if (!X86SelectAddress(Slot, AM)) return false;
2790 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2791 return true;
2792 }
2793 case Intrinsic::dbg_declare: {
2794 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2795 X86AddressMode AM;
2796 assert(DI->getAddress() && "Null address should be checked earlier!")(static_cast <bool> (DI->getAddress() && "Null address should be checked earlier!"
) ? void (0) : __assert_fail ("DI->getAddress() && \"Null address should be checked earlier!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2796, __extension__ __PRETTY_FUNCTION__))
;
2797 if (!X86SelectAddress(DI->getAddress(), AM))
2798 return false;
2799 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2800 // FIXME may need to add RegState::Debug to any registers produced,
2801 // although ESP/EBP should be the only ones at the moment.
2802 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&(static_cast <bool> (DI->getVariable()->isValidLocationForIntrinsic
(DbgLoc) && "Expected inlined-at fields to agree") ? void
(0) : __assert_fail ("DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) && \"Expected inlined-at fields to agree\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2803, __extension__ __PRETTY_FUNCTION__))
2803 "Expected inlined-at fields to agree")(static_cast <bool> (DI->getVariable()->isValidLocationForIntrinsic
(DbgLoc) && "Expected inlined-at fields to agree") ? void
(0) : __assert_fail ("DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) && \"Expected inlined-at fields to agree\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2803, __extension__ __PRETTY_FUNCTION__))
;
2804 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2805 .addImm(0)
2806 .addMetadata(DI->getVariable())
2807 .addMetadata(DI->getExpression());
2808 return true;
2809 }
2810 case Intrinsic::trap: {
2811 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2812 return true;
2813 }
2814 case Intrinsic::sqrt: {
2815 if (!Subtarget->hasSSE1())
2816 return false;
2817
2818 Type *RetTy = II->getCalledFunction()->getReturnType();
2819
2820 MVT VT;
2821 if (!isTypeLegal(RetTy, VT))
2822 return false;
2823
2824 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2825 // is not generated by FastISel yet.
2826 // FIXME: Update this code once tablegen can handle it.
2827 static const uint16_t SqrtOpc[3][2] = {
2828 { X86::SQRTSSr, X86::SQRTSDr },
2829 { X86::VSQRTSSr, X86::VSQRTSDr },
2830 { X86::VSQRTSSZr, X86::VSQRTSDZr },
2831 };
2832 unsigned AVXLevel = Subtarget->hasAVX512() ? 2 :
2833 Subtarget->hasAVX() ? 1 :
2834 0;
2835 unsigned Opc;
2836 switch (VT.SimpleTy) {
2837 default: return false;
2838 case MVT::f32: Opc = SqrtOpc[AVXLevel][0]; break;
2839 case MVT::f64: Opc = SqrtOpc[AVXLevel][1]; break;
2840 }
2841
2842 const Value *SrcVal = II->getArgOperand(0);
2843 unsigned SrcReg = getRegForValue(SrcVal);
2844
2845 if (SrcReg == 0)
2846 return false;
2847
2848 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2849 unsigned ImplicitDefReg = 0;
2850 if (AVXLevel > 0) {
2851 ImplicitDefReg = createResultReg(RC);
2852 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2853 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2854 }
2855
2856 unsigned ResultReg = createResultReg(RC);
2857 MachineInstrBuilder MIB;
2858 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2859 ResultReg);
2860
2861 if (ImplicitDefReg)
2862 MIB.addReg(ImplicitDefReg);
2863
2864 MIB.addReg(SrcReg);
2865
2866 updateValueMap(II, ResultReg);
2867 return true;
2868 }
2869 case Intrinsic::sadd_with_overflow:
2870 case Intrinsic::uadd_with_overflow:
2871 case Intrinsic::ssub_with_overflow:
2872 case Intrinsic::usub_with_overflow:
2873 case Intrinsic::smul_with_overflow:
2874 case Intrinsic::umul_with_overflow: {
2875 // This implements the basic lowering of the xalu with overflow intrinsics
2876 // into add/sub/mul followed by either seto or setb.
2877 const Function *Callee = II->getCalledFunction();
2878 auto *Ty = cast<StructType>(Callee->getReturnType());
2879 Type *RetTy = Ty->getTypeAtIndex(0U);
2880 assert(Ty->getTypeAtIndex(1)->isIntegerTy() &&(static_cast <bool> (Ty->getTypeAtIndex(1)->isIntegerTy
() && Ty->getTypeAtIndex(1)->getScalarSizeInBits
() == 1 && "Overflow value expected to be an i1") ? void
(0) : __assert_fail ("Ty->getTypeAtIndex(1)->isIntegerTy() && Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 && \"Overflow value expected to be an i1\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2882, __extension__ __PRETTY_FUNCTION__))
2881 Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 &&(static_cast <bool> (Ty->getTypeAtIndex(1)->isIntegerTy
() && Ty->getTypeAtIndex(1)->getScalarSizeInBits
() == 1 && "Overflow value expected to be an i1") ? void
(0) : __assert_fail ("Ty->getTypeAtIndex(1)->isIntegerTy() && Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 && \"Overflow value expected to be an i1\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2882, __extension__ __PRETTY_FUNCTION__))
2882 "Overflow value expected to be an i1")(static_cast <bool> (Ty->getTypeAtIndex(1)->isIntegerTy
() && Ty->getTypeAtIndex(1)->getScalarSizeInBits
() == 1 && "Overflow value expected to be an i1") ? void
(0) : __assert_fail ("Ty->getTypeAtIndex(1)->isIntegerTy() && Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 && \"Overflow value expected to be an i1\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2882, __extension__ __PRETTY_FUNCTION__))
;
2883
2884 MVT VT;
2885 if (!isTypeLegal(RetTy, VT))
2886 return false;
2887
2888 if (VT < MVT::i8 || VT > MVT::i64)
2889 return false;
2890
2891 const Value *LHS = II->getArgOperand(0);
2892 const Value *RHS = II->getArgOperand(1);
2893
2894 // Canonicalize immediate to the RHS.
2895 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2896 isCommutativeIntrinsic(II))
2897 std::swap(LHS, RHS);
2898
2899 bool UseIncDec = false;
2900 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2901 UseIncDec = true;
2902
2903 unsigned BaseOpc, CondOpc;
2904 switch (II->getIntrinsicID()) {
2905 default: llvm_unreachable("Unexpected intrinsic!")::llvm::llvm_unreachable_internal("Unexpected intrinsic!", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2905)
;
2906 case Intrinsic::sadd_with_overflow:
2907 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2908 CondOpc = X86::SETOr;
2909 break;
2910 case Intrinsic::uadd_with_overflow:
2911 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2912 case Intrinsic::ssub_with_overflow:
2913 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2914 CondOpc = X86::SETOr;
2915 break;
2916 case Intrinsic::usub_with_overflow:
2917 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2918 case Intrinsic::smul_with_overflow:
2919 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2920 case Intrinsic::umul_with_overflow:
2921 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2922 }
2923
2924 unsigned LHSReg = getRegForValue(LHS);
2925 if (LHSReg == 0)
2926 return false;
2927 bool LHSIsKill = hasTrivialKill(LHS);
2928
2929 unsigned ResultReg = 0;
2930 // Check if we have an immediate version.
2931 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2932 static const uint16_t Opc[2][4] = {
2933 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2934 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2935 };
2936
2937 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2938 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2939 bool IsDec = BaseOpc == X86ISD::DEC;
2940 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2941 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2942 .addReg(LHSReg, getKillRegState(LHSIsKill));
2943 } else
2944 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2945 CI->getZExtValue());
2946 }
2947
2948 unsigned RHSReg;
2949 bool RHSIsKill;
2950 if (!ResultReg) {
2951 RHSReg = getRegForValue(RHS);
2952 if (RHSReg == 0)
2953 return false;
2954 RHSIsKill = hasTrivialKill(RHS);
2955 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2956 RHSIsKill);
2957 }
2958
2959 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2960 // it manually.
2961 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2962 static const uint16_t MULOpc[] =
2963 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2964 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2965 // First copy the first operand into RAX, which is an implicit input to
2966 // the X86::MUL*r instruction.
2967 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2968 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2969 .addReg(LHSReg, getKillRegState(LHSIsKill));
2970 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2971 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2972 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2973 static const uint16_t MULOpc[] =
2974 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2975 if (VT == MVT::i8) {
2976 // Copy the first operand into AL, which is an implicit input to the
2977 // X86::IMUL8r instruction.
2978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2979 TII.get(TargetOpcode::COPY), X86::AL)
2980 .addReg(LHSReg, getKillRegState(LHSIsKill));
2981 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2982 RHSIsKill);
2983 } else
2984 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2985 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2986 RHSReg, RHSIsKill);
2987 }
2988
2989 if (!ResultReg)
2990 return false;
2991
2992 // Assign to a GPR since the overflow return value is lowered to a SETcc.
2993 unsigned ResultReg2 = createResultReg(&X86::GR8RegClass);
2994 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.")(static_cast <bool> ((ResultReg+1) == ResultReg2 &&
"Nonconsecutive result registers.") ? void (0) : __assert_fail
("(ResultReg+1) == ResultReg2 && \"Nonconsecutive result registers.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 2994, __extension__ __PRETTY_FUNCTION__))
;
2995 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2996 ResultReg2);
2997
2998 updateValueMap(II, ResultReg, 2);
2999 return true;
3000 }
3001 case Intrinsic::x86_sse_cvttss2si:
3002 case Intrinsic::x86_sse_cvttss2si64:
3003 case Intrinsic::x86_sse2_cvttsd2si:
3004 case Intrinsic::x86_sse2_cvttsd2si64: {
3005 bool IsInputDouble;
3006 switch (II->getIntrinsicID()) {
3007 default: llvm_unreachable("Unexpected intrinsic.")::llvm::llvm_unreachable_internal("Unexpected intrinsic.", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3007)
;
3008 case Intrinsic::x86_sse_cvttss2si:
3009 case Intrinsic::x86_sse_cvttss2si64:
3010 if (!Subtarget->hasSSE1())
3011 return false;
3012 IsInputDouble = false;
3013 break;
3014 case Intrinsic::x86_sse2_cvttsd2si:
3015 case Intrinsic::x86_sse2_cvttsd2si64:
3016 if (!Subtarget->hasSSE2())
3017 return false;
3018 IsInputDouble = true;
3019 break;
3020 }
3021
3022 Type *RetTy = II->getCalledFunction()->getReturnType();
3023 MVT VT;
3024 if (!isTypeLegal(RetTy, VT))
3025 return false;
3026
3027 static const uint16_t CvtOpc[3][2][2] = {
3028 { { X86::CVTTSS2SIrr, X86::CVTTSS2SI64rr },
3029 { X86::CVTTSD2SIrr, X86::CVTTSD2SI64rr } },
3030 { { X86::VCVTTSS2SIrr, X86::VCVTTSS2SI64rr },
3031 { X86::VCVTTSD2SIrr, X86::VCVTTSD2SI64rr } },
3032 { { X86::VCVTTSS2SIZrr, X86::VCVTTSS2SI64Zrr },
3033 { X86::VCVTTSD2SIZrr, X86::VCVTTSD2SI64Zrr } },
3034 };
3035 unsigned AVXLevel = Subtarget->hasAVX512() ? 2 :
3036 Subtarget->hasAVX() ? 1 :
3037 0;
3038 unsigned Opc;
3039 switch (VT.SimpleTy) {
3040 default: llvm_unreachable("Unexpected result type.")::llvm::llvm_unreachable_internal("Unexpected result type.", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3040)
;
3041 case MVT::i32: Opc = CvtOpc[AVXLevel][IsInputDouble][0]; break;
3042 case MVT::i64: Opc = CvtOpc[AVXLevel][IsInputDouble][1]; break;
3043 }
3044
3045 // Check if we can fold insertelement instructions into the convert.
3046 const Value *Op = II->getArgOperand(0);
3047 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
3048 const Value *Index = IE->getOperand(2);
3049 if (!isa<ConstantInt>(Index))
3050 break;
3051 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
3052
3053 if (Idx == 0) {
3054 Op = IE->getOperand(1);
3055 break;
3056 }
3057 Op = IE->getOperand(0);
3058 }
3059
3060 unsigned Reg = getRegForValue(Op);
3061 if (Reg == 0)
3062 return false;
3063
3064 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3066 .addReg(Reg);
3067
3068 updateValueMap(II, ResultReg);
3069 return true;
3070 }
3071 }
3072}
3073
3074bool X86FastISel::fastLowerArguments() {
3075 if (!FuncInfo.CanLowerReturn)
3076 return false;
3077
3078 const Function *F = FuncInfo.Fn;
3079 if (F->isVarArg())
3080 return false;
3081
3082 CallingConv::ID CC = F->getCallingConv();
3083 if (CC != CallingConv::C)
3084 return false;
3085
3086 if (Subtarget->isCallingConvWin64(CC))
3087 return false;
3088
3089 if (!Subtarget->is64Bit())
3090 return false;
3091
3092 if (Subtarget->useSoftFloat())
3093 return false;
3094
3095 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
3096 unsigned GPRCnt = 0;
3097 unsigned FPRCnt = 0;
3098 for (auto const &Arg : F->args()) {
3099 if (Arg.hasAttribute(Attribute::ByVal) ||
3100 Arg.hasAttribute(Attribute::InReg) ||
3101 Arg.hasAttribute(Attribute::StructRet) ||
3102 Arg.hasAttribute(Attribute::SwiftSelf) ||
3103 Arg.hasAttribute(Attribute::SwiftError) ||
3104 Arg.hasAttribute(Attribute::Nest))
3105 return false;
3106
3107 Type *ArgTy = Arg.getType();
3108 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3109 return false;
3110
3111 EVT ArgVT = TLI.getValueType(DL, ArgTy);
3112 if (!ArgVT.isSimple()) return false;
3113 switch (ArgVT.getSimpleVT().SimpleTy) {
3114 default: return false;
3115 case MVT::i32:
3116 case MVT::i64:
3117 ++GPRCnt;
3118 break;
3119 case MVT::f32:
3120 case MVT::f64:
3121 if (!Subtarget->hasSSE1())
3122 return false;
3123 ++FPRCnt;
3124 break;
3125 }
3126
3127 if (GPRCnt > 6)
3128 return false;
3129
3130 if (FPRCnt > 8)
3131 return false;
3132 }
3133
3134 static const MCPhysReg GPR32ArgRegs[] = {
3135 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
3136 };
3137 static const MCPhysReg GPR64ArgRegs[] = {
3138 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
3139 };
3140 static const MCPhysReg XMMArgRegs[] = {
3141 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3142 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3143 };
3144
3145 unsigned GPRIdx = 0;
3146 unsigned FPRIdx = 0;
3147 for (auto const &Arg : F->args()) {
3148 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
3149 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
3150 unsigned SrcReg;
3151 switch (VT.SimpleTy) {
3152 default: llvm_unreachable("Unexpected value type.")::llvm::llvm_unreachable_internal("Unexpected value type.", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3152)
;
3153 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
3154 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
3155 case MVT::f32: LLVM_FALLTHROUGH[[clang::fallthrough]];
3156 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
3157 }
3158 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3159 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3160 // Without this, EmitLiveInCopies may eliminate the livein if its only
3161 // use is a bitcast (which isn't turned into an instruction).
3162 unsigned ResultReg = createResultReg(RC);
3163 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3164 TII.get(TargetOpcode::COPY), ResultReg)
3165 .addReg(DstReg, getKillRegState(true));
3166 updateValueMap(&Arg, ResultReg);
3167 }
3168 return true;
3169}
3170
3171static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
3172 CallingConv::ID CC,
3173 ImmutableCallSite *CS) {
3174 if (Subtarget->is64Bit())
3175 return 0;
3176 if (Subtarget->getTargetTriple().isOSMSVCRT())
3177 return 0;
3178 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3179 CC == CallingConv::HiPE)
3180 return 0;
3181
3182 if (CS)
3183 if (CS->arg_empty() || !CS->paramHasAttr(0, Attribute::StructRet) ||
3184 CS->paramHasAttr(0, Attribute::InReg) || Subtarget->isTargetMCU())
3185 return 0;
3186
3187 return 4;
3188}
3189
3190bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3191 auto &OutVals = CLI.OutVals;
3192 auto &OutFlags = CLI.OutFlags;
3193 auto &OutRegs = CLI.OutRegs;
3194 auto &Ins = CLI.Ins;
3195 auto &InRegs = CLI.InRegs;
3196 CallingConv::ID CC = CLI.CallConv;
3197 bool &IsTailCall = CLI.IsTailCall;
3198 bool IsVarArg = CLI.IsVarArg;
3199 const Value *Callee = CLI.Callee;
3200 MCSymbol *Symbol = CLI.Symbol;
3201
3202 bool Is64Bit = Subtarget->is64Bit();
3203 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3204
3205 const CallInst *CI =
3206 CLI.CS ? dyn_cast<CallInst>(CLI.CS->getInstruction()) : nullptr;
3207 const Function *CalledFn = CI ? CI->getCalledFunction() : nullptr;
3208
3209 // Call / invoke instructions with NoCfCheck attribute require special
3210 // handling.
3211 const auto *II =
3212 CLI.CS ? dyn_cast<InvokeInst>(CLI.CS->getInstruction()) : nullptr;
3213 if ((CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck()))
3214 return false;
3215
3216 // Functions with no_caller_saved_registers that need special handling.
3217 if ((CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3218 (CalledFn && CalledFn->hasFnAttribute("no_caller_saved_registers")))
3219 return false;
3220
3221 // Functions using retpoline should use SDISel for calls.
3222 if (Subtarget->useRetpoline())
3223 return false;
3224
3225 // Handle only C, fastcc, and webkit_js calling conventions for now.
3226 switch (CC) {
3227 default: return false;
3228 case CallingConv::C:
3229 case CallingConv::Fast:
3230 case CallingConv::WebKit_JS:
3231 case CallingConv::Swift:
3232 case CallingConv::X86_FastCall:
3233 case CallingConv::X86_StdCall:
3234 case CallingConv::X86_ThisCall:
3235 case CallingConv::Win64:
3236 case CallingConv::X86_64_SysV:
3237 break;
3238 }
3239
3240 // Allow SelectionDAG isel to handle tail calls.
3241 if (IsTailCall)
3242 return false;
3243
3244 // fastcc with -tailcallopt is intended to provide a guaranteed
3245 // tail call optimization. Fastisel doesn't know how to do that.
3246 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3247 return false;
3248
3249 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3250 // x86-32. Special handling for x86-64 is implemented.
3251 if (IsVarArg && IsWin64)
3252 return false;
3253
3254 // Don't know about inalloca yet.
3255 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3256 return false;
3257
3258 for (auto Flag : CLI.OutFlags)
3259 if (Flag.isSwiftError())
3260 return false;
3261
3262 SmallVector<MVT, 16> OutVTs;
3263 SmallVector<unsigned, 16> ArgRegs;
3264
3265 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3266 // instruction. This is safe because it is common to all FastISel supported
3267 // calling conventions on x86.
3268 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3269 Value *&Val = OutVals[i];
3270 ISD::ArgFlagsTy Flags = OutFlags[i];
3271 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3272 if (CI->getBitWidth() < 32) {
3273 if (Flags.isSExt())
3274 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3275 else
3276 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3277 }
3278 }
3279
3280 // Passing bools around ends up doing a trunc to i1 and passing it.
3281 // Codegen this as an argument + "and 1".
3282 MVT VT;
3283 auto *TI = dyn_cast<TruncInst>(Val);
3284 unsigned ResultReg;
3285 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3286 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3287 TI->hasOneUse()) {
3288 Value *PrevVal = TI->getOperand(0);
3289 ResultReg = getRegForValue(PrevVal);
3290
3291 if (!ResultReg)
3292 return false;
3293
3294 if (!isTypeLegal(PrevVal->getType(), VT))
3295 return false;
3296
3297 ResultReg =
3298 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3299 } else {
3300 if (!isTypeLegal(Val->getType(), VT))
3301 return false;
3302 ResultReg = getRegForValue(Val);
3303 }
3304
3305 if (!ResultReg)
3306 return false;
3307
3308 ArgRegs.push_back(ResultReg);
3309 OutVTs.push_back(VT);
3310 }
3311
3312 // Analyze operands of the call, assigning locations to each operand.
3313 SmallVector<CCValAssign, 16> ArgLocs;
3314 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3315
3316 // Allocate shadow area for Win64
3317 if (IsWin64)
3318 CCInfo.AllocateStack(32, 8);
3319
3320 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3321
3322 // Get a count of how many bytes are to be pushed on the stack.
3323 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3324
3325 // Issue CALLSEQ_START
3326 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3327 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
3328 .addImm(NumBytes).addImm(0).addImm(0);
3329
3330 // Walk the register/memloc assignments, inserting copies/loads.
3331 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3332 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3333 CCValAssign const &VA = ArgLocs[i];
3334 const Value *ArgVal = OutVals[VA.getValNo()];
3335 MVT ArgVT = OutVTs[VA.getValNo()];
3336
3337 if (ArgVT == MVT::x86mmx)
3338 return false;
3339
3340 unsigned ArgReg = ArgRegs[VA.getValNo()];
3341
3342 // Promote the value if needed.
3343 switch (VA.getLocInfo()) {
3344 case CCValAssign::Full: break;
3345 case CCValAssign::SExt: {
3346 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&(static_cast <bool> (VA.getLocVT().isInteger() &&
!VA.getLocVT().isVector() && "Unexpected extend") ? void
(0) : __assert_fail ("VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && \"Unexpected extend\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3347, __extension__ __PRETTY_FUNCTION__))
3347 "Unexpected extend")(static_cast <bool> (VA.getLocVT().isInteger() &&
!VA.getLocVT().isVector() && "Unexpected extend") ? void
(0) : __assert_fail ("VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && \"Unexpected extend\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3347, __extension__ __PRETTY_FUNCTION__))
;
3348
3349 if (ArgVT == MVT::i1)
3350 return false;
3351
3352 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3353 ArgVT, ArgReg);
3354 assert(Emitted && "Failed to emit a sext!")(static_cast <bool> (Emitted && "Failed to emit a sext!"
) ? void (0) : __assert_fail ("Emitted && \"Failed to emit a sext!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3354, __extension__ __PRETTY_FUNCTION__))
; (void)Emitted;
3355 ArgVT = VA.getLocVT();
3356 break;
3357 }
3358 case CCValAssign::ZExt: {
3359 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&(static_cast <bool> (VA.getLocVT().isInteger() &&
!VA.getLocVT().isVector() && "Unexpected extend") ? void
(0) : __assert_fail ("VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && \"Unexpected extend\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3360, __extension__ __PRETTY_FUNCTION__))
3360 "Unexpected extend")(static_cast <bool> (VA.getLocVT().isInteger() &&
!VA.getLocVT().isVector() && "Unexpected extend") ? void
(0) : __assert_fail ("VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && \"Unexpected extend\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3360, __extension__ __PRETTY_FUNCTION__))
;
3361
3362 // Handle zero-extension from i1 to i8, which is common.
3363 if (ArgVT == MVT::i1) {
3364 // Set the high bits to zero.
3365 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3366 ArgVT = MVT::i8;
3367
3368 if (ArgReg == 0)
3369 return false;
3370 }
3371
3372 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3373 ArgVT, ArgReg);
3374 assert(Emitted && "Failed to emit a zext!")(static_cast <bool> (Emitted && "Failed to emit a zext!"
) ? void (0) : __assert_fail ("Emitted && \"Failed to emit a zext!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3374, __extension__ __PRETTY_FUNCTION__))
; (void)Emitted;
3375 ArgVT = VA.getLocVT();
3376 break;
3377 }
3378 case CCValAssign::AExt: {
3379 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&(static_cast <bool> (VA.getLocVT().isInteger() &&
!VA.getLocVT().isVector() && "Unexpected extend") ? void
(0) : __assert_fail ("VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && \"Unexpected extend\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3380, __extension__ __PRETTY_FUNCTION__))
3380 "Unexpected extend")(static_cast <bool> (VA.getLocVT().isInteger() &&
!VA.getLocVT().isVector() && "Unexpected extend") ? void
(0) : __assert_fail ("VA.getLocVT().isInteger() && !VA.getLocVT().isVector() && \"Unexpected extend\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3380, __extension__ __PRETTY_FUNCTION__))
;
3381 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3382 ArgVT, ArgReg);
3383 if (!Emitted)
3384 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3385 ArgVT, ArgReg);
3386 if (!Emitted)
3387 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3388 ArgVT, ArgReg);
3389
3390 assert(Emitted && "Failed to emit a aext!")(static_cast <bool> (Emitted && "Failed to emit a aext!"
) ? void (0) : __assert_fail ("Emitted && \"Failed to emit a aext!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3390, __extension__ __PRETTY_FUNCTION__))
; (void)Emitted;
3391 ArgVT = VA.getLocVT();
3392 break;
3393 }
3394 case CCValAssign::BCvt: {
3395 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3396 /*TODO: Kill=*/false);
3397 assert(ArgReg && "Failed to emit a bitcast!")(static_cast <bool> (ArgReg && "Failed to emit a bitcast!"
) ? void (0) : __assert_fail ("ArgReg && \"Failed to emit a bitcast!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3397, __extension__ __PRETTY_FUNCTION__))
;
3398 ArgVT = VA.getLocVT();
3399 break;
3400 }
3401 case CCValAssign::VExt:
3402 // VExt has not been implemented, so this should be impossible to reach
3403 // for now. However, fallback to Selection DAG isel once implemented.
3404 return false;
3405 case CCValAssign::AExtUpper:
3406 case CCValAssign::SExtUpper:
3407 case CCValAssign::ZExtUpper:
3408 case CCValAssign::FPExt:
3409 llvm_unreachable("Unexpected loc info!")::llvm::llvm_unreachable_internal("Unexpected loc info!", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3409)
;
3410 case CCValAssign::Indirect:
3411 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3412 // support this.
3413 return false;
3414 }
3415
3416 if (VA.isRegLoc()) {
3417 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3418 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3419 OutRegs.push_back(VA.getLocReg());
3420 } else {
3421 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3421, __extension__ __PRETTY_FUNCTION__))
;
3422
3423 // Don't emit stores for undef values.
3424 if (isa<UndefValue>(ArgVal))
3425 continue;
3426
3427 unsigned LocMemOffset = VA.getLocMemOffset();
3428 X86AddressMode AM;
3429 AM.Base.Reg = RegInfo->getStackRegister();
3430 AM.Disp = LocMemOffset;
3431 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3432 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3433 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3434 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3435 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3436 if (Flags.isByVal()) {
3437 X86AddressMode SrcAM;
3438 SrcAM.Base.Reg = ArgReg;
3439 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3440 return false;
3441 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3442 // If this is a really simple value, emit this with the Value* version
3443 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3444 // as it can cause us to reevaluate the argument.
3445 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3446 return false;
3447 } else {
3448 bool ValIsKill = hasTrivialKill(ArgVal);
3449 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3450 return false;
3451 }
3452 }
3453 }
3454
3455 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3456 // GOT pointer.
3457 if (Subtarget->isPICStyleGOT()) {
3458 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3459 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3460 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3461 }
3462
3463 if (Is64Bit && IsVarArg && !IsWin64) {
3464 // From AMD64 ABI document:
3465 // For calls that may call functions that use varargs or stdargs
3466 // (prototype-less calls or calls to functions containing ellipsis (...) in
3467 // the declaration) %al is used as hidden argument to specify the number
3468 // of SSE registers used. The contents of %al do not need to match exactly
3469 // the number of registers, but must be an ubound on the number of SSE
3470 // registers used and is in the range 0 - 8 inclusive.
3471
3472 // Count the number of XMM registers allocated.
3473 static const MCPhysReg XMMArgRegs[] = {
3474 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3475 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3476 };
3477 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3478 assert((Subtarget->hasSSE1() || !NumXMMRegs)(static_cast <bool> ((Subtarget->hasSSE1() || !NumXMMRegs
) && "SSE registers cannot be used when SSE is disabled"
) ? void (0) : __assert_fail ("(Subtarget->hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3479, __extension__ __PRETTY_FUNCTION__))
3479 && "SSE registers cannot be used when SSE is disabled")(static_cast <bool> ((Subtarget->hasSSE1() || !NumXMMRegs
) && "SSE registers cannot be used when SSE is disabled"
) ? void (0) : __assert_fail ("(Subtarget->hasSSE1() || !NumXMMRegs) && \"SSE registers cannot be used when SSE is disabled\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3479, __extension__ __PRETTY_FUNCTION__))
;
3480 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3481 X86::AL).addImm(NumXMMRegs);
3482 }
3483
3484 // Materialize callee address in a register. FIXME: GV address can be
3485 // handled with a CALLpcrel32 instead.
3486 X86AddressMode CalleeAM;
3487 if (!X86SelectCallAddress(Callee, CalleeAM))
3488 return false;
3489
3490 unsigned CalleeOp = 0;
3491 const GlobalValue *GV = nullptr;
3492 if (CalleeAM.GV != nullptr) {
3493 GV = CalleeAM.GV;
3494 } else if (CalleeAM.Base.Reg != 0) {
3495 CalleeOp = CalleeAM.Base.Reg;
3496 } else
3497 return false;
3498
3499 // Issue the call.
3500 MachineInstrBuilder MIB;
3501 if (CalleeOp) {
3502 // Register-indirect call.
3503 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3504 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3505 .addReg(CalleeOp);
3506 } else {
3507 // Direct call.
3508 assert(GV && "Not a direct call")(static_cast <bool> (GV && "Not a direct call")
? void (0) : __assert_fail ("GV && \"Not a direct call\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3508, __extension__ __PRETTY_FUNCTION__))
;
3509 // See if we need any target-specific flags on the GV operand.
3510 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
3511
3512 // This will be a direct call, or an indirect call through memory for
3513 // NonLazyBind calls or dllimport calls.
3514 bool NeedLoad =
3515 OpFlags == X86II::MO_DLLIMPORT || OpFlags == X86II::MO_GOTPCREL;
3516 unsigned CallOpc = NeedLoad
3517 ? (Is64Bit ? X86::CALL64m : X86::CALL32m)
3518 : (Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32);
3519
3520 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
3521 if (NeedLoad)
3522 MIB.addReg(Is64Bit ? X86::RIP : 0).addImm(1).addReg(0);
3523 if (Symbol)
3524 MIB.addSym(Symbol, OpFlags);
3525 else
3526 MIB.addGlobalAddress(GV, 0, OpFlags);
3527 if (NeedLoad)
3528 MIB.addReg(0);
3529 }
3530
3531 // Add a register mask operand representing the call-preserved registers.
3532 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3533 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3534
3535 // Add an implicit use GOT pointer in EBX.
3536 if (Subtarget->isPICStyleGOT())
3537 MIB.addReg(X86::EBX, RegState::Implicit);
3538
3539 if (Is64Bit && IsVarArg && !IsWin64)
3540 MIB.addReg(X86::AL, RegState::Implicit);
3541
3542 // Add implicit physical register uses to the call.
3543 for (auto Reg : OutRegs)
3544 MIB.addReg(Reg, RegState::Implicit);
3545
3546 // Issue CALLSEQ_END
3547 unsigned NumBytesForCalleeToPop =
3548 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3549 TM.Options.GuaranteedTailCallOpt)
3550 ? NumBytes // Callee pops everything.
3551 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
3552 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3553 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3554 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3555
3556 // Now handle call return values.
3557 SmallVector<CCValAssign, 16> RVLocs;
3558 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3559 CLI.RetTy->getContext());
3560 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3561
3562 // Copy all of the result registers out of their specified physreg.
3563 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3564 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3565 CCValAssign &VA = RVLocs[i];
3566 EVT CopyVT = VA.getValVT();
3567 unsigned CopyReg = ResultReg + i;
3568 unsigned SrcReg = VA.getLocReg();
3569
3570 // If this is x86-64, and we disabled SSE, we can't return FP values
3571 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3572 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3573 report_fatal_error("SSE register return with SSE disabled");
3574 }
3575
3576 // If we prefer to use the value in xmm registers, copy it out as f80 and
3577 // use a truncate to move it from fp stack reg to xmm reg.
3578 if ((SrcReg == X86::FP0 || SrcReg == X86::FP1) &&
3579 isScalarFPTypeInSSEReg(VA.getValVT())) {
3580 CopyVT = MVT::f80;
3581 CopyReg = createResultReg(&X86::RFP80RegClass);
3582 }
3583
3584 // Copy out the result.
3585 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3586 TII.get(TargetOpcode::COPY), CopyReg).addReg(SrcReg);
3587 InRegs.push_back(VA.getLocReg());
3588
3589 // Round the f80 to the right size, which also moves it to the appropriate
3590 // xmm register. This is accomplished by storing the f80 value in memory
3591 // and then loading it back.
3592 if (CopyVT != VA.getValVT()) {
3593 EVT ResVT = VA.getValVT();
3594 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3595 unsigned MemSize = ResVT.getSizeInBits()/8;
3596 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3597 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3598 TII.get(Opc)), FI)
3599 .addReg(CopyReg);
3600 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3601 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3602 TII.get(Opc), ResultReg + i), FI);
3603 }
3604 }
3605
3606 CLI.ResultReg = ResultReg;
3607 CLI.NumResultRegs = RVLocs.size();
3608 CLI.Call = MIB;
3609
3610 return true;
3611}
3612
3613bool
3614X86FastISel::fastSelectInstruction(const Instruction *I) {
3615 switch (I->getOpcode()) {
1
Control jumps to 'case FPExt:' at line 3645
3616 default: break;
3617 case Instruction::Load:
3618 return X86SelectLoad(I);
3619 case Instruction::Store:
3620 return X86SelectStore(I);
3621 case Instruction::Ret:
3622 return X86SelectRet(I);
3623 case Instruction::ICmp:
3624 case Instruction::FCmp:
3625 return X86SelectCmp(I);
3626 case Instruction::ZExt:
3627 return X86SelectZExt(I);
3628 case Instruction::SExt:
3629 return X86SelectSExt(I);
3630 case Instruction::Br:
3631 return X86SelectBranch(I);
3632 case Instruction::LShr:
3633 case Instruction::AShr:
3634 case Instruction::Shl:
3635 return X86SelectShift(I);
3636 case Instruction::SDiv:
3637 case Instruction::UDiv:
3638 case Instruction::SRem:
3639 case Instruction::URem:
3640 return X86SelectDivRem(I);
3641 case Instruction::Select:
3642 return X86SelectSelect(I);
3643 case Instruction::Trunc:
3644 return X86SelectTrunc(I);
3645 case Instruction::FPExt:
3646 return X86SelectFPExt(I);
2
Calling 'X86FastISel::X86SelectFPExt'
3647 case Instruction::FPTrunc:
3648 return X86SelectFPTrunc(I);
3649 case Instruction::SIToFP:
3650 return X86SelectSIToFP(I);
3651 case Instruction::UIToFP:
3652 return X86SelectUIToFP(I);
3653 case Instruction::IntToPtr: // Deliberate fall-through.
3654 case Instruction::PtrToInt: {
3655 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3656 EVT DstVT = TLI.getValueType(DL, I->getType());
3657 if (DstVT.bitsGT(SrcVT))
3658 return X86SelectZExt(I);
3659 if (DstVT.bitsLT(SrcVT))
3660 return X86SelectTrunc(I);
3661 unsigned Reg = getRegForValue(I->getOperand(0));
3662 if (Reg == 0) return false;
3663 updateValueMap(I, Reg);
3664 return true;
3665 }
3666 case Instruction::BitCast: {
3667 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3668 if (!Subtarget->hasSSE2())
3669 return false;
3670
3671 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3672 EVT DstVT = TLI.getValueType(DL, I->getType());
3673
3674 if (!SrcVT.isSimple() || !DstVT.isSimple())
3675 return false;
3676
3677 MVT SVT = SrcVT.getSimpleVT();
3678 MVT DVT = DstVT.getSimpleVT();
3679
3680 if (!SVT.is128BitVector() &&
3681 !(Subtarget->hasAVX() && SVT.is256BitVector()) &&
3682 !(Subtarget->hasAVX512() && SVT.is512BitVector() &&
3683 (Subtarget->hasBWI() || (SVT.getScalarSizeInBits() >= 32 &&
3684 DVT.getScalarSizeInBits() >= 32))))
3685 return false;
3686
3687 unsigned Reg = getRegForValue(I->getOperand(0));
3688 if (Reg == 0)
3689 return false;
3690
3691 // No instruction is needed for conversion. Reuse the register used by
3692 // the fist operand.
3693 updateValueMap(I, Reg);
3694 return true;
3695 }
3696 }
3697
3698 return false;
3699}
3700
3701unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3702 if (VT > MVT::i64)
3703 return 0;
3704
3705 uint64_t Imm = CI->getZExtValue();
3706 if (Imm == 0) {
3707 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3708 switch (VT.SimpleTy) {
3709 default: llvm_unreachable("Unexpected value type")::llvm::llvm_unreachable_internal("Unexpected value type", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3709)
;
3710 case MVT::i1:
3711 case MVT::i8:
3712 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3713 X86::sub_8bit);
3714 case MVT::i16:
3715 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3716 X86::sub_16bit);
3717 case MVT::i32:
3718 return SrcReg;
3719 case MVT::i64: {
3720 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3721 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3722 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3723 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3724 return ResultReg;
3725 }
3726 }
3727 }
3728
3729 unsigned Opc = 0;
3730 switch (VT.SimpleTy) {
3731 default: llvm_unreachable("Unexpected value type")::llvm::llvm_unreachable_internal("Unexpected value type", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3731)
;
3732 case MVT::i1:
3733 // TODO: Support this properly.
3734 if (Subtarget->hasAVX512())
3735 return 0;
3736 VT = MVT::i8;
3737 LLVM_FALLTHROUGH[[clang::fallthrough]];
3738 case MVT::i8: Opc = X86::MOV8ri; break;
3739 case MVT::i16: Opc = X86::MOV16ri; break;
3740 case MVT::i32: Opc = X86::MOV32ri; break;
3741 case MVT::i64: {
3742 if (isUInt<32>(Imm))
3743 Opc = X86::MOV32ri;
3744 else if (isInt<32>(Imm))
3745 Opc = X86::MOV64ri32;
3746 else
3747 Opc = X86::MOV64ri;
3748 break;
3749 }
3750 }
3751 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3752 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3753 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3754 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3755 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3756 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3757 return ResultReg;
3758 }
3759 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3760}
3761
3762unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3763 if (CFP->isNullValue())
3764 return fastMaterializeFloatZero(CFP);
3765
3766 // Can't handle alternate code models yet.
3767 CodeModel::Model CM = TM.getCodeModel();
3768 if (CM != CodeModel::Small && CM != CodeModel::Large)
3769 return 0;
3770
3771 // Get opcode and regclass of the output for the given load instruction.
3772 unsigned Opc = 0;
3773 const TargetRegisterClass *RC = nullptr;
3774 switch (VT.SimpleTy) {
3775 default: return 0;
3776 case MVT::f32:
3777 if (X86ScalarSSEf32) {
3778 Opc = Subtarget->hasAVX512()
3779 ? X86::VMOVSSZrm
3780 : Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3781 RC = Subtarget->hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3782 } else {
3783 Opc = X86::LD_Fp32m;
3784 RC = &X86::RFP32RegClass;
3785 }
3786 break;
3787 case MVT::f64:
3788 if (X86ScalarSSEf64) {
3789 Opc = Subtarget->hasAVX512()
3790 ? X86::VMOVSDZrm
3791 : Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3792 RC = Subtarget->hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3793 } else {
3794 Opc = X86::LD_Fp64m;
3795 RC = &X86::RFP64RegClass;
3796 }
3797 break;
3798 case MVT::f80:
3799 // No f80 support yet.
3800 return 0;
3801 }
3802
3803 // MachineConstantPool wants an explicit alignment.
3804 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3805 if (Align == 0) {
3806 // Alignment of vector types. FIXME!
3807 Align = DL.getTypeAllocSize(CFP->getType());
3808 }
3809
3810 // x86-32 PIC requires a PIC base register for constant pools.
3811 unsigned PICBase = 0;
3812 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3813 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
3814 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3815 else if (OpFlag == X86II::MO_GOTOFF)
3816 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3817 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
3818 PICBase = X86::RIP;
3819
3820 // Create the load from the constant pool.
3821 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3822 unsigned ResultReg = createResultReg(RC);
3823
3824 if (CM == CodeModel::Large) {
3825 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3826 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3827 AddrReg)
3828 .addConstantPoolIndex(CPI, 0, OpFlag);
3829 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3830 TII.get(Opc), ResultReg);
3831 addDirectMem(MIB, AddrReg);
3832 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3833 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3834 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
3835 MIB->addMemOperand(*FuncInfo.MF, MMO);
3836 return ResultReg;
3837 }
3838
3839 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3840 TII.get(Opc), ResultReg),
3841 CPI, PICBase, OpFlag);
3842 return ResultReg;
3843}
3844
3845unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3846 // Can't handle alternate code models yet.
3847 if (TM.getCodeModel() != CodeModel::Small)
3848 return 0;
3849
3850 // Materialize addresses with LEA/MOV instructions.
3851 X86AddressMode AM;
3852 if (X86SelectAddress(GV, AM)) {
3853 // If the expression is just a basereg, then we're done, otherwise we need
3854 // to emit an LEA.
3855 if (AM.BaseType == X86AddressMode::RegBase &&
3856 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3857 return AM.Base.Reg;
3858
3859 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3860 if (TM.getRelocationModel() == Reloc::Static &&
3861 TLI.getPointerTy(DL) == MVT::i64) {
3862 // The displacement code could be more than 32 bits away so we need to use
3863 // an instruction with a 64 bit immediate
3864 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3865 ResultReg)
3866 .addGlobalAddress(GV);
3867 } else {
3868 unsigned Opc =
3869 TLI.getPointerTy(DL) == MVT::i32
3870 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3871 : X86::LEA64r;
3872 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3873 TII.get(Opc), ResultReg), AM);
3874 }
3875 return ResultReg;
3876 }
3877 return 0;
3878}
3879
3880unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
3881 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
3882
3883 // Only handle simple types.
3884 if (!CEVT.isSimple())
3885 return 0;
3886 MVT VT = CEVT.getSimpleVT();
3887
3888 if (const auto *CI = dyn_cast<ConstantInt>(C))
3889 return X86MaterializeInt(CI, VT);
3890 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3891 return X86MaterializeFP(CFP, VT);
3892 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3893 return X86MaterializeGV(GV, VT);
3894
3895 return 0;
3896}
3897
3898unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3899 // Fail on dynamic allocas. At this point, getRegForValue has already
3900 // checked its CSE maps, so if we're here trying to handle a dynamic
3901 // alloca, we're not going to succeed. X86SelectAddress has a
3902 // check for dynamic allocas, because it's called directly from
3903 // various places, but targetMaterializeAlloca also needs a check
3904 // in order to avoid recursion between getRegForValue,
3905 // X86SelectAddrss, and targetMaterializeAlloca.
3906 if (!FuncInfo.StaticAllocaMap.count(C))
3907 return 0;
3908 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?")(static_cast <bool> (C->isStaticAlloca() && "dynamic alloca in the static alloca map?"
) ? void (0) : __assert_fail ("C->isStaticAlloca() && \"dynamic alloca in the static alloca map?\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Target/X86/X86FastISel.cpp"
, 3908, __extension__ __PRETTY_FUNCTION__))
;
3909
3910 X86AddressMode AM;
3911 if (!X86SelectAddress(C, AM))
3912 return 0;
3913 unsigned Opc =
3914 TLI.getPointerTy(DL) == MVT::i32
3915 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3916 : X86::LEA64r;
3917 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
3918 unsigned ResultReg = createResultReg(RC);
3919 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3920 TII.get(Opc), ResultReg), AM);
3921 return ResultReg;
3922}
3923
3924unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3925 MVT VT;
3926 if (!isTypeLegal(CF->getType(), VT))
3927 return 0;
3928
3929 // Get opcode and regclass for the given zero.
3930 bool HasAVX512 = Subtarget->hasAVX512();
3931 unsigned Opc = 0;
3932 const TargetRegisterClass *RC = nullptr;
3933 switch (VT.SimpleTy) {
3934 default: return 0;
3935 case MVT::f32:
3936 if (X86ScalarSSEf32) {
3937 Opc = HasAVX512 ? X86::AVX512_FsFLD0SS : X86::FsFLD0SS;
3938 RC = HasAVX512 ? &X86::FR32XRegClass : &X86::FR32RegClass;
3939 } else {
3940 Opc = X86::LD_Fp032;
3941 RC = &X86::RFP32RegClass;
3942 }
3943 break;
3944 case MVT::f64:
3945 if (X86ScalarSSEf64) {
3946 Opc = HasAVX512 ? X86::AVX512_FsFLD0SD : X86::FsFLD0SD;
3947 RC = HasAVX512 ? &X86::FR64XRegClass : &X86::FR64RegClass;
3948 } else {
3949 Opc = X86::LD_Fp064;
3950 RC = &X86::RFP64RegClass;
3951 }
3952 break;
3953 case MVT::f80:
3954 // No f80 support yet.
3955 return 0;
3956 }
3957
3958 unsigned ResultReg = createResultReg(RC);
3959 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3960 return ResultReg;
3961}
3962
3963
3964bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3965 const LoadInst *LI) {
3966 const Value *Ptr = LI->getPointerOperand();
3967 X86AddressMode AM;
3968 if (!X86SelectAddress(Ptr, AM))
3969 return false;
3970
3971 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3972
3973 unsigned Size = DL.getTypeAllocSize(LI->getType());
3974 unsigned Alignment = LI->getAlignment();
3975
3976 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3977 Alignment = DL.getABITypeAlignment(LI->getType());
3978
3979 SmallVector<MachineOperand, 8> AddrOps;
3980 AM.getFullAddress(AddrOps);
3981
3982 MachineInstr *Result = XII.foldMemoryOperandImpl(
3983 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3984 /*AllowCommute=*/true);
3985 if (!Result)
3986 return false;
3987
3988 // The index register could be in the wrong register class. Unfortunately,
3989 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3990 // to just look at OpNo + the offset to the index reg. We actually need to
3991 // scan the instruction to find the index reg and see if its the correct reg
3992 // class.
3993 unsigned OperandNo = 0;
3994 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3995 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3996 MachineOperand &MO = *I;
3997 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
3998 continue;
3999 // Found the index reg, now try to rewrite it.
4000 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
4001 MO.getReg(), OperandNo);
4002 if (IndexReg == MO.getReg())
4003 continue;
4004 MO.setReg(IndexReg);
4005 }
4006
4007 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
4008 MI->eraseFromParent();
4009 return true;
4010}
4011
4012unsigned X86FastISel::fastEmitInst_rrrr(unsigned MachineInstOpcode,
4013 const TargetRegisterClass *RC,
4014 unsigned Op0, bool Op0IsKill,
4015 unsigned Op1, bool Op1IsKill,
4016 unsigned Op2, bool Op2IsKill,
4017 unsigned Op3, bool Op3IsKill) {
4018 const MCInstrDesc &II = TII.get(MachineInstOpcode);
4019
4020 unsigned ResultReg = createResultReg(RC);
4021 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
4022 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
4023 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
4024 Op3 = constrainOperandRegClass(II, Op3, II.getNumDefs() + 3);
4025
4026 if (II.getNumDefs() >= 1)
4027 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
4028 .addReg(Op0, getKillRegState(Op0IsKill))
4029 .addReg(Op1, getKillRegState(Op1IsKill))
4030 .addReg(Op2, getKillRegState(Op2IsKill))
4031 .addReg(Op3, getKillRegState(Op3IsKill));
4032 else {
4033 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
4034 .addReg(Op0, getKillRegState(Op0IsKill))
4035 .addReg(Op1, getKillRegState(Op1IsKill))
4036 .addReg(Op2, getKillRegState(Op2IsKill))
4037 .addReg(Op3, getKillRegState(Op3IsKill));
4038 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4039 TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
4040 }
4041 return ResultReg;
4042}
4043
4044
4045namespace llvm {
4046 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
4047 const TargetLibraryInfo *libInfo) {
4048 return new X86FastISel(funcInfo, libInfo);
4049 }
4050}