blob: 0cc061501e4fb7552c6fd257bb987a94c88edafa [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"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000025#include "llvm/CodeGen/FastISel.h"
26#include "llvm/CodeGen/FunctionLoweringInfo.h"
27#include "llvm/CodeGen/MachineConstantPool.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineRegisterInfo.h"
30#include "llvm/IR/CallSite.h"
31#include "llvm/IR/CallingConv.h"
Reid Kleckner28865802016-04-14 18:29:59 +000032#include "llvm/IR/DebugInfo.h"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000033#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/GetElementPtrTypeIterator.h"
35#include "llvm/IR/GlobalAlias.h"
36#include "llvm/IR/GlobalVariable.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/Operator.h"
David Majnemerca194852015-02-10 22:00:34 +000040#include "llvm/MC/MCAsmInfo.h"
Rafael Espindolace4c2bc2015-06-23 12:21:54 +000041#include "llvm/MC/MCSymbol.h"
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000042#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Target/TargetOptions.h"
44using namespace llvm;
45
46namespace {
47
48class X86FastISel final : public FastISel {
49 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
50 /// make the right decision when generating code for different targets.
51 const X86Subtarget *Subtarget;
52
53 /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
54 /// floating point ops.
55 /// When SSE is available, use it for f32 operations.
56 /// When SSE2 is available, use it for f64 operations.
57 bool X86ScalarSSEf64;
58 bool X86ScalarSSEf32;
59
60public:
61 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
62 const TargetLibraryInfo *libInfo)
Eric Christophera1c535b2015-02-02 23:03:45 +000063 : FastISel(funcInfo, libInfo) {
64 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000065 X86ScalarSSEf64 = Subtarget->hasSSE2();
66 X86ScalarSSEf32 = Subtarget->hasSSE1();
67 }
68
69 bool fastSelectInstruction(const Instruction *I) override;
70
71 /// \brief The specified machine instr operand is a vreg, and that
72 /// vreg is being provided by the specified load instruction. If possible,
73 /// try to fold the load as an operand to the instruction, returning true if
74 /// possible.
75 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
76 const LoadInst *LI) override;
77
78 bool fastLowerArguments() override;
79 bool fastLowerCall(CallLoweringInfo &CLI) override;
80 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
81
82#include "X86GenFastISel.inc"
83
84private:
Benjamin Kramerbdc49562016-06-12 15:39:02 +000085 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
86 const DebugLoc &DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000087
Pete Cooperd0dae3e2015-05-05 23:41:53 +000088 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +000089 unsigned &ResultReg, unsigned Alignment = 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000090
Pete Cooperd0dae3e2015-05-05 23:41:53 +000091 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000092 MachineMemOperand *MMO = nullptr, bool Aligned = false);
93 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +000094 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000095 MachineMemOperand *MMO = nullptr, bool Aligned = false);
96
97 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
98 unsigned &ResultReg);
99
100 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
101 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
102
103 bool X86SelectLoad(const Instruction *I);
104
105 bool X86SelectStore(const Instruction *I);
106
107 bool X86SelectRet(const Instruction *I);
108
109 bool X86SelectCmp(const Instruction *I);
110
111 bool X86SelectZExt(const Instruction *I);
112
113 bool X86SelectBranch(const Instruction *I);
114
115 bool X86SelectShift(const Instruction *I);
116
117 bool X86SelectDivRem(const Instruction *I);
118
119 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
120
121 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
122
123 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
124
125 bool X86SelectSelect(const Instruction *I);
126
127 bool X86SelectTrunc(const Instruction *I);
128
Andrea Di Biagio62622d22015-02-10 12:04:41 +0000129 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
130 const TargetRegisterClass *RC);
131
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000132 bool X86SelectFPExt(const Instruction *I);
133 bool X86SelectFPTrunc(const Instruction *I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +0000134 bool X86SelectSIToFP(const Instruction *I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000135
136 const X86InstrInfo *getInstrInfo() const {
Eric Christophera1c535b2015-02-02 23:03:45 +0000137 return Subtarget->getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000138 }
139 const X86TargetMachine *getTargetMachine() const {
140 return static_cast<const X86TargetMachine *>(&TM);
141 }
142
143 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
144
145 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
146 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
147 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
148 unsigned fastMaterializeConstant(const Constant *C) override;
149
150 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
151
152 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
153
154 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
155 /// computed in an SSE register, not on the X87 floating point stack.
156 bool isScalarFPTypeInSSEReg(EVT VT) const {
157 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
158 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
159 }
160
161 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
162
163 bool IsMemcpySmall(uint64_t Len);
164
165 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
166 X86AddressMode SrcAM, uint64_t Len);
167
168 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
169 const Value *Cond);
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000170
171 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
172 X86AddressMode &AM);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000173};
174
175} // end anonymous namespace.
176
177static std::pair<X86::CondCode, bool>
178getX86ConditionCode(CmpInst::Predicate Predicate) {
179 X86::CondCode CC = X86::COND_INVALID;
180 bool NeedSwap = false;
181 switch (Predicate) {
182 default: break;
183 // Floating-point Predicates
184 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000185 case CmpInst::FCMP_OLT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000186 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000187 case CmpInst::FCMP_OLE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000188 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000189 case CmpInst::FCMP_UGT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000190 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000191 case CmpInst::FCMP_UGE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000192 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
193 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
194 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
195 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000196 case CmpInst::FCMP_OEQ: LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000197 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
198
199 // Integer Predicates
200 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
201 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
202 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
203 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
204 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
205 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
206 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
207 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
208 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
209 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
210 }
211
212 return std::make_pair(CC, NeedSwap);
213}
214
215static std::pair<unsigned, bool>
216getX86SSEConditionCode(CmpInst::Predicate Predicate) {
217 unsigned CC;
218 bool NeedSwap = false;
219
220 // SSE Condition code mapping:
221 // 0 - EQ
222 // 1 - LT
223 // 2 - LE
224 // 3 - UNORD
225 // 4 - NEQ
226 // 5 - NLT
227 // 6 - NLE
228 // 7 - ORD
229 switch (Predicate) {
230 default: llvm_unreachable("Unexpected predicate");
231 case CmpInst::FCMP_OEQ: CC = 0; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000232 case CmpInst::FCMP_OGT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000233 case CmpInst::FCMP_OLT: CC = 1; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000234 case CmpInst::FCMP_OGE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000235 case CmpInst::FCMP_OLE: CC = 2; break;
236 case CmpInst::FCMP_UNO: CC = 3; break;
237 case CmpInst::FCMP_UNE: CC = 4; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000238 case CmpInst::FCMP_ULE: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000239 case CmpInst::FCMP_UGE: CC = 5; break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000240 case CmpInst::FCMP_ULT: NeedSwap = true; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000241 case CmpInst::FCMP_UGT: CC = 6; break;
242 case CmpInst::FCMP_ORD: CC = 7; break;
243 case CmpInst::FCMP_UEQ:
244 case CmpInst::FCMP_ONE: CC = 8; break;
245 }
246
247 return std::make_pair(CC, NeedSwap);
248}
249
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000250/// \brief Adds a complex addressing mode to the given machine instr builder.
251/// Note, this will constrain the index register. If its not possible to
252/// constrain the given index register, then a new one will be created. The
253/// IndexReg field of the addressing mode will be updated to match in this case.
254const MachineInstrBuilder &
255X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
256 X86AddressMode &AM) {
257 // First constrain the index register. It needs to be a GR64_NOSP.
258 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
259 MIB->getNumOperands() +
260 X86::AddrIndexReg);
261 return ::addFullAddress(MIB, AM);
262}
263
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000264/// \brief Check if it is possible to fold the condition from the XALU intrinsic
265/// into the user. The condition code will only be updated on success.
266bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
267 const Value *Cond) {
268 if (!isa<ExtractValueInst>(Cond))
269 return false;
270
271 const auto *EV = cast<ExtractValueInst>(Cond);
272 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
273 return false;
274
275 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
276 MVT RetVT;
277 const Function *Callee = II->getCalledFunction();
278 Type *RetTy =
279 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
280 if (!isTypeLegal(RetTy, RetVT))
281 return false;
282
283 if (RetVT != MVT::i32 && RetVT != MVT::i64)
284 return false;
285
286 X86::CondCode TmpCC;
287 switch (II->getIntrinsicID()) {
288 default: return false;
289 case Intrinsic::sadd_with_overflow:
290 case Intrinsic::ssub_with_overflow:
291 case Intrinsic::smul_with_overflow:
292 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
293 case Intrinsic::uadd_with_overflow:
294 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
295 }
296
297 // Check if both instructions are in the same basic block.
298 if (II->getParent() != I->getParent())
299 return false;
300
301 // Make sure nothing is in the way
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000302 BasicBlock::const_iterator Start(I);
303 BasicBlock::const_iterator End(II);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000304 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
305 // We only expect extractvalue instructions between the intrinsic and the
306 // instruction to be selected.
307 if (!isa<ExtractValueInst>(Itr))
308 return false;
309
310 // Check that the extractvalue operand comes from the intrinsic.
311 const auto *EVI = cast<ExtractValueInst>(Itr);
312 if (EVI->getAggregateOperand() != II)
313 return false;
314 }
315
316 CC = TmpCC;
317 return true;
318}
319
320bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000321 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000322 if (evt == MVT::Other || !evt.isSimple())
323 // Unhandled type. Halt "fast" selection and bail.
324 return false;
325
326 VT = evt.getSimpleVT();
327 // For now, require SSE/SSE2 for performing floating-point operations,
328 // since x87 requires additional work.
329 if (VT == MVT::f64 && !X86ScalarSSEf64)
330 return false;
331 if (VT == MVT::f32 && !X86ScalarSSEf32)
332 return false;
333 // Similarly, no f80 support yet.
334 if (VT == MVT::f80)
335 return false;
336 // We only handle legal types. For example, on x86-32 the instruction
337 // selector contains all of the 64-bit instructions from x86-64,
338 // under the assumption that i64 won't be used if the target doesn't
339 // support it.
340 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
341}
342
343#include "X86GenCallingConv.inc"
344
345/// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
346/// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
347/// Return true and the result register by reference if it is possible.
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000348bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000349 MachineMemOperand *MMO, unsigned &ResultReg,
350 unsigned Alignment) {
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000351 bool HasSSE41 = Subtarget->hasSSE41();
Craig Topperca9c0802016-06-02 04:19:45 +0000352 bool HasAVX = Subtarget->hasAVX();
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000353 bool HasAVX2 = Subtarget->hasAVX2();
Craig Topperdfc4fc92016-09-05 23:58:40 +0000354 bool HasAVX512 = Subtarget->hasAVX512();
355 bool HasVLX = Subtarget->hasVLX();
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000356 bool IsNonTemporal = MMO && MMO->isNonTemporal();
357
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000358 // Get opcode and regclass of the output for the given load instruction.
359 unsigned Opc = 0;
360 const TargetRegisterClass *RC = nullptr;
361 switch (VT.getSimpleVT().SimpleTy) {
362 default: return false;
363 case MVT::i1:
364 case MVT::i8:
365 Opc = X86::MOV8rm;
366 RC = &X86::GR8RegClass;
367 break;
368 case MVT::i16:
369 Opc = X86::MOV16rm;
370 RC = &X86::GR16RegClass;
371 break;
372 case MVT::i32:
373 Opc = X86::MOV32rm;
374 RC = &X86::GR32RegClass;
375 break;
376 case MVT::i64:
377 // Must be in x86-64 mode.
378 Opc = X86::MOV64rm;
379 RC = &X86::GR64RegClass;
380 break;
381 case MVT::f32:
382 if (X86ScalarSSEf32) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000383 Opc = HasAVX512 ? X86::VMOVSSZrm : HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000384 RC = &X86::FR32RegClass;
385 } else {
386 Opc = X86::LD_Fp32m;
387 RC = &X86::RFP32RegClass;
388 }
389 break;
390 case MVT::f64:
391 if (X86ScalarSSEf64) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000392 Opc = HasAVX512 ? X86::VMOVSDZrm : HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000393 RC = &X86::FR64RegClass;
394 } else {
395 Opc = X86::LD_Fp64m;
396 RC = &X86::RFP64RegClass;
397 }
398 break;
399 case MVT::f80:
400 // No f80 support yet.
401 return false;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000402 case MVT::v4f32:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000403 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000404 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
405 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000406 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000407 Opc = HasVLX ? X86::VMOVAPSZ128rm :
408 HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000409 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000410 Opc = HasVLX ? X86::VMOVUPSZ128rm :
411 HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000412 RC = &X86::VR128RegClass;
413 break;
414 case MVT::v2f64:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000415 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000416 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
417 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000418 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000419 Opc = HasVLX ? X86::VMOVAPDZ128rm :
420 HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000421 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000422 Opc = HasVLX ? X86::VMOVUPDZ128rm :
423 HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000424 RC = &X86::VR128RegClass;
425 break;
426 case MVT::v4i32:
427 case MVT::v2i64:
428 case MVT::v8i16:
429 case MVT::v16i8:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000430 if (IsNonTemporal && Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000431 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
432 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000433 else if (Alignment >= 16)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000434 Opc = HasVLX ? X86::VMOVDQA64Z128rm :
435 HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000436 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000437 Opc = HasVLX ? X86::VMOVDQU64Z128rm :
438 HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000439 RC = &X86::VR128RegClass;
440 break;
Craig Topperca9c0802016-06-02 04:19:45 +0000441 case MVT::v8f32:
442 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000443 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000444 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
445 else if (Alignment >= 32)
446 Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000447 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000448 Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000449 RC = &X86::VR256RegClass;
450 break;
451 case MVT::v4f64:
452 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000453 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
454 Opc = X86::VMOVNTDQAYrm;
Craig Topperdfc4fc92016-09-05 23:58:40 +0000455 else if (Alignment >= 32)
456 Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000457 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000458 Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000459 RC = &X86::VR256RegClass;
460 break;
461 case MVT::v8i32:
462 case MVT::v4i64:
463 case MVT::v16i16:
464 case MVT::v32i8:
465 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000466 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
467 Opc = X86::VMOVNTDQAYrm;
Craig Topperdfc4fc92016-09-05 23:58:40 +0000468 else if (Alignment >= 32)
469 Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000470 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000471 Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000472 RC = &X86::VR256RegClass;
473 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000474 case MVT::v16f32:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000475 assert(HasAVX512);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000476 if (IsNonTemporal && Alignment >= 64)
477 Opc = X86::VMOVNTDQAZrm;
478 else
479 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000480 RC = &X86::VR512RegClass;
481 break;
482 case MVT::v8f64:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000483 assert(HasAVX512);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000484 if (IsNonTemporal && Alignment >= 64)
485 Opc = X86::VMOVNTDQAZrm;
486 else
487 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000488 RC = &X86::VR512RegClass;
489 break;
490 case MVT::v8i64:
491 case MVT::v16i32:
492 case MVT::v32i16:
493 case MVT::v64i8:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000494 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000495 // Note: There are a lot more choices based on type with AVX-512, but
496 // there's really no advantage when the load isn't masked.
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000497 if (IsNonTemporal && Alignment >= 64)
498 Opc = X86::VMOVNTDQAZrm;
499 else
500 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000501 RC = &X86::VR512RegClass;
502 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000503 }
504
505 ResultReg = createResultReg(RC);
506 MachineInstrBuilder MIB =
507 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
508 addFullAddress(MIB, AM);
509 if (MMO)
510 MIB->addMemOperand(*FuncInfo.MF, MMO);
511 return true;
512}
513
514/// X86FastEmitStore - Emit a machine instruction to store a value Val of
515/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
516/// and a displacement offset, or a GlobalAddress,
517/// i.e. V. Return true if it is possible.
518bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000519 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000520 MachineMemOperand *MMO, bool Aligned) {
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000521 bool HasSSE2 = Subtarget->hasSSE2();
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000522 bool HasSSE4A = Subtarget->hasSSE4A();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000523 bool HasAVX = Subtarget->hasAVX();
Craig Topperdfc4fc92016-09-05 23:58:40 +0000524 bool HasAVX512 = Subtarget->hasAVX512();
525 bool HasVLX = Subtarget->hasVLX();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000526 bool IsNonTemporal = MMO && MMO->isNonTemporal();
527
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000528 // Get opcode and regclass of the output for the given store instruction.
529 unsigned Opc = 0;
530 switch (VT.getSimpleVT().SimpleTy) {
531 case MVT::f80: // No f80 support yet.
532 default: return false;
533 case MVT::i1: {
534 // Mask out all but lowest bit.
535 unsigned AndResult = createResultReg(&X86::GR8RegClass);
536 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
537 TII.get(X86::AND8ri), AndResult)
538 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
539 ValReg = AndResult;
Justin Bognerb03fd122016-08-17 05:10:15 +0000540 LLVM_FALLTHROUGH; // handle i1 as i8.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000541 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000542 case MVT::i8: Opc = X86::MOV8mr; break;
543 case MVT::i16: Opc = X86::MOV16mr; break;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000544 case MVT::i32:
545 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
546 break;
547 case MVT::i64:
548 // Must be in x86-64 mode.
549 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
550 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000551 case MVT::f32:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000552 if (X86ScalarSSEf32) {
553 if (IsNonTemporal && HasSSE4A)
554 Opc = X86::MOVNTSS;
555 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000556 Opc = HasAVX512 ? X86::VMOVSSZmr :
557 HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000558 } else
559 Opc = X86::ST_Fp32m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000560 break;
561 case MVT::f64:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000562 if (X86ScalarSSEf32) {
563 if (IsNonTemporal && HasSSE4A)
564 Opc = X86::MOVNTSD;
565 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000566 Opc = HasAVX512 ? X86::VMOVSDZmr :
567 HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000568 } else
569 Opc = X86::ST_Fp64m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000570 break;
571 case MVT::v4f32:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000572 if (Aligned) {
573 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000574 Opc = HasVLX ? X86::VMOVNTPSZ128mr :
575 HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000576 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000577 Opc = HasVLX ? X86::VMOVAPSZ128mr :
578 HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000579 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000580 Opc = HasVLX ? X86::VMOVUPSZ128mr :
581 HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000582 break;
583 case MVT::v2f64:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000584 if (Aligned) {
585 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000586 Opc = HasVLX ? X86::VMOVNTPDZ128mr :
587 HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000588 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000589 Opc = HasVLX ? X86::VMOVAPDZ128mr :
590 HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000591 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000592 Opc = HasVLX ? X86::VMOVUPDZ128mr :
593 HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000594 break;
595 case MVT::v4i32:
596 case MVT::v2i64:
597 case MVT::v8i16:
598 case MVT::v16i8:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000599 if (Aligned) {
600 if (IsNonTemporal)
Craig Topperdfc4fc92016-09-05 23:58:40 +0000601 Opc = HasVLX ? X86::VMOVNTDQZ128mr :
602 HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000603 else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000604 Opc = HasVLX ? X86::VMOVDQA64Z128mr :
605 HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000606 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000607 Opc = HasVLX ? X86::VMOVDQU64Z128mr :
608 HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000609 break;
610 case MVT::v8f32:
611 assert(HasAVX);
Craig Topperdfc4fc92016-09-05 23:58:40 +0000612 if (Aligned) {
613 if (IsNonTemporal)
614 Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
615 else
616 Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
617 } else
618 Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000619 break;
620 case MVT::v4f64:
621 assert(HasAVX);
622 if (Aligned) {
Craig Topperdfc4fc92016-09-05 23:58:40 +0000623 if (IsNonTemporal)
624 Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
625 else
626 Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000627 } else
Craig Topperdfc4fc92016-09-05 23:58:40 +0000628 Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
Craig Topperca9c0802016-06-02 04:19:45 +0000629 break;
630 case MVT::v8i32:
631 case MVT::v4i64:
632 case MVT::v16i16:
633 case MVT::v32i8:
634 assert(HasAVX);
Craig Topperdfc4fc92016-09-05 23:58:40 +0000635 if (Aligned) {
636 if (IsNonTemporal)
637 Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
638 else
639 Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
640 } else
641 Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000642 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000643 case MVT::v16f32:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000644 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000645 if (Aligned)
646 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
647 else
648 Opc = X86::VMOVUPSZmr;
649 break;
650 case MVT::v8f64:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000651 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000652 if (Aligned) {
653 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
654 } else
655 Opc = X86::VMOVUPDZmr;
656 break;
657 case MVT::v8i64:
658 case MVT::v16i32:
659 case MVT::v32i16:
660 case MVT::v64i8:
Craig Topperdfc4fc92016-09-05 23:58:40 +0000661 assert(HasAVX512);
Craig Topper048a08a2016-06-02 04:51:37 +0000662 // Note: There are a lot more choices based on type with AVX-512, but
663 // there's really no advantage when the store isn't masked.
664 if (Aligned)
665 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
666 else
667 Opc = X86::VMOVDQU64Zmr;
668 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000669 }
670
Quentin Colombetbf200682016-04-27 22:33:42 +0000671 const MCInstrDesc &Desc = TII.get(Opc);
672 // Some of the instructions in the previous switch use FR128 instead
673 // of FR32 for ValReg. Make sure the register we feed the instruction
674 // matches its register class constraints.
675 // Note: This is fine to do a copy from FR32 to FR128, this is the
676 // same registers behind the scene and actually why it did not trigger
677 // any bugs before.
678 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000679 MachineInstrBuilder MIB =
Quentin Colombetbf200682016-04-27 22:33:42 +0000680 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000681 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
682 if (MMO)
683 MIB->addMemOperand(*FuncInfo.MF, MMO);
684
685 return true;
686}
687
688bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000689 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000690 MachineMemOperand *MMO, bool Aligned) {
691 // Handle 'null' like i32/i64 0.
692 if (isa<ConstantPointerNull>(Val))
693 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
694
695 // If this is a store of a simple constant, fold the constant into the store.
696 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
697 unsigned Opc = 0;
698 bool Signed = true;
699 switch (VT.getSimpleVT().SimpleTy) {
700 default: break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000701 case MVT::i1:
702 Signed = false;
703 LLVM_FALLTHROUGH; // Handle as i8.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000704 case MVT::i8: Opc = X86::MOV8mi; break;
705 case MVT::i16: Opc = X86::MOV16mi; break;
706 case MVT::i32: Opc = X86::MOV32mi; break;
707 case MVT::i64:
708 // Must be a 32-bit sign extended value.
709 if (isInt<32>(CI->getSExtValue()))
710 Opc = X86::MOV64mi32;
711 break;
712 }
713
714 if (Opc) {
715 MachineInstrBuilder MIB =
716 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
717 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
718 : CI->getZExtValue());
719 if (MMO)
720 MIB->addMemOperand(*FuncInfo.MF, MMO);
721 return true;
722 }
723 }
724
725 unsigned ValReg = getRegForValue(Val);
726 if (ValReg == 0)
727 return false;
728
729 bool ValKill = hasTrivialKill(Val);
730 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
731}
732
733/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
734/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
735/// ISD::SIGN_EXTEND).
736bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
737 unsigned Src, EVT SrcVT,
738 unsigned &ResultReg) {
739 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
740 Src, /*TODO: Kill=*/false);
741 if (RR == 0)
742 return false;
743
744 ResultReg = RR;
745 return true;
746}
747
748bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
749 // Handle constant address.
750 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
751 // Can't handle alternate code models yet.
752 if (TM.getCodeModel() != CodeModel::Small)
753 return false;
754
755 // Can't handle TLS yet.
756 if (GV->isThreadLocal())
757 return false;
758
759 // RIP-relative addresses can't have additional register operands, so if
760 // we've already folded stuff into the addressing mode, just force the
761 // global value into its own register, which we can use as the basereg.
762 if (!Subtarget->isPICStyleRIPRel() ||
763 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
764 // Okay, we've committed to selecting this global. Set up the address.
765 AM.GV = GV;
766
767 // Allow the subtarget to classify the global.
Rafael Espindolaab03eb02016-05-19 22:07:57 +0000768 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000769
770 // If this reference is relative to the pic base, set it now.
771 if (isGlobalRelativeToPICBase(GVFlags)) {
772 // FIXME: How do we know Base.Reg is free??
773 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
774 }
775
776 // Unless the ABI requires an extra load, return a direct reference to
777 // the global.
778 if (!isGlobalStubReference(GVFlags)) {
779 if (Subtarget->isPICStyleRIPRel()) {
780 // Use rip-relative addressing if we can. Above we verified that the
781 // base and index registers are unused.
782 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
783 AM.Base.Reg = X86::RIP;
784 }
785 AM.GVOpFlags = GVFlags;
786 return true;
787 }
788
789 // Ok, we need to do a load from a stub. If we've already loaded from
790 // this stub, reuse the loaded pointer, otherwise emit the load now.
791 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
792 unsigned LoadReg;
793 if (I != LocalValueMap.end() && I->second != 0) {
794 LoadReg = I->second;
795 } else {
796 // Issue load from stub.
797 unsigned Opc = 0;
798 const TargetRegisterClass *RC = nullptr;
799 X86AddressMode StubAM;
800 StubAM.Base.Reg = AM.Base.Reg;
801 StubAM.GV = GV;
802 StubAM.GVOpFlags = GVFlags;
803
804 // Prepare for inserting code in the local-value area.
805 SavePoint SaveInsertPt = enterLocalValueArea();
806
Mehdi Amini44ede332015-07-09 02:09:04 +0000807 if (TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000808 Opc = X86::MOV64rm;
809 RC = &X86::GR64RegClass;
810
811 if (Subtarget->isPICStyleRIPRel())
812 StubAM.Base.Reg = X86::RIP;
813 } else {
814 Opc = X86::MOV32rm;
815 RC = &X86::GR32RegClass;
816 }
817
818 LoadReg = createResultReg(RC);
819 MachineInstrBuilder LoadMI =
820 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
821 addFullAddress(LoadMI, StubAM);
822
823 // Ok, back to normal mode.
824 leaveLocalValueArea(SaveInsertPt);
825
826 // Prevent loading GV stub multiple times in same MBB.
827 LocalValueMap[V] = LoadReg;
828 }
829
830 // Now construct the final address. Note that the Disp, Scale,
831 // and Index values may already be set here.
832 AM.Base.Reg = LoadReg;
833 AM.GV = nullptr;
834 return true;
835 }
836 }
837
838 // If all else fails, try to materialize the value in a register.
839 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
840 if (AM.Base.Reg == 0) {
841 AM.Base.Reg = getRegForValue(V);
842 return AM.Base.Reg != 0;
843 }
844 if (AM.IndexReg == 0) {
845 assert(AM.Scale == 1 && "Scale with no index!");
846 AM.IndexReg = getRegForValue(V);
847 return AM.IndexReg != 0;
848 }
849 }
850
851 return false;
852}
853
854/// X86SelectAddress - Attempt to fill in an address from the given value.
855///
856bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
857 SmallVector<const Value *, 32> GEPs;
858redo_gep:
859 const User *U = nullptr;
860 unsigned Opcode = Instruction::UserOp1;
861 if (const Instruction *I = dyn_cast<Instruction>(V)) {
862 // Don't walk into other basic blocks; it's possible we haven't
863 // visited them yet, so the instructions may not yet be assigned
864 // virtual registers.
865 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
866 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
867 Opcode = I->getOpcode();
868 U = I;
869 }
870 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
871 Opcode = C->getOpcode();
872 U = C;
873 }
874
875 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
876 if (Ty->getAddressSpace() > 255)
877 // Fast instruction selection doesn't support the special
878 // address spaces.
879 return false;
880
881 switch (Opcode) {
882 default: break;
883 case Instruction::BitCast:
884 // Look past bitcasts.
885 return X86SelectAddress(U->getOperand(0), AM);
886
887 case Instruction::IntToPtr:
888 // Look past no-op inttoptrs.
Mehdi Amini44ede332015-07-09 02:09:04 +0000889 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
890 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000891 return X86SelectAddress(U->getOperand(0), AM);
892 break;
893
894 case Instruction::PtrToInt:
895 // Look past no-op ptrtoints.
Mehdi Amini44ede332015-07-09 02:09:04 +0000896 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000897 return X86SelectAddress(U->getOperand(0), AM);
898 break;
899
900 case Instruction::Alloca: {
901 // Do static allocas.
902 const AllocaInst *A = cast<AllocaInst>(V);
903 DenseMap<const AllocaInst *, int>::iterator SI =
904 FuncInfo.StaticAllocaMap.find(A);
905 if (SI != FuncInfo.StaticAllocaMap.end()) {
906 AM.BaseType = X86AddressMode::FrameIndexBase;
907 AM.Base.FrameIndex = SI->second;
908 return true;
909 }
910 break;
911 }
912
913 case Instruction::Add: {
914 // Adds of constants are common and easy enough.
915 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
916 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
917 // They have to fit in the 32-bit signed displacement field though.
918 if (isInt<32>(Disp)) {
919 AM.Disp = (uint32_t)Disp;
920 return X86SelectAddress(U->getOperand(0), AM);
921 }
922 }
923 break;
924 }
925
926 case Instruction::GetElementPtr: {
927 X86AddressMode SavedAM = AM;
928
929 // Pattern-match simple GEPs.
930 uint64_t Disp = (int32_t)AM.Disp;
931 unsigned IndexReg = AM.IndexReg;
932 unsigned Scale = AM.Scale;
933 gep_type_iterator GTI = gep_type_begin(U);
934 // Iterate through the indices, folding what we can. Constants can be
935 // folded, and one dynamic index can be handled, if the scale is supported.
936 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
937 i != e; ++i, ++GTI) {
938 const Value *Op = *i;
Peter Collingbourneab85225b2016-12-02 02:24:42 +0000939 if (StructType *STy = GTI.getStructTypeOrNull()) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000940 const StructLayout *SL = DL.getStructLayout(STy);
941 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
942 continue;
943 }
944
945 // A array/variable index is always of the form i*S where S is the
946 // constant scale size. See if we can push the scale into immediates.
947 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
948 for (;;) {
949 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
950 // Constant-offset addressing.
951 Disp += CI->getSExtValue() * S;
952 break;
953 }
954 if (canFoldAddIntoGEP(U, Op)) {
955 // A compatible add with a constant operand. Fold the constant.
956 ConstantInt *CI =
957 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
958 Disp += CI->getSExtValue() * S;
959 // Iterate on the other operand.
960 Op = cast<AddOperator>(Op)->getOperand(0);
961 continue;
962 }
963 if (IndexReg == 0 &&
964 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
965 (S == 1 || S == 2 || S == 4 || S == 8)) {
966 // Scaled-index addressing.
967 Scale = S;
968 IndexReg = getRegForGEPIndex(Op).first;
969 if (IndexReg == 0)
970 return false;
971 break;
972 }
973 // Unsupported.
974 goto unsupported_gep;
975 }
976 }
977
978 // Check for displacement overflow.
979 if (!isInt<32>(Disp))
980 break;
981
982 AM.IndexReg = IndexReg;
983 AM.Scale = Scale;
984 AM.Disp = (uint32_t)Disp;
985 GEPs.push_back(V);
986
987 if (const GetElementPtrInst *GEP =
988 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
989 // Ok, the GEP indices were covered by constant-offset and scaled-index
990 // addressing. Update the address state and move on to examining the base.
991 V = GEP;
992 goto redo_gep;
993 } else if (X86SelectAddress(U->getOperand(0), AM)) {
994 return true;
995 }
996
997 // If we couldn't merge the gep value into this addr mode, revert back to
998 // our address and just match the value instead of completely failing.
999 AM = SavedAM;
1000
David Majnemerd7708772016-06-24 04:05:21 +00001001 for (const Value *I : reverse(GEPs))
1002 if (handleConstantAddresses(I, AM))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001003 return true;
1004
1005 return false;
1006 unsupported_gep:
1007 // Ok, the GEP indices weren't all covered.
1008 break;
1009 }
1010 }
1011
1012 return handleConstantAddresses(V, AM);
1013}
1014
1015/// X86SelectCallAddress - Attempt to fill in an address from the given value.
1016///
1017bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
1018 const User *U = nullptr;
1019 unsigned Opcode = Instruction::UserOp1;
1020 const Instruction *I = dyn_cast<Instruction>(V);
1021 // Record if the value is defined in the same basic block.
1022 //
1023 // This information is crucial to know whether or not folding an
1024 // operand is valid.
1025 // Indeed, FastISel generates or reuses a virtual register for all
1026 // operands of all instructions it selects. Obviously, the definition and
1027 // its uses must use the same virtual register otherwise the produced
1028 // code is incorrect.
1029 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
1030 // registers for values that are alive across basic blocks. This ensures
1031 // that the values are consistently set between across basic block, even
1032 // if different instruction selection mechanisms are used (e.g., a mix of
1033 // SDISel and FastISel).
1034 // For values local to a basic block, the instruction selection process
1035 // generates these virtual registers with whatever method is appropriate
1036 // for its needs. In particular, FastISel and SDISel do not share the way
1037 // local virtual registers are set.
1038 // Therefore, this is impossible (or at least unsafe) to share values
1039 // between basic blocks unless they use the same instruction selection
1040 // method, which is not guarantee for X86.
1041 // Moreover, things like hasOneUse could not be used accurately, if we
1042 // allow to reference values across basic blocks whereas they are not
1043 // alive across basic blocks initially.
1044 bool InMBB = true;
1045 if (I) {
1046 Opcode = I->getOpcode();
1047 U = I;
1048 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1049 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1050 Opcode = C->getOpcode();
1051 U = C;
1052 }
1053
1054 switch (Opcode) {
1055 default: break;
1056 case Instruction::BitCast:
1057 // Look past bitcasts if its operand is in the same BB.
1058 if (InMBB)
1059 return X86SelectCallAddress(U->getOperand(0), AM);
1060 break;
1061
1062 case Instruction::IntToPtr:
1063 // Look past no-op inttoptrs if its operand is in the same BB.
1064 if (InMBB &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001065 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1066 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001067 return X86SelectCallAddress(U->getOperand(0), AM);
1068 break;
1069
1070 case Instruction::PtrToInt:
1071 // Look past no-op ptrtoints if its operand is in the same BB.
Mehdi Amini44ede332015-07-09 02:09:04 +00001072 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001073 return X86SelectCallAddress(U->getOperand(0), AM);
1074 break;
1075 }
1076
1077 // Handle constant address.
1078 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1079 // Can't handle alternate code models yet.
1080 if (TM.getCodeModel() != CodeModel::Small)
1081 return false;
1082
1083 // RIP-relative addresses can't have additional register operands.
1084 if (Subtarget->isPICStyleRIPRel() &&
1085 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1086 return false;
1087
1088 // Can't handle DLL Import.
1089 if (GV->hasDLLImportStorageClass())
1090 return false;
1091
1092 // Can't handle TLS.
1093 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1094 if (GVar->isThreadLocal())
1095 return false;
1096
1097 // Okay, we've committed to selecting this global. Set up the basic address.
1098 AM.GV = GV;
1099
1100 // No ABI requires an extra load for anything other than DLLImport, which
1101 // we rejected above. Return a direct reference to the global.
1102 if (Subtarget->isPICStyleRIPRel()) {
1103 // Use rip-relative addressing if we can. Above we verified that the
1104 // base and index registers are unused.
1105 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1106 AM.Base.Reg = X86::RIP;
Rafael Espindolac7e98132016-05-20 12:20:10 +00001107 } else {
1108 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001109 }
1110
1111 return true;
1112 }
1113
1114 // If all else fails, try to materialize the value in a register.
1115 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1116 if (AM.Base.Reg == 0) {
1117 AM.Base.Reg = getRegForValue(V);
1118 return AM.Base.Reg != 0;
1119 }
1120 if (AM.IndexReg == 0) {
1121 assert(AM.Scale == 1 && "Scale with no index!");
1122 AM.IndexReg = getRegForValue(V);
1123 return AM.IndexReg != 0;
1124 }
1125 }
1126
1127 return false;
1128}
1129
1130
1131/// X86SelectStore - Select and emit code to implement store instructions.
1132bool X86FastISel::X86SelectStore(const Instruction *I) {
1133 // Atomic stores need special handling.
1134 const StoreInst *S = cast<StoreInst>(I);
1135
1136 if (S->isAtomic())
1137 return false;
1138
Manman Ren57518142016-04-11 21:08:06 +00001139 const Value *PtrV = I->getOperand(1);
1140 if (TLI.supportSwiftError()) {
1141 // Swifterror values can come from either a function parameter with
1142 // swifterror attribute or an alloca with swifterror attribute.
1143 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1144 if (Arg->hasSwiftErrorAttr())
1145 return false;
1146 }
1147
1148 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1149 if (Alloca->isSwiftError())
1150 return false;
1151 }
1152 }
1153
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001154 const Value *Val = S->getValueOperand();
1155 const Value *Ptr = S->getPointerOperand();
1156
1157 MVT VT;
1158 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1159 return false;
1160
1161 unsigned Alignment = S->getAlignment();
1162 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1163 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1164 Alignment = ABIAlignment;
1165 bool Aligned = Alignment >= ABIAlignment;
1166
1167 X86AddressMode AM;
1168 if (!X86SelectAddress(Ptr, AM))
1169 return false;
1170
1171 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1172}
1173
1174/// X86SelectRet - Select and emit code to implement ret instructions.
1175bool X86FastISel::X86SelectRet(const Instruction *I) {
1176 const ReturnInst *Ret = cast<ReturnInst>(I);
1177 const Function &F = *I->getParent()->getParent();
1178 const X86MachineFunctionInfo *X86MFInfo =
1179 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1180
1181 if (!FuncInfo.CanLowerReturn)
1182 return false;
1183
Manman Ren57518142016-04-11 21:08:06 +00001184 if (TLI.supportSwiftError() &&
1185 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1186 return false;
1187
Manman Rened967f32016-01-12 01:08:46 +00001188 if (TLI.supportSplitCSR(FuncInfo.MF))
1189 return false;
1190
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001191 CallingConv::ID CC = F.getCallingConv();
1192 if (CC != CallingConv::C &&
1193 CC != CallingConv::Fast &&
1194 CC != CallingConv::X86_FastCall &&
Nico Weberecdf45b2016-07-14 13:54:26 +00001195 CC != CallingConv::X86_StdCall &&
Nico Weberc7bf6462016-07-12 01:30:35 +00001196 CC != CallingConv::X86_ThisCall &&
Nico Weber8d66df12016-07-15 20:18:37 +00001197 CC != CallingConv::X86_64_SysV &&
1198 CC != CallingConv::X86_64_Win64)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001199 return false;
1200
Nico Weberc7bf6462016-07-12 01:30:35 +00001201 // Don't handle popping bytes if they don't fit the ret's immediate.
1202 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001203 return false;
1204
1205 // fastcc with -tailcallopt is intended to provide a guaranteed
1206 // tail call optimization. Fastisel doesn't know how to do that.
1207 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1208 return false;
1209
1210 // Let SDISel handle vararg functions.
1211 if (F.isVarArg())
1212 return false;
1213
1214 // Build a list of return value registers.
1215 SmallVector<unsigned, 4> RetRegs;
1216
1217 if (Ret->getNumOperands() > 0) {
1218 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001219 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001220
1221 // Analyze operands of the call, assigning locations to each operand.
1222 SmallVector<CCValAssign, 16> ValLocs;
1223 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1224 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1225
1226 const Value *RV = Ret->getOperand(0);
1227 unsigned Reg = getRegForValue(RV);
1228 if (Reg == 0)
1229 return false;
1230
1231 // Only handle a single return value for now.
1232 if (ValLocs.size() != 1)
1233 return false;
1234
1235 CCValAssign &VA = ValLocs[0];
1236
1237 // Don't bother handling odd stuff for now.
1238 if (VA.getLocInfo() != CCValAssign::Full)
1239 return false;
1240 // Only handle register returns for now.
1241 if (!VA.isRegLoc())
1242 return false;
1243
1244 // The calling-convention tables for x87 returns don't tell
1245 // the whole story.
1246 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1247 return false;
1248
1249 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001250 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001251 EVT DstVT = VA.getValVT();
1252 // Special handling for extended integers.
1253 if (SrcVT != DstVT) {
1254 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1255 return false;
1256
1257 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1258 return false;
1259
1260 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1261
1262 if (SrcVT == MVT::i1) {
1263 if (Outs[0].Flags.isSExt())
1264 return false;
1265 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1266 SrcVT = MVT::i8;
1267 }
1268 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1269 ISD::SIGN_EXTEND;
1270 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1271 SrcReg, /*TODO: Kill=*/false);
1272 }
1273
1274 // Make the copy.
1275 unsigned DstReg = VA.getLocReg();
1276 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1277 // Avoid a cross-class copy. This is very unlikely.
1278 if (!SrcRC->contains(DstReg))
1279 return false;
1280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1281 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1282
1283 // Add register to return instruction.
1284 RetRegs.push_back(VA.getLocReg());
1285 }
1286
Manman Ren1c3f65a2016-04-26 18:08:06 +00001287 // Swift calling convention does not require we copy the sret argument
1288 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1289
Dimitry Andric227b9282016-01-03 17:22:03 +00001290 // All x86 ABIs require that for returning structs by value we copy
1291 // the sret argument into %rax/%eax (depending on ABI) for the return.
1292 // We saved the argument into a virtual register in the entry block,
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00001293 // so now we copy the value out and into %rax/%eax.
Manman Ren1c3f65a2016-04-26 18:08:06 +00001294 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001295 unsigned Reg = X86MFInfo->getSRetReturnReg();
1296 assert(Reg &&
1297 "SRetReturnReg should have been set in LowerFormalArguments()!");
1298 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1299 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1300 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1301 RetRegs.push_back(RetReg);
1302 }
1303
1304 // Now emit the RET.
Nico Weberc7bf6462016-07-12 01:30:35 +00001305 MachineInstrBuilder MIB;
1306 if (X86MFInfo->getBytesToPopOnReturn()) {
1307 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1308 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1309 .addImm(X86MFInfo->getBytesToPopOnReturn());
1310 } else {
1311 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1312 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1313 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001314 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1315 MIB.addReg(RetRegs[i], RegState::Implicit);
1316 return true;
1317}
1318
1319/// X86SelectLoad - Select and emit code to implement load instructions.
1320///
1321bool X86FastISel::X86SelectLoad(const Instruction *I) {
1322 const LoadInst *LI = cast<LoadInst>(I);
1323
1324 // Atomic loads need special handling.
1325 if (LI->isAtomic())
1326 return false;
1327
Manman Ren57518142016-04-11 21:08:06 +00001328 const Value *SV = I->getOperand(0);
1329 if (TLI.supportSwiftError()) {
1330 // Swifterror values can come from either a function parameter with
1331 // swifterror attribute or an alloca with swifterror attribute.
1332 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1333 if (Arg->hasSwiftErrorAttr())
1334 return false;
1335 }
1336
1337 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1338 if (Alloca->isSwiftError())
1339 return false;
1340 }
1341 }
1342
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001343 MVT VT;
1344 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1345 return false;
1346
1347 const Value *Ptr = LI->getPointerOperand();
1348
1349 X86AddressMode AM;
1350 if (!X86SelectAddress(Ptr, AM))
1351 return false;
1352
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001353 unsigned Alignment = LI->getAlignment();
1354 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1355 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1356 Alignment = ABIAlignment;
1357
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001358 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001359 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1360 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001361 return false;
1362
1363 updateValueMap(I, ResultReg);
1364 return true;
1365}
1366
1367static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1368 bool HasAVX = Subtarget->hasAVX();
1369 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1370 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1371
1372 switch (VT.getSimpleVT().SimpleTy) {
1373 default: return 0;
1374 case MVT::i8: return X86::CMP8rr;
1375 case MVT::i16: return X86::CMP16rr;
1376 case MVT::i32: return X86::CMP32rr;
1377 case MVT::i64: return X86::CMP64rr;
1378 case MVT::f32:
1379 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1380 case MVT::f64:
1381 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1382 }
1383}
1384
Rafael Espindola19141f22015-03-16 14:05:49 +00001385/// If we have a comparison with RHS as the RHS of the comparison, return an
1386/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001387static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001388 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001389 switch (VT.getSimpleVT().SimpleTy) {
1390 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001391 default:
1392 return 0;
1393 case MVT::i8:
1394 return X86::CMP8ri;
1395 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001396 if (isInt<8>(Val))
1397 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001398 return X86::CMP16ri;
1399 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001400 if (isInt<8>(Val))
1401 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001402 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001403 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001404 if (isInt<8>(Val))
1405 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001406 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1407 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001408 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001409 return X86::CMP64ri32;
1410 return 0;
1411 }
1412}
1413
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001414bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1415 const DebugLoc &CurDbgLoc) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001416 unsigned Op0Reg = getRegForValue(Op0);
1417 if (Op0Reg == 0) return false;
1418
1419 // Handle 'null' like i32/i64 0.
1420 if (isa<ConstantPointerNull>(Op1))
1421 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1422
1423 // We have two options: compare with register or immediate. If the RHS of
1424 // the compare is an immediate that we can fold into this compare, use
1425 // CMPri, otherwise use CMPrr.
1426 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1427 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1428 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1429 .addReg(Op0Reg)
1430 .addImm(Op1C->getSExtValue());
1431 return true;
1432 }
1433 }
1434
1435 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1436 if (CompareOpc == 0) return false;
1437
1438 unsigned Op1Reg = getRegForValue(Op1);
1439 if (Op1Reg == 0) return false;
1440 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1441 .addReg(Op0Reg)
1442 .addReg(Op1Reg);
1443
1444 return true;
1445}
1446
1447bool X86FastISel::X86SelectCmp(const Instruction *I) {
1448 const CmpInst *CI = cast<CmpInst>(I);
1449
1450 MVT VT;
1451 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1452 return false;
1453
Elena Demikhovskyad0a56f2016-07-06 14:15:43 +00001454 if (I->getType()->isIntegerTy(1) && Subtarget->hasAVX512())
1455 return false;
1456
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001457 // Try to optimize or fold the cmp.
1458 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1459 unsigned ResultReg = 0;
1460 switch (Predicate) {
1461 default: break;
1462 case CmpInst::FCMP_FALSE: {
1463 ResultReg = createResultReg(&X86::GR32RegClass);
1464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1465 ResultReg);
1466 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1467 X86::sub_8bit);
1468 if (!ResultReg)
1469 return false;
1470 break;
1471 }
1472 case CmpInst::FCMP_TRUE: {
1473 ResultReg = createResultReg(&X86::GR8RegClass);
1474 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1475 ResultReg).addImm(1);
1476 break;
1477 }
1478 }
1479
1480 if (ResultReg) {
1481 updateValueMap(I, ResultReg);
1482 return true;
1483 }
1484
1485 const Value *LHS = CI->getOperand(0);
1486 const Value *RHS = CI->getOperand(1);
1487
1488 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1489 // We don't have to materialize a zero constant for this case and can just use
1490 // %x again on the RHS.
1491 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1492 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1493 if (RHSC && RHSC->isNullValue())
1494 RHS = LHS;
1495 }
1496
1497 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
Craig Topper428169a2016-09-05 07:14:21 +00001498 static const uint16_t SETFOpcTable[2][3] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001499 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1500 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1501 };
Craig Topper428169a2016-09-05 07:14:21 +00001502 const uint16_t *SETFOpc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001503 switch (Predicate) {
1504 default: break;
1505 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1506 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1507 }
1508
1509 ResultReg = createResultReg(&X86::GR8RegClass);
1510 if (SETFOpc) {
1511 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1512 return false;
1513
1514 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1515 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1517 FlagReg1);
1518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1519 FlagReg2);
1520 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1521 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1522 updateValueMap(I, ResultReg);
1523 return true;
1524 }
1525
1526 X86::CondCode CC;
1527 bool SwapArgs;
1528 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1529 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1530 unsigned Opc = X86::getSETFromCond(CC);
1531
1532 if (SwapArgs)
1533 std::swap(LHS, RHS);
1534
1535 // Emit a compare of LHS/RHS.
1536 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1537 return false;
1538
1539 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1540 updateValueMap(I, ResultReg);
1541 return true;
1542}
1543
1544bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001545 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001546 if (!TLI.isTypeLegal(DstVT))
1547 return false;
1548
1549 unsigned ResultReg = getRegForValue(I->getOperand(0));
1550 if (ResultReg == 0)
1551 return false;
1552
1553 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001554 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001555 if (SrcVT.SimpleTy == MVT::i1) {
1556 // Set the high bits to zero.
1557 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1558 SrcVT = MVT::i8;
1559
1560 if (ResultReg == 0)
1561 return false;
1562 }
1563
1564 if (DstVT == MVT::i64) {
1565 // Handle extension to 64-bits via sub-register shenanigans.
1566 unsigned MovInst;
1567
1568 switch (SrcVT.SimpleTy) {
1569 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1570 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1571 case MVT::i32: MovInst = X86::MOV32rr; break;
1572 default: llvm_unreachable("Unexpected zext to i64 source type");
1573 }
1574
1575 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1576 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1577 .addReg(ResultReg);
1578
1579 ResultReg = createResultReg(&X86::GR64RegClass);
1580 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1581 ResultReg)
1582 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1583 } else if (DstVT != MVT::i8) {
1584 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1585 ResultReg, /*Kill=*/true);
1586 if (ResultReg == 0)
1587 return false;
1588 }
1589
1590 updateValueMap(I, ResultReg);
1591 return true;
1592}
1593
1594bool X86FastISel::X86SelectBranch(const Instruction *I) {
1595 // Unconditional branches are selected by tablegen-generated code.
1596 // Handle a conditional branch.
1597 const BranchInst *BI = cast<BranchInst>(I);
1598 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1599 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1600
1601 // Fold the common case of a conditional branch with a comparison
1602 // in the same block (values defined on other blocks may not have
1603 // initialized registers).
1604 X86::CondCode CC;
1605 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1606 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001607 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001608
1609 // Try to optimize or fold the cmp.
1610 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1611 switch (Predicate) {
1612 default: break;
1613 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1614 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1615 }
1616
1617 const Value *CmpLHS = CI->getOperand(0);
1618 const Value *CmpRHS = CI->getOperand(1);
1619
1620 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1621 // 0.0.
1622 // We don't have to materialize a zero constant for this case and can just
1623 // use %x again on the RHS.
1624 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1625 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1626 if (CmpRHSC && CmpRHSC->isNullValue())
1627 CmpRHS = CmpLHS;
1628 }
1629
1630 // Try to take advantage of fallthrough opportunities.
1631 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1632 std::swap(TrueMBB, FalseMBB);
1633 Predicate = CmpInst::getInversePredicate(Predicate);
1634 }
1635
1636 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1637 // code check. Instead two branch instructions are required to check all
1638 // the flags. First we change the predicate to a supported condition code,
1639 // which will be the first branch. Later one we will emit the second
1640 // branch.
1641 bool NeedExtraBranch = false;
1642 switch (Predicate) {
1643 default: break;
1644 case CmpInst::FCMP_OEQ:
Justin Bognerb03fd122016-08-17 05:10:15 +00001645 std::swap(TrueMBB, FalseMBB);
1646 LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001647 case CmpInst::FCMP_UNE:
1648 NeedExtraBranch = true;
1649 Predicate = CmpInst::FCMP_ONE;
1650 break;
1651 }
1652
1653 bool SwapArgs;
1654 unsigned BranchOpc;
1655 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1656 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1657
1658 BranchOpc = X86::GetCondBranchFromCond(CC);
1659 if (SwapArgs)
1660 std::swap(CmpLHS, CmpRHS);
1661
1662 // Emit a compare of the LHS and RHS, setting the flags.
1663 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1664 return false;
1665
1666 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1667 .addMBB(TrueMBB);
1668
1669 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1670 // to UNE above).
1671 if (NeedExtraBranch) {
1672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1673 .addMBB(TrueMBB);
1674 }
1675
Matthias Braun17af6072015-08-26 01:38:00 +00001676 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001677 return true;
1678 }
1679 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1680 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1681 // typically happen for _Bool and C++ bools.
1682 MVT SourceVT;
1683 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1684 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1685 unsigned TestOpc = 0;
1686 switch (SourceVT.SimpleTy) {
1687 default: break;
1688 case MVT::i8: TestOpc = X86::TEST8ri; break;
1689 case MVT::i16: TestOpc = X86::TEST16ri; break;
1690 case MVT::i32: TestOpc = X86::TEST32ri; break;
1691 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1692 }
1693 if (TestOpc) {
1694 unsigned OpReg = getRegForValue(TI->getOperand(0));
1695 if (OpReg == 0) return false;
Guy Blank9ae797a2016-08-21 08:02:27 +00001696
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001697 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1698 .addReg(OpReg).addImm(1);
1699
1700 unsigned JmpOpc = X86::JNE_1;
1701 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1702 std::swap(TrueMBB, FalseMBB);
1703 JmpOpc = X86::JE_1;
1704 }
1705
1706 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1707 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001708
1709 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001710 return true;
1711 }
1712 }
1713 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1714 // Fake request the condition, otherwise the intrinsic might be completely
1715 // optimized away.
1716 unsigned TmpReg = getRegForValue(BI->getCondition());
1717 if (TmpReg == 0)
1718 return false;
1719
1720 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1721
1722 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1723 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001724 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001725 return true;
1726 }
1727
1728 // Otherwise do a clumsy setcc and re-test it.
1729 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1730 // in an explicit cast, so make sure to handle that correctly.
1731 unsigned OpReg = getRegForValue(BI->getCondition());
1732 if (OpReg == 0) return false;
1733
Guy Blank2bdc74a2016-09-28 11:22:17 +00001734 // In case OpReg is a K register, COPY to a GPR
1735 if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) {
1736 unsigned KOpReg = OpReg;
1737 OpReg = createResultReg(&X86::GR8RegClass);
1738 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1739 TII.get(TargetOpcode::COPY), OpReg)
1740 .addReg(KOpReg);
1741 }
1742 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1743 .addReg(OpReg)
1744 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001745 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1746 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001747 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001748 return true;
1749}
1750
1751bool X86FastISel::X86SelectShift(const Instruction *I) {
1752 unsigned CReg = 0, OpReg = 0;
1753 const TargetRegisterClass *RC = nullptr;
1754 if (I->getType()->isIntegerTy(8)) {
1755 CReg = X86::CL;
1756 RC = &X86::GR8RegClass;
1757 switch (I->getOpcode()) {
1758 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1759 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1760 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1761 default: return false;
1762 }
1763 } else if (I->getType()->isIntegerTy(16)) {
1764 CReg = X86::CX;
1765 RC = &X86::GR16RegClass;
1766 switch (I->getOpcode()) {
1767 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1768 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1769 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1770 default: return false;
1771 }
1772 } else if (I->getType()->isIntegerTy(32)) {
1773 CReg = X86::ECX;
1774 RC = &X86::GR32RegClass;
1775 switch (I->getOpcode()) {
1776 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1777 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1778 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1779 default: return false;
1780 }
1781 } else if (I->getType()->isIntegerTy(64)) {
1782 CReg = X86::RCX;
1783 RC = &X86::GR64RegClass;
1784 switch (I->getOpcode()) {
1785 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1786 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1787 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1788 default: return false;
1789 }
1790 } else {
1791 return false;
1792 }
1793
1794 MVT VT;
1795 if (!isTypeLegal(I->getType(), VT))
1796 return false;
1797
1798 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1799 if (Op0Reg == 0) return false;
1800
1801 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1802 if (Op1Reg == 0) return false;
1803 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1804 CReg).addReg(Op1Reg);
1805
1806 // The shift instruction uses X86::CL. If we defined a super-register
1807 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1808 if (CReg != X86::CL)
1809 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1810 TII.get(TargetOpcode::KILL), X86::CL)
1811 .addReg(CReg, RegState::Kill);
1812
1813 unsigned ResultReg = createResultReg(RC);
1814 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1815 .addReg(Op0Reg);
1816 updateValueMap(I, ResultReg);
1817 return true;
1818}
1819
1820bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1821 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1822 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1823 const static bool S = true; // IsSigned
1824 const static bool U = false; // !IsSigned
1825 const static unsigned Copy = TargetOpcode::COPY;
1826 // For the X86 DIV/IDIV instruction, in most cases the dividend
1827 // (numerator) must be in a specific register pair highreg:lowreg,
1828 // producing the quotient in lowreg and the remainder in highreg.
1829 // For most data types, to set up the instruction, the dividend is
1830 // copied into lowreg, and lowreg is sign-extended or zero-extended
1831 // into highreg. The exception is i8, where the dividend is defined
1832 // as a single register rather than a register pair, and we
1833 // therefore directly sign-extend or zero-extend the dividend into
1834 // lowreg, instead of copying, and ignore the highreg.
1835 const static struct DivRemEntry {
1836 // The following portion depends only on the data type.
1837 const TargetRegisterClass *RC;
1838 unsigned LowInReg; // low part of the register pair
1839 unsigned HighInReg; // high part of the register pair
1840 // The following portion depends on both the data type and the operation.
1841 struct DivRemResult {
1842 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1843 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1844 // highreg, or copying a zero into highreg.
1845 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1846 // zero/sign-extending into lowreg for i8.
1847 unsigned DivRemResultReg; // Register containing the desired result.
1848 bool IsOpSigned; // Whether to use signed or unsigned form.
1849 } ResultTable[NumOps];
1850 } OpTable[NumTypes] = {
1851 { &X86::GR8RegClass, X86::AX, 0, {
1852 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1853 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1854 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1855 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1856 }
1857 }, // i8
1858 { &X86::GR16RegClass, X86::AX, X86::DX, {
1859 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1860 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1861 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1862 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1863 }
1864 }, // i16
1865 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1866 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1867 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1868 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1869 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1870 }
1871 }, // i32
1872 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1873 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1874 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1875 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1876 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1877 }
1878 }, // i64
1879 };
1880
1881 MVT VT;
1882 if (!isTypeLegal(I->getType(), VT))
1883 return false;
1884
1885 unsigned TypeIndex, OpIndex;
1886 switch (VT.SimpleTy) {
1887 default: return false;
1888 case MVT::i8: TypeIndex = 0; break;
1889 case MVT::i16: TypeIndex = 1; break;
1890 case MVT::i32: TypeIndex = 2; break;
1891 case MVT::i64: TypeIndex = 3;
1892 if (!Subtarget->is64Bit())
1893 return false;
1894 break;
1895 }
1896
1897 switch (I->getOpcode()) {
1898 default: llvm_unreachable("Unexpected div/rem opcode");
1899 case Instruction::SDiv: OpIndex = 0; break;
1900 case Instruction::SRem: OpIndex = 1; break;
1901 case Instruction::UDiv: OpIndex = 2; break;
1902 case Instruction::URem: OpIndex = 3; break;
1903 }
1904
1905 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1906 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1907 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1908 if (Op0Reg == 0)
1909 return false;
1910 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1911 if (Op1Reg == 0)
1912 return false;
1913
1914 // Move op0 into low-order input register.
1915 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1916 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1917 // Zero-extend or sign-extend into high-order input register.
1918 if (OpEntry.OpSignExtend) {
1919 if (OpEntry.IsOpSigned)
1920 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1921 TII.get(OpEntry.OpSignExtend));
1922 else {
1923 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1924 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1925 TII.get(X86::MOV32r0), Zero32);
1926
1927 // Copy the zero into the appropriate sub/super/identical physical
1928 // register. Unfortunately the operations needed are not uniform enough
1929 // to fit neatly into the table above.
1930 if (VT.SimpleTy == MVT::i16) {
1931 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1932 TII.get(Copy), TypeEntry.HighInReg)
1933 .addReg(Zero32, 0, X86::sub_16bit);
1934 } else if (VT.SimpleTy == MVT::i32) {
1935 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1936 TII.get(Copy), TypeEntry.HighInReg)
1937 .addReg(Zero32);
1938 } else if (VT.SimpleTy == MVT::i64) {
1939 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1940 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1941 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1942 }
1943 }
1944 }
1945 // Generate the DIV/IDIV instruction.
1946 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1947 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1948 // For i8 remainder, we can't reference AH directly, as we'll end
1949 // up with bogus copies like %R9B = COPY %AH. Reference AX
1950 // instead to prevent AH references in a REX instruction.
1951 //
1952 // The current assumption of the fast register allocator is that isel
1953 // won't generate explicit references to the GPR8_NOREX registers. If
1954 // the allocator and/or the backend get enhanced to be more robust in
1955 // that regard, this can be, and should be, removed.
1956 unsigned ResultReg = 0;
1957 if ((I->getOpcode() == Instruction::SRem ||
1958 I->getOpcode() == Instruction::URem) &&
1959 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1960 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1961 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1962 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1963 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1964
1965 // Shift AX right by 8 bits instead of using AH.
1966 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1967 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1968
1969 // Now reference the 8-bit subreg of the result.
1970 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1971 /*Kill=*/true, X86::sub_8bit);
1972 }
1973 // Copy the result out of the physreg if we haven't already.
1974 if (!ResultReg) {
1975 ResultReg = createResultReg(TypeEntry.RC);
1976 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1977 .addReg(OpEntry.DivRemResultReg);
1978 }
1979 updateValueMap(I, ResultReg);
1980
1981 return true;
1982}
1983
1984/// \brief Emit a conditional move instruction (if the are supported) to lower
1985/// the select.
1986bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1987 // Check if the subtarget supports these instructions.
1988 if (!Subtarget->hasCMov())
1989 return false;
1990
1991 // FIXME: Add support for i8.
1992 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1993 return false;
1994
1995 const Value *Cond = I->getOperand(0);
1996 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1997 bool NeedTest = true;
1998 X86::CondCode CC = X86::COND_NE;
1999
2000 // Optimize conditions coming from a compare if both instructions are in the
2001 // same basic block (values defined in other basic blocks may not have
2002 // initialized registers).
2003 const auto *CI = dyn_cast<CmpInst>(Cond);
2004 if (CI && (CI->getParent() == I->getParent())) {
2005 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2006
2007 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
Craig Topper428169a2016-09-05 07:14:21 +00002008 static const uint16_t SETFOpcTable[2][3] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002009 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
2010 { X86::SETPr, X86::SETNEr, X86::OR8rr }
2011 };
Craig Topper428169a2016-09-05 07:14:21 +00002012 const uint16_t *SETFOpc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002013 switch (Predicate) {
2014 default: break;
2015 case CmpInst::FCMP_OEQ:
2016 SETFOpc = &SETFOpcTable[0][0];
2017 Predicate = CmpInst::ICMP_NE;
2018 break;
2019 case CmpInst::FCMP_UNE:
2020 SETFOpc = &SETFOpcTable[1][0];
2021 Predicate = CmpInst::ICMP_NE;
2022 break;
2023 }
2024
2025 bool NeedSwap;
2026 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
2027 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
2028
2029 const Value *CmpLHS = CI->getOperand(0);
2030 const Value *CmpRHS = CI->getOperand(1);
2031 if (NeedSwap)
2032 std::swap(CmpLHS, CmpRHS);
2033
Mehdi Amini44ede332015-07-09 02:09:04 +00002034 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002035 // Emit a compare of the LHS and RHS, setting the flags.
2036 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2037 return false;
2038
2039 if (SETFOpc) {
2040 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
2041 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
2042 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
2043 FlagReg1);
2044 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
2045 FlagReg2);
2046 auto const &II = TII.get(SETFOpc[2]);
2047 if (II.getNumDefs()) {
2048 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
2049 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
2050 .addReg(FlagReg2).addReg(FlagReg1);
2051 } else {
2052 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2053 .addReg(FlagReg2).addReg(FlagReg1);
2054 }
2055 }
2056 NeedTest = false;
2057 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2058 // Fake request the condition, otherwise the intrinsic might be completely
2059 // optimized away.
2060 unsigned TmpReg = getRegForValue(Cond);
2061 if (TmpReg == 0)
2062 return false;
2063
2064 NeedTest = false;
2065 }
2066
2067 if (NeedTest) {
2068 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2069 // garbage. Indeed, only the less significant bit is supposed to be
2070 // accurate. If we read more than the lsb, we may see non-zero values
2071 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2072 // the select. This is achieved by performing TEST against 1.
2073 unsigned CondReg = getRegForValue(Cond);
2074 if (CondReg == 0)
2075 return false;
2076 bool CondIsKill = hasTrivialKill(Cond);
2077
Guy Blank2bdc74a2016-09-28 11:22:17 +00002078 // In case OpReg is a K register, COPY to a GPR
2079 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2080 unsigned KCondReg = CondReg;
2081 CondReg = createResultReg(&X86::GR8RegClass);
Guy Blank9ae797a2016-08-21 08:02:27 +00002082 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
Guy Blank2bdc74a2016-09-28 11:22:17 +00002083 TII.get(TargetOpcode::COPY), CondReg)
2084 .addReg(KCondReg, getKillRegState(CondIsKill));
2085 }
2086 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2087 .addReg(CondReg, getKillRegState(CondIsKill))
2088 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002089 }
2090
2091 const Value *LHS = I->getOperand(1);
2092 const Value *RHS = I->getOperand(2);
2093
2094 unsigned RHSReg = getRegForValue(RHS);
2095 bool RHSIsKill = hasTrivialKill(RHS);
2096
2097 unsigned LHSReg = getRegForValue(LHS);
2098 bool LHSIsKill = hasTrivialKill(LHS);
2099
2100 if (!LHSReg || !RHSReg)
2101 return false;
2102
2103 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
2104 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2105 LHSReg, LHSIsKill);
2106 updateValueMap(I, ResultReg);
2107 return true;
2108}
2109
Sanjay Patel302404b2015-03-05 21:46:54 +00002110/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002111///
2112/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2113/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00002114/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002115bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2116 // Optimize conditions coming from a compare if both instructions are in the
2117 // same basic block (values defined in other basic blocks may not have
2118 // initialized registers).
2119 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2120 if (!CI || (CI->getParent() != I->getParent()))
2121 return false;
2122
2123 if (I->getType() != CI->getOperand(0)->getType() ||
2124 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2125 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2126 return false;
2127
2128 const Value *CmpLHS = CI->getOperand(0);
2129 const Value *CmpRHS = CI->getOperand(1);
2130 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2131
2132 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2133 // We don't have to materialize a zero constant for this case and can just use
2134 // %x again on the RHS.
2135 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2136 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2137 if (CmpRHSC && CmpRHSC->isNullValue())
2138 CmpRHS = CmpLHS;
2139 }
2140
2141 unsigned CC;
2142 bool NeedSwap;
2143 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2144 if (CC > 7)
2145 return false;
2146
2147 if (NeedSwap)
2148 std::swap(CmpLHS, CmpRHS);
2149
Sanjay Patel302404b2015-03-05 21:46:54 +00002150 // Choose the SSE instruction sequence based on data type (float or double).
Craig Topper428169a2016-09-05 07:14:21 +00002151 static const uint16_t OpcTable[2][4] = {
Sanjay Patel302404b2015-03-05 21:46:54 +00002152 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
2153 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002154 };
2155
Craig Topper428169a2016-09-05 07:14:21 +00002156 const uint16_t *Opc = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002157 switch (RetVT.SimpleTy) {
2158 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00002159 case MVT::f32: Opc = &OpcTable[0][0]; break;
2160 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002161 }
2162
2163 const Value *LHS = I->getOperand(1);
2164 const Value *RHS = I->getOperand(2);
2165
2166 unsigned LHSReg = getRegForValue(LHS);
2167 bool LHSIsKill = hasTrivialKill(LHS);
2168
2169 unsigned RHSReg = getRegForValue(RHS);
2170 bool RHSIsKill = hasTrivialKill(RHS);
2171
2172 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2173 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2174
2175 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2176 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2177
2178 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2179 return false;
2180
2181 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00002182 unsigned ResultReg;
2183
2184 if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00002185 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
2186 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2187
Sanjay Patel302404b2015-03-05 21:46:54 +00002188 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2189 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2190 // uses XMM0 as the selection register. That may need just as many
2191 // instructions as the AND/ANDN/OR sequence due to register moves, so
2192 // don't bother.
2193 unsigned CmpOpcode =
2194 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2195 unsigned BlendOpcode =
2196 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2197
Matthias Braun818c78d2015-08-31 18:25:11 +00002198 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00002199 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00002200 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2201 LHSReg, LHSIsKill, CmpReg, true);
2202 ResultReg = createResultReg(RC);
2203 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2204 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002205 } else {
2206 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2207 CmpRHSReg, CmpRHSIsKill, CC);
2208 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
2209 LHSReg, LHSIsKill);
2210 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
2211 RHSReg, RHSIsKill);
2212 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
2213 AndReg, /*IsKill=*/true);
2214 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002215 updateValueMap(I, ResultReg);
2216 return true;
2217}
2218
2219bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2220 // These are pseudo CMOV instructions and will be later expanded into control-
2221 // flow.
2222 unsigned Opc;
2223 switch (RetVT.SimpleTy) {
2224 default: return false;
2225 case MVT::i8: Opc = X86::CMOV_GR8; break;
2226 case MVT::i16: Opc = X86::CMOV_GR16; break;
2227 case MVT::i32: Opc = X86::CMOV_GR32; break;
2228 case MVT::f32: Opc = X86::CMOV_FR32; break;
2229 case MVT::f64: Opc = X86::CMOV_FR64; break;
2230 }
2231
2232 const Value *Cond = I->getOperand(0);
2233 X86::CondCode CC = X86::COND_NE;
2234
2235 // Optimize conditions coming from a compare if both instructions are in the
2236 // same basic block (values defined in other basic blocks may not have
2237 // initialized registers).
2238 const auto *CI = dyn_cast<CmpInst>(Cond);
2239 if (CI && (CI->getParent() == I->getParent())) {
2240 bool NeedSwap;
2241 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2242 if (CC > X86::LAST_VALID_COND)
2243 return false;
2244
2245 const Value *CmpLHS = CI->getOperand(0);
2246 const Value *CmpRHS = CI->getOperand(1);
2247
2248 if (NeedSwap)
2249 std::swap(CmpLHS, CmpRHS);
2250
Mehdi Amini44ede332015-07-09 02:09:04 +00002251 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002252 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2253 return false;
2254 } else {
2255 unsigned CondReg = getRegForValue(Cond);
2256 if (CondReg == 0)
2257 return false;
2258 bool CondIsKill = hasTrivialKill(Cond);
Guy Blank9ae797a2016-08-21 08:02:27 +00002259
Guy Blank2bdc74a2016-09-28 11:22:17 +00002260 // In case OpReg is a K register, COPY to a GPR
2261 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2262 unsigned KCondReg = CondReg;
2263 CondReg = createResultReg(&X86::GR8RegClass);
Guy Blank9ae797a2016-08-21 08:02:27 +00002264 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
Guy Blank2bdc74a2016-09-28 11:22:17 +00002265 TII.get(TargetOpcode::COPY), CondReg)
2266 .addReg(KCondReg, getKillRegState(CondIsKill));
2267 }
2268 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2269 .addReg(CondReg, getKillRegState(CondIsKill))
2270 .addImm(1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002271 }
2272
2273 const Value *LHS = I->getOperand(1);
2274 const Value *RHS = I->getOperand(2);
2275
2276 unsigned LHSReg = getRegForValue(LHS);
2277 bool LHSIsKill = hasTrivialKill(LHS);
2278
2279 unsigned RHSReg = getRegForValue(RHS);
2280 bool RHSIsKill = hasTrivialKill(RHS);
2281
2282 if (!LHSReg || !RHSReg)
2283 return false;
2284
2285 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2286
2287 unsigned ResultReg =
2288 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2289 updateValueMap(I, ResultReg);
2290 return true;
2291}
2292
2293bool X86FastISel::X86SelectSelect(const Instruction *I) {
2294 MVT RetVT;
2295 if (!isTypeLegal(I->getType(), RetVT))
2296 return false;
2297
2298 // Check if we can fold the select.
2299 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2300 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2301 const Value *Opnd = nullptr;
2302 switch (Predicate) {
2303 default: break;
2304 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2305 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2306 }
2307 // No need for a select anymore - this is an unconditional move.
2308 if (Opnd) {
2309 unsigned OpReg = getRegForValue(Opnd);
2310 if (OpReg == 0)
2311 return false;
2312 bool OpIsKill = hasTrivialKill(Opnd);
2313 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2314 unsigned ResultReg = createResultReg(RC);
2315 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2316 TII.get(TargetOpcode::COPY), ResultReg)
2317 .addReg(OpReg, getKillRegState(OpIsKill));
2318 updateValueMap(I, ResultReg);
2319 return true;
2320 }
2321 }
2322
2323 // First try to use real conditional move instructions.
2324 if (X86FastEmitCMoveSelect(RetVT, I))
2325 return true;
2326
2327 // Try to use a sequence of SSE instructions to simulate a conditional move.
2328 if (X86FastEmitSSESelect(RetVT, I))
2329 return true;
2330
2331 // Fall-back to pseudo conditional move instructions, which will be later
2332 // converted to control-flow.
2333 if (X86FastEmitPseudoSelect(RetVT, I))
2334 return true;
2335
2336 return false;
2337}
2338
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002339bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002340 // The target-independent selection algorithm in FastISel already knows how
2341 // to select a SINT_TO_FP if the target is SSE but not AVX.
2342 // Early exit if the subtarget doesn't have AVX.
2343 if (!Subtarget->hasAVX())
2344 return false;
2345
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002346 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2347 return false;
2348
2349 // Select integer to float/double conversion.
2350 unsigned OpReg = getRegForValue(I->getOperand(0));
2351 if (OpReg == 0)
2352 return false;
2353
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002354 const TargetRegisterClass *RC = nullptr;
2355 unsigned Opcode;
2356
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002357 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002358 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002359 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002360 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002361 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002362 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002363 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002364 RC = &X86::FR32RegClass;
2365 } else
2366 return false;
2367
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002368 unsigned ImplicitDefReg = createResultReg(RC);
2369 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2370 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2371 unsigned ResultReg =
2372 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002373 updateValueMap(I, ResultReg);
2374 return true;
2375}
2376
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002377// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2378bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2379 unsigned TargetOpc,
2380 const TargetRegisterClass *RC) {
2381 assert((I->getOpcode() == Instruction::FPExt ||
2382 I->getOpcode() == Instruction::FPTrunc) &&
2383 "Instruction must be an FPExt or FPTrunc!");
2384
2385 unsigned OpReg = getRegForValue(I->getOperand(0));
2386 if (OpReg == 0)
2387 return false;
2388
2389 unsigned ResultReg = createResultReg(RC);
2390 MachineInstrBuilder MIB;
2391 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2392 ResultReg);
2393 if (Subtarget->hasAVX())
2394 MIB.addReg(OpReg);
2395 MIB.addReg(OpReg);
2396 updateValueMap(I, ResultReg);
2397 return true;
2398}
2399
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002400bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002401 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2402 I->getOperand(0)->getType()->isFloatTy()) {
2403 // fpext from float to double.
2404 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2405 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002406 }
2407
2408 return false;
2409}
2410
2411bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002412 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2413 I->getOperand(0)->getType()->isDoubleTy()) {
2414 // fptrunc from double to float.
2415 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2416 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002417 }
2418
2419 return false;
2420}
2421
2422bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002423 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2424 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002425
2426 // This code only handles truncation to byte.
2427 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2428 return false;
2429 if (!TLI.isTypeLegal(SrcVT))
2430 return false;
2431
2432 unsigned InputReg = getRegForValue(I->getOperand(0));
2433 if (!InputReg)
2434 // Unhandled operand. Halt "fast" selection and bail.
2435 return false;
2436
2437 if (SrcVT == MVT::i8) {
2438 // Truncate from i8 to i1; no code needed.
2439 updateValueMap(I, InputReg);
2440 return true;
2441 }
2442
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002443 bool KillInputReg = false;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002444 if (!Subtarget->is64Bit()) {
2445 // If we're on x86-32; we can't extract an i8 from a general register.
2446 // First issue a copy to GR16_ABCD or GR32_ABCD.
2447 const TargetRegisterClass *CopyRC =
2448 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2449 unsigned CopyReg = createResultReg(CopyRC);
2450 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2451 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2452 InputReg = CopyReg;
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002453 KillInputReg = true;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002454 }
2455
2456 // Issue an extract_subreg.
2457 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002458 InputReg, KillInputReg,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002459 X86::sub_8bit);
2460 if (!ResultReg)
2461 return false;
2462
2463 updateValueMap(I, ResultReg);
2464 return true;
2465}
2466
2467bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2468 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2469}
2470
2471bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2472 X86AddressMode SrcAM, uint64_t Len) {
2473
2474 // Make sure we don't bloat code by inlining very large memcpy's.
2475 if (!IsMemcpySmall(Len))
2476 return false;
2477
2478 bool i64Legal = Subtarget->is64Bit();
2479
2480 // We don't care about alignment here since we just emit integer accesses.
2481 while (Len) {
2482 MVT VT;
2483 if (Len >= 8 && i64Legal)
2484 VT = MVT::i64;
2485 else if (Len >= 4)
2486 VT = MVT::i32;
2487 else if (Len >= 2)
2488 VT = MVT::i16;
2489 else
2490 VT = MVT::i8;
2491
2492 unsigned Reg;
2493 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2494 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2495 assert(RV && "Failed to emit load or store??");
2496
2497 unsigned Size = VT.getSizeInBits()/8;
2498 Len -= Size;
2499 DestAM.Disp += Size;
2500 SrcAM.Disp += Size;
2501 }
2502
2503 return true;
2504}
2505
2506bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2507 // FIXME: Handle more intrinsics.
2508 switch (II->getIntrinsicID()) {
2509 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002510 case Intrinsic::convert_from_fp16:
2511 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002512 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002513 return false;
2514
2515 const Value *Op = II->getArgOperand(0);
2516 unsigned InputReg = getRegForValue(Op);
2517 if (InputReg == 0)
2518 return false;
2519
2520 // F16C only allows converting from float to half and from half to float.
2521 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2522 if (IsFloatToHalf) {
2523 if (!Op->getType()->isFloatTy())
2524 return false;
2525 } else {
2526 if (!II->getType()->isFloatTy())
2527 return false;
2528 }
2529
2530 unsigned ResultReg = 0;
2531 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2532 if (IsFloatToHalf) {
2533 // 'InputReg' is implicitly promoted from register class FR32 to
2534 // register class VR128 by method 'constrainOperandRegClass' which is
2535 // directly called by 'fastEmitInst_ri'.
2536 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
Ahmed Bougacha68a8efa2016-02-02 01:44:03 +00002537 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2538 // It's consistent with the other FP instructions, which are usually
2539 // controlled by MXCSR.
2540 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
Andrea Di Biagio70351782015-02-20 19:37:14 +00002541
2542 // Move the lower 32-bits of ResultReg to another register of class GR32.
2543 ResultReg = createResultReg(&X86::GR32RegClass);
2544 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2545 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2546 .addReg(InputReg, RegState::Kill);
2547
2548 // The result value is in the lower 16-bits of ResultReg.
2549 unsigned RegIdx = X86::sub_16bit;
2550 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2551 } else {
2552 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2553 // Explicitly sign-extend the input to 32-bit.
2554 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2555 /*Kill=*/false);
2556
2557 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2558 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2559 InputReg, /*Kill=*/true);
2560
2561 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2562
2563 // The result value is in the lower 32-bits of ResultReg.
2564 // Emit an explicit copy from register class VR128 to register class FR32.
2565 ResultReg = createResultReg(&X86::FR32RegClass);
2566 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2567 TII.get(TargetOpcode::COPY), ResultReg)
2568 .addReg(InputReg, RegState::Kill);
2569 }
2570
2571 updateValueMap(II, ResultReg);
2572 return true;
2573 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002574 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002575 MachineFunction *MF = FuncInfo.MF;
2576 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2577 return false;
2578
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002579 Type *RetTy = II->getCalledFunction()->getReturnType();
2580
2581 MVT VT;
2582 if (!isTypeLegal(RetTy, VT))
2583 return false;
2584
2585 unsigned Opc;
2586 const TargetRegisterClass *RC = nullptr;
2587
2588 switch (VT.SimpleTy) {
2589 default: llvm_unreachable("Invalid result type for frameaddress.");
2590 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2591 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2592 }
2593
2594 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2595 // we get the wrong frame register.
Matthias Braun941a7052016-07-28 18:40:00 +00002596 MachineFrameInfo &MFI = MF->getFrameInfo();
2597 MFI.setFrameAddressIsTaken(true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002598
Eric Christophera1c535b2015-02-02 23:03:45 +00002599 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002600 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002601 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2602 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2603 "Invalid Frame Register!");
2604
2605 // Always make a copy of the frame register to to a vreg first, so that we
2606 // never directly reference the frame register (the TwoAddressInstruction-
2607 // Pass doesn't like that).
2608 unsigned SrcReg = createResultReg(RC);
2609 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2610 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2611
2612 // Now recursively load from the frame address.
2613 // movq (%rbp), %rax
2614 // movq (%rax), %rax
2615 // movq (%rax), %rax
2616 // ...
2617 unsigned DestReg;
2618 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2619 while (Depth--) {
2620 DestReg = createResultReg(RC);
2621 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2622 TII.get(Opc), DestReg), SrcReg);
2623 SrcReg = DestReg;
2624 }
2625
2626 updateValueMap(II, SrcReg);
2627 return true;
2628 }
2629 case Intrinsic::memcpy: {
2630 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2631 // Don't handle volatile or variable length memcpys.
2632 if (MCI->isVolatile())
2633 return false;
2634
2635 if (isa<ConstantInt>(MCI->getLength())) {
2636 // Small memcpy's are common enough that we want to do them
2637 // without a call if possible.
2638 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2639 if (IsMemcpySmall(Len)) {
2640 X86AddressMode DestAM, SrcAM;
2641 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2642 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2643 return false;
2644 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2645 return true;
2646 }
2647 }
2648
2649 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2650 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2651 return false;
2652
2653 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2654 return false;
2655
Pete Cooper67cf9a72015-11-19 05:56:52 +00002656 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002657 }
2658 case Intrinsic::memset: {
2659 const MemSetInst *MSI = cast<MemSetInst>(II);
2660
2661 if (MSI->isVolatile())
2662 return false;
2663
2664 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2665 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2666 return false;
2667
2668 if (MSI->getDestAddressSpace() > 255)
2669 return false;
2670
Pete Cooper67cf9a72015-11-19 05:56:52 +00002671 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002672 }
2673 case Intrinsic::stackprotector: {
2674 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002675 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002676
2677 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2678 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2679
2680 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2681
2682 // Grab the frame index.
2683 X86AddressMode AM;
2684 if (!X86SelectAddress(Slot, AM)) return false;
2685 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2686 return true;
2687 }
2688 case Intrinsic::dbg_declare: {
2689 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2690 X86AddressMode AM;
2691 assert(DI->getAddress() && "Null address should be checked earlier!");
2692 if (!X86SelectAddress(DI->getAddress(), AM))
2693 return false;
2694 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2695 // FIXME may need to add RegState::Debug to any registers produced,
2696 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002697 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2698 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002699 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2700 .addImm(0)
2701 .addMetadata(DI->getVariable())
2702 .addMetadata(DI->getExpression());
2703 return true;
2704 }
2705 case Intrinsic::trap: {
2706 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2707 return true;
2708 }
2709 case Intrinsic::sqrt: {
2710 if (!Subtarget->hasSSE1())
2711 return false;
2712
2713 Type *RetTy = II->getCalledFunction()->getReturnType();
2714
2715 MVT VT;
2716 if (!isTypeLegal(RetTy, VT))
2717 return false;
2718
2719 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2720 // is not generated by FastISel yet.
2721 // FIXME: Update this code once tablegen can handle it.
Craig Toppercf65c622016-03-02 04:42:31 +00002722 static const uint16_t SqrtOpc[2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002723 {X86::SQRTSSr, X86::VSQRTSSr},
2724 {X86::SQRTSDr, X86::VSQRTSDr}
2725 };
2726 bool HasAVX = Subtarget->hasAVX();
2727 unsigned Opc;
2728 const TargetRegisterClass *RC;
2729 switch (VT.SimpleTy) {
2730 default: return false;
2731 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2732 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2733 }
2734
2735 const Value *SrcVal = II->getArgOperand(0);
2736 unsigned SrcReg = getRegForValue(SrcVal);
2737
2738 if (SrcReg == 0)
2739 return false;
2740
2741 unsigned ImplicitDefReg = 0;
2742 if (HasAVX) {
2743 ImplicitDefReg = createResultReg(RC);
2744 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2745 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2746 }
2747
2748 unsigned ResultReg = createResultReg(RC);
2749 MachineInstrBuilder MIB;
2750 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2751 ResultReg);
2752
2753 if (ImplicitDefReg)
2754 MIB.addReg(ImplicitDefReg);
2755
2756 MIB.addReg(SrcReg);
2757
2758 updateValueMap(II, ResultReg);
2759 return true;
2760 }
2761 case Intrinsic::sadd_with_overflow:
2762 case Intrinsic::uadd_with_overflow:
2763 case Intrinsic::ssub_with_overflow:
2764 case Intrinsic::usub_with_overflow:
2765 case Intrinsic::smul_with_overflow:
2766 case Intrinsic::umul_with_overflow: {
2767 // This implements the basic lowering of the xalu with overflow intrinsics
2768 // into add/sub/mul followed by either seto or setb.
2769 const Function *Callee = II->getCalledFunction();
2770 auto *Ty = cast<StructType>(Callee->getReturnType());
2771 Type *RetTy = Ty->getTypeAtIndex(0U);
Zvi Rackover6f76f462016-11-15 13:50:35 +00002772 assert(Ty->getTypeAtIndex(1)->isIntegerTy() &&
2773 Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 &&
2774 "Overflow value expected to be an i1");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002775
2776 MVT VT;
2777 if (!isTypeLegal(RetTy, VT))
2778 return false;
2779
2780 if (VT < MVT::i8 || VT > MVT::i64)
2781 return false;
2782
2783 const Value *LHS = II->getArgOperand(0);
2784 const Value *RHS = II->getArgOperand(1);
2785
2786 // Canonicalize immediate to the RHS.
2787 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2788 isCommutativeIntrinsic(II))
2789 std::swap(LHS, RHS);
2790
2791 bool UseIncDec = false;
2792 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2793 UseIncDec = true;
2794
2795 unsigned BaseOpc, CondOpc;
2796 switch (II->getIntrinsicID()) {
2797 default: llvm_unreachable("Unexpected intrinsic!");
2798 case Intrinsic::sadd_with_overflow:
2799 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2800 CondOpc = X86::SETOr;
2801 break;
2802 case Intrinsic::uadd_with_overflow:
2803 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2804 case Intrinsic::ssub_with_overflow:
2805 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2806 CondOpc = X86::SETOr;
2807 break;
2808 case Intrinsic::usub_with_overflow:
2809 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2810 case Intrinsic::smul_with_overflow:
2811 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2812 case Intrinsic::umul_with_overflow:
2813 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2814 }
2815
2816 unsigned LHSReg = getRegForValue(LHS);
2817 if (LHSReg == 0)
2818 return false;
2819 bool LHSIsKill = hasTrivialKill(LHS);
2820
2821 unsigned ResultReg = 0;
2822 // Check if we have an immediate version.
2823 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topper66111882016-06-02 04:19:42 +00002824 static const uint16_t Opc[2][4] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002825 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2826 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2827 };
2828
2829 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2830 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2831 bool IsDec = BaseOpc == X86ISD::DEC;
2832 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2833 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2834 .addReg(LHSReg, getKillRegState(LHSIsKill));
2835 } else
2836 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2837 CI->getZExtValue());
2838 }
2839
2840 unsigned RHSReg;
2841 bool RHSIsKill;
2842 if (!ResultReg) {
2843 RHSReg = getRegForValue(RHS);
2844 if (RHSReg == 0)
2845 return false;
2846 RHSIsKill = hasTrivialKill(RHS);
2847 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2848 RHSIsKill);
2849 }
2850
2851 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2852 // it manually.
2853 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002854 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002855 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002856 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002857 // First copy the first operand into RAX, which is an implicit input to
2858 // the X86::MUL*r instruction.
2859 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2860 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2861 .addReg(LHSReg, getKillRegState(LHSIsKill));
2862 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2863 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2864 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002865 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002866 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2867 if (VT == MVT::i8) {
2868 // Copy the first operand into AL, which is an implicit input to the
2869 // X86::IMUL8r instruction.
2870 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2871 TII.get(TargetOpcode::COPY), X86::AL)
2872 .addReg(LHSReg, getKillRegState(LHSIsKill));
2873 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2874 RHSIsKill);
2875 } else
2876 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2877 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2878 RHSReg, RHSIsKill);
2879 }
2880
2881 if (!ResultReg)
2882 return false;
2883
Zvi Rackoverf0b9b57b2016-11-15 13:29:23 +00002884 // Assign to a GPR since the overflow return value is lowered to a SETcc.
2885 unsigned ResultReg2 = createResultReg(&X86::GR8RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002886 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2887 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2888 ResultReg2);
2889
2890 updateValueMap(II, ResultReg, 2);
2891 return true;
2892 }
2893 case Intrinsic::x86_sse_cvttss2si:
2894 case Intrinsic::x86_sse_cvttss2si64:
2895 case Intrinsic::x86_sse2_cvttsd2si:
2896 case Intrinsic::x86_sse2_cvttsd2si64: {
2897 bool IsInputDouble;
2898 switch (II->getIntrinsicID()) {
2899 default: llvm_unreachable("Unexpected intrinsic.");
2900 case Intrinsic::x86_sse_cvttss2si:
2901 case Intrinsic::x86_sse_cvttss2si64:
2902 if (!Subtarget->hasSSE1())
2903 return false;
2904 IsInputDouble = false;
2905 break;
2906 case Intrinsic::x86_sse2_cvttsd2si:
2907 case Intrinsic::x86_sse2_cvttsd2si64:
2908 if (!Subtarget->hasSSE2())
2909 return false;
2910 IsInputDouble = true;
2911 break;
2912 }
2913
2914 Type *RetTy = II->getCalledFunction()->getReturnType();
2915 MVT VT;
2916 if (!isTypeLegal(RetTy, VT))
2917 return false;
2918
Craig Topper66111882016-06-02 04:19:42 +00002919 static const uint16_t CvtOpc[2][2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002920 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2921 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2922 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2923 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2924 };
2925 bool HasAVX = Subtarget->hasAVX();
2926 unsigned Opc;
2927 switch (VT.SimpleTy) {
2928 default: llvm_unreachable("Unexpected result type.");
2929 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2930 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2931 }
2932
2933 // Check if we can fold insertelement instructions into the convert.
2934 const Value *Op = II->getArgOperand(0);
2935 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2936 const Value *Index = IE->getOperand(2);
2937 if (!isa<ConstantInt>(Index))
2938 break;
2939 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2940
2941 if (Idx == 0) {
2942 Op = IE->getOperand(1);
2943 break;
2944 }
2945 Op = IE->getOperand(0);
2946 }
2947
2948 unsigned Reg = getRegForValue(Op);
2949 if (Reg == 0)
2950 return false;
2951
2952 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2953 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2954 .addReg(Reg);
2955
2956 updateValueMap(II, ResultReg);
2957 return true;
2958 }
2959 }
2960}
2961
2962bool X86FastISel::fastLowerArguments() {
2963 if (!FuncInfo.CanLowerReturn)
2964 return false;
2965
2966 const Function *F = FuncInfo.Fn;
2967 if (F->isVarArg())
2968 return false;
2969
2970 CallingConv::ID CC = F->getCallingConv();
2971 if (CC != CallingConv::C)
2972 return false;
2973
2974 if (Subtarget->isCallingConvWin64(CC))
2975 return false;
2976
2977 if (!Subtarget->is64Bit())
2978 return false;
2979
2980 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2981 unsigned GPRCnt = 0;
2982 unsigned FPRCnt = 0;
2983 unsigned Idx = 0;
2984 for (auto const &Arg : F->args()) {
2985 // The first argument is at index 1.
2986 ++Idx;
2987 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2988 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2989 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
Manman Renf46262e2016-03-29 17:37:21 +00002990 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
Manman Ren57518142016-04-11 21:08:06 +00002991 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002992 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2993 return false;
2994
2995 Type *ArgTy = Arg.getType();
2996 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2997 return false;
2998
Mehdi Amini44ede332015-07-09 02:09:04 +00002999 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003000 if (!ArgVT.isSimple()) return false;
3001 switch (ArgVT.getSimpleVT().SimpleTy) {
3002 default: return false;
3003 case MVT::i32:
3004 case MVT::i64:
3005 ++GPRCnt;
3006 break;
3007 case MVT::f32:
3008 case MVT::f64:
3009 if (!Subtarget->hasSSE1())
3010 return false;
3011 ++FPRCnt;
3012 break;
3013 }
3014
3015 if (GPRCnt > 6)
3016 return false;
3017
3018 if (FPRCnt > 8)
3019 return false;
3020 }
3021
3022 static const MCPhysReg GPR32ArgRegs[] = {
3023 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
3024 };
3025 static const MCPhysReg GPR64ArgRegs[] = {
3026 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
3027 };
3028 static const MCPhysReg XMMArgRegs[] = {
3029 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3030 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3031 };
3032
3033 unsigned GPRIdx = 0;
3034 unsigned FPRIdx = 0;
3035 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003036 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003037 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
3038 unsigned SrcReg;
3039 switch (VT.SimpleTy) {
3040 default: llvm_unreachable("Unexpected value type.");
3041 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
3042 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003043 case MVT::f32: LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003044 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
3045 }
3046 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3047 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3048 // Without this, EmitLiveInCopies may eliminate the livein if its only
3049 // use is a bitcast (which isn't turned into an instruction).
3050 unsigned ResultReg = createResultReg(RC);
3051 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3052 TII.get(TargetOpcode::COPY), ResultReg)
3053 .addReg(DstReg, getKillRegState(true));
3054 updateValueMap(&Arg, ResultReg);
3055 }
3056 return true;
3057}
3058
Nico Weberaf7e8462016-07-14 01:52:51 +00003059static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
3060 CallingConv::ID CC,
3061 ImmutableCallSite *CS) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003062 if (Subtarget->is64Bit())
3063 return 0;
3064 if (Subtarget->getTargetTriple().isOSMSVCRT())
3065 return 0;
3066 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3067 CC == CallingConv::HiPE)
3068 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003069
3070 if (CS)
3071 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00003072 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003073 return 0;
3074
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003075 return 4;
3076}
3077
3078bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3079 auto &OutVals = CLI.OutVals;
3080 auto &OutFlags = CLI.OutFlags;
3081 auto &OutRegs = CLI.OutRegs;
3082 auto &Ins = CLI.Ins;
3083 auto &InRegs = CLI.InRegs;
3084 CallingConv::ID CC = CLI.CallConv;
3085 bool &IsTailCall = CLI.IsTailCall;
3086 bool IsVarArg = CLI.IsVarArg;
3087 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003088 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003089
3090 bool Is64Bit = Subtarget->is64Bit();
3091 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3092
3093 // Handle only C, fastcc, and webkit_js calling conventions for now.
3094 switch (CC) {
3095 default: return false;
3096 case CallingConv::C:
3097 case CallingConv::Fast:
3098 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00003099 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003100 case CallingConv::X86_FastCall:
Nico Weberecdf45b2016-07-14 13:54:26 +00003101 case CallingConv::X86_StdCall:
Nico Weberaf7e8462016-07-14 01:52:51 +00003102 case CallingConv::X86_ThisCall:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003103 case CallingConv::X86_64_Win64:
3104 case CallingConv::X86_64_SysV:
3105 break;
3106 }
3107
3108 // Allow SelectionDAG isel to handle tail calls.
3109 if (IsTailCall)
3110 return false;
3111
3112 // fastcc with -tailcallopt is intended to provide a guaranteed
3113 // tail call optimization. Fastisel doesn't know how to do that.
3114 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3115 return false;
3116
3117 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3118 // x86-32. Special handling for x86-64 is implemented.
3119 if (IsVarArg && IsWin64)
3120 return false;
3121
3122 // Don't know about inalloca yet.
3123 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3124 return false;
3125
Manman Ren57518142016-04-11 21:08:06 +00003126 for (auto Flag : CLI.OutFlags)
3127 if (Flag.isSwiftError())
3128 return false;
3129
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003130 SmallVector<MVT, 16> OutVTs;
3131 SmallVector<unsigned, 16> ArgRegs;
3132
3133 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3134 // instruction. This is safe because it is common to all FastISel supported
3135 // calling conventions on x86.
3136 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3137 Value *&Val = OutVals[i];
3138 ISD::ArgFlagsTy Flags = OutFlags[i];
3139 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3140 if (CI->getBitWidth() < 32) {
3141 if (Flags.isSExt())
3142 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3143 else
3144 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3145 }
3146 }
3147
3148 // Passing bools around ends up doing a trunc to i1 and passing it.
3149 // Codegen this as an argument + "and 1".
3150 MVT VT;
3151 auto *TI = dyn_cast<TruncInst>(Val);
3152 unsigned ResultReg;
3153 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3154 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3155 TI->hasOneUse()) {
3156 Value *PrevVal = TI->getOperand(0);
3157 ResultReg = getRegForValue(PrevVal);
3158
3159 if (!ResultReg)
3160 return false;
3161
3162 if (!isTypeLegal(PrevVal->getType(), VT))
3163 return false;
3164
3165 ResultReg =
3166 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3167 } else {
3168 if (!isTypeLegal(Val->getType(), VT))
3169 return false;
3170 ResultReg = getRegForValue(Val);
3171 }
3172
3173 if (!ResultReg)
3174 return false;
3175
3176 ArgRegs.push_back(ResultReg);
3177 OutVTs.push_back(VT);
3178 }
3179
3180 // Analyze operands of the call, assigning locations to each operand.
3181 SmallVector<CCValAssign, 16> ArgLocs;
3182 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3183
3184 // Allocate shadow area for Win64
3185 if (IsWin64)
3186 CCInfo.AllocateStack(32, 8);
3187
3188 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3189
3190 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00003191 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003192
3193 // Issue CALLSEQ_START
3194 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3195 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00003196 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003197
3198 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00003199 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003200 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3201 CCValAssign const &VA = ArgLocs[i];
3202 const Value *ArgVal = OutVals[VA.getValNo()];
3203 MVT ArgVT = OutVTs[VA.getValNo()];
3204
3205 if (ArgVT == MVT::x86mmx)
3206 return false;
3207
3208 unsigned ArgReg = ArgRegs[VA.getValNo()];
3209
3210 // Promote the value if needed.
3211 switch (VA.getLocInfo()) {
3212 case CCValAssign::Full: break;
3213 case CCValAssign::SExt: {
3214 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3215 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003216
3217 if (ArgVT.SimpleTy == MVT::i1)
3218 return false;
3219
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003220 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3221 ArgVT, ArgReg);
3222 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3223 ArgVT = VA.getLocVT();
3224 break;
3225 }
3226 case CCValAssign::ZExt: {
3227 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3228 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003229
3230 // Handle zero-extension from i1 to i8, which is common.
3231 if (ArgVT.SimpleTy == MVT::i1) {
3232 // Set the high bits to zero.
3233 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3234 ArgVT = MVT::i8;
3235
3236 if (ArgReg == 0)
3237 return false;
3238 }
3239
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003240 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3241 ArgVT, ArgReg);
3242 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3243 ArgVT = VA.getLocVT();
3244 break;
3245 }
3246 case CCValAssign::AExt: {
3247 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3248 "Unexpected extend");
3249 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3250 ArgVT, ArgReg);
3251 if (!Emitted)
3252 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3253 ArgVT, ArgReg);
3254 if (!Emitted)
3255 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3256 ArgVT, ArgReg);
3257
3258 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3259 ArgVT = VA.getLocVT();
3260 break;
3261 }
3262 case CCValAssign::BCvt: {
3263 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3264 /*TODO: Kill=*/false);
3265 assert(ArgReg && "Failed to emit a bitcast!");
3266 ArgVT = VA.getLocVT();
3267 break;
3268 }
3269 case CCValAssign::VExt:
3270 // VExt has not been implemented, so this should be impossible to reach
3271 // for now. However, fallback to Selection DAG isel once implemented.
3272 return false;
3273 case CCValAssign::AExtUpper:
3274 case CCValAssign::SExtUpper:
3275 case CCValAssign::ZExtUpper:
3276 case CCValAssign::FPExt:
3277 llvm_unreachable("Unexpected loc info!");
3278 case CCValAssign::Indirect:
3279 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3280 // support this.
3281 return false;
3282 }
3283
3284 if (VA.isRegLoc()) {
3285 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3286 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3287 OutRegs.push_back(VA.getLocReg());
3288 } else {
3289 assert(VA.isMemLoc());
3290
3291 // Don't emit stores for undef values.
3292 if (isa<UndefValue>(ArgVal))
3293 continue;
3294
3295 unsigned LocMemOffset = VA.getLocMemOffset();
3296 X86AddressMode AM;
3297 AM.Base.Reg = RegInfo->getStackRegister();
3298 AM.Disp = LocMemOffset;
3299 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3300 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3301 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003302 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3303 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003304 if (Flags.isByVal()) {
3305 X86AddressMode SrcAM;
3306 SrcAM.Base.Reg = ArgReg;
3307 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3308 return false;
3309 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3310 // If this is a really simple value, emit this with the Value* version
3311 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3312 // as it can cause us to reevaluate the argument.
3313 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3314 return false;
3315 } else {
3316 bool ValIsKill = hasTrivialKill(ArgVal);
3317 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3318 return false;
3319 }
3320 }
3321 }
3322
3323 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3324 // GOT pointer.
3325 if (Subtarget->isPICStyleGOT()) {
3326 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3327 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3328 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3329 }
3330
3331 if (Is64Bit && IsVarArg && !IsWin64) {
3332 // From AMD64 ABI document:
3333 // For calls that may call functions that use varargs or stdargs
3334 // (prototype-less calls or calls to functions containing ellipsis (...) in
3335 // the declaration) %al is used as hidden argument to specify the number
3336 // of SSE registers used. The contents of %al do not need to match exactly
3337 // the number of registers, but must be an ubound on the number of SSE
3338 // registers used and is in the range 0 - 8 inclusive.
3339
3340 // Count the number of XMM registers allocated.
3341 static const MCPhysReg XMMArgRegs[] = {
3342 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3343 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3344 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003345 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003346 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3347 && "SSE registers cannot be used when SSE is disabled");
3348 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3349 X86::AL).addImm(NumXMMRegs);
3350 }
3351
3352 // Materialize callee address in a register. FIXME: GV address can be
3353 // handled with a CALLpcrel32 instead.
3354 X86AddressMode CalleeAM;
3355 if (!X86SelectCallAddress(Callee, CalleeAM))
3356 return false;
3357
3358 unsigned CalleeOp = 0;
3359 const GlobalValue *GV = nullptr;
3360 if (CalleeAM.GV != nullptr) {
3361 GV = CalleeAM.GV;
3362 } else if (CalleeAM.Base.Reg != 0) {
3363 CalleeOp = CalleeAM.Base.Reg;
3364 } else
3365 return false;
3366
3367 // Issue the call.
3368 MachineInstrBuilder MIB;
3369 if (CalleeOp) {
3370 // Register-indirect call.
3371 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3372 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3373 .addReg(CalleeOp);
3374 } else {
3375 // Direct call.
3376 assert(GV && "Not a direct call");
3377 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3378
3379 // See if we need any target-specific flags on the GV operand.
Rafael Espindola46107b92016-05-19 18:49:29 +00003380 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
Asaf Badouh89406d12016-04-20 08:32:57 +00003381 // Ignore NonLazyBind attribute in FastISel
3382 if (OpFlags == X86II::MO_GOTPCREL)
3383 OpFlags = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003384
3385 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003386 if (Symbol)
3387 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003388 else
3389 MIB.addGlobalAddress(GV, 0, OpFlags);
3390 }
3391
3392 // Add a register mask operand representing the call-preserved registers.
3393 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003394 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003395
3396 // Add an implicit use GOT pointer in EBX.
3397 if (Subtarget->isPICStyleGOT())
3398 MIB.addReg(X86::EBX, RegState::Implicit);
3399
3400 if (Is64Bit && IsVarArg && !IsWin64)
3401 MIB.addReg(X86::AL, RegState::Implicit);
3402
3403 // Add implicit physical register uses to the call.
3404 for (auto Reg : OutRegs)
3405 MIB.addReg(Reg, RegState::Implicit);
3406
3407 // Issue CALLSEQ_END
3408 unsigned NumBytesForCalleeToPop =
Nico Weberaf7e8462016-07-14 01:52:51 +00003409 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3410 TM.Options.GuaranteedTailCallOpt)
3411 ? NumBytes // Callee pops everything.
3412 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003413 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3415 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3416
3417 // Now handle call return values.
3418 SmallVector<CCValAssign, 16> RVLocs;
3419 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3420 CLI.RetTy->getContext());
3421 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3422
3423 // Copy all of the result registers out of their specified physreg.
3424 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3425 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3426 CCValAssign &VA = RVLocs[i];
3427 EVT CopyVT = VA.getValVT();
3428 unsigned CopyReg = ResultReg + i;
3429
3430 // If this is x86-64, and we disabled SSE, we can't return FP values
3431 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3432 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3433 report_fatal_error("SSE register return with SSE disabled");
3434 }
3435
3436 // If we prefer to use the value in xmm registers, copy it out as f80 and
3437 // use a truncate to move it from fp stack reg to xmm reg.
3438 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3439 isScalarFPTypeInSSEReg(VA.getValVT())) {
3440 CopyVT = MVT::f80;
3441 CopyReg = createResultReg(&X86::RFP80RegClass);
3442 }
3443
3444 // Copy out the result.
3445 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3446 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3447 InRegs.push_back(VA.getLocReg());
3448
3449 // Round the f80 to the right size, which also moves it to the appropriate
3450 // xmm register. This is accomplished by storing the f80 value in memory
3451 // and then loading it back.
3452 if (CopyVT != VA.getValVT()) {
3453 EVT ResVT = VA.getValVT();
3454 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3455 unsigned MemSize = ResVT.getSizeInBits()/8;
3456 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3457 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3458 TII.get(Opc)), FI)
3459 .addReg(CopyReg);
3460 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3461 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3462 TII.get(Opc), ResultReg + i), FI);
3463 }
3464 }
3465
3466 CLI.ResultReg = ResultReg;
3467 CLI.NumResultRegs = RVLocs.size();
3468 CLI.Call = MIB;
3469
3470 return true;
3471}
3472
3473bool
3474X86FastISel::fastSelectInstruction(const Instruction *I) {
3475 switch (I->getOpcode()) {
3476 default: break;
3477 case Instruction::Load:
3478 return X86SelectLoad(I);
3479 case Instruction::Store:
3480 return X86SelectStore(I);
3481 case Instruction::Ret:
3482 return X86SelectRet(I);
3483 case Instruction::ICmp:
3484 case Instruction::FCmp:
3485 return X86SelectCmp(I);
3486 case Instruction::ZExt:
3487 return X86SelectZExt(I);
3488 case Instruction::Br:
3489 return X86SelectBranch(I);
3490 case Instruction::LShr:
3491 case Instruction::AShr:
3492 case Instruction::Shl:
3493 return X86SelectShift(I);
3494 case Instruction::SDiv:
3495 case Instruction::UDiv:
3496 case Instruction::SRem:
3497 case Instruction::URem:
3498 return X86SelectDivRem(I);
3499 case Instruction::Select:
3500 return X86SelectSelect(I);
3501 case Instruction::Trunc:
3502 return X86SelectTrunc(I);
3503 case Instruction::FPExt:
3504 return X86SelectFPExt(I);
3505 case Instruction::FPTrunc:
3506 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003507 case Instruction::SIToFP:
3508 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003509 case Instruction::IntToPtr: // Deliberate fall-through.
3510 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003511 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3512 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003513 if (DstVT.bitsGT(SrcVT))
3514 return X86SelectZExt(I);
3515 if (DstVT.bitsLT(SrcVT))
3516 return X86SelectTrunc(I);
3517 unsigned Reg = getRegForValue(I->getOperand(0));
3518 if (Reg == 0) return false;
3519 updateValueMap(I, Reg);
3520 return true;
3521 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003522 case Instruction::BitCast: {
3523 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3524 if (!Subtarget->hasSSE2())
3525 return false;
3526
3527 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3528 EVT DstVT = TLI.getValueType(DL, I->getType());
3529
3530 if (!SrcVT.isSimple() || !DstVT.isSimple())
3531 return false;
3532
3533 if (!SrcVT.is128BitVector() &&
3534 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3535 return false;
3536
3537 unsigned Reg = getRegForValue(I->getOperand(0));
3538 if (Reg == 0)
3539 return false;
3540
3541 // No instruction is needed for conversion. Reuse the register used by
3542 // the fist operand.
3543 updateValueMap(I, Reg);
3544 return true;
3545 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003546 }
3547
3548 return false;
3549}
3550
3551unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3552 if (VT > MVT::i64)
3553 return 0;
3554
3555 uint64_t Imm = CI->getZExtValue();
3556 if (Imm == 0) {
3557 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3558 switch (VT.SimpleTy) {
3559 default: llvm_unreachable("Unexpected value type");
3560 case MVT::i1:
3561 case MVT::i8:
3562 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3563 X86::sub_8bit);
3564 case MVT::i16:
3565 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3566 X86::sub_16bit);
3567 case MVT::i32:
3568 return SrcReg;
3569 case MVT::i64: {
3570 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3571 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3572 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3573 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3574 return ResultReg;
3575 }
3576 }
3577 }
3578
3579 unsigned Opc = 0;
3580 switch (VT.SimpleTy) {
3581 default: llvm_unreachable("Unexpected value type");
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003582 case MVT::i1: VT = MVT::i8; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003583 case MVT::i8: Opc = X86::MOV8ri; break;
3584 case MVT::i16: Opc = X86::MOV16ri; break;
3585 case MVT::i32: Opc = X86::MOV32ri; break;
3586 case MVT::i64: {
3587 if (isUInt<32>(Imm))
3588 Opc = X86::MOV32ri;
3589 else if (isInt<32>(Imm))
3590 Opc = X86::MOV64ri32;
3591 else
3592 Opc = X86::MOV64ri;
3593 break;
3594 }
3595 }
3596 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3597 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3598 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3599 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3600 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3601 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3602 return ResultReg;
3603 }
3604 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3605}
3606
3607unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3608 if (CFP->isNullValue())
3609 return fastMaterializeFloatZero(CFP);
3610
3611 // Can't handle alternate code models yet.
3612 CodeModel::Model CM = TM.getCodeModel();
3613 if (CM != CodeModel::Small && CM != CodeModel::Large)
3614 return 0;
3615
3616 // Get opcode and regclass of the output for the given load instruction.
3617 unsigned Opc = 0;
3618 const TargetRegisterClass *RC = nullptr;
3619 switch (VT.SimpleTy) {
3620 default: return 0;
3621 case MVT::f32:
3622 if (X86ScalarSSEf32) {
3623 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3624 RC = &X86::FR32RegClass;
3625 } else {
3626 Opc = X86::LD_Fp32m;
3627 RC = &X86::RFP32RegClass;
3628 }
3629 break;
3630 case MVT::f64:
3631 if (X86ScalarSSEf64) {
3632 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3633 RC = &X86::FR64RegClass;
3634 } else {
3635 Opc = X86::LD_Fp64m;
3636 RC = &X86::RFP64RegClass;
3637 }
3638 break;
3639 case MVT::f80:
3640 // No f80 support yet.
3641 return 0;
3642 }
3643
3644 // MachineConstantPool wants an explicit alignment.
3645 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3646 if (Align == 0) {
3647 // Alignment of vector types. FIXME!
3648 Align = DL.getTypeAllocSize(CFP->getType());
3649 }
3650
3651 // x86-32 PIC requires a PIC base register for constant pools.
3652 unsigned PICBase = 0;
Rafael Espindolac7e98132016-05-20 12:20:10 +00003653 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3654 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003655 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003656 else if (OpFlag == X86II::MO_GOTOFF)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003657 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003658 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003659 PICBase = X86::RIP;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003660
3661 // Create the load from the constant pool.
3662 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3663 unsigned ResultReg = createResultReg(RC);
3664
3665 if (CM == CodeModel::Large) {
3666 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3667 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3668 AddrReg)
3669 .addConstantPoolIndex(CPI, 0, OpFlag);
3670 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3671 TII.get(Opc), ResultReg);
3672 addDirectMem(MIB, AddrReg);
3673 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003674 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3675 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003676 MIB->addMemOperand(*FuncInfo.MF, MMO);
3677 return ResultReg;
3678 }
3679
3680 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3681 TII.get(Opc), ResultReg),
3682 CPI, PICBase, OpFlag);
3683 return ResultReg;
3684}
3685
3686unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3687 // Can't handle alternate code models yet.
3688 if (TM.getCodeModel() != CodeModel::Small)
3689 return 0;
3690
3691 // Materialize addresses with LEA/MOV instructions.
3692 X86AddressMode AM;
3693 if (X86SelectAddress(GV, AM)) {
3694 // If the expression is just a basereg, then we're done, otherwise we need
3695 // to emit an LEA.
3696 if (AM.BaseType == X86AddressMode::RegBase &&
3697 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3698 return AM.Base.Reg;
3699
3700 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3701 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003702 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003703 // The displacement code could be more than 32 bits away so we need to use
3704 // an instruction with a 64 bit immediate
3705 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3706 ResultReg)
3707 .addGlobalAddress(GV);
3708 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003709 unsigned Opc =
3710 TLI.getPointerTy(DL) == MVT::i32
3711 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3712 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003713 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3714 TII.get(Opc), ResultReg), AM);
3715 }
3716 return ResultReg;
3717 }
3718 return 0;
3719}
3720
3721unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003722 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003723
3724 // Only handle simple types.
3725 if (!CEVT.isSimple())
3726 return 0;
3727 MVT VT = CEVT.getSimpleVT();
3728
3729 if (const auto *CI = dyn_cast<ConstantInt>(C))
3730 return X86MaterializeInt(CI, VT);
3731 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3732 return X86MaterializeFP(CFP, VT);
3733 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3734 return X86MaterializeGV(GV, VT);
3735
3736 return 0;
3737}
3738
3739unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3740 // Fail on dynamic allocas. At this point, getRegForValue has already
3741 // checked its CSE maps, so if we're here trying to handle a dynamic
3742 // alloca, we're not going to succeed. X86SelectAddress has a
3743 // check for dynamic allocas, because it's called directly from
3744 // various places, but targetMaterializeAlloca also needs a check
3745 // in order to avoid recursion between getRegForValue,
3746 // X86SelectAddrss, and targetMaterializeAlloca.
3747 if (!FuncInfo.StaticAllocaMap.count(C))
3748 return 0;
3749 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3750
3751 X86AddressMode AM;
3752 if (!X86SelectAddress(C, AM))
3753 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003754 unsigned Opc =
3755 TLI.getPointerTy(DL) == MVT::i32
3756 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3757 : X86::LEA64r;
3758 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003759 unsigned ResultReg = createResultReg(RC);
3760 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3761 TII.get(Opc), ResultReg), AM);
3762 return ResultReg;
3763}
3764
3765unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3766 MVT VT;
3767 if (!isTypeLegal(CF->getType(), VT))
3768 return 0;
3769
3770 // Get opcode and regclass for the given zero.
3771 unsigned Opc = 0;
3772 const TargetRegisterClass *RC = nullptr;
3773 switch (VT.SimpleTy) {
3774 default: return 0;
3775 case MVT::f32:
3776 if (X86ScalarSSEf32) {
3777 Opc = X86::FsFLD0SS;
3778 RC = &X86::FR32RegClass;
3779 } else {
3780 Opc = X86::LD_Fp032;
3781 RC = &X86::RFP32RegClass;
3782 }
3783 break;
3784 case MVT::f64:
3785 if (X86ScalarSSEf64) {
3786 Opc = X86::FsFLD0SD;
3787 RC = &X86::FR64RegClass;
3788 } else {
3789 Opc = X86::LD_Fp064;
3790 RC = &X86::RFP64RegClass;
3791 }
3792 break;
3793 case MVT::f80:
3794 // No f80 support yet.
3795 return 0;
3796 }
3797
3798 unsigned ResultReg = createResultReg(RC);
3799 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3800 return ResultReg;
3801}
3802
3803
3804bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3805 const LoadInst *LI) {
3806 const Value *Ptr = LI->getPointerOperand();
3807 X86AddressMode AM;
3808 if (!X86SelectAddress(Ptr, AM))
3809 return false;
3810
3811 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3812
3813 unsigned Size = DL.getTypeAllocSize(LI->getType());
3814 unsigned Alignment = LI->getAlignment();
3815
3816 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3817 Alignment = DL.getABITypeAlignment(LI->getType());
3818
3819 SmallVector<MachineOperand, 8> AddrOps;
3820 AM.getFullAddress(AddrOps);
3821
Keno Fischere70b31f2015-06-08 20:09:58 +00003822 MachineInstr *Result = XII.foldMemoryOperandImpl(
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00003823 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
Keno Fischere70b31f2015-06-08 20:09:58 +00003824 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003825 if (!Result)
3826 return false;
3827
Pete Cooperd31583d2015-05-06 21:37:19 +00003828 // The index register could be in the wrong register class. Unfortunately,
3829 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3830 // to just look at OpNo + the offset to the index reg. We actually need to
3831 // scan the instruction to find the index reg and see if its the correct reg
3832 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003833 unsigned OperandNo = 0;
3834 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3835 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3836 MachineOperand &MO = *I;
3837 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003838 continue;
3839 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003840 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003841 MO.getReg(), OperandNo);
3842 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003843 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003844 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003845 }
3846
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003847 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003848 MI->eraseFromParent();
3849 return true;
3850}
3851
3852
3853namespace llvm {
3854 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3855 const TargetLibraryInfo *libInfo) {
3856 return new X86FastISel(funcInfo, libInfo);
3857 }
3858}