blob: 6258e4f6cf345a95405e96bfe40b4a44119cf058 [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;
185 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
186 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
187 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
188 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
189 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
190 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
191 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
192 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;
196 case CmpInst::FCMP_OEQ: // fall-through
197 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;
232 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
233 case CmpInst::FCMP_OLT: CC = 1; break;
234 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
235 case CmpInst::FCMP_OLE: CC = 2; break;
236 case CmpInst::FCMP_UNO: CC = 3; break;
237 case CmpInst::FCMP_UNE: CC = 4; break;
238 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
239 case CmpInst::FCMP_UGE: CC = 5; break;
240 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
241 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;
521 }
522 // FALLTHROUGH, handling i1 as i8.
523 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;
662 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
663 case MVT::i8: Opc = X86::MOV8mi; break;
664 case MVT::i16: Opc = X86::MOV16mi; break;
665 case MVT::i32: Opc = X86::MOV32mi; break;
666 case MVT::i64:
667 // Must be a 32-bit sign extended value.
668 if (isInt<32>(CI->getSExtValue()))
669 Opc = X86::MOV64mi32;
670 break;
671 }
672
673 if (Opc) {
674 MachineInstrBuilder MIB =
675 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
676 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
677 : CI->getZExtValue());
678 if (MMO)
679 MIB->addMemOperand(*FuncInfo.MF, MMO);
680 return true;
681 }
682 }
683
684 unsigned ValReg = getRegForValue(Val);
685 if (ValReg == 0)
686 return false;
687
688 bool ValKill = hasTrivialKill(Val);
689 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
690}
691
692/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
693/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
694/// ISD::SIGN_EXTEND).
695bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
696 unsigned Src, EVT SrcVT,
697 unsigned &ResultReg) {
698 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
699 Src, /*TODO: Kill=*/false);
700 if (RR == 0)
701 return false;
702
703 ResultReg = RR;
704 return true;
705}
706
707bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
708 // Handle constant address.
709 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
710 // Can't handle alternate code models yet.
711 if (TM.getCodeModel() != CodeModel::Small)
712 return false;
713
714 // Can't handle TLS yet.
715 if (GV->isThreadLocal())
716 return false;
717
718 // RIP-relative addresses can't have additional register operands, so if
719 // we've already folded stuff into the addressing mode, just force the
720 // global value into its own register, which we can use as the basereg.
721 if (!Subtarget->isPICStyleRIPRel() ||
722 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
723 // Okay, we've committed to selecting this global. Set up the address.
724 AM.GV = GV;
725
726 // Allow the subtarget to classify the global.
Rafael Espindolaab03eb02016-05-19 22:07:57 +0000727 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000728
729 // If this reference is relative to the pic base, set it now.
730 if (isGlobalRelativeToPICBase(GVFlags)) {
731 // FIXME: How do we know Base.Reg is free??
732 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
733 }
734
735 // Unless the ABI requires an extra load, return a direct reference to
736 // the global.
737 if (!isGlobalStubReference(GVFlags)) {
738 if (Subtarget->isPICStyleRIPRel()) {
739 // Use rip-relative addressing if we can. Above we verified that the
740 // base and index registers are unused.
741 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
742 AM.Base.Reg = X86::RIP;
743 }
744 AM.GVOpFlags = GVFlags;
745 return true;
746 }
747
748 // Ok, we need to do a load from a stub. If we've already loaded from
749 // this stub, reuse the loaded pointer, otherwise emit the load now.
750 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
751 unsigned LoadReg;
752 if (I != LocalValueMap.end() && I->second != 0) {
753 LoadReg = I->second;
754 } else {
755 // Issue load from stub.
756 unsigned Opc = 0;
757 const TargetRegisterClass *RC = nullptr;
758 X86AddressMode StubAM;
759 StubAM.Base.Reg = AM.Base.Reg;
760 StubAM.GV = GV;
761 StubAM.GVOpFlags = GVFlags;
762
763 // Prepare for inserting code in the local-value area.
764 SavePoint SaveInsertPt = enterLocalValueArea();
765
Mehdi Amini44ede332015-07-09 02:09:04 +0000766 if (TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000767 Opc = X86::MOV64rm;
768 RC = &X86::GR64RegClass;
769
770 if (Subtarget->isPICStyleRIPRel())
771 StubAM.Base.Reg = X86::RIP;
772 } else {
773 Opc = X86::MOV32rm;
774 RC = &X86::GR32RegClass;
775 }
776
777 LoadReg = createResultReg(RC);
778 MachineInstrBuilder LoadMI =
779 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
780 addFullAddress(LoadMI, StubAM);
781
782 // Ok, back to normal mode.
783 leaveLocalValueArea(SaveInsertPt);
784
785 // Prevent loading GV stub multiple times in same MBB.
786 LocalValueMap[V] = LoadReg;
787 }
788
789 // Now construct the final address. Note that the Disp, Scale,
790 // and Index values may already be set here.
791 AM.Base.Reg = LoadReg;
792 AM.GV = nullptr;
793 return true;
794 }
795 }
796
797 // If all else fails, try to materialize the value in a register.
798 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
799 if (AM.Base.Reg == 0) {
800 AM.Base.Reg = getRegForValue(V);
801 return AM.Base.Reg != 0;
802 }
803 if (AM.IndexReg == 0) {
804 assert(AM.Scale == 1 && "Scale with no index!");
805 AM.IndexReg = getRegForValue(V);
806 return AM.IndexReg != 0;
807 }
808 }
809
810 return false;
811}
812
813/// X86SelectAddress - Attempt to fill in an address from the given value.
814///
815bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
816 SmallVector<const Value *, 32> GEPs;
817redo_gep:
818 const User *U = nullptr;
819 unsigned Opcode = Instruction::UserOp1;
820 if (const Instruction *I = dyn_cast<Instruction>(V)) {
821 // Don't walk into other basic blocks; it's possible we haven't
822 // visited them yet, so the instructions may not yet be assigned
823 // virtual registers.
824 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
825 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
826 Opcode = I->getOpcode();
827 U = I;
828 }
829 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
830 Opcode = C->getOpcode();
831 U = C;
832 }
833
834 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
835 if (Ty->getAddressSpace() > 255)
836 // Fast instruction selection doesn't support the special
837 // address spaces.
838 return false;
839
840 switch (Opcode) {
841 default: break;
842 case Instruction::BitCast:
843 // Look past bitcasts.
844 return X86SelectAddress(U->getOperand(0), AM);
845
846 case Instruction::IntToPtr:
847 // Look past no-op inttoptrs.
Mehdi Amini44ede332015-07-09 02:09:04 +0000848 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
849 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000850 return X86SelectAddress(U->getOperand(0), AM);
851 break;
852
853 case Instruction::PtrToInt:
854 // Look past no-op ptrtoints.
Mehdi Amini44ede332015-07-09 02:09:04 +0000855 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000856 return X86SelectAddress(U->getOperand(0), AM);
857 break;
858
859 case Instruction::Alloca: {
860 // Do static allocas.
861 const AllocaInst *A = cast<AllocaInst>(V);
862 DenseMap<const AllocaInst *, int>::iterator SI =
863 FuncInfo.StaticAllocaMap.find(A);
864 if (SI != FuncInfo.StaticAllocaMap.end()) {
865 AM.BaseType = X86AddressMode::FrameIndexBase;
866 AM.Base.FrameIndex = SI->second;
867 return true;
868 }
869 break;
870 }
871
872 case Instruction::Add: {
873 // Adds of constants are common and easy enough.
874 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
875 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
876 // They have to fit in the 32-bit signed displacement field though.
877 if (isInt<32>(Disp)) {
878 AM.Disp = (uint32_t)Disp;
879 return X86SelectAddress(U->getOperand(0), AM);
880 }
881 }
882 break;
883 }
884
885 case Instruction::GetElementPtr: {
886 X86AddressMode SavedAM = AM;
887
888 // Pattern-match simple GEPs.
889 uint64_t Disp = (int32_t)AM.Disp;
890 unsigned IndexReg = AM.IndexReg;
891 unsigned Scale = AM.Scale;
892 gep_type_iterator GTI = gep_type_begin(U);
893 // Iterate through the indices, folding what we can. Constants can be
894 // folded, and one dynamic index can be handled, if the scale is supported.
895 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
896 i != e; ++i, ++GTI) {
897 const Value *Op = *i;
898 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
899 const StructLayout *SL = DL.getStructLayout(STy);
900 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
901 continue;
902 }
903
904 // A array/variable index is always of the form i*S where S is the
905 // constant scale size. See if we can push the scale into immediates.
906 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
907 for (;;) {
908 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
909 // Constant-offset addressing.
910 Disp += CI->getSExtValue() * S;
911 break;
912 }
913 if (canFoldAddIntoGEP(U, Op)) {
914 // A compatible add with a constant operand. Fold the constant.
915 ConstantInt *CI =
916 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
917 Disp += CI->getSExtValue() * S;
918 // Iterate on the other operand.
919 Op = cast<AddOperator>(Op)->getOperand(0);
920 continue;
921 }
922 if (IndexReg == 0 &&
923 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
924 (S == 1 || S == 2 || S == 4 || S == 8)) {
925 // Scaled-index addressing.
926 Scale = S;
927 IndexReg = getRegForGEPIndex(Op).first;
928 if (IndexReg == 0)
929 return false;
930 break;
931 }
932 // Unsupported.
933 goto unsupported_gep;
934 }
935 }
936
937 // Check for displacement overflow.
938 if (!isInt<32>(Disp))
939 break;
940
941 AM.IndexReg = IndexReg;
942 AM.Scale = Scale;
943 AM.Disp = (uint32_t)Disp;
944 GEPs.push_back(V);
945
946 if (const GetElementPtrInst *GEP =
947 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
948 // Ok, the GEP indices were covered by constant-offset and scaled-index
949 // addressing. Update the address state and move on to examining the base.
950 V = GEP;
951 goto redo_gep;
952 } else if (X86SelectAddress(U->getOperand(0), AM)) {
953 return true;
954 }
955
956 // If we couldn't merge the gep value into this addr mode, revert back to
957 // our address and just match the value instead of completely failing.
958 AM = SavedAM;
959
David Majnemerd7708772016-06-24 04:05:21 +0000960 for (const Value *I : reverse(GEPs))
961 if (handleConstantAddresses(I, AM))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000962 return true;
963
964 return false;
965 unsupported_gep:
966 // Ok, the GEP indices weren't all covered.
967 break;
968 }
969 }
970
971 return handleConstantAddresses(V, AM);
972}
973
974/// X86SelectCallAddress - Attempt to fill in an address from the given value.
975///
976bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
977 const User *U = nullptr;
978 unsigned Opcode = Instruction::UserOp1;
979 const Instruction *I = dyn_cast<Instruction>(V);
980 // Record if the value is defined in the same basic block.
981 //
982 // This information is crucial to know whether or not folding an
983 // operand is valid.
984 // Indeed, FastISel generates or reuses a virtual register for all
985 // operands of all instructions it selects. Obviously, the definition and
986 // its uses must use the same virtual register otherwise the produced
987 // code is incorrect.
988 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
989 // registers for values that are alive across basic blocks. This ensures
990 // that the values are consistently set between across basic block, even
991 // if different instruction selection mechanisms are used (e.g., a mix of
992 // SDISel and FastISel).
993 // For values local to a basic block, the instruction selection process
994 // generates these virtual registers with whatever method is appropriate
995 // for its needs. In particular, FastISel and SDISel do not share the way
996 // local virtual registers are set.
997 // Therefore, this is impossible (or at least unsafe) to share values
998 // between basic blocks unless they use the same instruction selection
999 // method, which is not guarantee for X86.
1000 // Moreover, things like hasOneUse could not be used accurately, if we
1001 // allow to reference values across basic blocks whereas they are not
1002 // alive across basic blocks initially.
1003 bool InMBB = true;
1004 if (I) {
1005 Opcode = I->getOpcode();
1006 U = I;
1007 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1008 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1009 Opcode = C->getOpcode();
1010 U = C;
1011 }
1012
1013 switch (Opcode) {
1014 default: break;
1015 case Instruction::BitCast:
1016 // Look past bitcasts if its operand is in the same BB.
1017 if (InMBB)
1018 return X86SelectCallAddress(U->getOperand(0), AM);
1019 break;
1020
1021 case Instruction::IntToPtr:
1022 // Look past no-op inttoptrs if its operand is in the same BB.
1023 if (InMBB &&
Mehdi Amini44ede332015-07-09 02:09:04 +00001024 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1025 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001026 return X86SelectCallAddress(U->getOperand(0), AM);
1027 break;
1028
1029 case Instruction::PtrToInt:
1030 // Look past no-op ptrtoints if its operand is in the same BB.
Mehdi Amini44ede332015-07-09 02:09:04 +00001031 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001032 return X86SelectCallAddress(U->getOperand(0), AM);
1033 break;
1034 }
1035
1036 // Handle constant address.
1037 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1038 // Can't handle alternate code models yet.
1039 if (TM.getCodeModel() != CodeModel::Small)
1040 return false;
1041
1042 // RIP-relative addresses can't have additional register operands.
1043 if (Subtarget->isPICStyleRIPRel() &&
1044 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1045 return false;
1046
1047 // Can't handle DLL Import.
1048 if (GV->hasDLLImportStorageClass())
1049 return false;
1050
1051 // Can't handle TLS.
1052 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1053 if (GVar->isThreadLocal())
1054 return false;
1055
1056 // Okay, we've committed to selecting this global. Set up the basic address.
1057 AM.GV = GV;
1058
1059 // No ABI requires an extra load for anything other than DLLImport, which
1060 // we rejected above. Return a direct reference to the global.
1061 if (Subtarget->isPICStyleRIPRel()) {
1062 // Use rip-relative addressing if we can. Above we verified that the
1063 // base and index registers are unused.
1064 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1065 AM.Base.Reg = X86::RIP;
Rafael Espindolac7e98132016-05-20 12:20:10 +00001066 } else {
1067 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001068 }
1069
1070 return true;
1071 }
1072
1073 // If all else fails, try to materialize the value in a register.
1074 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1075 if (AM.Base.Reg == 0) {
1076 AM.Base.Reg = getRegForValue(V);
1077 return AM.Base.Reg != 0;
1078 }
1079 if (AM.IndexReg == 0) {
1080 assert(AM.Scale == 1 && "Scale with no index!");
1081 AM.IndexReg = getRegForValue(V);
1082 return AM.IndexReg != 0;
1083 }
1084 }
1085
1086 return false;
1087}
1088
1089
1090/// X86SelectStore - Select and emit code to implement store instructions.
1091bool X86FastISel::X86SelectStore(const Instruction *I) {
1092 // Atomic stores need special handling.
1093 const StoreInst *S = cast<StoreInst>(I);
1094
1095 if (S->isAtomic())
1096 return false;
1097
Manman Ren57518142016-04-11 21:08:06 +00001098 const Value *PtrV = I->getOperand(1);
1099 if (TLI.supportSwiftError()) {
1100 // Swifterror values can come from either a function parameter with
1101 // swifterror attribute or an alloca with swifterror attribute.
1102 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1103 if (Arg->hasSwiftErrorAttr())
1104 return false;
1105 }
1106
1107 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1108 if (Alloca->isSwiftError())
1109 return false;
1110 }
1111 }
1112
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001113 const Value *Val = S->getValueOperand();
1114 const Value *Ptr = S->getPointerOperand();
1115
1116 MVT VT;
1117 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1118 return false;
1119
1120 unsigned Alignment = S->getAlignment();
1121 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
1122 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1123 Alignment = ABIAlignment;
1124 bool Aligned = Alignment >= ABIAlignment;
1125
1126 X86AddressMode AM;
1127 if (!X86SelectAddress(Ptr, AM))
1128 return false;
1129
1130 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1131}
1132
1133/// X86SelectRet - Select and emit code to implement ret instructions.
1134bool X86FastISel::X86SelectRet(const Instruction *I) {
1135 const ReturnInst *Ret = cast<ReturnInst>(I);
1136 const Function &F = *I->getParent()->getParent();
1137 const X86MachineFunctionInfo *X86MFInfo =
1138 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1139
1140 if (!FuncInfo.CanLowerReturn)
1141 return false;
1142
Manman Ren57518142016-04-11 21:08:06 +00001143 if (TLI.supportSwiftError() &&
1144 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1145 return false;
1146
Manman Rened967f32016-01-12 01:08:46 +00001147 if (TLI.supportSplitCSR(FuncInfo.MF))
1148 return false;
1149
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001150 CallingConv::ID CC = F.getCallingConv();
1151 if (CC != CallingConv::C &&
1152 CC != CallingConv::Fast &&
1153 CC != CallingConv::X86_FastCall &&
Nico Weberc7bf6462016-07-12 01:30:35 +00001154 CC != CallingConv::X86_ThisCall &&
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001155 CC != CallingConv::X86_64_SysV)
1156 return false;
1157
1158 if (Subtarget->isCallingConvWin64(CC))
1159 return false;
1160
Nico Weberc7bf6462016-07-12 01:30:35 +00001161 // Don't handle popping bytes if they don't fit the ret's immediate.
1162 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001163 return false;
1164
1165 // fastcc with -tailcallopt is intended to provide a guaranteed
1166 // tail call optimization. Fastisel doesn't know how to do that.
1167 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1168 return false;
1169
1170 // Let SDISel handle vararg functions.
1171 if (F.isVarArg())
1172 return false;
1173
1174 // Build a list of return value registers.
1175 SmallVector<unsigned, 4> RetRegs;
1176
1177 if (Ret->getNumOperands() > 0) {
1178 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001179 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001180
1181 // Analyze operands of the call, assigning locations to each operand.
1182 SmallVector<CCValAssign, 16> ValLocs;
1183 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1184 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1185
1186 const Value *RV = Ret->getOperand(0);
1187 unsigned Reg = getRegForValue(RV);
1188 if (Reg == 0)
1189 return false;
1190
1191 // Only handle a single return value for now.
1192 if (ValLocs.size() != 1)
1193 return false;
1194
1195 CCValAssign &VA = ValLocs[0];
1196
1197 // Don't bother handling odd stuff for now.
1198 if (VA.getLocInfo() != CCValAssign::Full)
1199 return false;
1200 // Only handle register returns for now.
1201 if (!VA.isRegLoc())
1202 return false;
1203
1204 // The calling-convention tables for x87 returns don't tell
1205 // the whole story.
1206 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1207 return false;
1208
1209 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001210 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001211 EVT DstVT = VA.getValVT();
1212 // Special handling for extended integers.
1213 if (SrcVT != DstVT) {
1214 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1215 return false;
1216
1217 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1218 return false;
1219
1220 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1221
1222 if (SrcVT == MVT::i1) {
1223 if (Outs[0].Flags.isSExt())
1224 return false;
1225 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1226 SrcVT = MVT::i8;
1227 }
1228 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1229 ISD::SIGN_EXTEND;
1230 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1231 SrcReg, /*TODO: Kill=*/false);
1232 }
1233
1234 // Make the copy.
1235 unsigned DstReg = VA.getLocReg();
1236 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1237 // Avoid a cross-class copy. This is very unlikely.
1238 if (!SrcRC->contains(DstReg))
1239 return false;
1240 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1241 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1242
1243 // Add register to return instruction.
1244 RetRegs.push_back(VA.getLocReg());
1245 }
1246
Manman Ren1c3f65a2016-04-26 18:08:06 +00001247 // Swift calling convention does not require we copy the sret argument
1248 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1249
Dimitry Andric227b9282016-01-03 17:22:03 +00001250 // All x86 ABIs require that for returning structs by value we copy
1251 // the sret argument into %rax/%eax (depending on ABI) for the return.
1252 // We saved the argument into a virtual register in the entry block,
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00001253 // so now we copy the value out and into %rax/%eax.
Manman Ren1c3f65a2016-04-26 18:08:06 +00001254 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001255 unsigned Reg = X86MFInfo->getSRetReturnReg();
1256 assert(Reg &&
1257 "SRetReturnReg should have been set in LowerFormalArguments()!");
1258 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1259 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1260 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1261 RetRegs.push_back(RetReg);
1262 }
1263
1264 // Now emit the RET.
Nico Weberc7bf6462016-07-12 01:30:35 +00001265 MachineInstrBuilder MIB;
1266 if (X86MFInfo->getBytesToPopOnReturn()) {
1267 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1268 TII.get(Subtarget->is64Bit() ? X86::RETIQ : X86::RETIL))
1269 .addImm(X86MFInfo->getBytesToPopOnReturn());
1270 } else {
1271 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1272 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1273 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001274 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1275 MIB.addReg(RetRegs[i], RegState::Implicit);
1276 return true;
1277}
1278
1279/// X86SelectLoad - Select and emit code to implement load instructions.
1280///
1281bool X86FastISel::X86SelectLoad(const Instruction *I) {
1282 const LoadInst *LI = cast<LoadInst>(I);
1283
1284 // Atomic loads need special handling.
1285 if (LI->isAtomic())
1286 return false;
1287
Manman Ren57518142016-04-11 21:08:06 +00001288 const Value *SV = I->getOperand(0);
1289 if (TLI.supportSwiftError()) {
1290 // Swifterror values can come from either a function parameter with
1291 // swifterror attribute or an alloca with swifterror attribute.
1292 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1293 if (Arg->hasSwiftErrorAttr())
1294 return false;
1295 }
1296
1297 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1298 if (Alloca->isSwiftError())
1299 return false;
1300 }
1301 }
1302
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001303 MVT VT;
1304 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1305 return false;
1306
1307 const Value *Ptr = LI->getPointerOperand();
1308
1309 X86AddressMode AM;
1310 if (!X86SelectAddress(Ptr, AM))
1311 return false;
1312
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001313 unsigned Alignment = LI->getAlignment();
1314 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1315 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1316 Alignment = ABIAlignment;
1317
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001318 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001319 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1320 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001321 return false;
1322
1323 updateValueMap(I, ResultReg);
1324 return true;
1325}
1326
1327static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1328 bool HasAVX = Subtarget->hasAVX();
1329 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1330 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1331
1332 switch (VT.getSimpleVT().SimpleTy) {
1333 default: return 0;
1334 case MVT::i8: return X86::CMP8rr;
1335 case MVT::i16: return X86::CMP16rr;
1336 case MVT::i32: return X86::CMP32rr;
1337 case MVT::i64: return X86::CMP64rr;
1338 case MVT::f32:
1339 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1340 case MVT::f64:
1341 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1342 }
1343}
1344
Rafael Espindola19141f22015-03-16 14:05:49 +00001345/// If we have a comparison with RHS as the RHS of the comparison, return an
1346/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001347static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001348 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001349 switch (VT.getSimpleVT().SimpleTy) {
1350 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001351 default:
1352 return 0;
1353 case MVT::i8:
1354 return X86::CMP8ri;
1355 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001356 if (isInt<8>(Val))
1357 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001358 return X86::CMP16ri;
1359 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001360 if (isInt<8>(Val))
1361 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001362 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001363 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001364 if (isInt<8>(Val))
1365 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001366 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1367 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001368 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001369 return X86::CMP64ri32;
1370 return 0;
1371 }
1372}
1373
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001374bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1375 const DebugLoc &CurDbgLoc) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001376 unsigned Op0Reg = getRegForValue(Op0);
1377 if (Op0Reg == 0) return false;
1378
1379 // Handle 'null' like i32/i64 0.
1380 if (isa<ConstantPointerNull>(Op1))
1381 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1382
1383 // We have two options: compare with register or immediate. If the RHS of
1384 // the compare is an immediate that we can fold into this compare, use
1385 // CMPri, otherwise use CMPrr.
1386 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1387 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1388 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1389 .addReg(Op0Reg)
1390 .addImm(Op1C->getSExtValue());
1391 return true;
1392 }
1393 }
1394
1395 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1396 if (CompareOpc == 0) return false;
1397
1398 unsigned Op1Reg = getRegForValue(Op1);
1399 if (Op1Reg == 0) return false;
1400 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1401 .addReg(Op0Reg)
1402 .addReg(Op1Reg);
1403
1404 return true;
1405}
1406
1407bool X86FastISel::X86SelectCmp(const Instruction *I) {
1408 const CmpInst *CI = cast<CmpInst>(I);
1409
1410 MVT VT;
1411 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1412 return false;
1413
Elena Demikhovskyad0a56f2016-07-06 14:15:43 +00001414 if (I->getType()->isIntegerTy(1) && Subtarget->hasAVX512())
1415 return false;
1416
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001417 // Try to optimize or fold the cmp.
1418 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1419 unsigned ResultReg = 0;
1420 switch (Predicate) {
1421 default: break;
1422 case CmpInst::FCMP_FALSE: {
1423 ResultReg = createResultReg(&X86::GR32RegClass);
1424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1425 ResultReg);
1426 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1427 X86::sub_8bit);
1428 if (!ResultReg)
1429 return false;
1430 break;
1431 }
1432 case CmpInst::FCMP_TRUE: {
1433 ResultReg = createResultReg(&X86::GR8RegClass);
1434 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1435 ResultReg).addImm(1);
1436 break;
1437 }
1438 }
1439
1440 if (ResultReg) {
1441 updateValueMap(I, ResultReg);
1442 return true;
1443 }
1444
1445 const Value *LHS = CI->getOperand(0);
1446 const Value *RHS = CI->getOperand(1);
1447
1448 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1449 // We don't have to materialize a zero constant for this case and can just use
1450 // %x again on the RHS.
1451 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1452 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1453 if (RHSC && RHSC->isNullValue())
1454 RHS = LHS;
1455 }
1456
1457 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1458 static unsigned SETFOpcTable[2][3] = {
1459 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1460 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1461 };
1462 unsigned *SETFOpc = nullptr;
1463 switch (Predicate) {
1464 default: break;
1465 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1466 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1467 }
1468
1469 ResultReg = createResultReg(&X86::GR8RegClass);
1470 if (SETFOpc) {
1471 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1472 return false;
1473
1474 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1475 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1476 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1477 FlagReg1);
1478 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1479 FlagReg2);
1480 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1481 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1482 updateValueMap(I, ResultReg);
1483 return true;
1484 }
1485
1486 X86::CondCode CC;
1487 bool SwapArgs;
1488 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1489 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1490 unsigned Opc = X86::getSETFromCond(CC);
1491
1492 if (SwapArgs)
1493 std::swap(LHS, RHS);
1494
1495 // Emit a compare of LHS/RHS.
1496 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1497 return false;
1498
1499 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1500 updateValueMap(I, ResultReg);
1501 return true;
1502}
1503
1504bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001505 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001506 if (!TLI.isTypeLegal(DstVT))
1507 return false;
1508
1509 unsigned ResultReg = getRegForValue(I->getOperand(0));
1510 if (ResultReg == 0)
1511 return false;
1512
1513 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001514 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001515 if (SrcVT.SimpleTy == MVT::i1) {
1516 // Set the high bits to zero.
1517 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1518 SrcVT = MVT::i8;
1519
1520 if (ResultReg == 0)
1521 return false;
1522 }
1523
1524 if (DstVT == MVT::i64) {
1525 // Handle extension to 64-bits via sub-register shenanigans.
1526 unsigned MovInst;
1527
1528 switch (SrcVT.SimpleTy) {
1529 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1530 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1531 case MVT::i32: MovInst = X86::MOV32rr; break;
1532 default: llvm_unreachable("Unexpected zext to i64 source type");
1533 }
1534
1535 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1536 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1537 .addReg(ResultReg);
1538
1539 ResultReg = createResultReg(&X86::GR64RegClass);
1540 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1541 ResultReg)
1542 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1543 } else if (DstVT != MVT::i8) {
1544 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1545 ResultReg, /*Kill=*/true);
1546 if (ResultReg == 0)
1547 return false;
1548 }
1549
1550 updateValueMap(I, ResultReg);
1551 return true;
1552}
1553
1554bool X86FastISel::X86SelectBranch(const Instruction *I) {
1555 // Unconditional branches are selected by tablegen-generated code.
1556 // Handle a conditional branch.
1557 const BranchInst *BI = cast<BranchInst>(I);
1558 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1559 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1560
1561 // Fold the common case of a conditional branch with a comparison
1562 // in the same block (values defined on other blocks may not have
1563 // initialized registers).
1564 X86::CondCode CC;
1565 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1566 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001567 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001568
1569 // Try to optimize or fold the cmp.
1570 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1571 switch (Predicate) {
1572 default: break;
1573 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1574 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1575 }
1576
1577 const Value *CmpLHS = CI->getOperand(0);
1578 const Value *CmpRHS = CI->getOperand(1);
1579
1580 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1581 // 0.0.
1582 // We don't have to materialize a zero constant for this case and can just
1583 // use %x again on the RHS.
1584 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1585 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1586 if (CmpRHSC && CmpRHSC->isNullValue())
1587 CmpRHS = CmpLHS;
1588 }
1589
1590 // Try to take advantage of fallthrough opportunities.
1591 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1592 std::swap(TrueMBB, FalseMBB);
1593 Predicate = CmpInst::getInversePredicate(Predicate);
1594 }
1595
1596 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1597 // code check. Instead two branch instructions are required to check all
1598 // the flags. First we change the predicate to a supported condition code,
1599 // which will be the first branch. Later one we will emit the second
1600 // branch.
1601 bool NeedExtraBranch = false;
1602 switch (Predicate) {
1603 default: break;
1604 case CmpInst::FCMP_OEQ:
1605 std::swap(TrueMBB, FalseMBB); // fall-through
1606 case CmpInst::FCMP_UNE:
1607 NeedExtraBranch = true;
1608 Predicate = CmpInst::FCMP_ONE;
1609 break;
1610 }
1611
1612 bool SwapArgs;
1613 unsigned BranchOpc;
1614 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1615 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1616
1617 BranchOpc = X86::GetCondBranchFromCond(CC);
1618 if (SwapArgs)
1619 std::swap(CmpLHS, CmpRHS);
1620
1621 // Emit a compare of the LHS and RHS, setting the flags.
1622 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1623 return false;
1624
1625 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1626 .addMBB(TrueMBB);
1627
1628 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1629 // to UNE above).
1630 if (NeedExtraBranch) {
1631 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1632 .addMBB(TrueMBB);
1633 }
1634
Matthias Braun17af6072015-08-26 01:38:00 +00001635 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001636 return true;
1637 }
1638 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1639 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1640 // typically happen for _Bool and C++ bools.
1641 MVT SourceVT;
1642 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1643 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1644 unsigned TestOpc = 0;
1645 switch (SourceVT.SimpleTy) {
1646 default: break;
1647 case MVT::i8: TestOpc = X86::TEST8ri; break;
1648 case MVT::i16: TestOpc = X86::TEST16ri; break;
1649 case MVT::i32: TestOpc = X86::TEST32ri; break;
1650 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1651 }
1652 if (TestOpc) {
1653 unsigned OpReg = getRegForValue(TI->getOperand(0));
1654 if (OpReg == 0) return false;
1655 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1656 .addReg(OpReg).addImm(1);
1657
1658 unsigned JmpOpc = X86::JNE_1;
1659 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1660 std::swap(TrueMBB, FalseMBB);
1661 JmpOpc = X86::JE_1;
1662 }
1663
1664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1665 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001666
1667 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001668 return true;
1669 }
1670 }
1671 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1672 // Fake request the condition, otherwise the intrinsic might be completely
1673 // optimized away.
1674 unsigned TmpReg = getRegForValue(BI->getCondition());
1675 if (TmpReg == 0)
1676 return false;
1677
1678 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1679
1680 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1681 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001682 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001683 return true;
1684 }
1685
1686 // Otherwise do a clumsy setcc and re-test it.
1687 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1688 // in an explicit cast, so make sure to handle that correctly.
1689 unsigned OpReg = getRegForValue(BI->getCondition());
1690 if (OpReg == 0) return false;
1691
1692 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1693 .addReg(OpReg).addImm(1);
1694 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1695 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001696 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001697 return true;
1698}
1699
1700bool X86FastISel::X86SelectShift(const Instruction *I) {
1701 unsigned CReg = 0, OpReg = 0;
1702 const TargetRegisterClass *RC = nullptr;
1703 if (I->getType()->isIntegerTy(8)) {
1704 CReg = X86::CL;
1705 RC = &X86::GR8RegClass;
1706 switch (I->getOpcode()) {
1707 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1708 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1709 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1710 default: return false;
1711 }
1712 } else if (I->getType()->isIntegerTy(16)) {
1713 CReg = X86::CX;
1714 RC = &X86::GR16RegClass;
1715 switch (I->getOpcode()) {
1716 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1717 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1718 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1719 default: return false;
1720 }
1721 } else if (I->getType()->isIntegerTy(32)) {
1722 CReg = X86::ECX;
1723 RC = &X86::GR32RegClass;
1724 switch (I->getOpcode()) {
1725 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1726 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1727 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1728 default: return false;
1729 }
1730 } else if (I->getType()->isIntegerTy(64)) {
1731 CReg = X86::RCX;
1732 RC = &X86::GR64RegClass;
1733 switch (I->getOpcode()) {
1734 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1735 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1736 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1737 default: return false;
1738 }
1739 } else {
1740 return false;
1741 }
1742
1743 MVT VT;
1744 if (!isTypeLegal(I->getType(), VT))
1745 return false;
1746
1747 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1748 if (Op0Reg == 0) return false;
1749
1750 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1751 if (Op1Reg == 0) return false;
1752 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1753 CReg).addReg(Op1Reg);
1754
1755 // The shift instruction uses X86::CL. If we defined a super-register
1756 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1757 if (CReg != X86::CL)
1758 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1759 TII.get(TargetOpcode::KILL), X86::CL)
1760 .addReg(CReg, RegState::Kill);
1761
1762 unsigned ResultReg = createResultReg(RC);
1763 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1764 .addReg(Op0Reg);
1765 updateValueMap(I, ResultReg);
1766 return true;
1767}
1768
1769bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1770 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1771 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1772 const static bool S = true; // IsSigned
1773 const static bool U = false; // !IsSigned
1774 const static unsigned Copy = TargetOpcode::COPY;
1775 // For the X86 DIV/IDIV instruction, in most cases the dividend
1776 // (numerator) must be in a specific register pair highreg:lowreg,
1777 // producing the quotient in lowreg and the remainder in highreg.
1778 // For most data types, to set up the instruction, the dividend is
1779 // copied into lowreg, and lowreg is sign-extended or zero-extended
1780 // into highreg. The exception is i8, where the dividend is defined
1781 // as a single register rather than a register pair, and we
1782 // therefore directly sign-extend or zero-extend the dividend into
1783 // lowreg, instead of copying, and ignore the highreg.
1784 const static struct DivRemEntry {
1785 // The following portion depends only on the data type.
1786 const TargetRegisterClass *RC;
1787 unsigned LowInReg; // low part of the register pair
1788 unsigned HighInReg; // high part of the register pair
1789 // The following portion depends on both the data type and the operation.
1790 struct DivRemResult {
1791 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1792 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1793 // highreg, or copying a zero into highreg.
1794 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1795 // zero/sign-extending into lowreg for i8.
1796 unsigned DivRemResultReg; // Register containing the desired result.
1797 bool IsOpSigned; // Whether to use signed or unsigned form.
1798 } ResultTable[NumOps];
1799 } OpTable[NumTypes] = {
1800 { &X86::GR8RegClass, X86::AX, 0, {
1801 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1802 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1803 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1804 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1805 }
1806 }, // i8
1807 { &X86::GR16RegClass, X86::AX, X86::DX, {
1808 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1809 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1810 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1811 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1812 }
1813 }, // i16
1814 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1815 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1816 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1817 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1818 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1819 }
1820 }, // i32
1821 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1822 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1823 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1824 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1825 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1826 }
1827 }, // i64
1828 };
1829
1830 MVT VT;
1831 if (!isTypeLegal(I->getType(), VT))
1832 return false;
1833
1834 unsigned TypeIndex, OpIndex;
1835 switch (VT.SimpleTy) {
1836 default: return false;
1837 case MVT::i8: TypeIndex = 0; break;
1838 case MVT::i16: TypeIndex = 1; break;
1839 case MVT::i32: TypeIndex = 2; break;
1840 case MVT::i64: TypeIndex = 3;
1841 if (!Subtarget->is64Bit())
1842 return false;
1843 break;
1844 }
1845
1846 switch (I->getOpcode()) {
1847 default: llvm_unreachable("Unexpected div/rem opcode");
1848 case Instruction::SDiv: OpIndex = 0; break;
1849 case Instruction::SRem: OpIndex = 1; break;
1850 case Instruction::UDiv: OpIndex = 2; break;
1851 case Instruction::URem: OpIndex = 3; break;
1852 }
1853
1854 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1855 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1856 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1857 if (Op0Reg == 0)
1858 return false;
1859 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1860 if (Op1Reg == 0)
1861 return false;
1862
1863 // Move op0 into low-order input register.
1864 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1865 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1866 // Zero-extend or sign-extend into high-order input register.
1867 if (OpEntry.OpSignExtend) {
1868 if (OpEntry.IsOpSigned)
1869 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1870 TII.get(OpEntry.OpSignExtend));
1871 else {
1872 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1873 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1874 TII.get(X86::MOV32r0), Zero32);
1875
1876 // Copy the zero into the appropriate sub/super/identical physical
1877 // register. Unfortunately the operations needed are not uniform enough
1878 // to fit neatly into the table above.
1879 if (VT.SimpleTy == MVT::i16) {
1880 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1881 TII.get(Copy), TypeEntry.HighInReg)
1882 .addReg(Zero32, 0, X86::sub_16bit);
1883 } else if (VT.SimpleTy == MVT::i32) {
1884 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1885 TII.get(Copy), TypeEntry.HighInReg)
1886 .addReg(Zero32);
1887 } else if (VT.SimpleTy == MVT::i64) {
1888 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1889 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1890 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1891 }
1892 }
1893 }
1894 // Generate the DIV/IDIV instruction.
1895 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1896 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1897 // For i8 remainder, we can't reference AH directly, as we'll end
1898 // up with bogus copies like %R9B = COPY %AH. Reference AX
1899 // instead to prevent AH references in a REX instruction.
1900 //
1901 // The current assumption of the fast register allocator is that isel
1902 // won't generate explicit references to the GPR8_NOREX registers. If
1903 // the allocator and/or the backend get enhanced to be more robust in
1904 // that regard, this can be, and should be, removed.
1905 unsigned ResultReg = 0;
1906 if ((I->getOpcode() == Instruction::SRem ||
1907 I->getOpcode() == Instruction::URem) &&
1908 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1909 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1910 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1911 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1912 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1913
1914 // Shift AX right by 8 bits instead of using AH.
1915 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1916 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1917
1918 // Now reference the 8-bit subreg of the result.
1919 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1920 /*Kill=*/true, X86::sub_8bit);
1921 }
1922 // Copy the result out of the physreg if we haven't already.
1923 if (!ResultReg) {
1924 ResultReg = createResultReg(TypeEntry.RC);
1925 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1926 .addReg(OpEntry.DivRemResultReg);
1927 }
1928 updateValueMap(I, ResultReg);
1929
1930 return true;
1931}
1932
1933/// \brief Emit a conditional move instruction (if the are supported) to lower
1934/// the select.
1935bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1936 // Check if the subtarget supports these instructions.
1937 if (!Subtarget->hasCMov())
1938 return false;
1939
1940 // FIXME: Add support for i8.
1941 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1942 return false;
1943
1944 const Value *Cond = I->getOperand(0);
1945 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1946 bool NeedTest = true;
1947 X86::CondCode CC = X86::COND_NE;
1948
1949 // Optimize conditions coming from a compare if both instructions are in the
1950 // same basic block (values defined in other basic blocks may not have
1951 // initialized registers).
1952 const auto *CI = dyn_cast<CmpInst>(Cond);
1953 if (CI && (CI->getParent() == I->getParent())) {
1954 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1955
1956 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1957 static unsigned SETFOpcTable[2][3] = {
1958 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1959 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1960 };
1961 unsigned *SETFOpc = nullptr;
1962 switch (Predicate) {
1963 default: break;
1964 case CmpInst::FCMP_OEQ:
1965 SETFOpc = &SETFOpcTable[0][0];
1966 Predicate = CmpInst::ICMP_NE;
1967 break;
1968 case CmpInst::FCMP_UNE:
1969 SETFOpc = &SETFOpcTable[1][0];
1970 Predicate = CmpInst::ICMP_NE;
1971 break;
1972 }
1973
1974 bool NeedSwap;
1975 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1976 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1977
1978 const Value *CmpLHS = CI->getOperand(0);
1979 const Value *CmpRHS = CI->getOperand(1);
1980 if (NeedSwap)
1981 std::swap(CmpLHS, CmpRHS);
1982
Mehdi Amini44ede332015-07-09 02:09:04 +00001983 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001984 // Emit a compare of the LHS and RHS, setting the flags.
1985 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1986 return false;
1987
1988 if (SETFOpc) {
1989 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1990 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1991 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1992 FlagReg1);
1993 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1994 FlagReg2);
1995 auto const &II = TII.get(SETFOpc[2]);
1996 if (II.getNumDefs()) {
1997 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1999 .addReg(FlagReg2).addReg(FlagReg1);
2000 } else {
2001 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
2002 .addReg(FlagReg2).addReg(FlagReg1);
2003 }
2004 }
2005 NeedTest = false;
2006 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2007 // Fake request the condition, otherwise the intrinsic might be completely
2008 // optimized away.
2009 unsigned TmpReg = getRegForValue(Cond);
2010 if (TmpReg == 0)
2011 return false;
2012
2013 NeedTest = false;
2014 }
2015
2016 if (NeedTest) {
2017 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2018 // garbage. Indeed, only the less significant bit is supposed to be
2019 // accurate. If we read more than the lsb, we may see non-zero values
2020 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2021 // the select. This is achieved by performing TEST against 1.
2022 unsigned CondReg = getRegForValue(Cond);
2023 if (CondReg == 0)
2024 return false;
2025 bool CondIsKill = hasTrivialKill(Cond);
2026
2027 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2028 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2029 }
2030
2031 const Value *LHS = I->getOperand(1);
2032 const Value *RHS = I->getOperand(2);
2033
2034 unsigned RHSReg = getRegForValue(RHS);
2035 bool RHSIsKill = hasTrivialKill(RHS);
2036
2037 unsigned LHSReg = getRegForValue(LHS);
2038 bool LHSIsKill = hasTrivialKill(LHS);
2039
2040 if (!LHSReg || !RHSReg)
2041 return false;
2042
2043 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
2044 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2045 LHSReg, LHSIsKill);
2046 updateValueMap(I, ResultReg);
2047 return true;
2048}
2049
Sanjay Patel302404b2015-03-05 21:46:54 +00002050/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002051///
2052/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2053/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00002054/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002055bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2056 // Optimize conditions coming from a compare if both instructions are in the
2057 // same basic block (values defined in other basic blocks may not have
2058 // initialized registers).
2059 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2060 if (!CI || (CI->getParent() != I->getParent()))
2061 return false;
2062
2063 if (I->getType() != CI->getOperand(0)->getType() ||
2064 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2065 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2066 return false;
2067
2068 const Value *CmpLHS = CI->getOperand(0);
2069 const Value *CmpRHS = CI->getOperand(1);
2070 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2071
2072 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2073 // We don't have to materialize a zero constant for this case and can just use
2074 // %x again on the RHS.
2075 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2076 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2077 if (CmpRHSC && CmpRHSC->isNullValue())
2078 CmpRHS = CmpLHS;
2079 }
2080
2081 unsigned CC;
2082 bool NeedSwap;
2083 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2084 if (CC > 7)
2085 return false;
2086
2087 if (NeedSwap)
2088 std::swap(CmpLHS, CmpRHS);
2089
Sanjay Patel302404b2015-03-05 21:46:54 +00002090 // Choose the SSE instruction sequence based on data type (float or double).
2091 static unsigned OpcTable[2][4] = {
2092 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
2093 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002094 };
2095
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002096 unsigned *Opc = nullptr;
2097 switch (RetVT.SimpleTy) {
2098 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00002099 case MVT::f32: Opc = &OpcTable[0][0]; break;
2100 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002101 }
2102
2103 const Value *LHS = I->getOperand(1);
2104 const Value *RHS = I->getOperand(2);
2105
2106 unsigned LHSReg = getRegForValue(LHS);
2107 bool LHSIsKill = hasTrivialKill(LHS);
2108
2109 unsigned RHSReg = getRegForValue(RHS);
2110 bool RHSIsKill = hasTrivialKill(RHS);
2111
2112 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2113 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2114
2115 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2116 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2117
2118 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2119 return false;
2120
2121 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00002122 unsigned ResultReg;
2123
2124 if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00002125 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
2126 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2127
Sanjay Patel302404b2015-03-05 21:46:54 +00002128 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2129 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2130 // uses XMM0 as the selection register. That may need just as many
2131 // instructions as the AND/ANDN/OR sequence due to register moves, so
2132 // don't bother.
2133 unsigned CmpOpcode =
2134 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2135 unsigned BlendOpcode =
2136 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2137
Matthias Braun818c78d2015-08-31 18:25:11 +00002138 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00002139 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00002140 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2141 LHSReg, LHSIsKill, CmpReg, true);
2142 ResultReg = createResultReg(RC);
2143 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2144 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002145 } else {
2146 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2147 CmpRHSReg, CmpRHSIsKill, CC);
2148 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
2149 LHSReg, LHSIsKill);
2150 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
2151 RHSReg, RHSIsKill);
2152 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
2153 AndReg, /*IsKill=*/true);
2154 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002155 updateValueMap(I, ResultReg);
2156 return true;
2157}
2158
2159bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2160 // These are pseudo CMOV instructions and will be later expanded into control-
2161 // flow.
2162 unsigned Opc;
2163 switch (RetVT.SimpleTy) {
2164 default: return false;
2165 case MVT::i8: Opc = X86::CMOV_GR8; break;
2166 case MVT::i16: Opc = X86::CMOV_GR16; break;
2167 case MVT::i32: Opc = X86::CMOV_GR32; break;
2168 case MVT::f32: Opc = X86::CMOV_FR32; break;
2169 case MVT::f64: Opc = X86::CMOV_FR64; break;
2170 }
2171
2172 const Value *Cond = I->getOperand(0);
2173 X86::CondCode CC = X86::COND_NE;
2174
2175 // Optimize conditions coming from a compare if both instructions are in the
2176 // same basic block (values defined in other basic blocks may not have
2177 // initialized registers).
2178 const auto *CI = dyn_cast<CmpInst>(Cond);
2179 if (CI && (CI->getParent() == I->getParent())) {
2180 bool NeedSwap;
2181 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2182 if (CC > X86::LAST_VALID_COND)
2183 return false;
2184
2185 const Value *CmpLHS = CI->getOperand(0);
2186 const Value *CmpRHS = CI->getOperand(1);
2187
2188 if (NeedSwap)
2189 std::swap(CmpLHS, CmpRHS);
2190
Mehdi Amini44ede332015-07-09 02:09:04 +00002191 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002192 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2193 return false;
2194 } else {
2195 unsigned CondReg = getRegForValue(Cond);
2196 if (CondReg == 0)
2197 return false;
2198 bool CondIsKill = hasTrivialKill(Cond);
2199 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2200 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2201 }
2202
2203 const Value *LHS = I->getOperand(1);
2204 const Value *RHS = I->getOperand(2);
2205
2206 unsigned LHSReg = getRegForValue(LHS);
2207 bool LHSIsKill = hasTrivialKill(LHS);
2208
2209 unsigned RHSReg = getRegForValue(RHS);
2210 bool RHSIsKill = hasTrivialKill(RHS);
2211
2212 if (!LHSReg || !RHSReg)
2213 return false;
2214
2215 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2216
2217 unsigned ResultReg =
2218 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2219 updateValueMap(I, ResultReg);
2220 return true;
2221}
2222
2223bool X86FastISel::X86SelectSelect(const Instruction *I) {
2224 MVT RetVT;
2225 if (!isTypeLegal(I->getType(), RetVT))
2226 return false;
2227
2228 // Check if we can fold the select.
2229 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2230 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2231 const Value *Opnd = nullptr;
2232 switch (Predicate) {
2233 default: break;
2234 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2235 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2236 }
2237 // No need for a select anymore - this is an unconditional move.
2238 if (Opnd) {
2239 unsigned OpReg = getRegForValue(Opnd);
2240 if (OpReg == 0)
2241 return false;
2242 bool OpIsKill = hasTrivialKill(Opnd);
2243 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2244 unsigned ResultReg = createResultReg(RC);
2245 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2246 TII.get(TargetOpcode::COPY), ResultReg)
2247 .addReg(OpReg, getKillRegState(OpIsKill));
2248 updateValueMap(I, ResultReg);
2249 return true;
2250 }
2251 }
2252
2253 // First try to use real conditional move instructions.
2254 if (X86FastEmitCMoveSelect(RetVT, I))
2255 return true;
2256
2257 // Try to use a sequence of SSE instructions to simulate a conditional move.
2258 if (X86FastEmitSSESelect(RetVT, I))
2259 return true;
2260
2261 // Fall-back to pseudo conditional move instructions, which will be later
2262 // converted to control-flow.
2263 if (X86FastEmitPseudoSelect(RetVT, I))
2264 return true;
2265
2266 return false;
2267}
2268
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002269bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002270 // The target-independent selection algorithm in FastISel already knows how
2271 // to select a SINT_TO_FP if the target is SSE but not AVX.
2272 // Early exit if the subtarget doesn't have AVX.
2273 if (!Subtarget->hasAVX())
2274 return false;
2275
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002276 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2277 return false;
2278
2279 // Select integer to float/double conversion.
2280 unsigned OpReg = getRegForValue(I->getOperand(0));
2281 if (OpReg == 0)
2282 return false;
2283
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002284 const TargetRegisterClass *RC = nullptr;
2285 unsigned Opcode;
2286
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002287 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002288 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002289 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002290 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002291 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002292 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002293 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002294 RC = &X86::FR32RegClass;
2295 } else
2296 return false;
2297
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002298 unsigned ImplicitDefReg = createResultReg(RC);
2299 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2300 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2301 unsigned ResultReg =
2302 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002303 updateValueMap(I, ResultReg);
2304 return true;
2305}
2306
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002307// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2308bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2309 unsigned TargetOpc,
2310 const TargetRegisterClass *RC) {
2311 assert((I->getOpcode() == Instruction::FPExt ||
2312 I->getOpcode() == Instruction::FPTrunc) &&
2313 "Instruction must be an FPExt or FPTrunc!");
2314
2315 unsigned OpReg = getRegForValue(I->getOperand(0));
2316 if (OpReg == 0)
2317 return false;
2318
2319 unsigned ResultReg = createResultReg(RC);
2320 MachineInstrBuilder MIB;
2321 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2322 ResultReg);
2323 if (Subtarget->hasAVX())
2324 MIB.addReg(OpReg);
2325 MIB.addReg(OpReg);
2326 updateValueMap(I, ResultReg);
2327 return true;
2328}
2329
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002330bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002331 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2332 I->getOperand(0)->getType()->isFloatTy()) {
2333 // fpext from float to double.
2334 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2335 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002336 }
2337
2338 return false;
2339}
2340
2341bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002342 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2343 I->getOperand(0)->getType()->isDoubleTy()) {
2344 // fptrunc from double to float.
2345 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2346 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002347 }
2348
2349 return false;
2350}
2351
2352bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002353 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2354 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002355
2356 // This code only handles truncation to byte.
2357 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2358 return false;
2359 if (!TLI.isTypeLegal(SrcVT))
2360 return false;
2361
2362 unsigned InputReg = getRegForValue(I->getOperand(0));
2363 if (!InputReg)
2364 // Unhandled operand. Halt "fast" selection and bail.
2365 return false;
2366
2367 if (SrcVT == MVT::i8) {
2368 // Truncate from i8 to i1; no code needed.
2369 updateValueMap(I, InputReg);
2370 return true;
2371 }
2372
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002373 bool KillInputReg = false;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002374 if (!Subtarget->is64Bit()) {
2375 // If we're on x86-32; we can't extract an i8 from a general register.
2376 // First issue a copy to GR16_ABCD or GR32_ABCD.
2377 const TargetRegisterClass *CopyRC =
2378 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2379 unsigned CopyReg = createResultReg(CopyRC);
2380 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2381 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2382 InputReg = CopyReg;
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002383 KillInputReg = true;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002384 }
2385
2386 // Issue an extract_subreg.
2387 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002388 InputReg, KillInputReg,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002389 X86::sub_8bit);
2390 if (!ResultReg)
2391 return false;
2392
2393 updateValueMap(I, ResultReg);
2394 return true;
2395}
2396
2397bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2398 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2399}
2400
2401bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2402 X86AddressMode SrcAM, uint64_t Len) {
2403
2404 // Make sure we don't bloat code by inlining very large memcpy's.
2405 if (!IsMemcpySmall(Len))
2406 return false;
2407
2408 bool i64Legal = Subtarget->is64Bit();
2409
2410 // We don't care about alignment here since we just emit integer accesses.
2411 while (Len) {
2412 MVT VT;
2413 if (Len >= 8 && i64Legal)
2414 VT = MVT::i64;
2415 else if (Len >= 4)
2416 VT = MVT::i32;
2417 else if (Len >= 2)
2418 VT = MVT::i16;
2419 else
2420 VT = MVT::i8;
2421
2422 unsigned Reg;
2423 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2424 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2425 assert(RV && "Failed to emit load or store??");
2426
2427 unsigned Size = VT.getSizeInBits()/8;
2428 Len -= Size;
2429 DestAM.Disp += Size;
2430 SrcAM.Disp += Size;
2431 }
2432
2433 return true;
2434}
2435
2436bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2437 // FIXME: Handle more intrinsics.
2438 switch (II->getIntrinsicID()) {
2439 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002440 case Intrinsic::convert_from_fp16:
2441 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002442 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002443 return false;
2444
2445 const Value *Op = II->getArgOperand(0);
2446 unsigned InputReg = getRegForValue(Op);
2447 if (InputReg == 0)
2448 return false;
2449
2450 // F16C only allows converting from float to half and from half to float.
2451 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2452 if (IsFloatToHalf) {
2453 if (!Op->getType()->isFloatTy())
2454 return false;
2455 } else {
2456 if (!II->getType()->isFloatTy())
2457 return false;
2458 }
2459
2460 unsigned ResultReg = 0;
2461 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2462 if (IsFloatToHalf) {
2463 // 'InputReg' is implicitly promoted from register class FR32 to
2464 // register class VR128 by method 'constrainOperandRegClass' which is
2465 // directly called by 'fastEmitInst_ri'.
2466 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
Ahmed Bougacha68a8efa2016-02-02 01:44:03 +00002467 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2468 // It's consistent with the other FP instructions, which are usually
2469 // controlled by MXCSR.
2470 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
Andrea Di Biagio70351782015-02-20 19:37:14 +00002471
2472 // Move the lower 32-bits of ResultReg to another register of class GR32.
2473 ResultReg = createResultReg(&X86::GR32RegClass);
2474 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2475 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2476 .addReg(InputReg, RegState::Kill);
2477
2478 // The result value is in the lower 16-bits of ResultReg.
2479 unsigned RegIdx = X86::sub_16bit;
2480 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2481 } else {
2482 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2483 // Explicitly sign-extend the input to 32-bit.
2484 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2485 /*Kill=*/false);
2486
2487 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2488 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2489 InputReg, /*Kill=*/true);
2490
2491 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2492
2493 // The result value is in the lower 32-bits of ResultReg.
2494 // Emit an explicit copy from register class VR128 to register class FR32.
2495 ResultReg = createResultReg(&X86::FR32RegClass);
2496 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2497 TII.get(TargetOpcode::COPY), ResultReg)
2498 .addReg(InputReg, RegState::Kill);
2499 }
2500
2501 updateValueMap(II, ResultReg);
2502 return true;
2503 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002504 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002505 MachineFunction *MF = FuncInfo.MF;
2506 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2507 return false;
2508
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002509 Type *RetTy = II->getCalledFunction()->getReturnType();
2510
2511 MVT VT;
2512 if (!isTypeLegal(RetTy, VT))
2513 return false;
2514
2515 unsigned Opc;
2516 const TargetRegisterClass *RC = nullptr;
2517
2518 switch (VT.SimpleTy) {
2519 default: llvm_unreachable("Invalid result type for frameaddress.");
2520 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2521 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2522 }
2523
2524 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2525 // we get the wrong frame register.
David Majnemerca194852015-02-10 22:00:34 +00002526 MachineFrameInfo *MFI = MF->getFrameInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002527 MFI->setFrameAddressIsTaken(true);
2528
Eric Christophera1c535b2015-02-02 23:03:45 +00002529 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002530 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002531 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2532 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2533 "Invalid Frame Register!");
2534
2535 // Always make a copy of the frame register to to a vreg first, so that we
2536 // never directly reference the frame register (the TwoAddressInstruction-
2537 // Pass doesn't like that).
2538 unsigned SrcReg = createResultReg(RC);
2539 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2540 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2541
2542 // Now recursively load from the frame address.
2543 // movq (%rbp), %rax
2544 // movq (%rax), %rax
2545 // movq (%rax), %rax
2546 // ...
2547 unsigned DestReg;
2548 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2549 while (Depth--) {
2550 DestReg = createResultReg(RC);
2551 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2552 TII.get(Opc), DestReg), SrcReg);
2553 SrcReg = DestReg;
2554 }
2555
2556 updateValueMap(II, SrcReg);
2557 return true;
2558 }
2559 case Intrinsic::memcpy: {
2560 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2561 // Don't handle volatile or variable length memcpys.
2562 if (MCI->isVolatile())
2563 return false;
2564
2565 if (isa<ConstantInt>(MCI->getLength())) {
2566 // Small memcpy's are common enough that we want to do them
2567 // without a call if possible.
2568 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2569 if (IsMemcpySmall(Len)) {
2570 X86AddressMode DestAM, SrcAM;
2571 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2572 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2573 return false;
2574 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2575 return true;
2576 }
2577 }
2578
2579 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2580 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2581 return false;
2582
2583 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2584 return false;
2585
Pete Cooper67cf9a72015-11-19 05:56:52 +00002586 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002587 }
2588 case Intrinsic::memset: {
2589 const MemSetInst *MSI = cast<MemSetInst>(II);
2590
2591 if (MSI->isVolatile())
2592 return false;
2593
2594 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2595 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2596 return false;
2597
2598 if (MSI->getDestAddressSpace() > 255)
2599 return false;
2600
Pete Cooper67cf9a72015-11-19 05:56:52 +00002601 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002602 }
2603 case Intrinsic::stackprotector: {
2604 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002605 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002606
2607 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2608 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2609
2610 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2611
2612 // Grab the frame index.
2613 X86AddressMode AM;
2614 if (!X86SelectAddress(Slot, AM)) return false;
2615 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2616 return true;
2617 }
2618 case Intrinsic::dbg_declare: {
2619 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2620 X86AddressMode AM;
2621 assert(DI->getAddress() && "Null address should be checked earlier!");
2622 if (!X86SelectAddress(DI->getAddress(), AM))
2623 return false;
2624 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2625 // FIXME may need to add RegState::Debug to any registers produced,
2626 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002627 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2628 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002629 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2630 .addImm(0)
2631 .addMetadata(DI->getVariable())
2632 .addMetadata(DI->getExpression());
2633 return true;
2634 }
2635 case Intrinsic::trap: {
2636 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2637 return true;
2638 }
2639 case Intrinsic::sqrt: {
2640 if (!Subtarget->hasSSE1())
2641 return false;
2642
2643 Type *RetTy = II->getCalledFunction()->getReturnType();
2644
2645 MVT VT;
2646 if (!isTypeLegal(RetTy, VT))
2647 return false;
2648
2649 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2650 // is not generated by FastISel yet.
2651 // FIXME: Update this code once tablegen can handle it.
Craig Toppercf65c622016-03-02 04:42:31 +00002652 static const uint16_t SqrtOpc[2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002653 {X86::SQRTSSr, X86::VSQRTSSr},
2654 {X86::SQRTSDr, X86::VSQRTSDr}
2655 };
2656 bool HasAVX = Subtarget->hasAVX();
2657 unsigned Opc;
2658 const TargetRegisterClass *RC;
2659 switch (VT.SimpleTy) {
2660 default: return false;
2661 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2662 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2663 }
2664
2665 const Value *SrcVal = II->getArgOperand(0);
2666 unsigned SrcReg = getRegForValue(SrcVal);
2667
2668 if (SrcReg == 0)
2669 return false;
2670
2671 unsigned ImplicitDefReg = 0;
2672 if (HasAVX) {
2673 ImplicitDefReg = createResultReg(RC);
2674 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2675 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2676 }
2677
2678 unsigned ResultReg = createResultReg(RC);
2679 MachineInstrBuilder MIB;
2680 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2681 ResultReg);
2682
2683 if (ImplicitDefReg)
2684 MIB.addReg(ImplicitDefReg);
2685
2686 MIB.addReg(SrcReg);
2687
2688 updateValueMap(II, ResultReg);
2689 return true;
2690 }
2691 case Intrinsic::sadd_with_overflow:
2692 case Intrinsic::uadd_with_overflow:
2693 case Intrinsic::ssub_with_overflow:
2694 case Intrinsic::usub_with_overflow:
2695 case Intrinsic::smul_with_overflow:
2696 case Intrinsic::umul_with_overflow: {
2697 // This implements the basic lowering of the xalu with overflow intrinsics
2698 // into add/sub/mul followed by either seto or setb.
2699 const Function *Callee = II->getCalledFunction();
2700 auto *Ty = cast<StructType>(Callee->getReturnType());
2701 Type *RetTy = Ty->getTypeAtIndex(0U);
2702 Type *CondTy = Ty->getTypeAtIndex(1);
2703
2704 MVT VT;
2705 if (!isTypeLegal(RetTy, VT))
2706 return false;
2707
2708 if (VT < MVT::i8 || VT > MVT::i64)
2709 return false;
2710
2711 const Value *LHS = II->getArgOperand(0);
2712 const Value *RHS = II->getArgOperand(1);
2713
2714 // Canonicalize immediate to the RHS.
2715 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2716 isCommutativeIntrinsic(II))
2717 std::swap(LHS, RHS);
2718
2719 bool UseIncDec = false;
2720 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2721 UseIncDec = true;
2722
2723 unsigned BaseOpc, CondOpc;
2724 switch (II->getIntrinsicID()) {
2725 default: llvm_unreachable("Unexpected intrinsic!");
2726 case Intrinsic::sadd_with_overflow:
2727 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2728 CondOpc = X86::SETOr;
2729 break;
2730 case Intrinsic::uadd_with_overflow:
2731 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2732 case Intrinsic::ssub_with_overflow:
2733 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2734 CondOpc = X86::SETOr;
2735 break;
2736 case Intrinsic::usub_with_overflow:
2737 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2738 case Intrinsic::smul_with_overflow:
2739 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2740 case Intrinsic::umul_with_overflow:
2741 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2742 }
2743
2744 unsigned LHSReg = getRegForValue(LHS);
2745 if (LHSReg == 0)
2746 return false;
2747 bool LHSIsKill = hasTrivialKill(LHS);
2748
2749 unsigned ResultReg = 0;
2750 // Check if we have an immediate version.
2751 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topper66111882016-06-02 04:19:42 +00002752 static const uint16_t Opc[2][4] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002753 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2754 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2755 };
2756
2757 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2758 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2759 bool IsDec = BaseOpc == X86ISD::DEC;
2760 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2761 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2762 .addReg(LHSReg, getKillRegState(LHSIsKill));
2763 } else
2764 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2765 CI->getZExtValue());
2766 }
2767
2768 unsigned RHSReg;
2769 bool RHSIsKill;
2770 if (!ResultReg) {
2771 RHSReg = getRegForValue(RHS);
2772 if (RHSReg == 0)
2773 return false;
2774 RHSIsKill = hasTrivialKill(RHS);
2775 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2776 RHSIsKill);
2777 }
2778
2779 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2780 // it manually.
2781 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002782 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002783 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002784 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002785 // First copy the first operand into RAX, which is an implicit input to
2786 // the X86::MUL*r instruction.
2787 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2788 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2789 .addReg(LHSReg, getKillRegState(LHSIsKill));
2790 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2791 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2792 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002793 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002794 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2795 if (VT == MVT::i8) {
2796 // Copy the first operand into AL, which is an implicit input to the
2797 // X86::IMUL8r instruction.
2798 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2799 TII.get(TargetOpcode::COPY), X86::AL)
2800 .addReg(LHSReg, getKillRegState(LHSIsKill));
2801 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2802 RHSIsKill);
2803 } else
2804 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2805 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2806 RHSReg, RHSIsKill);
2807 }
2808
2809 if (!ResultReg)
2810 return false;
2811
2812 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2813 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2814 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2815 ResultReg2);
2816
2817 updateValueMap(II, ResultReg, 2);
2818 return true;
2819 }
2820 case Intrinsic::x86_sse_cvttss2si:
2821 case Intrinsic::x86_sse_cvttss2si64:
2822 case Intrinsic::x86_sse2_cvttsd2si:
2823 case Intrinsic::x86_sse2_cvttsd2si64: {
2824 bool IsInputDouble;
2825 switch (II->getIntrinsicID()) {
2826 default: llvm_unreachable("Unexpected intrinsic.");
2827 case Intrinsic::x86_sse_cvttss2si:
2828 case Intrinsic::x86_sse_cvttss2si64:
2829 if (!Subtarget->hasSSE1())
2830 return false;
2831 IsInputDouble = false;
2832 break;
2833 case Intrinsic::x86_sse2_cvttsd2si:
2834 case Intrinsic::x86_sse2_cvttsd2si64:
2835 if (!Subtarget->hasSSE2())
2836 return false;
2837 IsInputDouble = true;
2838 break;
2839 }
2840
2841 Type *RetTy = II->getCalledFunction()->getReturnType();
2842 MVT VT;
2843 if (!isTypeLegal(RetTy, VT))
2844 return false;
2845
Craig Topper66111882016-06-02 04:19:42 +00002846 static const uint16_t CvtOpc[2][2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002847 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2848 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2849 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2850 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2851 };
2852 bool HasAVX = Subtarget->hasAVX();
2853 unsigned Opc;
2854 switch (VT.SimpleTy) {
2855 default: llvm_unreachable("Unexpected result type.");
2856 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2857 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2858 }
2859
2860 // Check if we can fold insertelement instructions into the convert.
2861 const Value *Op = II->getArgOperand(0);
2862 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2863 const Value *Index = IE->getOperand(2);
2864 if (!isa<ConstantInt>(Index))
2865 break;
2866 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2867
2868 if (Idx == 0) {
2869 Op = IE->getOperand(1);
2870 break;
2871 }
2872 Op = IE->getOperand(0);
2873 }
2874
2875 unsigned Reg = getRegForValue(Op);
2876 if (Reg == 0)
2877 return false;
2878
2879 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2880 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2881 .addReg(Reg);
2882
2883 updateValueMap(II, ResultReg);
2884 return true;
2885 }
2886 }
2887}
2888
2889bool X86FastISel::fastLowerArguments() {
2890 if (!FuncInfo.CanLowerReturn)
2891 return false;
2892
2893 const Function *F = FuncInfo.Fn;
2894 if (F->isVarArg())
2895 return false;
2896
2897 CallingConv::ID CC = F->getCallingConv();
2898 if (CC != CallingConv::C)
2899 return false;
2900
2901 if (Subtarget->isCallingConvWin64(CC))
2902 return false;
2903
2904 if (!Subtarget->is64Bit())
2905 return false;
2906
2907 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2908 unsigned GPRCnt = 0;
2909 unsigned FPRCnt = 0;
2910 unsigned Idx = 0;
2911 for (auto const &Arg : F->args()) {
2912 // The first argument is at index 1.
2913 ++Idx;
2914 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2915 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2916 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
Manman Renf46262e2016-03-29 17:37:21 +00002917 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
Manman Ren57518142016-04-11 21:08:06 +00002918 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002919 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2920 return false;
2921
2922 Type *ArgTy = Arg.getType();
2923 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2924 return false;
2925
Mehdi Amini44ede332015-07-09 02:09:04 +00002926 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002927 if (!ArgVT.isSimple()) return false;
2928 switch (ArgVT.getSimpleVT().SimpleTy) {
2929 default: return false;
2930 case MVT::i32:
2931 case MVT::i64:
2932 ++GPRCnt;
2933 break;
2934 case MVT::f32:
2935 case MVT::f64:
2936 if (!Subtarget->hasSSE1())
2937 return false;
2938 ++FPRCnt;
2939 break;
2940 }
2941
2942 if (GPRCnt > 6)
2943 return false;
2944
2945 if (FPRCnt > 8)
2946 return false;
2947 }
2948
2949 static const MCPhysReg GPR32ArgRegs[] = {
2950 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2951 };
2952 static const MCPhysReg GPR64ArgRegs[] = {
2953 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2954 };
2955 static const MCPhysReg XMMArgRegs[] = {
2956 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2957 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2958 };
2959
2960 unsigned GPRIdx = 0;
2961 unsigned FPRIdx = 0;
2962 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002963 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002964 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2965 unsigned SrcReg;
2966 switch (VT.SimpleTy) {
2967 default: llvm_unreachable("Unexpected value type.");
2968 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2969 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2970 case MVT::f32: // fall-through
2971 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2972 }
2973 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2974 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2975 // Without this, EmitLiveInCopies may eliminate the livein if its only
2976 // use is a bitcast (which isn't turned into an instruction).
2977 unsigned ResultReg = createResultReg(RC);
2978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2979 TII.get(TargetOpcode::COPY), ResultReg)
2980 .addReg(DstReg, getKillRegState(true));
2981 updateValueMap(&Arg, ResultReg);
2982 }
2983 return true;
2984}
2985
2986static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2987 CallingConv::ID CC,
2988 ImmutableCallSite *CS) {
2989 if (Subtarget->is64Bit())
2990 return 0;
2991 if (Subtarget->getTargetTriple().isOSMSVCRT())
2992 return 0;
2993 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2994 CC == CallingConv::HiPE)
2995 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00002996
2997 if (CS)
2998 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00002999 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00003000 return 0;
3001
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003002 return 4;
3003}
3004
3005bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3006 auto &OutVals = CLI.OutVals;
3007 auto &OutFlags = CLI.OutFlags;
3008 auto &OutRegs = CLI.OutRegs;
3009 auto &Ins = CLI.Ins;
3010 auto &InRegs = CLI.InRegs;
3011 CallingConv::ID CC = CLI.CallConv;
3012 bool &IsTailCall = CLI.IsTailCall;
3013 bool IsVarArg = CLI.IsVarArg;
3014 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003015 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003016
3017 bool Is64Bit = Subtarget->is64Bit();
3018 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3019
3020 // Handle only C, fastcc, and webkit_js calling conventions for now.
3021 switch (CC) {
3022 default: return false;
3023 case CallingConv::C:
3024 case CallingConv::Fast:
3025 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00003026 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003027 case CallingConv::X86_FastCall:
3028 case CallingConv::X86_64_Win64:
3029 case CallingConv::X86_64_SysV:
3030 break;
3031 }
3032
3033 // Allow SelectionDAG isel to handle tail calls.
3034 if (IsTailCall)
3035 return false;
3036
3037 // fastcc with -tailcallopt is intended to provide a guaranteed
3038 // tail call optimization. Fastisel doesn't know how to do that.
3039 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3040 return false;
3041
3042 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3043 // x86-32. Special handling for x86-64 is implemented.
3044 if (IsVarArg && IsWin64)
3045 return false;
3046
3047 // Don't know about inalloca yet.
3048 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3049 return false;
3050
Manman Ren57518142016-04-11 21:08:06 +00003051 for (auto Flag : CLI.OutFlags)
3052 if (Flag.isSwiftError())
3053 return false;
3054
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003055 // Fast-isel doesn't know about callee-pop yet.
3056 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3057 TM.Options.GuaranteedTailCallOpt))
3058 return false;
3059
3060 SmallVector<MVT, 16> OutVTs;
3061 SmallVector<unsigned, 16> ArgRegs;
3062
3063 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3064 // instruction. This is safe because it is common to all FastISel supported
3065 // calling conventions on x86.
3066 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3067 Value *&Val = OutVals[i];
3068 ISD::ArgFlagsTy Flags = OutFlags[i];
3069 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3070 if (CI->getBitWidth() < 32) {
3071 if (Flags.isSExt())
3072 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3073 else
3074 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3075 }
3076 }
3077
3078 // Passing bools around ends up doing a trunc to i1 and passing it.
3079 // Codegen this as an argument + "and 1".
3080 MVT VT;
3081 auto *TI = dyn_cast<TruncInst>(Val);
3082 unsigned ResultReg;
3083 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3084 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3085 TI->hasOneUse()) {
3086 Value *PrevVal = TI->getOperand(0);
3087 ResultReg = getRegForValue(PrevVal);
3088
3089 if (!ResultReg)
3090 return false;
3091
3092 if (!isTypeLegal(PrevVal->getType(), VT))
3093 return false;
3094
3095 ResultReg =
3096 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3097 } else {
3098 if (!isTypeLegal(Val->getType(), VT))
3099 return false;
3100 ResultReg = getRegForValue(Val);
3101 }
3102
3103 if (!ResultReg)
3104 return false;
3105
3106 ArgRegs.push_back(ResultReg);
3107 OutVTs.push_back(VT);
3108 }
3109
3110 // Analyze operands of the call, assigning locations to each operand.
3111 SmallVector<CCValAssign, 16> ArgLocs;
3112 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3113
3114 // Allocate shadow area for Win64
3115 if (IsWin64)
3116 CCInfo.AllocateStack(32, 8);
3117
3118 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3119
3120 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00003121 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003122
3123 // Issue CALLSEQ_START
3124 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3125 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00003126 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003127
3128 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00003129 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003130 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3131 CCValAssign const &VA = ArgLocs[i];
3132 const Value *ArgVal = OutVals[VA.getValNo()];
3133 MVT ArgVT = OutVTs[VA.getValNo()];
3134
3135 if (ArgVT == MVT::x86mmx)
3136 return false;
3137
3138 unsigned ArgReg = ArgRegs[VA.getValNo()];
3139
3140 // Promote the value if needed.
3141 switch (VA.getLocInfo()) {
3142 case CCValAssign::Full: break;
3143 case CCValAssign::SExt: {
3144 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3145 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003146
3147 if (ArgVT.SimpleTy == MVT::i1)
3148 return false;
3149
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003150 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3151 ArgVT, ArgReg);
3152 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3153 ArgVT = VA.getLocVT();
3154 break;
3155 }
3156 case CCValAssign::ZExt: {
3157 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3158 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003159
3160 // Handle zero-extension from i1 to i8, which is common.
3161 if (ArgVT.SimpleTy == MVT::i1) {
3162 // Set the high bits to zero.
3163 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3164 ArgVT = MVT::i8;
3165
3166 if (ArgReg == 0)
3167 return false;
3168 }
3169
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003170 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3171 ArgVT, ArgReg);
3172 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3173 ArgVT = VA.getLocVT();
3174 break;
3175 }
3176 case CCValAssign::AExt: {
3177 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3178 "Unexpected extend");
3179 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3180 ArgVT, ArgReg);
3181 if (!Emitted)
3182 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3183 ArgVT, ArgReg);
3184 if (!Emitted)
3185 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3186 ArgVT, ArgReg);
3187
3188 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3189 ArgVT = VA.getLocVT();
3190 break;
3191 }
3192 case CCValAssign::BCvt: {
3193 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3194 /*TODO: Kill=*/false);
3195 assert(ArgReg && "Failed to emit a bitcast!");
3196 ArgVT = VA.getLocVT();
3197 break;
3198 }
3199 case CCValAssign::VExt:
3200 // VExt has not been implemented, so this should be impossible to reach
3201 // for now. However, fallback to Selection DAG isel once implemented.
3202 return false;
3203 case CCValAssign::AExtUpper:
3204 case CCValAssign::SExtUpper:
3205 case CCValAssign::ZExtUpper:
3206 case CCValAssign::FPExt:
3207 llvm_unreachable("Unexpected loc info!");
3208 case CCValAssign::Indirect:
3209 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3210 // support this.
3211 return false;
3212 }
3213
3214 if (VA.isRegLoc()) {
3215 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3216 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3217 OutRegs.push_back(VA.getLocReg());
3218 } else {
3219 assert(VA.isMemLoc());
3220
3221 // Don't emit stores for undef values.
3222 if (isa<UndefValue>(ArgVal))
3223 continue;
3224
3225 unsigned LocMemOffset = VA.getLocMemOffset();
3226 X86AddressMode AM;
3227 AM.Base.Reg = RegInfo->getStackRegister();
3228 AM.Disp = LocMemOffset;
3229 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3230 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3231 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003232 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3233 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003234 if (Flags.isByVal()) {
3235 X86AddressMode SrcAM;
3236 SrcAM.Base.Reg = ArgReg;
3237 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3238 return false;
3239 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3240 // If this is a really simple value, emit this with the Value* version
3241 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3242 // as it can cause us to reevaluate the argument.
3243 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3244 return false;
3245 } else {
3246 bool ValIsKill = hasTrivialKill(ArgVal);
3247 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3248 return false;
3249 }
3250 }
3251 }
3252
3253 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3254 // GOT pointer.
3255 if (Subtarget->isPICStyleGOT()) {
3256 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3257 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3258 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3259 }
3260
3261 if (Is64Bit && IsVarArg && !IsWin64) {
3262 // From AMD64 ABI document:
3263 // For calls that may call functions that use varargs or stdargs
3264 // (prototype-less calls or calls to functions containing ellipsis (...) in
3265 // the declaration) %al is used as hidden argument to specify the number
3266 // of SSE registers used. The contents of %al do not need to match exactly
3267 // the number of registers, but must be an ubound on the number of SSE
3268 // registers used and is in the range 0 - 8 inclusive.
3269
3270 // Count the number of XMM registers allocated.
3271 static const MCPhysReg XMMArgRegs[] = {
3272 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3273 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3274 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003275 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003276 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3277 && "SSE registers cannot be used when SSE is disabled");
3278 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3279 X86::AL).addImm(NumXMMRegs);
3280 }
3281
3282 // Materialize callee address in a register. FIXME: GV address can be
3283 // handled with a CALLpcrel32 instead.
3284 X86AddressMode CalleeAM;
3285 if (!X86SelectCallAddress(Callee, CalleeAM))
3286 return false;
3287
3288 unsigned CalleeOp = 0;
3289 const GlobalValue *GV = nullptr;
3290 if (CalleeAM.GV != nullptr) {
3291 GV = CalleeAM.GV;
3292 } else if (CalleeAM.Base.Reg != 0) {
3293 CalleeOp = CalleeAM.Base.Reg;
3294 } else
3295 return false;
3296
3297 // Issue the call.
3298 MachineInstrBuilder MIB;
3299 if (CalleeOp) {
3300 // Register-indirect call.
3301 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3302 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3303 .addReg(CalleeOp);
3304 } else {
3305 // Direct call.
3306 assert(GV && "Not a direct call");
3307 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3308
3309 // See if we need any target-specific flags on the GV operand.
Rafael Espindola46107b92016-05-19 18:49:29 +00003310 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
Asaf Badouh89406d12016-04-20 08:32:57 +00003311 // Ignore NonLazyBind attribute in FastISel
3312 if (OpFlags == X86II::MO_GOTPCREL)
3313 OpFlags = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003314
3315 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003316 if (Symbol)
3317 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003318 else
3319 MIB.addGlobalAddress(GV, 0, OpFlags);
3320 }
3321
3322 // Add a register mask operand representing the call-preserved registers.
3323 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003324 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003325
3326 // Add an implicit use GOT pointer in EBX.
3327 if (Subtarget->isPICStyleGOT())
3328 MIB.addReg(X86::EBX, RegState::Implicit);
3329
3330 if (Is64Bit && IsVarArg && !IsWin64)
3331 MIB.addReg(X86::AL, RegState::Implicit);
3332
3333 // Add implicit physical register uses to the call.
3334 for (auto Reg : OutRegs)
3335 MIB.addReg(Reg, RegState::Implicit);
3336
3337 // Issue CALLSEQ_END
3338 unsigned NumBytesForCalleeToPop =
3339 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3340 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3341 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3342 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3343
3344 // Now handle call return values.
3345 SmallVector<CCValAssign, 16> RVLocs;
3346 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3347 CLI.RetTy->getContext());
3348 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3349
3350 // Copy all of the result registers out of their specified physreg.
3351 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3352 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3353 CCValAssign &VA = RVLocs[i];
3354 EVT CopyVT = VA.getValVT();
3355 unsigned CopyReg = ResultReg + i;
3356
3357 // If this is x86-64, and we disabled SSE, we can't return FP values
3358 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3359 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3360 report_fatal_error("SSE register return with SSE disabled");
3361 }
3362
3363 // If we prefer to use the value in xmm registers, copy it out as f80 and
3364 // use a truncate to move it from fp stack reg to xmm reg.
3365 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3366 isScalarFPTypeInSSEReg(VA.getValVT())) {
3367 CopyVT = MVT::f80;
3368 CopyReg = createResultReg(&X86::RFP80RegClass);
3369 }
3370
3371 // Copy out the result.
3372 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3373 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3374 InRegs.push_back(VA.getLocReg());
3375
3376 // Round the f80 to the right size, which also moves it to the appropriate
3377 // xmm register. This is accomplished by storing the f80 value in memory
3378 // and then loading it back.
3379 if (CopyVT != VA.getValVT()) {
3380 EVT ResVT = VA.getValVT();
3381 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3382 unsigned MemSize = ResVT.getSizeInBits()/8;
3383 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3384 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3385 TII.get(Opc)), FI)
3386 .addReg(CopyReg);
3387 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3388 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3389 TII.get(Opc), ResultReg + i), FI);
3390 }
3391 }
3392
3393 CLI.ResultReg = ResultReg;
3394 CLI.NumResultRegs = RVLocs.size();
3395 CLI.Call = MIB;
3396
3397 return true;
3398}
3399
3400bool
3401X86FastISel::fastSelectInstruction(const Instruction *I) {
3402 switch (I->getOpcode()) {
3403 default: break;
3404 case Instruction::Load:
3405 return X86SelectLoad(I);
3406 case Instruction::Store:
3407 return X86SelectStore(I);
3408 case Instruction::Ret:
3409 return X86SelectRet(I);
3410 case Instruction::ICmp:
3411 case Instruction::FCmp:
3412 return X86SelectCmp(I);
3413 case Instruction::ZExt:
3414 return X86SelectZExt(I);
3415 case Instruction::Br:
3416 return X86SelectBranch(I);
3417 case Instruction::LShr:
3418 case Instruction::AShr:
3419 case Instruction::Shl:
3420 return X86SelectShift(I);
3421 case Instruction::SDiv:
3422 case Instruction::UDiv:
3423 case Instruction::SRem:
3424 case Instruction::URem:
3425 return X86SelectDivRem(I);
3426 case Instruction::Select:
3427 return X86SelectSelect(I);
3428 case Instruction::Trunc:
3429 return X86SelectTrunc(I);
3430 case Instruction::FPExt:
3431 return X86SelectFPExt(I);
3432 case Instruction::FPTrunc:
3433 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003434 case Instruction::SIToFP:
3435 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003436 case Instruction::IntToPtr: // Deliberate fall-through.
3437 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003438 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3439 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003440 if (DstVT.bitsGT(SrcVT))
3441 return X86SelectZExt(I);
3442 if (DstVT.bitsLT(SrcVT))
3443 return X86SelectTrunc(I);
3444 unsigned Reg = getRegForValue(I->getOperand(0));
3445 if (Reg == 0) return false;
3446 updateValueMap(I, Reg);
3447 return true;
3448 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003449 case Instruction::BitCast: {
3450 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3451 if (!Subtarget->hasSSE2())
3452 return false;
3453
3454 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3455 EVT DstVT = TLI.getValueType(DL, I->getType());
3456
3457 if (!SrcVT.isSimple() || !DstVT.isSimple())
3458 return false;
3459
3460 if (!SrcVT.is128BitVector() &&
3461 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3462 return false;
3463
3464 unsigned Reg = getRegForValue(I->getOperand(0));
3465 if (Reg == 0)
3466 return false;
3467
3468 // No instruction is needed for conversion. Reuse the register used by
3469 // the fist operand.
3470 updateValueMap(I, Reg);
3471 return true;
3472 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003473 }
3474
3475 return false;
3476}
3477
3478unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3479 if (VT > MVT::i64)
3480 return 0;
3481
3482 uint64_t Imm = CI->getZExtValue();
3483 if (Imm == 0) {
3484 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3485 switch (VT.SimpleTy) {
3486 default: llvm_unreachable("Unexpected value type");
3487 case MVT::i1:
3488 case MVT::i8:
3489 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3490 X86::sub_8bit);
3491 case MVT::i16:
3492 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3493 X86::sub_16bit);
3494 case MVT::i32:
3495 return SrcReg;
3496 case MVT::i64: {
3497 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3498 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3499 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3500 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3501 return ResultReg;
3502 }
3503 }
3504 }
3505
3506 unsigned Opc = 0;
3507 switch (VT.SimpleTy) {
3508 default: llvm_unreachable("Unexpected value type");
3509 case MVT::i1: VT = MVT::i8; // fall-through
3510 case MVT::i8: Opc = X86::MOV8ri; break;
3511 case MVT::i16: Opc = X86::MOV16ri; break;
3512 case MVT::i32: Opc = X86::MOV32ri; break;
3513 case MVT::i64: {
3514 if (isUInt<32>(Imm))
3515 Opc = X86::MOV32ri;
3516 else if (isInt<32>(Imm))
3517 Opc = X86::MOV64ri32;
3518 else
3519 Opc = X86::MOV64ri;
3520 break;
3521 }
3522 }
3523 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3524 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3525 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3526 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3527 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3528 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3529 return ResultReg;
3530 }
3531 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3532}
3533
3534unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3535 if (CFP->isNullValue())
3536 return fastMaterializeFloatZero(CFP);
3537
3538 // Can't handle alternate code models yet.
3539 CodeModel::Model CM = TM.getCodeModel();
3540 if (CM != CodeModel::Small && CM != CodeModel::Large)
3541 return 0;
3542
3543 // Get opcode and regclass of the output for the given load instruction.
3544 unsigned Opc = 0;
3545 const TargetRegisterClass *RC = nullptr;
3546 switch (VT.SimpleTy) {
3547 default: return 0;
3548 case MVT::f32:
3549 if (X86ScalarSSEf32) {
3550 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3551 RC = &X86::FR32RegClass;
3552 } else {
3553 Opc = X86::LD_Fp32m;
3554 RC = &X86::RFP32RegClass;
3555 }
3556 break;
3557 case MVT::f64:
3558 if (X86ScalarSSEf64) {
3559 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3560 RC = &X86::FR64RegClass;
3561 } else {
3562 Opc = X86::LD_Fp64m;
3563 RC = &X86::RFP64RegClass;
3564 }
3565 break;
3566 case MVT::f80:
3567 // No f80 support yet.
3568 return 0;
3569 }
3570
3571 // MachineConstantPool wants an explicit alignment.
3572 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3573 if (Align == 0) {
3574 // Alignment of vector types. FIXME!
3575 Align = DL.getTypeAllocSize(CFP->getType());
3576 }
3577
3578 // x86-32 PIC requires a PIC base register for constant pools.
3579 unsigned PICBase = 0;
Rafael Espindolac7e98132016-05-20 12:20:10 +00003580 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3581 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003582 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003583 else if (OpFlag == X86II::MO_GOTOFF)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003584 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003585 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003586 PICBase = X86::RIP;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003587
3588 // Create the load from the constant pool.
3589 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3590 unsigned ResultReg = createResultReg(RC);
3591
3592 if (CM == CodeModel::Large) {
3593 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3594 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3595 AddrReg)
3596 .addConstantPoolIndex(CPI, 0, OpFlag);
3597 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3598 TII.get(Opc), ResultReg);
3599 addDirectMem(MIB, AddrReg);
3600 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003601 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3602 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003603 MIB->addMemOperand(*FuncInfo.MF, MMO);
3604 return ResultReg;
3605 }
3606
3607 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3608 TII.get(Opc), ResultReg),
3609 CPI, PICBase, OpFlag);
3610 return ResultReg;
3611}
3612
3613unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3614 // Can't handle alternate code models yet.
3615 if (TM.getCodeModel() != CodeModel::Small)
3616 return 0;
3617
3618 // Materialize addresses with LEA/MOV instructions.
3619 X86AddressMode AM;
3620 if (X86SelectAddress(GV, AM)) {
3621 // If the expression is just a basereg, then we're done, otherwise we need
3622 // to emit an LEA.
3623 if (AM.BaseType == X86AddressMode::RegBase &&
3624 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3625 return AM.Base.Reg;
3626
3627 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3628 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003629 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003630 // The displacement code could be more than 32 bits away so we need to use
3631 // an instruction with a 64 bit immediate
3632 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3633 ResultReg)
3634 .addGlobalAddress(GV);
3635 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003636 unsigned Opc =
3637 TLI.getPointerTy(DL) == MVT::i32
3638 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3639 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003640 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3641 TII.get(Opc), ResultReg), AM);
3642 }
3643 return ResultReg;
3644 }
3645 return 0;
3646}
3647
3648unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003649 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003650
3651 // Only handle simple types.
3652 if (!CEVT.isSimple())
3653 return 0;
3654 MVT VT = CEVT.getSimpleVT();
3655
3656 if (const auto *CI = dyn_cast<ConstantInt>(C))
3657 return X86MaterializeInt(CI, VT);
3658 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3659 return X86MaterializeFP(CFP, VT);
3660 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3661 return X86MaterializeGV(GV, VT);
3662
3663 return 0;
3664}
3665
3666unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3667 // Fail on dynamic allocas. At this point, getRegForValue has already
3668 // checked its CSE maps, so if we're here trying to handle a dynamic
3669 // alloca, we're not going to succeed. X86SelectAddress has a
3670 // check for dynamic allocas, because it's called directly from
3671 // various places, but targetMaterializeAlloca also needs a check
3672 // in order to avoid recursion between getRegForValue,
3673 // X86SelectAddrss, and targetMaterializeAlloca.
3674 if (!FuncInfo.StaticAllocaMap.count(C))
3675 return 0;
3676 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3677
3678 X86AddressMode AM;
3679 if (!X86SelectAddress(C, AM))
3680 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003681 unsigned Opc =
3682 TLI.getPointerTy(DL) == MVT::i32
3683 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3684 : X86::LEA64r;
3685 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003686 unsigned ResultReg = createResultReg(RC);
3687 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3688 TII.get(Opc), ResultReg), AM);
3689 return ResultReg;
3690}
3691
3692unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3693 MVT VT;
3694 if (!isTypeLegal(CF->getType(), VT))
3695 return 0;
3696
3697 // Get opcode and regclass for the given zero.
3698 unsigned Opc = 0;
3699 const TargetRegisterClass *RC = nullptr;
3700 switch (VT.SimpleTy) {
3701 default: return 0;
3702 case MVT::f32:
3703 if (X86ScalarSSEf32) {
3704 Opc = X86::FsFLD0SS;
3705 RC = &X86::FR32RegClass;
3706 } else {
3707 Opc = X86::LD_Fp032;
3708 RC = &X86::RFP32RegClass;
3709 }
3710 break;
3711 case MVT::f64:
3712 if (X86ScalarSSEf64) {
3713 Opc = X86::FsFLD0SD;
3714 RC = &X86::FR64RegClass;
3715 } else {
3716 Opc = X86::LD_Fp064;
3717 RC = &X86::RFP64RegClass;
3718 }
3719 break;
3720 case MVT::f80:
3721 // No f80 support yet.
3722 return 0;
3723 }
3724
3725 unsigned ResultReg = createResultReg(RC);
3726 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3727 return ResultReg;
3728}
3729
3730
3731bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3732 const LoadInst *LI) {
3733 const Value *Ptr = LI->getPointerOperand();
3734 X86AddressMode AM;
3735 if (!X86SelectAddress(Ptr, AM))
3736 return false;
3737
3738 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3739
3740 unsigned Size = DL.getTypeAllocSize(LI->getType());
3741 unsigned Alignment = LI->getAlignment();
3742
3743 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3744 Alignment = DL.getABITypeAlignment(LI->getType());
3745
3746 SmallVector<MachineOperand, 8> AddrOps;
3747 AM.getFullAddress(AddrOps);
3748
Keno Fischere70b31f2015-06-08 20:09:58 +00003749 MachineInstr *Result = XII.foldMemoryOperandImpl(
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00003750 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
Keno Fischere70b31f2015-06-08 20:09:58 +00003751 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003752 if (!Result)
3753 return false;
3754
Pete Cooperd31583d2015-05-06 21:37:19 +00003755 // The index register could be in the wrong register class. Unfortunately,
3756 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3757 // to just look at OpNo + the offset to the index reg. We actually need to
3758 // scan the instruction to find the index reg and see if its the correct reg
3759 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003760 unsigned OperandNo = 0;
3761 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3762 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3763 MachineOperand &MO = *I;
3764 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003765 continue;
3766 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003767 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003768 MO.getReg(), OperandNo);
3769 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003770 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003771 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003772 }
3773
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003774 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003775 MI->eraseFromParent();
3776 return true;
3777}
3778
3779
3780namespace llvm {
3781 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3782 const TargetLibraryInfo *libInfo) {
3783 return new X86FastISel(funcInfo, libInfo);
3784 }
3785}