blob: f30331f0a1126b780f1d401f6c9ce0e1f73ae112 [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();
354 bool IsNonTemporal = MMO && MMO->isNonTemporal();
355
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000356 // Get opcode and regclass of the output for the given load instruction.
357 unsigned Opc = 0;
358 const TargetRegisterClass *RC = nullptr;
359 switch (VT.getSimpleVT().SimpleTy) {
360 default: return false;
361 case MVT::i1:
362 case MVT::i8:
363 Opc = X86::MOV8rm;
364 RC = &X86::GR8RegClass;
365 break;
366 case MVT::i16:
367 Opc = X86::MOV16rm;
368 RC = &X86::GR16RegClass;
369 break;
370 case MVT::i32:
371 Opc = X86::MOV32rm;
372 RC = &X86::GR32RegClass;
373 break;
374 case MVT::i64:
375 // Must be in x86-64 mode.
376 Opc = X86::MOV64rm;
377 RC = &X86::GR64RegClass;
378 break;
379 case MVT::f32:
380 if (X86ScalarSSEf32) {
Craig Topperca9c0802016-06-02 04:19:45 +0000381 Opc = HasAVX ? X86::VMOVSSrm : X86::MOVSSrm;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000382 RC = &X86::FR32RegClass;
383 } else {
384 Opc = X86::LD_Fp32m;
385 RC = &X86::RFP32RegClass;
386 }
387 break;
388 case MVT::f64:
389 if (X86ScalarSSEf64) {
Craig Topperca9c0802016-06-02 04:19:45 +0000390 Opc = HasAVX ? X86::VMOVSDrm : X86::MOVSDrm;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000391 RC = &X86::FR64RegClass;
392 } else {
393 Opc = X86::LD_Fp64m;
394 RC = &X86::RFP64RegClass;
395 }
396 break;
397 case MVT::f80:
398 // No f80 support yet.
399 return false;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000400 case MVT::v4f32:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000401 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
402 Opc = HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
403 else if (Alignment >= 16)
Craig Topperca9c0802016-06-02 04:19:45 +0000404 Opc = HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000405 else
Craig Topperca9c0802016-06-02 04:19:45 +0000406 Opc = HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000407 RC = &X86::VR128RegClass;
408 break;
409 case MVT::v2f64:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000410 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
411 Opc = HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
412 else if (Alignment >= 16)
Craig Topperca9c0802016-06-02 04:19:45 +0000413 Opc = HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000414 else
Craig Topperca9c0802016-06-02 04:19:45 +0000415 Opc = HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000416 RC = &X86::VR128RegClass;
417 break;
418 case MVT::v4i32:
419 case MVT::v2i64:
420 case MVT::v8i16:
421 case MVT::v16i8:
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000422 if (IsNonTemporal && Alignment >= 16)
423 Opc = HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
424 else if (Alignment >= 16)
Craig Topperca9c0802016-06-02 04:19:45 +0000425 Opc = HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000426 else
Craig Topperca9c0802016-06-02 04:19:45 +0000427 Opc = HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000428 RC = &X86::VR128RegClass;
429 break;
Craig Topperca9c0802016-06-02 04:19:45 +0000430 case MVT::v8f32:
431 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000432 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
433 Opc = X86::VMOVNTDQAYrm;
434 else
435 Opc = (Alignment >= 32) ? X86::VMOVAPSYrm : X86::VMOVUPSYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000436 RC = &X86::VR256RegClass;
437 break;
438 case MVT::v4f64:
439 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000440 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
441 Opc = X86::VMOVNTDQAYrm;
442 else
443 Opc = (Alignment >= 32) ? X86::VMOVAPDYrm : X86::VMOVUPDYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000444 RC = &X86::VR256RegClass;
445 break;
446 case MVT::v8i32:
447 case MVT::v4i64:
448 case MVT::v16i16:
449 case MVT::v32i8:
450 assert(HasAVX);
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000451 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
452 Opc = X86::VMOVNTDQAYrm;
453 else
454 Opc = (Alignment >= 32) ? X86::VMOVDQAYrm : X86::VMOVDQUYrm;
Craig Topperca9c0802016-06-02 04:19:45 +0000455 RC = &X86::VR256RegClass;
456 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000457 case MVT::v16f32:
458 assert(Subtarget->hasAVX512());
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000459 if (IsNonTemporal && Alignment >= 64)
460 Opc = X86::VMOVNTDQAZrm;
461 else
462 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000463 RC = &X86::VR512RegClass;
464 break;
465 case MVT::v8f64:
466 assert(Subtarget->hasAVX512());
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000467 if (IsNonTemporal && Alignment >= 64)
468 Opc = X86::VMOVNTDQAZrm;
469 else
470 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000471 RC = &X86::VR512RegClass;
472 break;
473 case MVT::v8i64:
474 case MVT::v16i32:
475 case MVT::v32i16:
476 case MVT::v64i8:
477 assert(Subtarget->hasAVX512());
478 // Note: There are a lot more choices based on type with AVX-512, but
479 // there's really no advantage when the load isn't masked.
Simon Pilgrim35c06a02016-06-07 13:47:23 +0000480 if (IsNonTemporal && Alignment >= 64)
481 Opc = X86::VMOVNTDQAZrm;
482 else
483 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
Craig Topper048a08a2016-06-02 04:51:37 +0000484 RC = &X86::VR512RegClass;
485 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000486 }
487
488 ResultReg = createResultReg(RC);
489 MachineInstrBuilder MIB =
490 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
491 addFullAddress(MIB, AM);
492 if (MMO)
493 MIB->addMemOperand(*FuncInfo.MF, MMO);
494 return true;
495}
496
497/// X86FastEmitStore - Emit a machine instruction to store a value Val of
498/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
499/// and a displacement offset, or a GlobalAddress,
500/// i.e. V. Return true if it is possible.
501bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000502 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000503 MachineMemOperand *MMO, bool Aligned) {
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000504 bool HasSSE2 = Subtarget->hasSSE2();
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000505 bool HasSSE4A = Subtarget->hasSSE4A();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000506 bool HasAVX = Subtarget->hasAVX();
507 bool IsNonTemporal = MMO && MMO->isNonTemporal();
508
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000509 // Get opcode and regclass of the output for the given store instruction.
510 unsigned Opc = 0;
511 switch (VT.getSimpleVT().SimpleTy) {
512 case MVT::f80: // No f80 support yet.
513 default: return false;
514 case MVT::i1: {
515 // Mask out all but lowest bit.
516 unsigned AndResult = createResultReg(&X86::GR8RegClass);
517 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
518 TII.get(X86::AND8ri), AndResult)
519 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
520 ValReg = AndResult;
Justin Bognerb03fd122016-08-17 05:10:15 +0000521 LLVM_FALLTHROUGH; // handle i1 as i8.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000522 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000523 case MVT::i8: Opc = X86::MOV8mr; break;
524 case MVT::i16: Opc = X86::MOV16mr; break;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000525 case MVT::i32:
526 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
527 break;
528 case MVT::i64:
529 // Must be in x86-64 mode.
530 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
531 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000532 case MVT::f32:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000533 if (X86ScalarSSEf32) {
534 if (IsNonTemporal && HasSSE4A)
535 Opc = X86::MOVNTSS;
536 else
537 Opc = HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
538 } else
539 Opc = X86::ST_Fp32m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000540 break;
541 case MVT::f64:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000542 if (X86ScalarSSEf32) {
543 if (IsNonTemporal && HasSSE4A)
544 Opc = X86::MOVNTSD;
545 else
546 Opc = HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
547 } else
548 Opc = X86::ST_Fp64m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000549 break;
550 case MVT::v4f32:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000551 if (Aligned) {
552 if (IsNonTemporal)
553 Opc = HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
554 else
555 Opc = HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
556 } else
557 Opc = HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000558 break;
559 case MVT::v2f64:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000560 if (Aligned) {
561 if (IsNonTemporal)
562 Opc = HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
563 else
564 Opc = HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
565 } else
566 Opc = HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000567 break;
568 case MVT::v4i32:
569 case MVT::v2i64:
570 case MVT::v8i16:
571 case MVT::v16i8:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000572 if (Aligned) {
573 if (IsNonTemporal)
574 Opc = HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
575 else
576 Opc = HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
577 } else
Craig Topperca9c0802016-06-02 04:19:45 +0000578 Opc = HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
579 break;
580 case MVT::v8f32:
581 assert(HasAVX);
582 if (Aligned)
583 Opc = IsNonTemporal ? X86::VMOVNTPSYmr : X86::VMOVAPSYmr;
584 else
585 Opc = X86::VMOVUPSYmr;
586 break;
587 case MVT::v4f64:
588 assert(HasAVX);
589 if (Aligned) {
590 Opc = IsNonTemporal ? X86::VMOVNTPDYmr : X86::VMOVAPDYmr;
591 } else
592 Opc = X86::VMOVUPDYmr;
593 break;
594 case MVT::v8i32:
595 case MVT::v4i64:
596 case MVT::v16i16:
597 case MVT::v32i8:
598 assert(HasAVX);
599 if (Aligned)
600 Opc = IsNonTemporal ? X86::VMOVNTDQYmr : X86::VMOVDQAYmr;
601 else
602 Opc = X86::VMOVDQUYmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000603 break;
Craig Topper048a08a2016-06-02 04:51:37 +0000604 case MVT::v16f32:
605 assert(Subtarget->hasAVX512());
606 if (Aligned)
607 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
608 else
609 Opc = X86::VMOVUPSZmr;
610 break;
611 case MVT::v8f64:
612 assert(Subtarget->hasAVX512());
613 if (Aligned) {
614 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
615 } else
616 Opc = X86::VMOVUPDZmr;
617 break;
618 case MVT::v8i64:
619 case MVT::v16i32:
620 case MVT::v32i16:
621 case MVT::v64i8:
622 assert(Subtarget->hasAVX512());
623 // Note: There are a lot more choices based on type with AVX-512, but
624 // there's really no advantage when the store isn't masked.
625 if (Aligned)
626 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
627 else
628 Opc = X86::VMOVDQU64Zmr;
629 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000630 }
631
Quentin Colombetbf200682016-04-27 22:33:42 +0000632 const MCInstrDesc &Desc = TII.get(Opc);
633 // Some of the instructions in the previous switch use FR128 instead
634 // of FR32 for ValReg. Make sure the register we feed the instruction
635 // matches its register class constraints.
636 // Note: This is fine to do a copy from FR32 to FR128, this is the
637 // same registers behind the scene and actually why it did not trigger
638 // any bugs before.
639 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000640 MachineInstrBuilder MIB =
Quentin Colombetbf200682016-04-27 22:33:42 +0000641 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000642 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
643 if (MMO)
644 MIB->addMemOperand(*FuncInfo.MF, MMO);
645
646 return true;
647}
648
649bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000650 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000651 MachineMemOperand *MMO, bool Aligned) {
652 // Handle 'null' like i32/i64 0.
653 if (isa<ConstantPointerNull>(Val))
654 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
655
656 // If this is a store of a simple constant, fold the constant into the store.
657 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
658 unsigned Opc = 0;
659 bool Signed = true;
660 switch (VT.getSimpleVT().SimpleTy) {
661 default: break;
Justin Bognerb03fd122016-08-17 05:10:15 +0000662 case MVT::i1:
663 Signed = false;
664 LLVM_FALLTHROUGH; // Handle as i8.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000665 case MVT::i8: Opc = X86::MOV8mi; break;
666 case MVT::i16: Opc = X86::MOV16mi; break;
667 case MVT::i32: Opc = X86::MOV32mi; break;
668 case MVT::i64:
669 // Must be a 32-bit sign extended value.
670 if (isInt<32>(CI->getSExtValue()))
671 Opc = X86::MOV64mi32;
672 break;
673 }
674
675 if (Opc) {
676 MachineInstrBuilder MIB =
677 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
678 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
679 : CI->getZExtValue());
680 if (MMO)
681 MIB->addMemOperand(*FuncInfo.MF, MMO);
682 return true;
683 }
684 }
685
686 unsigned ValReg = getRegForValue(Val);
687 if (ValReg == 0)
688 return false;
689
690 bool ValKill = hasTrivialKill(Val);
691 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
692}
693
694/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
695/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
696/// ISD::SIGN_EXTEND).
697bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
698 unsigned Src, EVT SrcVT,
699 unsigned &ResultReg) {
700 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
701 Src, /*TODO: Kill=*/false);
702 if (RR == 0)
703 return false;
704
705 ResultReg = RR;
706 return true;
707}
708
709bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
710 // Handle constant address.
711 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
712 // Can't handle alternate code models yet.
713 if (TM.getCodeModel() != CodeModel::Small)
714 return false;
715
716 // Can't handle TLS yet.
717 if (GV->isThreadLocal())
718 return false;
719
720 // RIP-relative addresses can't have additional register operands, so if
721 // we've already folded stuff into the addressing mode, just force the
722 // global value into its own register, which we can use as the basereg.
723 if (!Subtarget->isPICStyleRIPRel() ||
724 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
725 // Okay, we've committed to selecting this global. Set up the address.
726 AM.GV = GV;
727
728 // Allow the subtarget to classify the global.
Rafael Espindolaab03eb02016-05-19 22:07:57 +0000729 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000730
731 // If this reference is relative to the pic base, set it now.
732 if (isGlobalRelativeToPICBase(GVFlags)) {
733 // FIXME: How do we know Base.Reg is free??
734 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
735 }
736
737 // Unless the ABI requires an extra load, return a direct reference to
738 // the global.
739 if (!isGlobalStubReference(GVFlags)) {
740 if (Subtarget->isPICStyleRIPRel()) {
741 // Use rip-relative addressing if we can. Above we verified that the
742 // base and index registers are unused.
743 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
744 AM.Base.Reg = X86::RIP;
745 }
746 AM.GVOpFlags = GVFlags;
747 return true;
748 }
749
750 // Ok, we need to do a load from a stub. If we've already loaded from
751 // this stub, reuse the loaded pointer, otherwise emit the load now.
752 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
753 unsigned LoadReg;
754 if (I != LocalValueMap.end() && I->second != 0) {
755 LoadReg = I->second;
756 } else {
757 // Issue load from stub.
758 unsigned Opc = 0;
759 const TargetRegisterClass *RC = nullptr;
760 X86AddressMode StubAM;
761 StubAM.Base.Reg = AM.Base.Reg;
762 StubAM.GV = GV;
763 StubAM.GVOpFlags = GVFlags;
764
765 // Prepare for inserting code in the local-value area.
766 SavePoint SaveInsertPt = enterLocalValueArea();
767
Mehdi Amini44ede332015-07-09 02:09:04 +0000768 if (TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000769 Opc = X86::MOV64rm;
770 RC = &X86::GR64RegClass;
771
772 if (Subtarget->isPICStyleRIPRel())
773 StubAM.Base.Reg = X86::RIP;
774 } else {
775 Opc = X86::MOV32rm;
776 RC = &X86::GR32RegClass;
777 }
778
779 LoadReg = createResultReg(RC);
780 MachineInstrBuilder LoadMI =
781 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
782 addFullAddress(LoadMI, StubAM);
783
784 // Ok, back to normal mode.
785 leaveLocalValueArea(SaveInsertPt);
786
787 // Prevent loading GV stub multiple times in same MBB.
788 LocalValueMap[V] = LoadReg;
789 }
790
791 // Now construct the final address. Note that the Disp, Scale,
792 // and Index values may already be set here.
793 AM.Base.Reg = LoadReg;
794 AM.GV = nullptr;
795 return true;
796 }
797 }
798
799 // If all else fails, try to materialize the value in a register.
800 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
801 if (AM.Base.Reg == 0) {
802 AM.Base.Reg = getRegForValue(V);
803 return AM.Base.Reg != 0;
804 }
805 if (AM.IndexReg == 0) {
806 assert(AM.Scale == 1 && "Scale with no index!");
807 AM.IndexReg = getRegForValue(V);
808 return AM.IndexReg != 0;
809 }
810 }
811
812 return false;
813}
814
815/// X86SelectAddress - Attempt to fill in an address from the given value.
816///
817bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
818 SmallVector<const Value *, 32> GEPs;
819redo_gep:
820 const User *U = nullptr;
821 unsigned Opcode = Instruction::UserOp1;
822 if (const Instruction *I = dyn_cast<Instruction>(V)) {
823 // Don't walk into other basic blocks; it's possible we haven't
824 // visited them yet, so the instructions may not yet be assigned
825 // virtual registers.
826 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
827 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
828 Opcode = I->getOpcode();
829 U = I;
830 }
831 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
832 Opcode = C->getOpcode();
833 U = C;
834 }
835
836 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
837 if (Ty->getAddressSpace() > 255)
838 // Fast instruction selection doesn't support the special
839 // address spaces.
840 return false;
841
842 switch (Opcode) {
843 default: break;
844 case Instruction::BitCast:
845 // Look past bitcasts.
846 return X86SelectAddress(U->getOperand(0), AM);
847
848 case Instruction::IntToPtr:
849 // Look past no-op inttoptrs.
Mehdi Amini44ede332015-07-09 02:09:04 +0000850 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
851 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000852 return X86SelectAddress(U->getOperand(0), AM);
853 break;
854
855 case Instruction::PtrToInt:
856 // Look past no-op ptrtoints.
Mehdi Amini44ede332015-07-09 02:09:04 +0000857 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000858 return X86SelectAddress(U->getOperand(0), AM);
859 break;
860
861 case Instruction::Alloca: {
862 // Do static allocas.
863 const AllocaInst *A = cast<AllocaInst>(V);
864 DenseMap<const AllocaInst *, int>::iterator SI =
865 FuncInfo.StaticAllocaMap.find(A);
866 if (SI != FuncInfo.StaticAllocaMap.end()) {
867 AM.BaseType = X86AddressMode::FrameIndexBase;
868 AM.Base.FrameIndex = SI->second;
869 return true;
870 }
871 break;
872 }
873
874 case Instruction::Add: {
875 // Adds of constants are common and easy enough.
876 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
877 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
878 // They have to fit in the 32-bit signed displacement field though.
879 if (isInt<32>(Disp)) {
880 AM.Disp = (uint32_t)Disp;
881 return X86SelectAddress(U->getOperand(0), AM);
882 }
883 }
884 break;
885 }
886
887 case Instruction::GetElementPtr: {
888 X86AddressMode SavedAM = AM;
889
890 // Pattern-match simple GEPs.
891 uint64_t Disp = (int32_t)AM.Disp;
892 unsigned IndexReg = AM.IndexReg;
893 unsigned Scale = AM.Scale;
894 gep_type_iterator GTI = gep_type_begin(U);
895 // Iterate through the indices, folding what we can. Constants can be
896 // folded, and one dynamic index can be handled, if the scale is supported.
897 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
898 i != e; ++i, ++GTI) {
899 const Value *Op = *i;
900 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
901 const StructLayout *SL = DL.getStructLayout(STy);
902 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
903 continue;
904 }
905
906 // A array/variable index is always of the form i*S where S is the
907 // constant scale size. See if we can push the scale into immediates.
908 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
909 for (;;) {
910 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
911 // Constant-offset addressing.
912 Disp += CI->getSExtValue() * S;
913 break;
914 }
915 if (canFoldAddIntoGEP(U, Op)) {
916 // A compatible add with a constant operand. Fold the constant.
917 ConstantInt *CI =
918 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
919 Disp += CI->getSExtValue() * S;
920 // Iterate on the other operand.
921 Op = cast<AddOperator>(Op)->getOperand(0);
922 continue;
923 }
924 if (IndexReg == 0 &&
925 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
926 (S == 1 || S == 2 || S == 4 || S == 8)) {
927 // Scaled-index addressing.
928 Scale = S;
929 IndexReg = getRegForGEPIndex(Op).first;
930 if (IndexReg == 0)
931 return false;
932 break;
933 }
934 // Unsupported.
935 goto unsupported_gep;
936 }
937 }
938
939 // Check for displacement overflow.
940 if (!isInt<32>(Disp))
941 break;
942
943 AM.IndexReg = IndexReg;
944 AM.Scale = Scale;
945 AM.Disp = (uint32_t)Disp;
946 GEPs.push_back(V);
947
948 if (const GetElementPtrInst *GEP =
949 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
950 // Ok, the GEP indices were covered by constant-offset and scaled-index
951 // addressing. Update the address state and move on to examining the base.
952 V = GEP;
953 goto redo_gep;
954 } else if (X86SelectAddress(U->getOperand(0), AM)) {
955 return true;
956 }
957
958 // If we couldn't merge the gep value into this addr mode, revert back to
959 // our address and just match the value instead of completely failing.
960 AM = SavedAM;
961
David Majnemerd7708772016-06-24 04:05:21 +0000962 for (const Value *I : reverse(GEPs))
963 if (handleConstantAddresses(I, AM))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000964 return true;
965
966 return false;
967 unsupported_gep:
968 // Ok, the GEP indices weren't all covered.
969 break;
970 }
971 }
972
973 return handleConstantAddresses(V, AM);
974}
975
976/// X86SelectCallAddress - Attempt to fill in an address from the given value.
977///
978bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
979 const User *U = nullptr;
980 unsigned Opcode = Instruction::UserOp1;
981 const Instruction *I = dyn_cast<Instruction>(V);
982 // Record if the value is defined in the same basic block.
983 //
984 // This information is crucial to know whether or not folding an
985 // operand is valid.
986 // Indeed, FastISel generates or reuses a virtual register for all
987 // operands of all instructions it selects. Obviously, the definition and
988 // its uses must use the same virtual register otherwise the produced
989 // code is incorrect.
990 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
991 // registers for values that are alive across basic blocks. This ensures
992 // that the values are consistently set between across basic block, even
993 // if different instruction selection mechanisms are used (e.g., a mix of
994 // SDISel and FastISel).
995 // For values local to a basic block, the instruction selection process
996 // generates these virtual registers with whatever method is appropriate
997 // for its needs. In particular, FastISel and SDISel do not share the way
998 // local virtual registers are set.
999 // Therefore, this is impossible (or at least unsafe) to share values
1000 // between basic blocks unless they use the same instruction selection
1001 // method, which is not guarantee for X86.
1002 // Moreover, things like hasOneUse could not be used accurately, if we
1003 // allow to reference values across basic blocks whereas they are not
1004 // alive across basic blocks initially.
1005 bool InMBB = true;
1006 if (I) {
1007 Opcode = I->getOpcode();
1008 U = I;
1009 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1010 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1011 Opcode = C->getOpcode();
1012 U = C;
1013 }
1014
1015 switch (Opcode) {
1016 default: break;
1017 case Instruction::BitCast:
1018 // Look past bitcasts if its operand is in the same BB.
1019 if (InMBB)
1020 return X86SelectCallAddress(U->getOperand(0), AM);
1021 break;
1022
1023 case Instruction::IntToPtr:
1024 // Look past no-op inttoptrs if its operand is in the same BB.
1025 if (InMBB &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001026 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1027 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001028 return X86SelectCallAddress(U->getOperand(0), AM);
1029 break;
1030
1031 case Instruction::PtrToInt:
1032 // Look past no-op ptrtoints if its operand is in the same BB.
Mehdi Amini44ede332015-07-09 02:09:04 +00001033 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001034 return X86SelectCallAddress(U->getOperand(0), AM);
1035 break;
1036 }
1037
1038 // Handle constant address.
1039 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1040 // Can't handle alternate code models yet.
1041 if (TM.getCodeModel() != CodeModel::Small)
1042 return false;
1043
1044 // RIP-relative addresses can't have additional register operands.
1045 if (Subtarget->isPICStyleRIPRel() &&
1046 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1047 return false;
1048
1049 // Can't handle DLL Import.
1050 if (GV->hasDLLImportStorageClass())
1051 return false;
1052
1053 // Can't handle TLS.
1054 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1055 if (GVar->isThreadLocal())
1056 return false;
1057
1058 // Okay, we've committed to selecting this global. Set up the basic address.
1059 AM.GV = GV;
1060
1061 // No ABI requires an extra load for anything other than DLLImport, which
1062 // we rejected above. Return a direct reference to the global.
1063 if (Subtarget->isPICStyleRIPRel()) {
1064 // Use rip-relative addressing if we can. Above we verified that the
1065 // base and index registers are unused.
1066 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1067 AM.Base.Reg = X86::RIP;
Rafael Espindolac7e98132016-05-20 12:20:10 +00001068 } else {
1069 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001070 }
1071
1072 return true;
1073 }
1074
1075 // If all else fails, try to materialize the value in a register.
1076 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1077 if (AM.Base.Reg == 0) {
1078 AM.Base.Reg = getRegForValue(V);
1079 return AM.Base.Reg != 0;
1080 }
1081 if (AM.IndexReg == 0) {
1082 assert(AM.Scale == 1 && "Scale with no index!");
1083 AM.IndexReg = getRegForValue(V);
1084 return AM.IndexReg != 0;
1085 }
1086 }
1087
1088 return false;
1089}
1090
1091
1092/// X86SelectStore - Select and emit code to implement store instructions.
1093bool X86FastISel::X86SelectStore(const Instruction *I) {
1094 // Atomic stores need special handling.
1095 const StoreInst *S = cast<StoreInst>(I);
1096
1097 if (S->isAtomic())
1098 return false;
1099
Manman Ren57518142016-04-11 21:08:06 +00001100 const Value *PtrV = I->getOperand(1);
1101 if (TLI.supportSwiftError()) {
1102 // Swifterror values can come from either a function parameter with
1103 // swifterror attribute or an alloca with swifterror attribute.
1104 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1105 if (Arg->hasSwiftErrorAttr())
1106 return false;
1107 }
1108
1109 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1110 if (Alloca->isSwiftError())
1111 return false;
1112 }
1113 }
1114
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001115 const Value *Val = S->getValueOperand();
1116 const Value *Ptr = S->getPointerOperand();
1117
1118 MVT VT;
1119 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1120 return false;
1121
1122 unsigned Alignment = S->getAlignment();
1123 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1124 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1125 Alignment = ABIAlignment;
1126 bool Aligned = Alignment >= ABIAlignment;
1127
1128 X86AddressMode AM;
1129 if (!X86SelectAddress(Ptr, AM))
1130 return false;
1131
1132 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1133}
1134
1135/// X86SelectRet - Select and emit code to implement ret instructions.
1136bool X86FastISel::X86SelectRet(const Instruction *I) {
1137 const ReturnInst *Ret = cast<ReturnInst>(I);
1138 const Function &F = *I->getParent()->getParent();
1139 const X86MachineFunctionInfo *X86MFInfo =
1140 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1141
1142 if (!FuncInfo.CanLowerReturn)
1143 return false;
1144
Manman Ren57518142016-04-11 21:08:06 +00001145 if (TLI.supportSwiftError() &&
1146 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1147 return false;
1148
Manman Rened967f32016-01-12 01:08:46 +00001149 if (TLI.supportSplitCSR(FuncInfo.MF))
1150 return false;
1151
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001152 CallingConv::ID CC = F.getCallingConv();
1153 if (CC != CallingConv::C &&
1154 CC != CallingConv::Fast &&
1155 CC != CallingConv::X86_FastCall &&
Nico Weberecdf45b2016-07-14 13:54:26 +00001156 CC != CallingConv::X86_StdCall &&
Nico Weberc7bf6462016-07-12 01:30:35 +00001157 CC != CallingConv::X86_ThisCall &&
Nico Weber8d66df12016-07-15 20:18:37 +00001158 CC != CallingConv::X86_64_SysV &&
1159 CC != CallingConv::X86_64_Win64)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001160 return false;
1161
Nico Weberc7bf6462016-07-12 01:30:35 +00001162 // Don't handle popping bytes if they don't fit the ret's immediate.
1163 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001164 return false;
1165
1166 // fastcc with -tailcallopt is intended to provide a guaranteed
1167 // tail call optimization. Fastisel doesn't know how to do that.
1168 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1169 return false;
1170
1171 // Let SDISel handle vararg functions.
1172 if (F.isVarArg())
1173 return false;
1174
1175 // Build a list of return value registers.
1176 SmallVector<unsigned, 4> RetRegs;
1177
1178 if (Ret->getNumOperands() > 0) {
1179 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001180 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001181
1182 // Analyze operands of the call, assigning locations to each operand.
1183 SmallVector<CCValAssign, 16> ValLocs;
1184 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1185 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1186
1187 const Value *RV = Ret->getOperand(0);
1188 unsigned Reg = getRegForValue(RV);
1189 if (Reg == 0)
1190 return false;
1191
1192 // Only handle a single return value for now.
1193 if (ValLocs.size() != 1)
1194 return false;
1195
1196 CCValAssign &VA = ValLocs[0];
1197
1198 // Don't bother handling odd stuff for now.
1199 if (VA.getLocInfo() != CCValAssign::Full)
1200 return false;
1201 // Only handle register returns for now.
1202 if (!VA.isRegLoc())
1203 return false;
1204
1205 // The calling-convention tables for x87 returns don't tell
1206 // the whole story.
1207 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1208 return false;
1209
1210 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001211 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001212 EVT DstVT = VA.getValVT();
1213 // Special handling for extended integers.
1214 if (SrcVT != DstVT) {
1215 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1216 return false;
1217
1218 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1219 return false;
1220
1221 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1222
1223 if (SrcVT == MVT::i1) {
1224 if (Outs[0].Flags.isSExt())
1225 return false;
1226 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1227 SrcVT = MVT::i8;
1228 }
1229 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1230 ISD::SIGN_EXTEND;
1231 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1232 SrcReg, /*TODO: Kill=*/false);
1233 }
1234
1235 // Make the copy.
1236 unsigned DstReg = VA.getLocReg();
1237 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1238 // Avoid a cross-class copy. This is very unlikely.
1239 if (!SrcRC->contains(DstReg))
1240 return false;
1241 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1242 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1243
1244 // Add register to return instruction.
1245 RetRegs.push_back(VA.getLocReg());
1246 }
1247
Manman Ren1c3f65a2016-04-26 18:08:06 +00001248 // Swift calling convention does not require we copy the sret argument
1249 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1250
Dimitry Andric227b9282016-01-03 17:22:03 +00001251 // All x86 ABIs require that for returning structs by value we copy
1252 // the sret argument into %rax/%eax (depending on ABI) for the return.
1253 // We saved the argument into a virtual register in the entry block,
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00001254 // so now we copy the value out and into %rax/%eax.
Manman Ren1c3f65a2016-04-26 18:08:06 +00001255 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001256 unsigned Reg = X86MFInfo->getSRetReturnReg();
1257 assert(Reg &&
1258 "SRetReturnReg should have been set in LowerFormalArguments()!");
1259 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1260 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1261 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1262 RetRegs.push_back(RetReg);
1263 }
1264
1265 // Now emit the RET.
Nico Weberc7bf6462016-07-12 01:30:35 +00001266 MachineInstrBuilder MIB;
1267 if (X86MFInfo->getBytesToPopOnReturn()) {
1268 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1269 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1270 .addImm(X86MFInfo->getBytesToPopOnReturn());
1271 } else {
1272 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1273 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1274 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001275 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1276 MIB.addReg(RetRegs[i], RegState::Implicit);
1277 return true;
1278}
1279
1280/// X86SelectLoad - Select and emit code to implement load instructions.
1281///
1282bool X86FastISel::X86SelectLoad(const Instruction *I) {
1283 const LoadInst *LI = cast<LoadInst>(I);
1284
1285 // Atomic loads need special handling.
1286 if (LI->isAtomic())
1287 return false;
1288
Manman Ren57518142016-04-11 21:08:06 +00001289 const Value *SV = I->getOperand(0);
1290 if (TLI.supportSwiftError()) {
1291 // Swifterror values can come from either a function parameter with
1292 // swifterror attribute or an alloca with swifterror attribute.
1293 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1294 if (Arg->hasSwiftErrorAttr())
1295 return false;
1296 }
1297
1298 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1299 if (Alloca->isSwiftError())
1300 return false;
1301 }
1302 }
1303
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001304 MVT VT;
1305 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1306 return false;
1307
1308 const Value *Ptr = LI->getPointerOperand();
1309
1310 X86AddressMode AM;
1311 if (!X86SelectAddress(Ptr, AM))
1312 return false;
1313
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001314 unsigned Alignment = LI->getAlignment();
1315 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1316 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1317 Alignment = ABIAlignment;
1318
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001319 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001320 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1321 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001322 return false;
1323
1324 updateValueMap(I, ResultReg);
1325 return true;
1326}
1327
1328static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1329 bool HasAVX = Subtarget->hasAVX();
1330 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1331 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1332
1333 switch (VT.getSimpleVT().SimpleTy) {
1334 default: return 0;
1335 case MVT::i8: return X86::CMP8rr;
1336 case MVT::i16: return X86::CMP16rr;
1337 case MVT::i32: return X86::CMP32rr;
1338 case MVT::i64: return X86::CMP64rr;
1339 case MVT::f32:
1340 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1341 case MVT::f64:
1342 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1343 }
1344}
1345
Rafael Espindola19141f22015-03-16 14:05:49 +00001346/// If we have a comparison with RHS as the RHS of the comparison, return an
1347/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001348static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001349 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001350 switch (VT.getSimpleVT().SimpleTy) {
1351 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001352 default:
1353 return 0;
1354 case MVT::i8:
1355 return X86::CMP8ri;
1356 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001357 if (isInt<8>(Val))
1358 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001359 return X86::CMP16ri;
1360 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001361 if (isInt<8>(Val))
1362 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001363 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001364 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001365 if (isInt<8>(Val))
1366 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001367 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1368 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001369 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001370 return X86::CMP64ri32;
1371 return 0;
1372 }
1373}
1374
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001375bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1376 const DebugLoc &CurDbgLoc) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001377 unsigned Op0Reg = getRegForValue(Op0);
1378 if (Op0Reg == 0) return false;
1379
1380 // Handle 'null' like i32/i64 0.
1381 if (isa<ConstantPointerNull>(Op1))
1382 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1383
1384 // We have two options: compare with register or immediate. If the RHS of
1385 // the compare is an immediate that we can fold into this compare, use
1386 // CMPri, otherwise use CMPrr.
1387 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1388 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1389 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1390 .addReg(Op0Reg)
1391 .addImm(Op1C->getSExtValue());
1392 return true;
1393 }
1394 }
1395
1396 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1397 if (CompareOpc == 0) return false;
1398
1399 unsigned Op1Reg = getRegForValue(Op1);
1400 if (Op1Reg == 0) return false;
1401 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1402 .addReg(Op0Reg)
1403 .addReg(Op1Reg);
1404
1405 return true;
1406}
1407
1408bool X86FastISel::X86SelectCmp(const Instruction *I) {
1409 const CmpInst *CI = cast<CmpInst>(I);
1410
1411 MVT VT;
1412 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1413 return false;
1414
Elena Demikhovskyad0a56f2016-07-06 14:15:43 +00001415 if (I->getType()->isIntegerTy(1) && Subtarget->hasAVX512())
1416 return false;
1417
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001418 // Try to optimize or fold the cmp.
1419 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1420 unsigned ResultReg = 0;
1421 switch (Predicate) {
1422 default: break;
1423 case CmpInst::FCMP_FALSE: {
1424 ResultReg = createResultReg(&X86::GR32RegClass);
1425 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1426 ResultReg);
1427 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1428 X86::sub_8bit);
1429 if (!ResultReg)
1430 return false;
1431 break;
1432 }
1433 case CmpInst::FCMP_TRUE: {
1434 ResultReg = createResultReg(&X86::GR8RegClass);
1435 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1436 ResultReg).addImm(1);
1437 break;
1438 }
1439 }
1440
1441 if (ResultReg) {
1442 updateValueMap(I, ResultReg);
1443 return true;
1444 }
1445
1446 const Value *LHS = CI->getOperand(0);
1447 const Value *RHS = CI->getOperand(1);
1448
1449 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1450 // We don't have to materialize a zero constant for this case and can just use
1451 // %x again on the RHS.
1452 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1453 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1454 if (RHSC && RHSC->isNullValue())
1455 RHS = LHS;
1456 }
1457
1458 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1459 static unsigned SETFOpcTable[2][3] = {
1460 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1461 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1462 };
1463 unsigned *SETFOpc = nullptr;
1464 switch (Predicate) {
1465 default: break;
1466 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1467 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1468 }
1469
1470 ResultReg = createResultReg(&X86::GR8RegClass);
1471 if (SETFOpc) {
1472 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1473 return false;
1474
1475 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1476 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1477 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1478 FlagReg1);
1479 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1480 FlagReg2);
1481 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1482 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1483 updateValueMap(I, ResultReg);
1484 return true;
1485 }
1486
1487 X86::CondCode CC;
1488 bool SwapArgs;
1489 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1490 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1491 unsigned Opc = X86::getSETFromCond(CC);
1492
1493 if (SwapArgs)
1494 std::swap(LHS, RHS);
1495
1496 // Emit a compare of LHS/RHS.
1497 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1498 return false;
1499
1500 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1501 updateValueMap(I, ResultReg);
1502 return true;
1503}
1504
1505bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001506 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001507 if (!TLI.isTypeLegal(DstVT))
1508 return false;
1509
1510 unsigned ResultReg = getRegForValue(I->getOperand(0));
1511 if (ResultReg == 0)
1512 return false;
1513
1514 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001515 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001516 if (SrcVT.SimpleTy == MVT::i1) {
1517 // Set the high bits to zero.
1518 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1519 SrcVT = MVT::i8;
1520
1521 if (ResultReg == 0)
1522 return false;
1523 }
1524
1525 if (DstVT == MVT::i64) {
1526 // Handle extension to 64-bits via sub-register shenanigans.
1527 unsigned MovInst;
1528
1529 switch (SrcVT.SimpleTy) {
1530 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1531 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1532 case MVT::i32: MovInst = X86::MOV32rr; break;
1533 default: llvm_unreachable("Unexpected zext to i64 source type");
1534 }
1535
1536 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1537 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1538 .addReg(ResultReg);
1539
1540 ResultReg = createResultReg(&X86::GR64RegClass);
1541 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1542 ResultReg)
1543 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1544 } else if (DstVT != MVT::i8) {
1545 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1546 ResultReg, /*Kill=*/true);
1547 if (ResultReg == 0)
1548 return false;
1549 }
1550
1551 updateValueMap(I, ResultReg);
1552 return true;
1553}
1554
1555bool X86FastISel::X86SelectBranch(const Instruction *I) {
1556 // Unconditional branches are selected by tablegen-generated code.
1557 // Handle a conditional branch.
1558 const BranchInst *BI = cast<BranchInst>(I);
1559 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1560 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1561
1562 // Fold the common case of a conditional branch with a comparison
1563 // in the same block (values defined on other blocks may not have
1564 // initialized registers).
1565 X86::CondCode CC;
1566 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1567 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001568 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001569
1570 // Try to optimize or fold the cmp.
1571 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1572 switch (Predicate) {
1573 default: break;
1574 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1575 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1576 }
1577
1578 const Value *CmpLHS = CI->getOperand(0);
1579 const Value *CmpRHS = CI->getOperand(1);
1580
1581 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1582 // 0.0.
1583 // We don't have to materialize a zero constant for this case and can just
1584 // use %x again on the RHS.
1585 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1586 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1587 if (CmpRHSC && CmpRHSC->isNullValue())
1588 CmpRHS = CmpLHS;
1589 }
1590
1591 // Try to take advantage of fallthrough opportunities.
1592 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1593 std::swap(TrueMBB, FalseMBB);
1594 Predicate = CmpInst::getInversePredicate(Predicate);
1595 }
1596
1597 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1598 // code check. Instead two branch instructions are required to check all
1599 // the flags. First we change the predicate to a supported condition code,
1600 // which will be the first branch. Later one we will emit the second
1601 // branch.
1602 bool NeedExtraBranch = false;
1603 switch (Predicate) {
1604 default: break;
1605 case CmpInst::FCMP_OEQ:
Justin Bognerb03fd122016-08-17 05:10:15 +00001606 std::swap(TrueMBB, FalseMBB);
1607 LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001608 case CmpInst::FCMP_UNE:
1609 NeedExtraBranch = true;
1610 Predicate = CmpInst::FCMP_ONE;
1611 break;
1612 }
1613
1614 bool SwapArgs;
1615 unsigned BranchOpc;
1616 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1617 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1618
1619 BranchOpc = X86::GetCondBranchFromCond(CC);
1620 if (SwapArgs)
1621 std::swap(CmpLHS, CmpRHS);
1622
1623 // Emit a compare of the LHS and RHS, setting the flags.
1624 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1625 return false;
1626
1627 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1628 .addMBB(TrueMBB);
1629
1630 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1631 // to UNE above).
1632 if (NeedExtraBranch) {
1633 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1634 .addMBB(TrueMBB);
1635 }
1636
Matthias Braun17af6072015-08-26 01:38:00 +00001637 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001638 return true;
1639 }
1640 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1641 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1642 // typically happen for _Bool and C++ bools.
1643 MVT SourceVT;
1644 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1645 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1646 unsigned TestOpc = 0;
1647 switch (SourceVT.SimpleTy) {
1648 default: break;
1649 case MVT::i8: TestOpc = X86::TEST8ri; break;
1650 case MVT::i16: TestOpc = X86::TEST16ri; break;
1651 case MVT::i32: TestOpc = X86::TEST32ri; break;
1652 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1653 }
1654 if (TestOpc) {
1655 unsigned OpReg = getRegForValue(TI->getOperand(0));
1656 if (OpReg == 0) return false;
1657 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1658 .addReg(OpReg).addImm(1);
1659
1660 unsigned JmpOpc = X86::JNE_1;
1661 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1662 std::swap(TrueMBB, FalseMBB);
1663 JmpOpc = X86::JE_1;
1664 }
1665
1666 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1667 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001668
1669 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001670 return true;
1671 }
1672 }
1673 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1674 // Fake request the condition, otherwise the intrinsic might be completely
1675 // optimized away.
1676 unsigned TmpReg = getRegForValue(BI->getCondition());
1677 if (TmpReg == 0)
1678 return false;
1679
1680 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1681
1682 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1683 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001684 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001685 return true;
1686 }
1687
1688 // Otherwise do a clumsy setcc and re-test it.
1689 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1690 // in an explicit cast, so make sure to handle that correctly.
1691 unsigned OpReg = getRegForValue(BI->getCondition());
1692 if (OpReg == 0) return false;
1693
1694 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1695 .addReg(OpReg).addImm(1);
1696 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1697 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001698 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001699 return true;
1700}
1701
1702bool X86FastISel::X86SelectShift(const Instruction *I) {
1703 unsigned CReg = 0, OpReg = 0;
1704 const TargetRegisterClass *RC = nullptr;
1705 if (I->getType()->isIntegerTy(8)) {
1706 CReg = X86::CL;
1707 RC = &X86::GR8RegClass;
1708 switch (I->getOpcode()) {
1709 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1710 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1711 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1712 default: return false;
1713 }
1714 } else if (I->getType()->isIntegerTy(16)) {
1715 CReg = X86::CX;
1716 RC = &X86::GR16RegClass;
1717 switch (I->getOpcode()) {
1718 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1719 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1720 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1721 default: return false;
1722 }
1723 } else if (I->getType()->isIntegerTy(32)) {
1724 CReg = X86::ECX;
1725 RC = &X86::GR32RegClass;
1726 switch (I->getOpcode()) {
1727 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1728 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1729 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1730 default: return false;
1731 }
1732 } else if (I->getType()->isIntegerTy(64)) {
1733 CReg = X86::RCX;
1734 RC = &X86::GR64RegClass;
1735 switch (I->getOpcode()) {
1736 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1737 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1738 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1739 default: return false;
1740 }
1741 } else {
1742 return false;
1743 }
1744
1745 MVT VT;
1746 if (!isTypeLegal(I->getType(), VT))
1747 return false;
1748
1749 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1750 if (Op0Reg == 0) return false;
1751
1752 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1753 if (Op1Reg == 0) return false;
1754 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1755 CReg).addReg(Op1Reg);
1756
1757 // The shift instruction uses X86::CL. If we defined a super-register
1758 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1759 if (CReg != X86::CL)
1760 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1761 TII.get(TargetOpcode::KILL), X86::CL)
1762 .addReg(CReg, RegState::Kill);
1763
1764 unsigned ResultReg = createResultReg(RC);
1765 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1766 .addReg(Op0Reg);
1767 updateValueMap(I, ResultReg);
1768 return true;
1769}
1770
1771bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1772 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1773 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1774 const static bool S = true; // IsSigned
1775 const static bool U = false; // !IsSigned
1776 const static unsigned Copy = TargetOpcode::COPY;
1777 // For the X86 DIV/IDIV instruction, in most cases the dividend
1778 // (numerator) must be in a specific register pair highreg:lowreg,
1779 // producing the quotient in lowreg and the remainder in highreg.
1780 // For most data types, to set up the instruction, the dividend is
1781 // copied into lowreg, and lowreg is sign-extended or zero-extended
1782 // into highreg. The exception is i8, where the dividend is defined
1783 // as a single register rather than a register pair, and we
1784 // therefore directly sign-extend or zero-extend the dividend into
1785 // lowreg, instead of copying, and ignore the highreg.
1786 const static struct DivRemEntry {
1787 // The following portion depends only on the data type.
1788 const TargetRegisterClass *RC;
1789 unsigned LowInReg; // low part of the register pair
1790 unsigned HighInReg; // high part of the register pair
1791 // The following portion depends on both the data type and the operation.
1792 struct DivRemResult {
1793 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1794 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1795 // highreg, or copying a zero into highreg.
1796 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1797 // zero/sign-extending into lowreg for i8.
1798 unsigned DivRemResultReg; // Register containing the desired result.
1799 bool IsOpSigned; // Whether to use signed or unsigned form.
1800 } ResultTable[NumOps];
1801 } OpTable[NumTypes] = {
1802 { &X86::GR8RegClass, X86::AX, 0, {
1803 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1804 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1805 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1806 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1807 }
1808 }, // i8
1809 { &X86::GR16RegClass, X86::AX, X86::DX, {
1810 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1811 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1812 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1813 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1814 }
1815 }, // i16
1816 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1817 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1818 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1819 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1820 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1821 }
1822 }, // i32
1823 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1824 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1825 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1826 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1827 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1828 }
1829 }, // i64
1830 };
1831
1832 MVT VT;
1833 if (!isTypeLegal(I->getType(), VT))
1834 return false;
1835
1836 unsigned TypeIndex, OpIndex;
1837 switch (VT.SimpleTy) {
1838 default: return false;
1839 case MVT::i8: TypeIndex = 0; break;
1840 case MVT::i16: TypeIndex = 1; break;
1841 case MVT::i32: TypeIndex = 2; break;
1842 case MVT::i64: TypeIndex = 3;
1843 if (!Subtarget->is64Bit())
1844 return false;
1845 break;
1846 }
1847
1848 switch (I->getOpcode()) {
1849 default: llvm_unreachable("Unexpected div/rem opcode");
1850 case Instruction::SDiv: OpIndex = 0; break;
1851 case Instruction::SRem: OpIndex = 1; break;
1852 case Instruction::UDiv: OpIndex = 2; break;
1853 case Instruction::URem: OpIndex = 3; break;
1854 }
1855
1856 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1857 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1858 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1859 if (Op0Reg == 0)
1860 return false;
1861 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1862 if (Op1Reg == 0)
1863 return false;
1864
1865 // Move op0 into low-order input register.
1866 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1867 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1868 // Zero-extend or sign-extend into high-order input register.
1869 if (OpEntry.OpSignExtend) {
1870 if (OpEntry.IsOpSigned)
1871 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1872 TII.get(OpEntry.OpSignExtend));
1873 else {
1874 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1875 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1876 TII.get(X86::MOV32r0), Zero32);
1877
1878 // Copy the zero into the appropriate sub/super/identical physical
1879 // register. Unfortunately the operations needed are not uniform enough
1880 // to fit neatly into the table above.
1881 if (VT.SimpleTy == MVT::i16) {
1882 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1883 TII.get(Copy), TypeEntry.HighInReg)
1884 .addReg(Zero32, 0, X86::sub_16bit);
1885 } else if (VT.SimpleTy == MVT::i32) {
1886 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1887 TII.get(Copy), TypeEntry.HighInReg)
1888 .addReg(Zero32);
1889 } else if (VT.SimpleTy == MVT::i64) {
1890 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1891 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1892 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1893 }
1894 }
1895 }
1896 // Generate the DIV/IDIV instruction.
1897 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1898 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1899 // For i8 remainder, we can't reference AH directly, as we'll end
1900 // up with bogus copies like %R9B = COPY %AH. Reference AX
1901 // instead to prevent AH references in a REX instruction.
1902 //
1903 // The current assumption of the fast register allocator is that isel
1904 // won't generate explicit references to the GPR8_NOREX registers. If
1905 // the allocator and/or the backend get enhanced to be more robust in
1906 // that regard, this can be, and should be, removed.
1907 unsigned ResultReg = 0;
1908 if ((I->getOpcode() == Instruction::SRem ||
1909 I->getOpcode() == Instruction::URem) &&
1910 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1911 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1912 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1913 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1914 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1915
1916 // Shift AX right by 8 bits instead of using AH.
1917 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1918 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1919
1920 // Now reference the 8-bit subreg of the result.
1921 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1922 /*Kill=*/true, X86::sub_8bit);
1923 }
1924 // Copy the result out of the physreg if we haven't already.
1925 if (!ResultReg) {
1926 ResultReg = createResultReg(TypeEntry.RC);
1927 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1928 .addReg(OpEntry.DivRemResultReg);
1929 }
1930 updateValueMap(I, ResultReg);
1931
1932 return true;
1933}
1934
1935/// \brief Emit a conditional move instruction (if the are supported) to lower
1936/// the select.
1937bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1938 // Check if the subtarget supports these instructions.
1939 if (!Subtarget->hasCMov())
1940 return false;
1941
1942 // FIXME: Add support for i8.
1943 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1944 return false;
1945
1946 const Value *Cond = I->getOperand(0);
1947 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1948 bool NeedTest = true;
1949 X86::CondCode CC = X86::COND_NE;
1950
1951 // Optimize conditions coming from a compare if both instructions are in the
1952 // same basic block (values defined in other basic blocks may not have
1953 // initialized registers).
1954 const auto *CI = dyn_cast<CmpInst>(Cond);
1955 if (CI && (CI->getParent() == I->getParent())) {
1956 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1957
1958 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1959 static unsigned SETFOpcTable[2][3] = {
1960 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1961 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1962 };
1963 unsigned *SETFOpc = nullptr;
1964 switch (Predicate) {
1965 default: break;
1966 case CmpInst::FCMP_OEQ:
1967 SETFOpc = &SETFOpcTable[0][0];
1968 Predicate = CmpInst::ICMP_NE;
1969 break;
1970 case CmpInst::FCMP_UNE:
1971 SETFOpc = &SETFOpcTable[1][0];
1972 Predicate = CmpInst::ICMP_NE;
1973 break;
1974 }
1975
1976 bool NeedSwap;
1977 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1978 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1979
1980 const Value *CmpLHS = CI->getOperand(0);
1981 const Value *CmpRHS = CI->getOperand(1);
1982 if (NeedSwap)
1983 std::swap(CmpLHS, CmpRHS);
1984
Mehdi Amini44ede332015-07-09 02:09:04 +00001985 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001986 // Emit a compare of the LHS and RHS, setting the flags.
1987 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1988 return false;
1989
1990 if (SETFOpc) {
1991 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1992 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1993 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1994 FlagReg1);
1995 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1996 FlagReg2);
1997 auto const &II = TII.get(SETFOpc[2]);
1998 if (II.getNumDefs()) {
1999 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
2000 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
2001 .addReg(FlagReg2).addReg(FlagReg1);
2002 } else {
2003 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2004 .addReg(FlagReg2).addReg(FlagReg1);
2005 }
2006 }
2007 NeedTest = false;
2008 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2009 // Fake request the condition, otherwise the intrinsic might be completely
2010 // optimized away.
2011 unsigned TmpReg = getRegForValue(Cond);
2012 if (TmpReg == 0)
2013 return false;
2014
2015 NeedTest = false;
2016 }
2017
2018 if (NeedTest) {
2019 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2020 // garbage. Indeed, only the less significant bit is supposed to be
2021 // accurate. If we read more than the lsb, we may see non-zero values
2022 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2023 // the select. This is achieved by performing TEST against 1.
2024 unsigned CondReg = getRegForValue(Cond);
2025 if (CondReg == 0)
2026 return false;
2027 bool CondIsKill = hasTrivialKill(Cond);
2028
2029 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2030 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2031 }
2032
2033 const Value *LHS = I->getOperand(1);
2034 const Value *RHS = I->getOperand(2);
2035
2036 unsigned RHSReg = getRegForValue(RHS);
2037 bool RHSIsKill = hasTrivialKill(RHS);
2038
2039 unsigned LHSReg = getRegForValue(LHS);
2040 bool LHSIsKill = hasTrivialKill(LHS);
2041
2042 if (!LHSReg || !RHSReg)
2043 return false;
2044
2045 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
2046 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2047 LHSReg, LHSIsKill);
2048 updateValueMap(I, ResultReg);
2049 return true;
2050}
2051
Sanjay Patel302404b2015-03-05 21:46:54 +00002052/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002053///
2054/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2055/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00002056/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002057bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2058 // Optimize conditions coming from a compare if both instructions are in the
2059 // same basic block (values defined in other basic blocks may not have
2060 // initialized registers).
2061 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2062 if (!CI || (CI->getParent() != I->getParent()))
2063 return false;
2064
2065 if (I->getType() != CI->getOperand(0)->getType() ||
2066 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2067 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2068 return false;
2069
2070 const Value *CmpLHS = CI->getOperand(0);
2071 const Value *CmpRHS = CI->getOperand(1);
2072 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2073
2074 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2075 // We don't have to materialize a zero constant for this case and can just use
2076 // %x again on the RHS.
2077 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2078 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2079 if (CmpRHSC && CmpRHSC->isNullValue())
2080 CmpRHS = CmpLHS;
2081 }
2082
2083 unsigned CC;
2084 bool NeedSwap;
2085 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2086 if (CC > 7)
2087 return false;
2088
2089 if (NeedSwap)
2090 std::swap(CmpLHS, CmpRHS);
2091
Sanjay Patel302404b2015-03-05 21:46:54 +00002092 // Choose the SSE instruction sequence based on data type (float or double).
2093 static unsigned OpcTable[2][4] = {
2094 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
2095 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002096 };
2097
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002098 unsigned *Opc = nullptr;
2099 switch (RetVT.SimpleTy) {
2100 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00002101 case MVT::f32: Opc = &OpcTable[0][0]; break;
2102 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002103 }
2104
2105 const Value *LHS = I->getOperand(1);
2106 const Value *RHS = I->getOperand(2);
2107
2108 unsigned LHSReg = getRegForValue(LHS);
2109 bool LHSIsKill = hasTrivialKill(LHS);
2110
2111 unsigned RHSReg = getRegForValue(RHS);
2112 bool RHSIsKill = hasTrivialKill(RHS);
2113
2114 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2115 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2116
2117 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2118 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2119
2120 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2121 return false;
2122
2123 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00002124 unsigned ResultReg;
2125
2126 if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00002127 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
2128 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2129
Sanjay Patel302404b2015-03-05 21:46:54 +00002130 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2131 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2132 // uses XMM0 as the selection register. That may need just as many
2133 // instructions as the AND/ANDN/OR sequence due to register moves, so
2134 // don't bother.
2135 unsigned CmpOpcode =
2136 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2137 unsigned BlendOpcode =
2138 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2139
Matthias Braun818c78d2015-08-31 18:25:11 +00002140 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00002141 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00002142 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2143 LHSReg, LHSIsKill, CmpReg, true);
2144 ResultReg = createResultReg(RC);
2145 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2146 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002147 } else {
2148 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2149 CmpRHSReg, CmpRHSIsKill, CC);
2150 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
2151 LHSReg, LHSIsKill);
2152 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
2153 RHSReg, RHSIsKill);
2154 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
2155 AndReg, /*IsKill=*/true);
2156 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002157 updateValueMap(I, ResultReg);
2158 return true;
2159}
2160
2161bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2162 // These are pseudo CMOV instructions and will be later expanded into control-
2163 // flow.
2164 unsigned Opc;
2165 switch (RetVT.SimpleTy) {
2166 default: return false;
2167 case MVT::i8: Opc = X86::CMOV_GR8; break;
2168 case MVT::i16: Opc = X86::CMOV_GR16; break;
2169 case MVT::i32: Opc = X86::CMOV_GR32; break;
2170 case MVT::f32: Opc = X86::CMOV_FR32; break;
2171 case MVT::f64: Opc = X86::CMOV_FR64; break;
2172 }
2173
2174 const Value *Cond = I->getOperand(0);
2175 X86::CondCode CC = X86::COND_NE;
2176
2177 // Optimize conditions coming from a compare if both instructions are in the
2178 // same basic block (values defined in other basic blocks may not have
2179 // initialized registers).
2180 const auto *CI = dyn_cast<CmpInst>(Cond);
2181 if (CI && (CI->getParent() == I->getParent())) {
2182 bool NeedSwap;
2183 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2184 if (CC > X86::LAST_VALID_COND)
2185 return false;
2186
2187 const Value *CmpLHS = CI->getOperand(0);
2188 const Value *CmpRHS = CI->getOperand(1);
2189
2190 if (NeedSwap)
2191 std::swap(CmpLHS, CmpRHS);
2192
Mehdi Amini44ede332015-07-09 02:09:04 +00002193 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002194 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2195 return false;
2196 } else {
2197 unsigned CondReg = getRegForValue(Cond);
2198 if (CondReg == 0)
2199 return false;
2200 bool CondIsKill = hasTrivialKill(Cond);
2201 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2202 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2203 }
2204
2205 const Value *LHS = I->getOperand(1);
2206 const Value *RHS = I->getOperand(2);
2207
2208 unsigned LHSReg = getRegForValue(LHS);
2209 bool LHSIsKill = hasTrivialKill(LHS);
2210
2211 unsigned RHSReg = getRegForValue(RHS);
2212 bool RHSIsKill = hasTrivialKill(RHS);
2213
2214 if (!LHSReg || !RHSReg)
2215 return false;
2216
2217 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2218
2219 unsigned ResultReg =
2220 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2221 updateValueMap(I, ResultReg);
2222 return true;
2223}
2224
2225bool X86FastISel::X86SelectSelect(const Instruction *I) {
2226 MVT RetVT;
2227 if (!isTypeLegal(I->getType(), RetVT))
2228 return false;
2229
2230 // Check if we can fold the select.
2231 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2232 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2233 const Value *Opnd = nullptr;
2234 switch (Predicate) {
2235 default: break;
2236 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2237 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2238 }
2239 // No need for a select anymore - this is an unconditional move.
2240 if (Opnd) {
2241 unsigned OpReg = getRegForValue(Opnd);
2242 if (OpReg == 0)
2243 return false;
2244 bool OpIsKill = hasTrivialKill(Opnd);
2245 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2246 unsigned ResultReg = createResultReg(RC);
2247 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2248 TII.get(TargetOpcode::COPY), ResultReg)
2249 .addReg(OpReg, getKillRegState(OpIsKill));
2250 updateValueMap(I, ResultReg);
2251 return true;
2252 }
2253 }
2254
2255 // First try to use real conditional move instructions.
2256 if (X86FastEmitCMoveSelect(RetVT, I))
2257 return true;
2258
2259 // Try to use a sequence of SSE instructions to simulate a conditional move.
2260 if (X86FastEmitSSESelect(RetVT, I))
2261 return true;
2262
2263 // Fall-back to pseudo conditional move instructions, which will be later
2264 // converted to control-flow.
2265 if (X86FastEmitPseudoSelect(RetVT, I))
2266 return true;
2267
2268 return false;
2269}
2270
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002271bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002272 // The target-independent selection algorithm in FastISel already knows how
2273 // to select a SINT_TO_FP if the target is SSE but not AVX.
2274 // Early exit if the subtarget doesn't have AVX.
2275 if (!Subtarget->hasAVX())
2276 return false;
2277
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002278 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2279 return false;
2280
2281 // Select integer to float/double conversion.
2282 unsigned OpReg = getRegForValue(I->getOperand(0));
2283 if (OpReg == 0)
2284 return false;
2285
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002286 const TargetRegisterClass *RC = nullptr;
2287 unsigned Opcode;
2288
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002289 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002290 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002291 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002292 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002293 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002294 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002295 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002296 RC = &X86::FR32RegClass;
2297 } else
2298 return false;
2299
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002300 unsigned ImplicitDefReg = createResultReg(RC);
2301 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2302 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2303 unsigned ResultReg =
2304 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002305 updateValueMap(I, ResultReg);
2306 return true;
2307}
2308
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002309// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2310bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2311 unsigned TargetOpc,
2312 const TargetRegisterClass *RC) {
2313 assert((I->getOpcode() == Instruction::FPExt ||
2314 I->getOpcode() == Instruction::FPTrunc) &&
2315 "Instruction must be an FPExt or FPTrunc!");
2316
2317 unsigned OpReg = getRegForValue(I->getOperand(0));
2318 if (OpReg == 0)
2319 return false;
2320
2321 unsigned ResultReg = createResultReg(RC);
2322 MachineInstrBuilder MIB;
2323 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2324 ResultReg);
2325 if (Subtarget->hasAVX())
2326 MIB.addReg(OpReg);
2327 MIB.addReg(OpReg);
2328 updateValueMap(I, ResultReg);
2329 return true;
2330}
2331
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002332bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002333 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2334 I->getOperand(0)->getType()->isFloatTy()) {
2335 // fpext from float to double.
2336 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2337 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002338 }
2339
2340 return false;
2341}
2342
2343bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002344 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2345 I->getOperand(0)->getType()->isDoubleTy()) {
2346 // fptrunc from double to float.
2347 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2348 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002349 }
2350
2351 return false;
2352}
2353
2354bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002355 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2356 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002357
2358 // This code only handles truncation to byte.
2359 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2360 return false;
2361 if (!TLI.isTypeLegal(SrcVT))
2362 return false;
2363
2364 unsigned InputReg = getRegForValue(I->getOperand(0));
2365 if (!InputReg)
2366 // Unhandled operand. Halt "fast" selection and bail.
2367 return false;
2368
2369 if (SrcVT == MVT::i8) {
2370 // Truncate from i8 to i1; no code needed.
2371 updateValueMap(I, InputReg);
2372 return true;
2373 }
2374
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002375 bool KillInputReg = false;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002376 if (!Subtarget->is64Bit()) {
2377 // If we're on x86-32; we can't extract an i8 from a general register.
2378 // First issue a copy to GR16_ABCD or GR32_ABCD.
2379 const TargetRegisterClass *CopyRC =
2380 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2381 unsigned CopyReg = createResultReg(CopyRC);
2382 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2383 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2384 InputReg = CopyReg;
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002385 KillInputReg = true;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002386 }
2387
2388 // Issue an extract_subreg.
2389 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002390 InputReg, KillInputReg,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002391 X86::sub_8bit);
2392 if (!ResultReg)
2393 return false;
2394
2395 updateValueMap(I, ResultReg);
2396 return true;
2397}
2398
2399bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2400 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2401}
2402
2403bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2404 X86AddressMode SrcAM, uint64_t Len) {
2405
2406 // Make sure we don't bloat code by inlining very large memcpy's.
2407 if (!IsMemcpySmall(Len))
2408 return false;
2409
2410 bool i64Legal = Subtarget->is64Bit();
2411
2412 // We don't care about alignment here since we just emit integer accesses.
2413 while (Len) {
2414 MVT VT;
2415 if (Len >= 8 && i64Legal)
2416 VT = MVT::i64;
2417 else if (Len >= 4)
2418 VT = MVT::i32;
2419 else if (Len >= 2)
2420 VT = MVT::i16;
2421 else
2422 VT = MVT::i8;
2423
2424 unsigned Reg;
2425 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2426 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2427 assert(RV && "Failed to emit load or store??");
2428
2429 unsigned Size = VT.getSizeInBits()/8;
2430 Len -= Size;
2431 DestAM.Disp += Size;
2432 SrcAM.Disp += Size;
2433 }
2434
2435 return true;
2436}
2437
2438bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2439 // FIXME: Handle more intrinsics.
2440 switch (II->getIntrinsicID()) {
2441 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002442 case Intrinsic::convert_from_fp16:
2443 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002444 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002445 return false;
2446
2447 const Value *Op = II->getArgOperand(0);
2448 unsigned InputReg = getRegForValue(Op);
2449 if (InputReg == 0)
2450 return false;
2451
2452 // F16C only allows converting from float to half and from half to float.
2453 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2454 if (IsFloatToHalf) {
2455 if (!Op->getType()->isFloatTy())
2456 return false;
2457 } else {
2458 if (!II->getType()->isFloatTy())
2459 return false;
2460 }
2461
2462 unsigned ResultReg = 0;
2463 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2464 if (IsFloatToHalf) {
2465 // 'InputReg' is implicitly promoted from register class FR32 to
2466 // register class VR128 by method 'constrainOperandRegClass' which is
2467 // directly called by 'fastEmitInst_ri'.
2468 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
Ahmed Bougacha68a8efa2016-02-02 01:44:03 +00002469 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2470 // It's consistent with the other FP instructions, which are usually
2471 // controlled by MXCSR.
2472 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
Andrea Di Biagio70351782015-02-20 19:37:14 +00002473
2474 // Move the lower 32-bits of ResultReg to another register of class GR32.
2475 ResultReg = createResultReg(&X86::GR32RegClass);
2476 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2477 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2478 .addReg(InputReg, RegState::Kill);
2479
2480 // The result value is in the lower 16-bits of ResultReg.
2481 unsigned RegIdx = X86::sub_16bit;
2482 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2483 } else {
2484 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2485 // Explicitly sign-extend the input to 32-bit.
2486 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2487 /*Kill=*/false);
2488
2489 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2490 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2491 InputReg, /*Kill=*/true);
2492
2493 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2494
2495 // The result value is in the lower 32-bits of ResultReg.
2496 // Emit an explicit copy from register class VR128 to register class FR32.
2497 ResultReg = createResultReg(&X86::FR32RegClass);
2498 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2499 TII.get(TargetOpcode::COPY), ResultReg)
2500 .addReg(InputReg, RegState::Kill);
2501 }
2502
2503 updateValueMap(II, ResultReg);
2504 return true;
2505 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002506 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002507 MachineFunction *MF = FuncInfo.MF;
2508 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2509 return false;
2510
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002511 Type *RetTy = II->getCalledFunction()->getReturnType();
2512
2513 MVT VT;
2514 if (!isTypeLegal(RetTy, VT))
2515 return false;
2516
2517 unsigned Opc;
2518 const TargetRegisterClass *RC = nullptr;
2519
2520 switch (VT.SimpleTy) {
2521 default: llvm_unreachable("Invalid result type for frameaddress.");
2522 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2523 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2524 }
2525
2526 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2527 // we get the wrong frame register.
Matthias Braun941a7052016-07-28 18:40:00 +00002528 MachineFrameInfo &MFI = MF->getFrameInfo();
2529 MFI.setFrameAddressIsTaken(true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002530
Eric Christophera1c535b2015-02-02 23:03:45 +00002531 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002532 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002533 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2534 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2535 "Invalid Frame Register!");
2536
2537 // Always make a copy of the frame register to to a vreg first, so that we
2538 // never directly reference the frame register (the TwoAddressInstruction-
2539 // Pass doesn't like that).
2540 unsigned SrcReg = createResultReg(RC);
2541 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2542 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2543
2544 // Now recursively load from the frame address.
2545 // movq (%rbp), %rax
2546 // movq (%rax), %rax
2547 // movq (%rax), %rax
2548 // ...
2549 unsigned DestReg;
2550 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2551 while (Depth--) {
2552 DestReg = createResultReg(RC);
2553 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2554 TII.get(Opc), DestReg), SrcReg);
2555 SrcReg = DestReg;
2556 }
2557
2558 updateValueMap(II, SrcReg);
2559 return true;
2560 }
2561 case Intrinsic::memcpy: {
2562 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2563 // Don't handle volatile or variable length memcpys.
2564 if (MCI->isVolatile())
2565 return false;
2566
2567 if (isa<ConstantInt>(MCI->getLength())) {
2568 // Small memcpy's are common enough that we want to do them
2569 // without a call if possible.
2570 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2571 if (IsMemcpySmall(Len)) {
2572 X86AddressMode DestAM, SrcAM;
2573 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2574 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2575 return false;
2576 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2577 return true;
2578 }
2579 }
2580
2581 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2582 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2583 return false;
2584
2585 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2586 return false;
2587
Pete Cooper67cf9a72015-11-19 05:56:52 +00002588 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002589 }
2590 case Intrinsic::memset: {
2591 const MemSetInst *MSI = cast<MemSetInst>(II);
2592
2593 if (MSI->isVolatile())
2594 return false;
2595
2596 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2597 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2598 return false;
2599
2600 if (MSI->getDestAddressSpace() > 255)
2601 return false;
2602
Pete Cooper67cf9a72015-11-19 05:56:52 +00002603 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002604 }
2605 case Intrinsic::stackprotector: {
2606 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002607 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002608
2609 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2610 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2611
2612 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2613
2614 // Grab the frame index.
2615 X86AddressMode AM;
2616 if (!X86SelectAddress(Slot, AM)) return false;
2617 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2618 return true;
2619 }
2620 case Intrinsic::dbg_declare: {
2621 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2622 X86AddressMode AM;
2623 assert(DI->getAddress() && "Null address should be checked earlier!");
2624 if (!X86SelectAddress(DI->getAddress(), AM))
2625 return false;
2626 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2627 // FIXME may need to add RegState::Debug to any registers produced,
2628 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002629 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2630 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002631 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2632 .addImm(0)
2633 .addMetadata(DI->getVariable())
2634 .addMetadata(DI->getExpression());
2635 return true;
2636 }
2637 case Intrinsic::trap: {
2638 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2639 return true;
2640 }
2641 case Intrinsic::sqrt: {
2642 if (!Subtarget->hasSSE1())
2643 return false;
2644
2645 Type *RetTy = II->getCalledFunction()->getReturnType();
2646
2647 MVT VT;
2648 if (!isTypeLegal(RetTy, VT))
2649 return false;
2650
2651 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2652 // is not generated by FastISel yet.
2653 // FIXME: Update this code once tablegen can handle it.
Craig Toppercf65c622016-03-02 04:42:31 +00002654 static const uint16_t SqrtOpc[2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002655 {X86::SQRTSSr, X86::VSQRTSSr},
2656 {X86::SQRTSDr, X86::VSQRTSDr}
2657 };
2658 bool HasAVX = Subtarget->hasAVX();
2659 unsigned Opc;
2660 const TargetRegisterClass *RC;
2661 switch (VT.SimpleTy) {
2662 default: return false;
2663 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2664 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2665 }
2666
2667 const Value *SrcVal = II->getArgOperand(0);
2668 unsigned SrcReg = getRegForValue(SrcVal);
2669
2670 if (SrcReg == 0)
2671 return false;
2672
2673 unsigned ImplicitDefReg = 0;
2674 if (HasAVX) {
2675 ImplicitDefReg = createResultReg(RC);
2676 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2677 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2678 }
2679
2680 unsigned ResultReg = createResultReg(RC);
2681 MachineInstrBuilder MIB;
2682 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2683 ResultReg);
2684
2685 if (ImplicitDefReg)
2686 MIB.addReg(ImplicitDefReg);
2687
2688 MIB.addReg(SrcReg);
2689
2690 updateValueMap(II, ResultReg);
2691 return true;
2692 }
2693 case Intrinsic::sadd_with_overflow:
2694 case Intrinsic::uadd_with_overflow:
2695 case Intrinsic::ssub_with_overflow:
2696 case Intrinsic::usub_with_overflow:
2697 case Intrinsic::smul_with_overflow:
2698 case Intrinsic::umul_with_overflow: {
2699 // This implements the basic lowering of the xalu with overflow intrinsics
2700 // into add/sub/mul followed by either seto or setb.
2701 const Function *Callee = II->getCalledFunction();
2702 auto *Ty = cast<StructType>(Callee->getReturnType());
2703 Type *RetTy = Ty->getTypeAtIndex(0U);
2704 Type *CondTy = Ty->getTypeAtIndex(1);
2705
2706 MVT VT;
2707 if (!isTypeLegal(RetTy, VT))
2708 return false;
2709
2710 if (VT < MVT::i8 || VT > MVT::i64)
2711 return false;
2712
2713 const Value *LHS = II->getArgOperand(0);
2714 const Value *RHS = II->getArgOperand(1);
2715
2716 // Canonicalize immediate to the RHS.
2717 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2718 isCommutativeIntrinsic(II))
2719 std::swap(LHS, RHS);
2720
2721 bool UseIncDec = false;
2722 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2723 UseIncDec = true;
2724
2725 unsigned BaseOpc, CondOpc;
2726 switch (II->getIntrinsicID()) {
2727 default: llvm_unreachable("Unexpected intrinsic!");
2728 case Intrinsic::sadd_with_overflow:
2729 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2730 CondOpc = X86::SETOr;
2731 break;
2732 case Intrinsic::uadd_with_overflow:
2733 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2734 case Intrinsic::ssub_with_overflow:
2735 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2736 CondOpc = X86::SETOr;
2737 break;
2738 case Intrinsic::usub_with_overflow:
2739 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2740 case Intrinsic::smul_with_overflow:
2741 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2742 case Intrinsic::umul_with_overflow:
2743 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2744 }
2745
2746 unsigned LHSReg = getRegForValue(LHS);
2747 if (LHSReg == 0)
2748 return false;
2749 bool LHSIsKill = hasTrivialKill(LHS);
2750
2751 unsigned ResultReg = 0;
2752 // Check if we have an immediate version.
2753 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topper66111882016-06-02 04:19:42 +00002754 static const uint16_t Opc[2][4] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002755 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2756 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2757 };
2758
2759 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2760 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2761 bool IsDec = BaseOpc == X86ISD::DEC;
2762 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2763 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2764 .addReg(LHSReg, getKillRegState(LHSIsKill));
2765 } else
2766 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2767 CI->getZExtValue());
2768 }
2769
2770 unsigned RHSReg;
2771 bool RHSIsKill;
2772 if (!ResultReg) {
2773 RHSReg = getRegForValue(RHS);
2774 if (RHSReg == 0)
2775 return false;
2776 RHSIsKill = hasTrivialKill(RHS);
2777 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2778 RHSIsKill);
2779 }
2780
2781 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2782 // it manually.
2783 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002784 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002785 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002786 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002787 // First copy the first operand into RAX, which is an implicit input to
2788 // the X86::MUL*r instruction.
2789 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2790 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2791 .addReg(LHSReg, getKillRegState(LHSIsKill));
2792 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2793 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2794 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002795 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002796 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2797 if (VT == MVT::i8) {
2798 // Copy the first operand into AL, which is an implicit input to the
2799 // X86::IMUL8r instruction.
2800 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2801 TII.get(TargetOpcode::COPY), X86::AL)
2802 .addReg(LHSReg, getKillRegState(LHSIsKill));
2803 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2804 RHSIsKill);
2805 } else
2806 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2807 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2808 RHSReg, RHSIsKill);
2809 }
2810
2811 if (!ResultReg)
2812 return false;
2813
2814 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2815 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2816 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2817 ResultReg2);
2818
2819 updateValueMap(II, ResultReg, 2);
2820 return true;
2821 }
2822 case Intrinsic::x86_sse_cvttss2si:
2823 case Intrinsic::x86_sse_cvttss2si64:
2824 case Intrinsic::x86_sse2_cvttsd2si:
2825 case Intrinsic::x86_sse2_cvttsd2si64: {
2826 bool IsInputDouble;
2827 switch (II->getIntrinsicID()) {
2828 default: llvm_unreachable("Unexpected intrinsic.");
2829 case Intrinsic::x86_sse_cvttss2si:
2830 case Intrinsic::x86_sse_cvttss2si64:
2831 if (!Subtarget->hasSSE1())
2832 return false;
2833 IsInputDouble = false;
2834 break;
2835 case Intrinsic::x86_sse2_cvttsd2si:
2836 case Intrinsic::x86_sse2_cvttsd2si64:
2837 if (!Subtarget->hasSSE2())
2838 return false;
2839 IsInputDouble = true;
2840 break;
2841 }
2842
2843 Type *RetTy = II->getCalledFunction()->getReturnType();
2844 MVT VT;
2845 if (!isTypeLegal(RetTy, VT))
2846 return false;
2847
Craig Topper66111882016-06-02 04:19:42 +00002848 static const uint16_t CvtOpc[2][2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002849 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2850 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2851 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2852 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2853 };
2854 bool HasAVX = Subtarget->hasAVX();
2855 unsigned Opc;
2856 switch (VT.SimpleTy) {
2857 default: llvm_unreachable("Unexpected result type.");
2858 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2859 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2860 }
2861
2862 // Check if we can fold insertelement instructions into the convert.
2863 const Value *Op = II->getArgOperand(0);
2864 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2865 const Value *Index = IE->getOperand(2);
2866 if (!isa<ConstantInt>(Index))
2867 break;
2868 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2869
2870 if (Idx == 0) {
2871 Op = IE->getOperand(1);
2872 break;
2873 }
2874 Op = IE->getOperand(0);
2875 }
2876
2877 unsigned Reg = getRegForValue(Op);
2878 if (Reg == 0)
2879 return false;
2880
2881 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2882 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2883 .addReg(Reg);
2884
2885 updateValueMap(II, ResultReg);
2886 return true;
2887 }
2888 }
2889}
2890
2891bool X86FastISel::fastLowerArguments() {
2892 if (!FuncInfo.CanLowerReturn)
2893 return false;
2894
2895 const Function *F = FuncInfo.Fn;
2896 if (F->isVarArg())
2897 return false;
2898
2899 CallingConv::ID CC = F->getCallingConv();
2900 if (CC != CallingConv::C)
2901 return false;
2902
2903 if (Subtarget->isCallingConvWin64(CC))
2904 return false;
2905
2906 if (!Subtarget->is64Bit())
2907 return false;
2908
2909 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2910 unsigned GPRCnt = 0;
2911 unsigned FPRCnt = 0;
2912 unsigned Idx = 0;
2913 for (auto const &Arg : F->args()) {
2914 // The first argument is at index 1.
2915 ++Idx;
2916 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2917 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2918 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
Manman Renf46262e2016-03-29 17:37:21 +00002919 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
Manman Ren57518142016-04-11 21:08:06 +00002920 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002921 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2922 return false;
2923
2924 Type *ArgTy = Arg.getType();
2925 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2926 return false;
2927
Mehdi Amini44ede332015-07-09 02:09:04 +00002928 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002929 if (!ArgVT.isSimple()) return false;
2930 switch (ArgVT.getSimpleVT().SimpleTy) {
2931 default: return false;
2932 case MVT::i32:
2933 case MVT::i64:
2934 ++GPRCnt;
2935 break;
2936 case MVT::f32:
2937 case MVT::f64:
2938 if (!Subtarget->hasSSE1())
2939 return false;
2940 ++FPRCnt;
2941 break;
2942 }
2943
2944 if (GPRCnt > 6)
2945 return false;
2946
2947 if (FPRCnt > 8)
2948 return false;
2949 }
2950
2951 static const MCPhysReg GPR32ArgRegs[] = {
2952 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2953 };
2954 static const MCPhysReg GPR64ArgRegs[] = {
2955 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2956 };
2957 static const MCPhysReg XMMArgRegs[] = {
2958 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2959 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2960 };
2961
2962 unsigned GPRIdx = 0;
2963 unsigned FPRIdx = 0;
2964 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002965 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002966 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2967 unsigned SrcReg;
2968 switch (VT.SimpleTy) {
2969 default: llvm_unreachable("Unexpected value type.");
2970 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2971 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002972 case MVT::f32: LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002973 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2974 }
2975 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2976 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2977 // Without this, EmitLiveInCopies may eliminate the livein if its only
2978 // use is a bitcast (which isn't turned into an instruction).
2979 unsigned ResultReg = createResultReg(RC);
2980 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2981 TII.get(TargetOpcode::COPY), ResultReg)
2982 .addReg(DstReg, getKillRegState(true));
2983 updateValueMap(&Arg, ResultReg);
2984 }
2985 return true;
2986}
2987
Nico Weberaf7e8462016-07-14 01:52:51 +00002988static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
2989 CallingConv::ID CC,
2990 ImmutableCallSite *CS) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002991 if (Subtarget->is64Bit())
2992 return 0;
2993 if (Subtarget->getTargetTriple().isOSMSVCRT())
2994 return 0;
2995 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2996 CC == CallingConv::HiPE)
2997 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00002998
2999 if (CS)
3000 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00003001 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003002 return 0;
3003
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003004 return 4;
3005}
3006
3007bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3008 auto &OutVals = CLI.OutVals;
3009 auto &OutFlags = CLI.OutFlags;
3010 auto &OutRegs = CLI.OutRegs;
3011 auto &Ins = CLI.Ins;
3012 auto &InRegs = CLI.InRegs;
3013 CallingConv::ID CC = CLI.CallConv;
3014 bool &IsTailCall = CLI.IsTailCall;
3015 bool IsVarArg = CLI.IsVarArg;
3016 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003017 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003018
3019 bool Is64Bit = Subtarget->is64Bit();
3020 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3021
3022 // Handle only C, fastcc, and webkit_js calling conventions for now.
3023 switch (CC) {
3024 default: return false;
3025 case CallingConv::C:
3026 case CallingConv::Fast:
3027 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00003028 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003029 case CallingConv::X86_FastCall:
Nico Weberecdf45b2016-07-14 13:54:26 +00003030 case CallingConv::X86_StdCall:
Nico Weberaf7e8462016-07-14 01:52:51 +00003031 case CallingConv::X86_ThisCall:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003032 case CallingConv::X86_64_Win64:
3033 case CallingConv::X86_64_SysV:
3034 break;
3035 }
3036
3037 // Allow SelectionDAG isel to handle tail calls.
3038 if (IsTailCall)
3039 return false;
3040
3041 // fastcc with -tailcallopt is intended to provide a guaranteed
3042 // tail call optimization. Fastisel doesn't know how to do that.
3043 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3044 return false;
3045
3046 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3047 // x86-32. Special handling for x86-64 is implemented.
3048 if (IsVarArg && IsWin64)
3049 return false;
3050
3051 // Don't know about inalloca yet.
3052 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3053 return false;
3054
Manman Ren57518142016-04-11 21:08:06 +00003055 for (auto Flag : CLI.OutFlags)
3056 if (Flag.isSwiftError())
3057 return false;
3058
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003059 SmallVector<MVT, 16> OutVTs;
3060 SmallVector<unsigned, 16> ArgRegs;
3061
3062 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3063 // instruction. This is safe because it is common to all FastISel supported
3064 // calling conventions on x86.
3065 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3066 Value *&Val = OutVals[i];
3067 ISD::ArgFlagsTy Flags = OutFlags[i];
3068 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3069 if (CI->getBitWidth() < 32) {
3070 if (Flags.isSExt())
3071 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3072 else
3073 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3074 }
3075 }
3076
3077 // Passing bools around ends up doing a trunc to i1 and passing it.
3078 // Codegen this as an argument + "and 1".
3079 MVT VT;
3080 auto *TI = dyn_cast<TruncInst>(Val);
3081 unsigned ResultReg;
3082 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3083 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3084 TI->hasOneUse()) {
3085 Value *PrevVal = TI->getOperand(0);
3086 ResultReg = getRegForValue(PrevVal);
3087
3088 if (!ResultReg)
3089 return false;
3090
3091 if (!isTypeLegal(PrevVal->getType(), VT))
3092 return false;
3093
3094 ResultReg =
3095 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3096 } else {
3097 if (!isTypeLegal(Val->getType(), VT))
3098 return false;
3099 ResultReg = getRegForValue(Val);
3100 }
3101
3102 if (!ResultReg)
3103 return false;
3104
3105 ArgRegs.push_back(ResultReg);
3106 OutVTs.push_back(VT);
3107 }
3108
3109 // Analyze operands of the call, assigning locations to each operand.
3110 SmallVector<CCValAssign, 16> ArgLocs;
3111 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3112
3113 // Allocate shadow area for Win64
3114 if (IsWin64)
3115 CCInfo.AllocateStack(32, 8);
3116
3117 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3118
3119 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00003120 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003121
3122 // Issue CALLSEQ_START
3123 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3124 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00003125 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003126
3127 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00003128 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003129 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3130 CCValAssign const &VA = ArgLocs[i];
3131 const Value *ArgVal = OutVals[VA.getValNo()];
3132 MVT ArgVT = OutVTs[VA.getValNo()];
3133
3134 if (ArgVT == MVT::x86mmx)
3135 return false;
3136
3137 unsigned ArgReg = ArgRegs[VA.getValNo()];
3138
3139 // Promote the value if needed.
3140 switch (VA.getLocInfo()) {
3141 case CCValAssign::Full: break;
3142 case CCValAssign::SExt: {
3143 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3144 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003145
3146 if (ArgVT.SimpleTy == MVT::i1)
3147 return false;
3148
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003149 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3150 ArgVT, ArgReg);
3151 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3152 ArgVT = VA.getLocVT();
3153 break;
3154 }
3155 case CCValAssign::ZExt: {
3156 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3157 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003158
3159 // Handle zero-extension from i1 to i8, which is common.
3160 if (ArgVT.SimpleTy == MVT::i1) {
3161 // Set the high bits to zero.
3162 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3163 ArgVT = MVT::i8;
3164
3165 if (ArgReg == 0)
3166 return false;
3167 }
3168
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003169 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3170 ArgVT, ArgReg);
3171 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3172 ArgVT = VA.getLocVT();
3173 break;
3174 }
3175 case CCValAssign::AExt: {
3176 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3177 "Unexpected extend");
3178 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3179 ArgVT, ArgReg);
3180 if (!Emitted)
3181 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3182 ArgVT, ArgReg);
3183 if (!Emitted)
3184 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3185 ArgVT, ArgReg);
3186
3187 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3188 ArgVT = VA.getLocVT();
3189 break;
3190 }
3191 case CCValAssign::BCvt: {
3192 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3193 /*TODO: Kill=*/false);
3194 assert(ArgReg && "Failed to emit a bitcast!");
3195 ArgVT = VA.getLocVT();
3196 break;
3197 }
3198 case CCValAssign::VExt:
3199 // VExt has not been implemented, so this should be impossible to reach
3200 // for now. However, fallback to Selection DAG isel once implemented.
3201 return false;
3202 case CCValAssign::AExtUpper:
3203 case CCValAssign::SExtUpper:
3204 case CCValAssign::ZExtUpper:
3205 case CCValAssign::FPExt:
3206 llvm_unreachable("Unexpected loc info!");
3207 case CCValAssign::Indirect:
3208 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3209 // support this.
3210 return false;
3211 }
3212
3213 if (VA.isRegLoc()) {
3214 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3215 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3216 OutRegs.push_back(VA.getLocReg());
3217 } else {
3218 assert(VA.isMemLoc());
3219
3220 // Don't emit stores for undef values.
3221 if (isa<UndefValue>(ArgVal))
3222 continue;
3223
3224 unsigned LocMemOffset = VA.getLocMemOffset();
3225 X86AddressMode AM;
3226 AM.Base.Reg = RegInfo->getStackRegister();
3227 AM.Disp = LocMemOffset;
3228 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3229 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3230 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003231 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3232 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003233 if (Flags.isByVal()) {
3234 X86AddressMode SrcAM;
3235 SrcAM.Base.Reg = ArgReg;
3236 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3237 return false;
3238 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3239 // If this is a really simple value, emit this with the Value* version
3240 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3241 // as it can cause us to reevaluate the argument.
3242 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3243 return false;
3244 } else {
3245 bool ValIsKill = hasTrivialKill(ArgVal);
3246 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3247 return false;
3248 }
3249 }
3250 }
3251
3252 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3253 // GOT pointer.
3254 if (Subtarget->isPICStyleGOT()) {
3255 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3256 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3257 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3258 }
3259
3260 if (Is64Bit && IsVarArg && !IsWin64) {
3261 // From AMD64 ABI document:
3262 // For calls that may call functions that use varargs or stdargs
3263 // (prototype-less calls or calls to functions containing ellipsis (...) in
3264 // the declaration) %al is used as hidden argument to specify the number
3265 // of SSE registers used. The contents of %al do not need to match exactly
3266 // the number of registers, but must be an ubound on the number of SSE
3267 // registers used and is in the range 0 - 8 inclusive.
3268
3269 // Count the number of XMM registers allocated.
3270 static const MCPhysReg XMMArgRegs[] = {
3271 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3272 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3273 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003274 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003275 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3276 && "SSE registers cannot be used when SSE is disabled");
3277 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3278 X86::AL).addImm(NumXMMRegs);
3279 }
3280
3281 // Materialize callee address in a register. FIXME: GV address can be
3282 // handled with a CALLpcrel32 instead.
3283 X86AddressMode CalleeAM;
3284 if (!X86SelectCallAddress(Callee, CalleeAM))
3285 return false;
3286
3287 unsigned CalleeOp = 0;
3288 const GlobalValue *GV = nullptr;
3289 if (CalleeAM.GV != nullptr) {
3290 GV = CalleeAM.GV;
3291 } else if (CalleeAM.Base.Reg != 0) {
3292 CalleeOp = CalleeAM.Base.Reg;
3293 } else
3294 return false;
3295
3296 // Issue the call.
3297 MachineInstrBuilder MIB;
3298 if (CalleeOp) {
3299 // Register-indirect call.
3300 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3301 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3302 .addReg(CalleeOp);
3303 } else {
3304 // Direct call.
3305 assert(GV && "Not a direct call");
3306 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3307
3308 // See if we need any target-specific flags on the GV operand.
Rafael Espindola46107b92016-05-19 18:49:29 +00003309 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
Asaf Badouh89406d12016-04-20 08:32:57 +00003310 // Ignore NonLazyBind attribute in FastISel
3311 if (OpFlags == X86II::MO_GOTPCREL)
3312 OpFlags = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003313
3314 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003315 if (Symbol)
3316 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003317 else
3318 MIB.addGlobalAddress(GV, 0, OpFlags);
3319 }
3320
3321 // Add a register mask operand representing the call-preserved registers.
3322 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003323 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003324
3325 // Add an implicit use GOT pointer in EBX.
3326 if (Subtarget->isPICStyleGOT())
3327 MIB.addReg(X86::EBX, RegState::Implicit);
3328
3329 if (Is64Bit && IsVarArg && !IsWin64)
3330 MIB.addReg(X86::AL, RegState::Implicit);
3331
3332 // Add implicit physical register uses to the call.
3333 for (auto Reg : OutRegs)
3334 MIB.addReg(Reg, RegState::Implicit);
3335
3336 // Issue CALLSEQ_END
3337 unsigned NumBytesForCalleeToPop =
Nico Weberaf7e8462016-07-14 01:52:51 +00003338 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3339 TM.Options.GuaranteedTailCallOpt)
3340 ? NumBytes // Callee pops everything.
3341 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CS);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003342 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3344 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3345
3346 // Now handle call return values.
3347 SmallVector<CCValAssign, 16> RVLocs;
3348 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3349 CLI.RetTy->getContext());
3350 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3351
3352 // Copy all of the result registers out of their specified physreg.
3353 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3354 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3355 CCValAssign &VA = RVLocs[i];
3356 EVT CopyVT = VA.getValVT();
3357 unsigned CopyReg = ResultReg + i;
3358
3359 // If this is x86-64, and we disabled SSE, we can't return FP values
3360 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3361 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3362 report_fatal_error("SSE register return with SSE disabled");
3363 }
3364
3365 // If we prefer to use the value in xmm registers, copy it out as f80 and
3366 // use a truncate to move it from fp stack reg to xmm reg.
3367 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3368 isScalarFPTypeInSSEReg(VA.getValVT())) {
3369 CopyVT = MVT::f80;
3370 CopyReg = createResultReg(&X86::RFP80RegClass);
3371 }
3372
3373 // Copy out the result.
3374 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3375 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3376 InRegs.push_back(VA.getLocReg());
3377
3378 // Round the f80 to the right size, which also moves it to the appropriate
3379 // xmm register. This is accomplished by storing the f80 value in memory
3380 // and then loading it back.
3381 if (CopyVT != VA.getValVT()) {
3382 EVT ResVT = VA.getValVT();
3383 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3384 unsigned MemSize = ResVT.getSizeInBits()/8;
3385 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3386 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3387 TII.get(Opc)), FI)
3388 .addReg(CopyReg);
3389 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3390 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3391 TII.get(Opc), ResultReg + i), FI);
3392 }
3393 }
3394
3395 CLI.ResultReg = ResultReg;
3396 CLI.NumResultRegs = RVLocs.size();
3397 CLI.Call = MIB;
3398
3399 return true;
3400}
3401
3402bool
3403X86FastISel::fastSelectInstruction(const Instruction *I) {
3404 switch (I->getOpcode()) {
3405 default: break;
3406 case Instruction::Load:
3407 return X86SelectLoad(I);
3408 case Instruction::Store:
3409 return X86SelectStore(I);
3410 case Instruction::Ret:
3411 return X86SelectRet(I);
3412 case Instruction::ICmp:
3413 case Instruction::FCmp:
3414 return X86SelectCmp(I);
3415 case Instruction::ZExt:
3416 return X86SelectZExt(I);
3417 case Instruction::Br:
3418 return X86SelectBranch(I);
3419 case Instruction::LShr:
3420 case Instruction::AShr:
3421 case Instruction::Shl:
3422 return X86SelectShift(I);
3423 case Instruction::SDiv:
3424 case Instruction::UDiv:
3425 case Instruction::SRem:
3426 case Instruction::URem:
3427 return X86SelectDivRem(I);
3428 case Instruction::Select:
3429 return X86SelectSelect(I);
3430 case Instruction::Trunc:
3431 return X86SelectTrunc(I);
3432 case Instruction::FPExt:
3433 return X86SelectFPExt(I);
3434 case Instruction::FPTrunc:
3435 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003436 case Instruction::SIToFP:
3437 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003438 case Instruction::IntToPtr: // Deliberate fall-through.
3439 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003440 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3441 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003442 if (DstVT.bitsGT(SrcVT))
3443 return X86SelectZExt(I);
3444 if (DstVT.bitsLT(SrcVT))
3445 return X86SelectTrunc(I);
3446 unsigned Reg = getRegForValue(I->getOperand(0));
3447 if (Reg == 0) return false;
3448 updateValueMap(I, Reg);
3449 return true;
3450 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003451 case Instruction::BitCast: {
3452 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3453 if (!Subtarget->hasSSE2())
3454 return false;
3455
3456 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3457 EVT DstVT = TLI.getValueType(DL, I->getType());
3458
3459 if (!SrcVT.isSimple() || !DstVT.isSimple())
3460 return false;
3461
3462 if (!SrcVT.is128BitVector() &&
3463 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3464 return false;
3465
3466 unsigned Reg = getRegForValue(I->getOperand(0));
3467 if (Reg == 0)
3468 return false;
3469
3470 // No instruction is needed for conversion. Reuse the register used by
3471 // the fist operand.
3472 updateValueMap(I, Reg);
3473 return true;
3474 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003475 }
3476
3477 return false;
3478}
3479
3480unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3481 if (VT > MVT::i64)
3482 return 0;
3483
3484 uint64_t Imm = CI->getZExtValue();
3485 if (Imm == 0) {
3486 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3487 switch (VT.SimpleTy) {
3488 default: llvm_unreachable("Unexpected value type");
3489 case MVT::i1:
3490 case MVT::i8:
3491 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3492 X86::sub_8bit);
3493 case MVT::i16:
3494 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3495 X86::sub_16bit);
3496 case MVT::i32:
3497 return SrcReg;
3498 case MVT::i64: {
3499 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3500 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3501 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3502 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3503 return ResultReg;
3504 }
3505 }
3506 }
3507
3508 unsigned Opc = 0;
3509 switch (VT.SimpleTy) {
3510 default: llvm_unreachable("Unexpected value type");
Justin Bognercd1d5aa2016-08-17 20:30:52 +00003511 case MVT::i1: VT = MVT::i8; LLVM_FALLTHROUGH;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003512 case MVT::i8: Opc = X86::MOV8ri; break;
3513 case MVT::i16: Opc = X86::MOV16ri; break;
3514 case MVT::i32: Opc = X86::MOV32ri; break;
3515 case MVT::i64: {
3516 if (isUInt<32>(Imm))
3517 Opc = X86::MOV32ri;
3518 else if (isInt<32>(Imm))
3519 Opc = X86::MOV64ri32;
3520 else
3521 Opc = X86::MOV64ri;
3522 break;
3523 }
3524 }
3525 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3526 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3527 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3528 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3529 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3530 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3531 return ResultReg;
3532 }
3533 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3534}
3535
3536unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3537 if (CFP->isNullValue())
3538 return fastMaterializeFloatZero(CFP);
3539
3540 // Can't handle alternate code models yet.
3541 CodeModel::Model CM = TM.getCodeModel();
3542 if (CM != CodeModel::Small && CM != CodeModel::Large)
3543 return 0;
3544
3545 // Get opcode and regclass of the output for the given load instruction.
3546 unsigned Opc = 0;
3547 const TargetRegisterClass *RC = nullptr;
3548 switch (VT.SimpleTy) {
3549 default: return 0;
3550 case MVT::f32:
3551 if (X86ScalarSSEf32) {
3552 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3553 RC = &X86::FR32RegClass;
3554 } else {
3555 Opc = X86::LD_Fp32m;
3556 RC = &X86::RFP32RegClass;
3557 }
3558 break;
3559 case MVT::f64:
3560 if (X86ScalarSSEf64) {
3561 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3562 RC = &X86::FR64RegClass;
3563 } else {
3564 Opc = X86::LD_Fp64m;
3565 RC = &X86::RFP64RegClass;
3566 }
3567 break;
3568 case MVT::f80:
3569 // No f80 support yet.
3570 return 0;
3571 }
3572
3573 // MachineConstantPool wants an explicit alignment.
3574 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3575 if (Align == 0) {
3576 // Alignment of vector types. FIXME!
3577 Align = DL.getTypeAllocSize(CFP->getType());
3578 }
3579
3580 // x86-32 PIC requires a PIC base register for constant pools.
3581 unsigned PICBase = 0;
Rafael Espindolac7e98132016-05-20 12:20:10 +00003582 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3583 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003584 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003585 else if (OpFlag == X86II::MO_GOTOFF)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003586 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003587 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003588 PICBase = X86::RIP;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003589
3590 // Create the load from the constant pool.
3591 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3592 unsigned ResultReg = createResultReg(RC);
3593
3594 if (CM == CodeModel::Large) {
3595 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3596 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3597 AddrReg)
3598 .addConstantPoolIndex(CPI, 0, OpFlag);
3599 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3600 TII.get(Opc), ResultReg);
3601 addDirectMem(MIB, AddrReg);
3602 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003603 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3604 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003605 MIB->addMemOperand(*FuncInfo.MF, MMO);
3606 return ResultReg;
3607 }
3608
3609 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3610 TII.get(Opc), ResultReg),
3611 CPI, PICBase, OpFlag);
3612 return ResultReg;
3613}
3614
3615unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3616 // Can't handle alternate code models yet.
3617 if (TM.getCodeModel() != CodeModel::Small)
3618 return 0;
3619
3620 // Materialize addresses with LEA/MOV instructions.
3621 X86AddressMode AM;
3622 if (X86SelectAddress(GV, AM)) {
3623 // If the expression is just a basereg, then we're done, otherwise we need
3624 // to emit an LEA.
3625 if (AM.BaseType == X86AddressMode::RegBase &&
3626 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3627 return AM.Base.Reg;
3628
3629 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3630 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003631 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003632 // The displacement code could be more than 32 bits away so we need to use
3633 // an instruction with a 64 bit immediate
3634 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3635 ResultReg)
3636 .addGlobalAddress(GV);
3637 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003638 unsigned Opc =
3639 TLI.getPointerTy(DL) == MVT::i32
3640 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3641 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003642 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3643 TII.get(Opc), ResultReg), AM);
3644 }
3645 return ResultReg;
3646 }
3647 return 0;
3648}
3649
3650unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003651 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003652
3653 // Only handle simple types.
3654 if (!CEVT.isSimple())
3655 return 0;
3656 MVT VT = CEVT.getSimpleVT();
3657
3658 if (const auto *CI = dyn_cast<ConstantInt>(C))
3659 return X86MaterializeInt(CI, VT);
3660 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3661 return X86MaterializeFP(CFP, VT);
3662 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3663 return X86MaterializeGV(GV, VT);
3664
3665 return 0;
3666}
3667
3668unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3669 // Fail on dynamic allocas. At this point, getRegForValue has already
3670 // checked its CSE maps, so if we're here trying to handle a dynamic
3671 // alloca, we're not going to succeed. X86SelectAddress has a
3672 // check for dynamic allocas, because it's called directly from
3673 // various places, but targetMaterializeAlloca also needs a check
3674 // in order to avoid recursion between getRegForValue,
3675 // X86SelectAddrss, and targetMaterializeAlloca.
3676 if (!FuncInfo.StaticAllocaMap.count(C))
3677 return 0;
3678 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3679
3680 X86AddressMode AM;
3681 if (!X86SelectAddress(C, AM))
3682 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003683 unsigned Opc =
3684 TLI.getPointerTy(DL) == MVT::i32
3685 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3686 : X86::LEA64r;
3687 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003688 unsigned ResultReg = createResultReg(RC);
3689 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3690 TII.get(Opc), ResultReg), AM);
3691 return ResultReg;
3692}
3693
3694unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3695 MVT VT;
3696 if (!isTypeLegal(CF->getType(), VT))
3697 return 0;
3698
3699 // Get opcode and regclass for the given zero.
3700 unsigned Opc = 0;
3701 const TargetRegisterClass *RC = nullptr;
3702 switch (VT.SimpleTy) {
3703 default: return 0;
3704 case MVT::f32:
3705 if (X86ScalarSSEf32) {
3706 Opc = X86::FsFLD0SS;
3707 RC = &X86::FR32RegClass;
3708 } else {
3709 Opc = X86::LD_Fp032;
3710 RC = &X86::RFP32RegClass;
3711 }
3712 break;
3713 case MVT::f64:
3714 if (X86ScalarSSEf64) {
3715 Opc = X86::FsFLD0SD;
3716 RC = &X86::FR64RegClass;
3717 } else {
3718 Opc = X86::LD_Fp064;
3719 RC = &X86::RFP64RegClass;
3720 }
3721 break;
3722 case MVT::f80:
3723 // No f80 support yet.
3724 return 0;
3725 }
3726
3727 unsigned ResultReg = createResultReg(RC);
3728 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3729 return ResultReg;
3730}
3731
3732
3733bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3734 const LoadInst *LI) {
3735 const Value *Ptr = LI->getPointerOperand();
3736 X86AddressMode AM;
3737 if (!X86SelectAddress(Ptr, AM))
3738 return false;
3739
3740 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3741
3742 unsigned Size = DL.getTypeAllocSize(LI->getType());
3743 unsigned Alignment = LI->getAlignment();
3744
3745 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3746 Alignment = DL.getABITypeAlignment(LI->getType());
3747
3748 SmallVector<MachineOperand, 8> AddrOps;
3749 AM.getFullAddress(AddrOps);
3750
Keno Fischere70b31f2015-06-08 20:09:58 +00003751 MachineInstr *Result = XII.foldMemoryOperandImpl(
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00003752 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
Keno Fischere70b31f2015-06-08 20:09:58 +00003753 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003754 if (!Result)
3755 return false;
3756
Pete Cooperd31583d2015-05-06 21:37:19 +00003757 // The index register could be in the wrong register class. Unfortunately,
3758 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3759 // to just look at OpNo + the offset to the index reg. We actually need to
3760 // scan the instruction to find the index reg and see if its the correct reg
3761 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003762 unsigned OperandNo = 0;
3763 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3764 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3765 MachineOperand &MO = *I;
3766 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003767 continue;
3768 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003769 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003770 MO.getReg(), OperandNo);
3771 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003772 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003773 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003774 }
3775
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003776 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003777 MI->eraseFromParent();
3778 return true;
3779}
3780
3781
3782namespace llvm {
3783 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3784 const TargetLibraryInfo *libInfo) {
3785 return new X86FastISel(funcInfo, libInfo);
3786 }
3787}