blob: d7eeb402b1dc646b716dcf9880a74d51aab686e7 [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;
939 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
940 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);
2772 Type *CondTy = Ty->getTypeAtIndex(1);
2773
2774 MVT VT;
2775 if (!isTypeLegal(RetTy, VT))
2776 return false;
2777
2778 if (VT < MVT::i8 || VT > MVT::i64)
2779 return false;
2780
2781 const Value *LHS = II->getArgOperand(0);
2782 const Value *RHS = II->getArgOperand(1);
2783
2784 // Canonicalize immediate to the RHS.
2785 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2786 isCommutativeIntrinsic(II))
2787 std::swap(LHS, RHS);
2788
2789 bool UseIncDec = false;
2790 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2791 UseIncDec = true;
2792
2793 unsigned BaseOpc, CondOpc;
2794 switch (II->getIntrinsicID()) {
2795 default: llvm_unreachable("Unexpected intrinsic!");
2796 case Intrinsic::sadd_with_overflow:
2797 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2798 CondOpc = X86::SETOr;
2799 break;
2800 case Intrinsic::uadd_with_overflow:
2801 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2802 case Intrinsic::ssub_with_overflow:
2803 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2804 CondOpc = X86::SETOr;
2805 break;
2806 case Intrinsic::usub_with_overflow:
2807 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2808 case Intrinsic::smul_with_overflow:
2809 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2810 case Intrinsic::umul_with_overflow:
2811 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2812 }
2813
2814 unsigned LHSReg = getRegForValue(LHS);
2815 if (LHSReg == 0)
2816 return false;
2817 bool LHSIsKill = hasTrivialKill(LHS);
2818
2819 unsigned ResultReg = 0;
2820 // Check if we have an immediate version.
2821 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topper66111882016-06-02 04:19:42 +00002822 static const uint16_t Opc[2][4] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002823 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2824 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2825 };
2826
2827 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2828 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2829 bool IsDec = BaseOpc == X86ISD::DEC;
2830 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2831 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2832 .addReg(LHSReg, getKillRegState(LHSIsKill));
2833 } else
2834 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2835 CI->getZExtValue());
2836 }
2837
2838 unsigned RHSReg;
2839 bool RHSIsKill;
2840 if (!ResultReg) {
2841 RHSReg = getRegForValue(RHS);
2842 if (RHSReg == 0)
2843 return false;
2844 RHSIsKill = hasTrivialKill(RHS);
2845 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2846 RHSIsKill);
2847 }
2848
2849 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2850 // it manually.
2851 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002852 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002853 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002854 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002855 // First copy the first operand into RAX, which is an implicit input to
2856 // the X86::MUL*r instruction.
2857 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2858 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2859 .addReg(LHSReg, getKillRegState(LHSIsKill));
2860 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2861 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2862 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002863 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002864 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2865 if (VT == MVT::i8) {
2866 // Copy the first operand into AL, which is an implicit input to the
2867 // X86::IMUL8r instruction.
2868 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2869 TII.get(TargetOpcode::COPY), X86::AL)
2870 .addReg(LHSReg, getKillRegState(LHSIsKill));
2871 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2872 RHSIsKill);
2873 } else
2874 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2875 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2876 RHSReg, RHSIsKill);
2877 }
2878
2879 if (!ResultReg)
2880 return false;
2881
2882 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2883 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2884 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2885 ResultReg2);
2886
2887 updateValueMap(II, ResultReg, 2);
2888 return true;
2889 }
2890 case Intrinsic::x86_sse_cvttss2si:
2891 case Intrinsic::x86_sse_cvttss2si64:
2892 case Intrinsic::x86_sse2_cvttsd2si:
2893 case Intrinsic::x86_sse2_cvttsd2si64: {
2894 bool IsInputDouble;
2895 switch (II->getIntrinsicID()) {
2896 default: llvm_unreachable("Unexpected intrinsic.");
2897 case Intrinsic::x86_sse_cvttss2si:
2898 case Intrinsic::x86_sse_cvttss2si64:
2899 if (!Subtarget->hasSSE1())
2900 return false;
2901 IsInputDouble = false;
2902 break;
2903 case Intrinsic::x86_sse2_cvttsd2si:
2904 case Intrinsic::x86_sse2_cvttsd2si64:
2905 if (!Subtarget->hasSSE2())
2906 return false;
2907 IsInputDouble = true;
2908 break;
2909 }
2910
2911 Type *RetTy = II->getCalledFunction()->getReturnType();
2912 MVT VT;
2913 if (!isTypeLegal(RetTy, VT))
2914 return false;
2915
Craig Topper66111882016-06-02 04:19:42 +00002916 static const uint16_t CvtOpc[2][2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002917 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2918 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2919 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2920 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2921 };
2922 bool HasAVX = Subtarget->hasAVX();
2923 unsigned Opc;
2924 switch (VT.SimpleTy) {
2925 default: llvm_unreachable("Unexpected result type.");
2926 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2927 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2928 }
2929
2930 // Check if we can fold insertelement instructions into the convert.
2931 const Value *Op = II->getArgOperand(0);
2932 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2933 const Value *Index = IE->getOperand(2);
2934 if (!isa<ConstantInt>(Index))
2935 break;
2936 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2937
2938 if (Idx == 0) {
2939 Op = IE->getOperand(1);
2940 break;
2941 }
2942 Op = IE->getOperand(0);
2943 }
2944
2945 unsigned Reg = getRegForValue(Op);
2946 if (Reg == 0)
2947 return false;
2948
2949 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2950 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2951 .addReg(Reg);
2952
2953 updateValueMap(II, ResultReg);
2954 return true;
2955 }
2956 }
2957}
2958
2959bool X86FastISel::fastLowerArguments() {
2960 if (!FuncInfo.CanLowerReturn)
2961 return false;
2962
2963 const Function *F = FuncInfo.Fn;
2964 if (F->isVarArg())
2965 return false;
2966
2967 CallingConv::ID CC = F->getCallingConv();
2968 if (CC != CallingConv::C)
2969 return false;
2970
2971 if (Subtarget->isCallingConvWin64(CC))
2972 return false;
2973
2974 if (!Subtarget->is64Bit())
2975 return false;
2976
2977 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2978 unsigned GPRCnt = 0;
2979 unsigned FPRCnt = 0;
2980 unsigned Idx = 0;
2981 for (auto const &Arg : F->args()) {
2982 // The first argument is at index 1.
2983 ++Idx;
2984 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2985 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2986 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
Manman Renf46262e2016-03-29 17:37:21 +00002987 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
Manman Ren57518142016-04-11 21:08:06 +00002988 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002989 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2990 return false;
2991
2992 Type *ArgTy = Arg.getType();
2993 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2994 return false;
2995
Mehdi Amini44ede332015-07-09 02:09:04 +00002996 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002997 if (!ArgVT.isSimple()) return false;
2998 switch (ArgVT.getSimpleVT().SimpleTy) {
2999 default: return false;
3000 case MVT::i32:
3001 case MVT::i64:
3002 ++GPRCnt;
3003 break;
3004 case MVT::f32:
3005 case MVT::f64:
3006 if (!Subtarget->hasSSE1())
3007 return false;
3008 ++FPRCnt;
3009 break;
3010 }
3011
3012 if (GPRCnt > 6)
3013 return false;
3014
3015 if (FPRCnt > 8)
3016 return false;
3017 }
3018
3019 static const MCPhysReg GPR32ArgRegs[] = {
3020 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
3021 };
3022 static const MCPhysReg GPR64ArgRegs[] = {
3023 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
3024 };
3025 static const MCPhysReg XMMArgRegs[] = {
3026 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3027 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3028 };
3029
3030 unsigned GPRIdx = 0;
3031 unsigned FPRIdx = 0;
3032 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003033 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003034 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
3035 unsigned SrcReg;
3036 switch (VT.SimpleTy) {
3037 default: llvm_unreachable("Unexpected value type.");
3038 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
3039 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003040 case MVT::f32: LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003041 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
3042 }
3043 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3044 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3045 // Without this, EmitLiveInCopies may eliminate the livein if its only
3046 // use is a bitcast (which isn't turned into an instruction).
3047 unsigned ResultReg = createResultReg(RC);
3048 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3049 TII.get(TargetOpcode::COPY), ResultReg)
3050 .addReg(DstReg, getKillRegState(true));
3051 updateValueMap(&Arg, ResultReg);
3052 }
3053 return true;
3054}
3055
Nico Weberaf7e8462016-07-14 01:52:51 +00003056static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
3057 CallingConv::ID CC,
3058 ImmutableCallSite *CS) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003059 if (Subtarget->is64Bit())
3060 return 0;
3061 if (Subtarget->getTargetTriple().isOSMSVCRT())
3062 return 0;
3063 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3064 CC == CallingConv::HiPE)
3065 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003066
3067 if (CS)
3068 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00003069 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003070 return 0;
3071
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003072 return 4;
3073}
3074
3075bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3076 auto &OutVals = CLI.OutVals;
3077 auto &OutFlags = CLI.OutFlags;
3078 auto &OutRegs = CLI.OutRegs;
3079 auto &Ins = CLI.Ins;
3080 auto &InRegs = CLI.InRegs;
3081 CallingConv::ID CC = CLI.CallConv;
3082 bool &IsTailCall = CLI.IsTailCall;
3083 bool IsVarArg = CLI.IsVarArg;
3084 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003085 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003086
3087 bool Is64Bit = Subtarget->is64Bit();
3088 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3089
3090 // Handle only C, fastcc, and webkit_js calling conventions for now.
3091 switch (CC) {
3092 default: return false;
3093 case CallingConv::C:
3094 case CallingConv::Fast:
3095 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00003096 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003097 case CallingConv::X86_FastCall:
Nico Weberecdf45b2016-07-14 13:54:26 +00003098 case CallingConv::X86_StdCall:
Nico Weberaf7e8462016-07-14 01:52:51 +00003099 case CallingConv::X86_ThisCall:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003100 case CallingConv::X86_64_Win64:
3101 case CallingConv::X86_64_SysV:
3102 break;
3103 }
3104
3105 // Allow SelectionDAG isel to handle tail calls.
3106 if (IsTailCall)
3107 return false;
3108
3109 // fastcc with -tailcallopt is intended to provide a guaranteed
3110 // tail call optimization. Fastisel doesn't know how to do that.
3111 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3112 return false;
3113
3114 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3115 // x86-32. Special handling for x86-64 is implemented.
3116 if (IsVarArg && IsWin64)
3117 return false;
3118
3119 // Don't know about inalloca yet.
3120 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3121 return false;
3122
Manman Ren57518142016-04-11 21:08:06 +00003123 for (auto Flag : CLI.OutFlags)
3124 if (Flag.isSwiftError())
3125 return false;
3126
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003127 SmallVector<MVT, 16> OutVTs;
3128 SmallVector<unsigned, 16> ArgRegs;
3129
3130 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3131 // instruction. This is safe because it is common to all FastISel supported
3132 // calling conventions on x86.
3133 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3134 Value *&Val = OutVals[i];
3135 ISD::ArgFlagsTy Flags = OutFlags[i];
3136 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3137 if (CI->getBitWidth() < 32) {
3138 if (Flags.isSExt())
3139 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3140 else
3141 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3142 }
3143 }
3144
3145 // Passing bools around ends up doing a trunc to i1 and passing it.
3146 // Codegen this as an argument + "and 1".
3147 MVT VT;
3148 auto *TI = dyn_cast<TruncInst>(Val);
3149 unsigned ResultReg;
3150 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3151 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3152 TI->hasOneUse()) {
3153 Value *PrevVal = TI->getOperand(0);
3154 ResultReg = getRegForValue(PrevVal);
3155
3156 if (!ResultReg)
3157 return false;
3158
3159 if (!isTypeLegal(PrevVal->getType(), VT))
3160 return false;
3161
3162 ResultReg =
3163 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3164 } else {
3165 if (!isTypeLegal(Val->getType(), VT))
3166 return false;
3167 ResultReg = getRegForValue(Val);
3168 }
3169
3170 if (!ResultReg)
3171 return false;
3172
3173 ArgRegs.push_back(ResultReg);
3174 OutVTs.push_back(VT);
3175 }
3176
3177 // Analyze operands of the call, assigning locations to each operand.
3178 SmallVector<CCValAssign, 16> ArgLocs;
3179 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3180
3181 // Allocate shadow area for Win64
3182 if (IsWin64)
3183 CCInfo.AllocateStack(32, 8);
3184
3185 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3186
3187 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00003188 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003189
3190 // Issue CALLSEQ_START
3191 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3192 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00003193 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003194
3195 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00003196 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003197 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3198 CCValAssign const &VA = ArgLocs[i];
3199 const Value *ArgVal = OutVals[VA.getValNo()];
3200 MVT ArgVT = OutVTs[VA.getValNo()];
3201
3202 if (ArgVT == MVT::x86mmx)
3203 return false;
3204
3205 unsigned ArgReg = ArgRegs[VA.getValNo()];
3206
3207 // Promote the value if needed.
3208 switch (VA.getLocInfo()) {
3209 case CCValAssign::Full: break;
3210 case CCValAssign::SExt: {
3211 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3212 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003213
3214 if (ArgVT.SimpleTy == MVT::i1)
3215 return false;
3216
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003217 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3218 ArgVT, ArgReg);
3219 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3220 ArgVT = VA.getLocVT();
3221 break;
3222 }
3223 case CCValAssign::ZExt: {
3224 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3225 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003226
3227 // Handle zero-extension from i1 to i8, which is common.
3228 if (ArgVT.SimpleTy == MVT::i1) {
3229 // Set the high bits to zero.
3230 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3231 ArgVT = MVT::i8;
3232
3233 if (ArgReg == 0)
3234 return false;
3235 }
3236
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003237 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3238 ArgVT, ArgReg);
3239 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3240 ArgVT = VA.getLocVT();
3241 break;
3242 }
3243 case CCValAssign::AExt: {
3244 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3245 "Unexpected extend");
3246 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3247 ArgVT, ArgReg);
3248 if (!Emitted)
3249 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3250 ArgVT, ArgReg);
3251 if (!Emitted)
3252 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3253 ArgVT, ArgReg);
3254
3255 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3256 ArgVT = VA.getLocVT();
3257 break;
3258 }
3259 case CCValAssign::BCvt: {
3260 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3261 /*TODO: Kill=*/false);
3262 assert(ArgReg && "Failed to emit a bitcast!");
3263 ArgVT = VA.getLocVT();
3264 break;
3265 }
3266 case CCValAssign::VExt:
3267 // VExt has not been implemented, so this should be impossible to reach
3268 // for now. However, fallback to Selection DAG isel once implemented.
3269 return false;
3270 case CCValAssign::AExtUpper:
3271 case CCValAssign::SExtUpper:
3272 case CCValAssign::ZExtUpper:
3273 case CCValAssign::FPExt:
3274 llvm_unreachable("Unexpected loc info!");
3275 case CCValAssign::Indirect:
3276 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3277 // support this.
3278 return false;
3279 }
3280
3281 if (VA.isRegLoc()) {
3282 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3283 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3284 OutRegs.push_back(VA.getLocReg());
3285 } else {
3286 assert(VA.isMemLoc());
3287
3288 // Don't emit stores for undef values.
3289 if (isa<UndefValue>(ArgVal))
3290 continue;
3291
3292 unsigned LocMemOffset = VA.getLocMemOffset();
3293 X86AddressMode AM;
3294 AM.Base.Reg = RegInfo->getStackRegister();
3295 AM.Disp = LocMemOffset;
3296 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3297 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3298 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003299 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3300 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003301 if (Flags.isByVal()) {
3302 X86AddressMode SrcAM;
3303 SrcAM.Base.Reg = ArgReg;
3304 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3305 return false;
3306 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3307 // If this is a really simple value, emit this with the Value* version
3308 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3309 // as it can cause us to reevaluate the argument.
3310 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3311 return false;
3312 } else {
3313 bool ValIsKill = hasTrivialKill(ArgVal);
3314 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3315 return false;
3316 }
3317 }
3318 }
3319
3320 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3321 // GOT pointer.
3322 if (Subtarget->isPICStyleGOT()) {
3323 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3324 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3325 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3326 }
3327
3328 if (Is64Bit && IsVarArg && !IsWin64) {
3329 // From AMD64 ABI document:
3330 // For calls that may call functions that use varargs or stdargs
3331 // (prototype-less calls or calls to functions containing ellipsis (...) in
3332 // the declaration) %al is used as hidden argument to specify the number
3333 // of SSE registers used. The contents of %al do not need to match exactly
3334 // the number of registers, but must be an ubound on the number of SSE
3335 // registers used and is in the range 0 - 8 inclusive.
3336
3337 // Count the number of XMM registers allocated.
3338 static const MCPhysReg XMMArgRegs[] = {
3339 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3340 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3341 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003342 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003343 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3344 && "SSE registers cannot be used when SSE is disabled");
3345 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3346 X86::AL).addImm(NumXMMRegs);
3347 }
3348
3349 // Materialize callee address in a register. FIXME: GV address can be
3350 // handled with a CALLpcrel32 instead.
3351 X86AddressMode CalleeAM;
3352 if (!X86SelectCallAddress(Callee, CalleeAM))
3353 return false;
3354
3355 unsigned CalleeOp = 0;
3356 const GlobalValue *GV = nullptr;
3357 if (CalleeAM.GV != nullptr) {
3358 GV = CalleeAM.GV;
3359 } else if (CalleeAM.Base.Reg != 0) {
3360 CalleeOp = CalleeAM.Base.Reg;
3361 } else
3362 return false;
3363
3364 // Issue the call.
3365 MachineInstrBuilder MIB;
3366 if (CalleeOp) {
3367 // Register-indirect call.
3368 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3369 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3370 .addReg(CalleeOp);
3371 } else {
3372 // Direct call.
3373 assert(GV && "Not a direct call");
3374 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3375
3376 // See if we need any target-specific flags on the GV operand.
Rafael Espindola46107b92016-05-19 18:49:29 +00003377 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
Asaf Badouh89406d12016-04-20 08:32:57 +00003378 // Ignore NonLazyBind attribute in FastISel
3379 if (OpFlags == X86II::MO_GOTPCREL)
3380 OpFlags = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003381
3382 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003383 if (Symbol)
3384 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003385 else
3386 MIB.addGlobalAddress(GV, 0, OpFlags);
3387 }
3388
3389 // Add a register mask operand representing the call-preserved registers.
3390 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003391 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003392
3393 // Add an implicit use GOT pointer in EBX.
3394 if (Subtarget->isPICStyleGOT())
3395 MIB.addReg(X86::EBX, RegState::Implicit);
3396
3397 if (Is64Bit && IsVarArg && !IsWin64)
3398 MIB.addReg(X86::AL, RegState::Implicit);
3399
3400 // Add implicit physical register uses to the call.
3401 for (auto Reg : OutRegs)
3402 MIB.addReg(Reg, RegState::Implicit);
3403
3404 // Issue CALLSEQ_END
3405 unsigned NumBytesForCalleeToPop =
Nico Weberaf7e8462016-07-14 01:52:51 +00003406 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3407 TM.Options.GuaranteedTailCallOpt)
3408 ? NumBytes // Callee pops everything.
3409 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003410 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3411 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3412 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3413
3414 // Now handle call return values.
3415 SmallVector<CCValAssign, 16> RVLocs;
3416 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3417 CLI.RetTy->getContext());
3418 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3419
3420 // Copy all of the result registers out of their specified physreg.
3421 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3422 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3423 CCValAssign &VA = RVLocs[i];
3424 EVT CopyVT = VA.getValVT();
3425 unsigned CopyReg = ResultReg + i;
3426
3427 // If this is x86-64, and we disabled SSE, we can't return FP values
3428 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3429 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3430 report_fatal_error("SSE register return with SSE disabled");
3431 }
3432
3433 // If we prefer to use the value in xmm registers, copy it out as f80 and
3434 // use a truncate to move it from fp stack reg to xmm reg.
3435 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3436 isScalarFPTypeInSSEReg(VA.getValVT())) {
3437 CopyVT = MVT::f80;
3438 CopyReg = createResultReg(&X86::RFP80RegClass);
3439 }
3440
3441 // Copy out the result.
3442 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3443 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3444 InRegs.push_back(VA.getLocReg());
3445
3446 // Round the f80 to the right size, which also moves it to the appropriate
3447 // xmm register. This is accomplished by storing the f80 value in memory
3448 // and then loading it back.
3449 if (CopyVT != VA.getValVT()) {
3450 EVT ResVT = VA.getValVT();
3451 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3452 unsigned MemSize = ResVT.getSizeInBits()/8;
3453 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3454 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3455 TII.get(Opc)), FI)
3456 .addReg(CopyReg);
3457 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3458 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3459 TII.get(Opc), ResultReg + i), FI);
3460 }
3461 }
3462
3463 CLI.ResultReg = ResultReg;
3464 CLI.NumResultRegs = RVLocs.size();
3465 CLI.Call = MIB;
3466
3467 return true;
3468}
3469
3470bool
3471X86FastISel::fastSelectInstruction(const Instruction *I) {
3472 switch (I->getOpcode()) {
3473 default: break;
3474 case Instruction::Load:
3475 return X86SelectLoad(I);
3476 case Instruction::Store:
3477 return X86SelectStore(I);
3478 case Instruction::Ret:
3479 return X86SelectRet(I);
3480 case Instruction::ICmp:
3481 case Instruction::FCmp:
3482 return X86SelectCmp(I);
3483 case Instruction::ZExt:
3484 return X86SelectZExt(I);
3485 case Instruction::Br:
3486 return X86SelectBranch(I);
3487 case Instruction::LShr:
3488 case Instruction::AShr:
3489 case Instruction::Shl:
3490 return X86SelectShift(I);
3491 case Instruction::SDiv:
3492 case Instruction::UDiv:
3493 case Instruction::SRem:
3494 case Instruction::URem:
3495 return X86SelectDivRem(I);
3496 case Instruction::Select:
3497 return X86SelectSelect(I);
3498 case Instruction::Trunc:
3499 return X86SelectTrunc(I);
3500 case Instruction::FPExt:
3501 return X86SelectFPExt(I);
3502 case Instruction::FPTrunc:
3503 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003504 case Instruction::SIToFP:
3505 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003506 case Instruction::IntToPtr: // Deliberate fall-through.
3507 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003508 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3509 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003510 if (DstVT.bitsGT(SrcVT))
3511 return X86SelectZExt(I);
3512 if (DstVT.bitsLT(SrcVT))
3513 return X86SelectTrunc(I);
3514 unsigned Reg = getRegForValue(I->getOperand(0));
3515 if (Reg == 0) return false;
3516 updateValueMap(I, Reg);
3517 return true;
3518 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003519 case Instruction::BitCast: {
3520 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3521 if (!Subtarget->hasSSE2())
3522 return false;
3523
3524 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3525 EVT DstVT = TLI.getValueType(DL, I->getType());
3526
3527 if (!SrcVT.isSimple() || !DstVT.isSimple())
3528 return false;
3529
3530 if (!SrcVT.is128BitVector() &&
3531 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3532 return false;
3533
3534 unsigned Reg = getRegForValue(I->getOperand(0));
3535 if (Reg == 0)
3536 return false;
3537
3538 // No instruction is needed for conversion. Reuse the register used by
3539 // the fist operand.
3540 updateValueMap(I, Reg);
3541 return true;
3542 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003543 }
3544
3545 return false;
3546}
3547
3548unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3549 if (VT > MVT::i64)
3550 return 0;
3551
3552 uint64_t Imm = CI->getZExtValue();
3553 if (Imm == 0) {
3554 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3555 switch (VT.SimpleTy) {
3556 default: llvm_unreachable("Unexpected value type");
3557 case MVT::i1:
3558 case MVT::i8:
3559 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3560 X86::sub_8bit);
3561 case MVT::i16:
3562 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3563 X86::sub_16bit);
3564 case MVT::i32:
3565 return SrcReg;
3566 case MVT::i64: {
3567 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3568 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3569 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3570 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3571 return ResultReg;
3572 }
3573 }
3574 }
3575
3576 unsigned Opc = 0;
3577 switch (VT.SimpleTy) {
3578 default: llvm_unreachable("Unexpected value type");
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003579 case MVT::i1: VT = MVT::i8; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003580 case MVT::i8: Opc = X86::MOV8ri; break;
3581 case MVT::i16: Opc = X86::MOV16ri; break;
3582 case MVT::i32: Opc = X86::MOV32ri; break;
3583 case MVT::i64: {
3584 if (isUInt<32>(Imm))
3585 Opc = X86::MOV32ri;
3586 else if (isInt<32>(Imm))
3587 Opc = X86::MOV64ri32;
3588 else
3589 Opc = X86::MOV64ri;
3590 break;
3591 }
3592 }
3593 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3594 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3595 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3596 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3597 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3598 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3599 return ResultReg;
3600 }
3601 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3602}
3603
3604unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3605 if (CFP->isNullValue())
3606 return fastMaterializeFloatZero(CFP);
3607
3608 // Can't handle alternate code models yet.
3609 CodeModel::Model CM = TM.getCodeModel();
3610 if (CM != CodeModel::Small && CM != CodeModel::Large)
3611 return 0;
3612
3613 // Get opcode and regclass of the output for the given load instruction.
3614 unsigned Opc = 0;
3615 const TargetRegisterClass *RC = nullptr;
3616 switch (VT.SimpleTy) {
3617 default: return 0;
3618 case MVT::f32:
3619 if (X86ScalarSSEf32) {
3620 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3621 RC = &X86::FR32RegClass;
3622 } else {
3623 Opc = X86::LD_Fp32m;
3624 RC = &X86::RFP32RegClass;
3625 }
3626 break;
3627 case MVT::f64:
3628 if (X86ScalarSSEf64) {
3629 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3630 RC = &X86::FR64RegClass;
3631 } else {
3632 Opc = X86::LD_Fp64m;
3633 RC = &X86::RFP64RegClass;
3634 }
3635 break;
3636 case MVT::f80:
3637 // No f80 support yet.
3638 return 0;
3639 }
3640
3641 // MachineConstantPool wants an explicit alignment.
3642 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3643 if (Align == 0) {
3644 // Alignment of vector types. FIXME!
3645 Align = DL.getTypeAllocSize(CFP->getType());
3646 }
3647
3648 // x86-32 PIC requires a PIC base register for constant pools.
3649 unsigned PICBase = 0;
Rafael Espindolac7e98132016-05-20 12:20:10 +00003650 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3651 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003652 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003653 else if (OpFlag == X86II::MO_GOTOFF)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003654 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003655 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003656 PICBase = X86::RIP;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003657
3658 // Create the load from the constant pool.
3659 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3660 unsigned ResultReg = createResultReg(RC);
3661
3662 if (CM == CodeModel::Large) {
3663 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3665 AddrReg)
3666 .addConstantPoolIndex(CPI, 0, OpFlag);
3667 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3668 TII.get(Opc), ResultReg);
3669 addDirectMem(MIB, AddrReg);
3670 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003671 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3672 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003673 MIB->addMemOperand(*FuncInfo.MF, MMO);
3674 return ResultReg;
3675 }
3676
3677 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3678 TII.get(Opc), ResultReg),
3679 CPI, PICBase, OpFlag);
3680 return ResultReg;
3681}
3682
3683unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3684 // Can't handle alternate code models yet.
3685 if (TM.getCodeModel() != CodeModel::Small)
3686 return 0;
3687
3688 // Materialize addresses with LEA/MOV instructions.
3689 X86AddressMode AM;
3690 if (X86SelectAddress(GV, AM)) {
3691 // If the expression is just a basereg, then we're done, otherwise we need
3692 // to emit an LEA.
3693 if (AM.BaseType == X86AddressMode::RegBase &&
3694 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3695 return AM.Base.Reg;
3696
3697 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3698 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003699 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003700 // The displacement code could be more than 32 bits away so we need to use
3701 // an instruction with a 64 bit immediate
3702 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3703 ResultReg)
3704 .addGlobalAddress(GV);
3705 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003706 unsigned Opc =
3707 TLI.getPointerTy(DL) == MVT::i32
3708 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3709 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003710 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3711 TII.get(Opc), ResultReg), AM);
3712 }
3713 return ResultReg;
3714 }
3715 return 0;
3716}
3717
3718unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003719 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003720
3721 // Only handle simple types.
3722 if (!CEVT.isSimple())
3723 return 0;
3724 MVT VT = CEVT.getSimpleVT();
3725
3726 if (const auto *CI = dyn_cast<ConstantInt>(C))
3727 return X86MaterializeInt(CI, VT);
3728 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3729 return X86MaterializeFP(CFP, VT);
3730 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3731 return X86MaterializeGV(GV, VT);
3732
3733 return 0;
3734}
3735
3736unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3737 // Fail on dynamic allocas. At this point, getRegForValue has already
3738 // checked its CSE maps, so if we're here trying to handle a dynamic
3739 // alloca, we're not going to succeed. X86SelectAddress has a
3740 // check for dynamic allocas, because it's called directly from
3741 // various places, but targetMaterializeAlloca also needs a check
3742 // in order to avoid recursion between getRegForValue,
3743 // X86SelectAddrss, and targetMaterializeAlloca.
3744 if (!FuncInfo.StaticAllocaMap.count(C))
3745 return 0;
3746 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3747
3748 X86AddressMode AM;
3749 if (!X86SelectAddress(C, AM))
3750 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003751 unsigned Opc =
3752 TLI.getPointerTy(DL) == MVT::i32
3753 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3754 : X86::LEA64r;
3755 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003756 unsigned ResultReg = createResultReg(RC);
3757 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3758 TII.get(Opc), ResultReg), AM);
3759 return ResultReg;
3760}
3761
3762unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3763 MVT VT;
3764 if (!isTypeLegal(CF->getType(), VT))
3765 return 0;
3766
3767 // Get opcode and regclass for the given zero.
3768 unsigned Opc = 0;
3769 const TargetRegisterClass *RC = nullptr;
3770 switch (VT.SimpleTy) {
3771 default: return 0;
3772 case MVT::f32:
3773 if (X86ScalarSSEf32) {
3774 Opc = X86::FsFLD0SS;
3775 RC = &X86::FR32RegClass;
3776 } else {
3777 Opc = X86::LD_Fp032;
3778 RC = &X86::RFP32RegClass;
3779 }
3780 break;
3781 case MVT::f64:
3782 if (X86ScalarSSEf64) {
3783 Opc = X86::FsFLD0SD;
3784 RC = &X86::FR64RegClass;
3785 } else {
3786 Opc = X86::LD_Fp064;
3787 RC = &X86::RFP64RegClass;
3788 }
3789 break;
3790 case MVT::f80:
3791 // No f80 support yet.
3792 return 0;
3793 }
3794
3795 unsigned ResultReg = createResultReg(RC);
3796 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3797 return ResultReg;
3798}
3799
3800
3801bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3802 const LoadInst *LI) {
3803 const Value *Ptr = LI->getPointerOperand();
3804 X86AddressMode AM;
3805 if (!X86SelectAddress(Ptr, AM))
3806 return false;
3807
3808 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3809
3810 unsigned Size = DL.getTypeAllocSize(LI->getType());
3811 unsigned Alignment = LI->getAlignment();
3812
3813 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3814 Alignment = DL.getABITypeAlignment(LI->getType());
3815
3816 SmallVector<MachineOperand, 8> AddrOps;
3817 AM.getFullAddress(AddrOps);
3818
Keno Fischere70b31f2015-06-08 20:09:58 +00003819 MachineInstr *Result = XII.foldMemoryOperandImpl(
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00003820 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
Keno Fischere70b31f2015-06-08 20:09:58 +00003821 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003822 if (!Result)
3823 return false;
3824
Pete Cooperd31583d2015-05-06 21:37:19 +00003825 // The index register could be in the wrong register class. Unfortunately,
3826 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3827 // to just look at OpNo + the offset to the index reg. We actually need to
3828 // scan the instruction to find the index reg and see if its the correct reg
3829 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003830 unsigned OperandNo = 0;
3831 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3832 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3833 MachineOperand &MO = *I;
3834 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003835 continue;
3836 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003837 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003838 MO.getReg(), OperandNo);
3839 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003840 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003841 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003842 }
3843
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003844 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003845 MI->eraseFromParent();
3846 return true;
3847}
3848
3849
3850namespace llvm {
3851 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3852 const TargetLibraryInfo *libInfo) {
3853 return new X86FastISel(funcInfo, libInfo);
3854 }
3855}