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