blob: e9aabeba236bd28e457a037625561d3def25c6a9 [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 &&
1154 CC != CallingConv::X86_64_SysV)
1155 return false;
1156
1157 if (Subtarget->isCallingConvWin64(CC))
1158 return false;
1159
1160 // Don't handle popping bytes on return for now.
1161 if (X86MFInfo->getBytesToPopOnReturn() != 0)
1162 return false;
1163
1164 // fastcc with -tailcallopt is intended to provide a guaranteed
1165 // tail call optimization. Fastisel doesn't know how to do that.
1166 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1167 return false;
1168
1169 // Let SDISel handle vararg functions.
1170 if (F.isVarArg())
1171 return false;
1172
1173 // Build a list of return value registers.
1174 SmallVector<unsigned, 4> RetRegs;
1175
1176 if (Ret->getNumOperands() > 0) {
1177 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001178 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001179
1180 // Analyze operands of the call, assigning locations to each operand.
1181 SmallVector<CCValAssign, 16> ValLocs;
1182 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1183 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1184
1185 const Value *RV = Ret->getOperand(0);
1186 unsigned Reg = getRegForValue(RV);
1187 if (Reg == 0)
1188 return false;
1189
1190 // Only handle a single return value for now.
1191 if (ValLocs.size() != 1)
1192 return false;
1193
1194 CCValAssign &VA = ValLocs[0];
1195
1196 // Don't bother handling odd stuff for now.
1197 if (VA.getLocInfo() != CCValAssign::Full)
1198 return false;
1199 // Only handle register returns for now.
1200 if (!VA.isRegLoc())
1201 return false;
1202
1203 // The calling-convention tables for x87 returns don't tell
1204 // the whole story.
1205 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1206 return false;
1207
1208 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001209 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001210 EVT DstVT = VA.getValVT();
1211 // Special handling for extended integers.
1212 if (SrcVT != DstVT) {
1213 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1214 return false;
1215
1216 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1217 return false;
1218
1219 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1220
1221 if (SrcVT == MVT::i1) {
1222 if (Outs[0].Flags.isSExt())
1223 return false;
1224 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1225 SrcVT = MVT::i8;
1226 }
1227 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1228 ISD::SIGN_EXTEND;
1229 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1230 SrcReg, /*TODO: Kill=*/false);
1231 }
1232
1233 // Make the copy.
1234 unsigned DstReg = VA.getLocReg();
1235 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1236 // Avoid a cross-class copy. This is very unlikely.
1237 if (!SrcRC->contains(DstReg))
1238 return false;
1239 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1240 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1241
1242 // Add register to return instruction.
1243 RetRegs.push_back(VA.getLocReg());
1244 }
1245
Manman Ren1c3f65a2016-04-26 18:08:06 +00001246 // Swift calling convention does not require we copy the sret argument
1247 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1248
Dimitry Andric227b9282016-01-03 17:22:03 +00001249 // All x86 ABIs require that for returning structs by value we copy
1250 // the sret argument into %rax/%eax (depending on ABI) for the return.
1251 // We saved the argument into a virtual register in the entry block,
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00001252 // so now we copy the value out and into %rax/%eax.
Manman Ren1c3f65a2016-04-26 18:08:06 +00001253 if (F.hasStructRetAttr() && CC != CallingConv::Swift) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001254 unsigned Reg = X86MFInfo->getSRetReturnReg();
1255 assert(Reg &&
1256 "SRetReturnReg should have been set in LowerFormalArguments()!");
1257 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1259 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1260 RetRegs.push_back(RetReg);
1261 }
1262
1263 // Now emit the RET.
1264 MachineInstrBuilder MIB =
1265 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1266 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1267 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1268 MIB.addReg(RetRegs[i], RegState::Implicit);
1269 return true;
1270}
1271
1272/// X86SelectLoad - Select and emit code to implement load instructions.
1273///
1274bool X86FastISel::X86SelectLoad(const Instruction *I) {
1275 const LoadInst *LI = cast<LoadInst>(I);
1276
1277 // Atomic loads need special handling.
1278 if (LI->isAtomic())
1279 return false;
1280
Manman Ren57518142016-04-11 21:08:06 +00001281 const Value *SV = I->getOperand(0);
1282 if (TLI.supportSwiftError()) {
1283 // Swifterror values can come from either a function parameter with
1284 // swifterror attribute or an alloca with swifterror attribute.
1285 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1286 if (Arg->hasSwiftErrorAttr())
1287 return false;
1288 }
1289
1290 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1291 if (Alloca->isSwiftError())
1292 return false;
1293 }
1294 }
1295
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001296 MVT VT;
1297 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1298 return false;
1299
1300 const Value *Ptr = LI->getPointerOperand();
1301
1302 X86AddressMode AM;
1303 if (!X86SelectAddress(Ptr, AM))
1304 return false;
1305
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001306 unsigned Alignment = LI->getAlignment();
1307 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1308 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1309 Alignment = ABIAlignment;
1310
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001311 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001312 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1313 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001314 return false;
1315
1316 updateValueMap(I, ResultReg);
1317 return true;
1318}
1319
1320static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1321 bool HasAVX = Subtarget->hasAVX();
1322 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1323 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1324
1325 switch (VT.getSimpleVT().SimpleTy) {
1326 default: return 0;
1327 case MVT::i8: return X86::CMP8rr;
1328 case MVT::i16: return X86::CMP16rr;
1329 case MVT::i32: return X86::CMP32rr;
1330 case MVT::i64: return X86::CMP64rr;
1331 case MVT::f32:
1332 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1333 case MVT::f64:
1334 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1335 }
1336}
1337
Rafael Espindola19141f22015-03-16 14:05:49 +00001338/// If we have a comparison with RHS as the RHS of the comparison, return an
1339/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001340static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001341 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001342 switch (VT.getSimpleVT().SimpleTy) {
1343 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001344 default:
1345 return 0;
1346 case MVT::i8:
1347 return X86::CMP8ri;
1348 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001349 if (isInt<8>(Val))
1350 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001351 return X86::CMP16ri;
1352 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001353 if (isInt<8>(Val))
1354 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001355 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001356 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001357 if (isInt<8>(Val))
1358 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001359 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1360 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001361 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001362 return X86::CMP64ri32;
1363 return 0;
1364 }
1365}
1366
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001367bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1368 const DebugLoc &CurDbgLoc) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001369 unsigned Op0Reg = getRegForValue(Op0);
1370 if (Op0Reg == 0) return false;
1371
1372 // Handle 'null' like i32/i64 0.
1373 if (isa<ConstantPointerNull>(Op1))
1374 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1375
1376 // We have two options: compare with register or immediate. If the RHS of
1377 // the compare is an immediate that we can fold into this compare, use
1378 // CMPri, otherwise use CMPrr.
1379 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1380 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1381 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1382 .addReg(Op0Reg)
1383 .addImm(Op1C->getSExtValue());
1384 return true;
1385 }
1386 }
1387
1388 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1389 if (CompareOpc == 0) return false;
1390
1391 unsigned Op1Reg = getRegForValue(Op1);
1392 if (Op1Reg == 0) return false;
1393 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1394 .addReg(Op0Reg)
1395 .addReg(Op1Reg);
1396
1397 return true;
1398}
1399
1400bool X86FastISel::X86SelectCmp(const Instruction *I) {
1401 const CmpInst *CI = cast<CmpInst>(I);
1402
1403 MVT VT;
1404 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1405 return false;
1406
1407 // Try to optimize or fold the cmp.
1408 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1409 unsigned ResultReg = 0;
1410 switch (Predicate) {
1411 default: break;
1412 case CmpInst::FCMP_FALSE: {
1413 ResultReg = createResultReg(&X86::GR32RegClass);
1414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1415 ResultReg);
1416 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1417 X86::sub_8bit);
1418 if (!ResultReg)
1419 return false;
1420 break;
1421 }
1422 case CmpInst::FCMP_TRUE: {
1423 ResultReg = createResultReg(&X86::GR8RegClass);
1424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1425 ResultReg).addImm(1);
1426 break;
1427 }
1428 }
1429
1430 if (ResultReg) {
1431 updateValueMap(I, ResultReg);
1432 return true;
1433 }
1434
1435 const Value *LHS = CI->getOperand(0);
1436 const Value *RHS = CI->getOperand(1);
1437
1438 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1439 // We don't have to materialize a zero constant for this case and can just use
1440 // %x again on the RHS.
1441 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1442 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1443 if (RHSC && RHSC->isNullValue())
1444 RHS = LHS;
1445 }
1446
1447 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1448 static unsigned SETFOpcTable[2][3] = {
1449 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1450 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1451 };
1452 unsigned *SETFOpc = nullptr;
1453 switch (Predicate) {
1454 default: break;
1455 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1456 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1457 }
1458
1459 ResultReg = createResultReg(&X86::GR8RegClass);
1460 if (SETFOpc) {
1461 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1462 return false;
1463
1464 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1465 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1466 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1467 FlagReg1);
1468 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1469 FlagReg2);
1470 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1471 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1472 updateValueMap(I, ResultReg);
1473 return true;
1474 }
1475
1476 X86::CondCode CC;
1477 bool SwapArgs;
1478 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1479 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1480 unsigned Opc = X86::getSETFromCond(CC);
1481
1482 if (SwapArgs)
1483 std::swap(LHS, RHS);
1484
1485 // Emit a compare of LHS/RHS.
1486 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1487 return false;
1488
1489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1490 updateValueMap(I, ResultReg);
1491 return true;
1492}
1493
1494bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001495 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001496 if (!TLI.isTypeLegal(DstVT))
1497 return false;
1498
1499 unsigned ResultReg = getRegForValue(I->getOperand(0));
1500 if (ResultReg == 0)
1501 return false;
1502
1503 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001504 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001505 if (SrcVT.SimpleTy == MVT::i1) {
1506 // Set the high bits to zero.
1507 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1508 SrcVT = MVT::i8;
1509
1510 if (ResultReg == 0)
1511 return false;
1512 }
1513
1514 if (DstVT == MVT::i64) {
1515 // Handle extension to 64-bits via sub-register shenanigans.
1516 unsigned MovInst;
1517
1518 switch (SrcVT.SimpleTy) {
1519 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1520 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1521 case MVT::i32: MovInst = X86::MOV32rr; break;
1522 default: llvm_unreachable("Unexpected zext to i64 source type");
1523 }
1524
1525 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1526 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1527 .addReg(ResultReg);
1528
1529 ResultReg = createResultReg(&X86::GR64RegClass);
1530 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1531 ResultReg)
1532 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1533 } else if (DstVT != MVT::i8) {
1534 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1535 ResultReg, /*Kill=*/true);
1536 if (ResultReg == 0)
1537 return false;
1538 }
1539
1540 updateValueMap(I, ResultReg);
1541 return true;
1542}
1543
1544bool X86FastISel::X86SelectBranch(const Instruction *I) {
1545 // Unconditional branches are selected by tablegen-generated code.
1546 // Handle a conditional branch.
1547 const BranchInst *BI = cast<BranchInst>(I);
1548 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1549 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1550
1551 // Fold the common case of a conditional branch with a comparison
1552 // in the same block (values defined on other blocks may not have
1553 // initialized registers).
1554 X86::CondCode CC;
1555 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1556 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001557 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001558
1559 // Try to optimize or fold the cmp.
1560 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1561 switch (Predicate) {
1562 default: break;
1563 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1564 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1565 }
1566
1567 const Value *CmpLHS = CI->getOperand(0);
1568 const Value *CmpRHS = CI->getOperand(1);
1569
1570 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1571 // 0.0.
1572 // We don't have to materialize a zero constant for this case and can just
1573 // use %x again on the RHS.
1574 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1575 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1576 if (CmpRHSC && CmpRHSC->isNullValue())
1577 CmpRHS = CmpLHS;
1578 }
1579
1580 // Try to take advantage of fallthrough opportunities.
1581 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1582 std::swap(TrueMBB, FalseMBB);
1583 Predicate = CmpInst::getInversePredicate(Predicate);
1584 }
1585
1586 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1587 // code check. Instead two branch instructions are required to check all
1588 // the flags. First we change the predicate to a supported condition code,
1589 // which will be the first branch. Later one we will emit the second
1590 // branch.
1591 bool NeedExtraBranch = false;
1592 switch (Predicate) {
1593 default: break;
1594 case CmpInst::FCMP_OEQ:
1595 std::swap(TrueMBB, FalseMBB); // fall-through
1596 case CmpInst::FCMP_UNE:
1597 NeedExtraBranch = true;
1598 Predicate = CmpInst::FCMP_ONE;
1599 break;
1600 }
1601
1602 bool SwapArgs;
1603 unsigned BranchOpc;
1604 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1605 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1606
1607 BranchOpc = X86::GetCondBranchFromCond(CC);
1608 if (SwapArgs)
1609 std::swap(CmpLHS, CmpRHS);
1610
1611 // Emit a compare of the LHS and RHS, setting the flags.
1612 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1613 return false;
1614
1615 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1616 .addMBB(TrueMBB);
1617
1618 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1619 // to UNE above).
1620 if (NeedExtraBranch) {
1621 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1622 .addMBB(TrueMBB);
1623 }
1624
Matthias Braun17af6072015-08-26 01:38:00 +00001625 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001626 return true;
1627 }
1628 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1629 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1630 // typically happen for _Bool and C++ bools.
1631 MVT SourceVT;
1632 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1633 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1634 unsigned TestOpc = 0;
1635 switch (SourceVT.SimpleTy) {
1636 default: break;
1637 case MVT::i8: TestOpc = X86::TEST8ri; break;
1638 case MVT::i16: TestOpc = X86::TEST16ri; break;
1639 case MVT::i32: TestOpc = X86::TEST32ri; break;
1640 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1641 }
1642 if (TestOpc) {
1643 unsigned OpReg = getRegForValue(TI->getOperand(0));
1644 if (OpReg == 0) return false;
1645 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1646 .addReg(OpReg).addImm(1);
1647
1648 unsigned JmpOpc = X86::JNE_1;
1649 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1650 std::swap(TrueMBB, FalseMBB);
1651 JmpOpc = X86::JE_1;
1652 }
1653
1654 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1655 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001656
1657 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001658 return true;
1659 }
1660 }
1661 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1662 // Fake request the condition, otherwise the intrinsic might be completely
1663 // optimized away.
1664 unsigned TmpReg = getRegForValue(BI->getCondition());
1665 if (TmpReg == 0)
1666 return false;
1667
1668 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1669
1670 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1671 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001672 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001673 return true;
1674 }
1675
1676 // Otherwise do a clumsy setcc and re-test it.
1677 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1678 // in an explicit cast, so make sure to handle that correctly.
1679 unsigned OpReg = getRegForValue(BI->getCondition());
1680 if (OpReg == 0) return false;
1681
1682 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1683 .addReg(OpReg).addImm(1);
1684 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1685 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001686 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001687 return true;
1688}
1689
1690bool X86FastISel::X86SelectShift(const Instruction *I) {
1691 unsigned CReg = 0, OpReg = 0;
1692 const TargetRegisterClass *RC = nullptr;
1693 if (I->getType()->isIntegerTy(8)) {
1694 CReg = X86::CL;
1695 RC = &X86::GR8RegClass;
1696 switch (I->getOpcode()) {
1697 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1698 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1699 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1700 default: return false;
1701 }
1702 } else if (I->getType()->isIntegerTy(16)) {
1703 CReg = X86::CX;
1704 RC = &X86::GR16RegClass;
1705 switch (I->getOpcode()) {
1706 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1707 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1708 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1709 default: return false;
1710 }
1711 } else if (I->getType()->isIntegerTy(32)) {
1712 CReg = X86::ECX;
1713 RC = &X86::GR32RegClass;
1714 switch (I->getOpcode()) {
1715 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1716 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1717 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1718 default: return false;
1719 }
1720 } else if (I->getType()->isIntegerTy(64)) {
1721 CReg = X86::RCX;
1722 RC = &X86::GR64RegClass;
1723 switch (I->getOpcode()) {
1724 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1725 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1726 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1727 default: return false;
1728 }
1729 } else {
1730 return false;
1731 }
1732
1733 MVT VT;
1734 if (!isTypeLegal(I->getType(), VT))
1735 return false;
1736
1737 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1738 if (Op0Reg == 0) return false;
1739
1740 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1741 if (Op1Reg == 0) return false;
1742 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1743 CReg).addReg(Op1Reg);
1744
1745 // The shift instruction uses X86::CL. If we defined a super-register
1746 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1747 if (CReg != X86::CL)
1748 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1749 TII.get(TargetOpcode::KILL), X86::CL)
1750 .addReg(CReg, RegState::Kill);
1751
1752 unsigned ResultReg = createResultReg(RC);
1753 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1754 .addReg(Op0Reg);
1755 updateValueMap(I, ResultReg);
1756 return true;
1757}
1758
1759bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1760 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1761 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1762 const static bool S = true; // IsSigned
1763 const static bool U = false; // !IsSigned
1764 const static unsigned Copy = TargetOpcode::COPY;
1765 // For the X86 DIV/IDIV instruction, in most cases the dividend
1766 // (numerator) must be in a specific register pair highreg:lowreg,
1767 // producing the quotient in lowreg and the remainder in highreg.
1768 // For most data types, to set up the instruction, the dividend is
1769 // copied into lowreg, and lowreg is sign-extended or zero-extended
1770 // into highreg. The exception is i8, where the dividend is defined
1771 // as a single register rather than a register pair, and we
1772 // therefore directly sign-extend or zero-extend the dividend into
1773 // lowreg, instead of copying, and ignore the highreg.
1774 const static struct DivRemEntry {
1775 // The following portion depends only on the data type.
1776 const TargetRegisterClass *RC;
1777 unsigned LowInReg; // low part of the register pair
1778 unsigned HighInReg; // high part of the register pair
1779 // The following portion depends on both the data type and the operation.
1780 struct DivRemResult {
1781 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1782 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1783 // highreg, or copying a zero into highreg.
1784 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1785 // zero/sign-extending into lowreg for i8.
1786 unsigned DivRemResultReg; // Register containing the desired result.
1787 bool IsOpSigned; // Whether to use signed or unsigned form.
1788 } ResultTable[NumOps];
1789 } OpTable[NumTypes] = {
1790 { &X86::GR8RegClass, X86::AX, 0, {
1791 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1792 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1793 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1794 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1795 }
1796 }, // i8
1797 { &X86::GR16RegClass, X86::AX, X86::DX, {
1798 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1799 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1800 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1801 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1802 }
1803 }, // i16
1804 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1805 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1806 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1807 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1808 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1809 }
1810 }, // i32
1811 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1812 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1813 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1814 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1815 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1816 }
1817 }, // i64
1818 };
1819
1820 MVT VT;
1821 if (!isTypeLegal(I->getType(), VT))
1822 return false;
1823
1824 unsigned TypeIndex, OpIndex;
1825 switch (VT.SimpleTy) {
1826 default: return false;
1827 case MVT::i8: TypeIndex = 0; break;
1828 case MVT::i16: TypeIndex = 1; break;
1829 case MVT::i32: TypeIndex = 2; break;
1830 case MVT::i64: TypeIndex = 3;
1831 if (!Subtarget->is64Bit())
1832 return false;
1833 break;
1834 }
1835
1836 switch (I->getOpcode()) {
1837 default: llvm_unreachable("Unexpected div/rem opcode");
1838 case Instruction::SDiv: OpIndex = 0; break;
1839 case Instruction::SRem: OpIndex = 1; break;
1840 case Instruction::UDiv: OpIndex = 2; break;
1841 case Instruction::URem: OpIndex = 3; break;
1842 }
1843
1844 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1845 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1846 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1847 if (Op0Reg == 0)
1848 return false;
1849 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1850 if (Op1Reg == 0)
1851 return false;
1852
1853 // Move op0 into low-order input register.
1854 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1855 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1856 // Zero-extend or sign-extend into high-order input register.
1857 if (OpEntry.OpSignExtend) {
1858 if (OpEntry.IsOpSigned)
1859 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1860 TII.get(OpEntry.OpSignExtend));
1861 else {
1862 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1863 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1864 TII.get(X86::MOV32r0), Zero32);
1865
1866 // Copy the zero into the appropriate sub/super/identical physical
1867 // register. Unfortunately the operations needed are not uniform enough
1868 // to fit neatly into the table above.
1869 if (VT.SimpleTy == MVT::i16) {
1870 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1871 TII.get(Copy), TypeEntry.HighInReg)
1872 .addReg(Zero32, 0, X86::sub_16bit);
1873 } else if (VT.SimpleTy == MVT::i32) {
1874 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1875 TII.get(Copy), TypeEntry.HighInReg)
1876 .addReg(Zero32);
1877 } else if (VT.SimpleTy == MVT::i64) {
1878 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1879 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1880 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1881 }
1882 }
1883 }
1884 // Generate the DIV/IDIV instruction.
1885 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1886 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1887 // For i8 remainder, we can't reference AH directly, as we'll end
1888 // up with bogus copies like %R9B = COPY %AH. Reference AX
1889 // instead to prevent AH references in a REX instruction.
1890 //
1891 // The current assumption of the fast register allocator is that isel
1892 // won't generate explicit references to the GPR8_NOREX registers. If
1893 // the allocator and/or the backend get enhanced to be more robust in
1894 // that regard, this can be, and should be, removed.
1895 unsigned ResultReg = 0;
1896 if ((I->getOpcode() == Instruction::SRem ||
1897 I->getOpcode() == Instruction::URem) &&
1898 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1899 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1900 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1901 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1902 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1903
1904 // Shift AX right by 8 bits instead of using AH.
1905 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1906 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1907
1908 // Now reference the 8-bit subreg of the result.
1909 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1910 /*Kill=*/true, X86::sub_8bit);
1911 }
1912 // Copy the result out of the physreg if we haven't already.
1913 if (!ResultReg) {
1914 ResultReg = createResultReg(TypeEntry.RC);
1915 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1916 .addReg(OpEntry.DivRemResultReg);
1917 }
1918 updateValueMap(I, ResultReg);
1919
1920 return true;
1921}
1922
1923/// \brief Emit a conditional move instruction (if the are supported) to lower
1924/// the select.
1925bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1926 // Check if the subtarget supports these instructions.
1927 if (!Subtarget->hasCMov())
1928 return false;
1929
1930 // FIXME: Add support for i8.
1931 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1932 return false;
1933
1934 const Value *Cond = I->getOperand(0);
1935 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1936 bool NeedTest = true;
1937 X86::CondCode CC = X86::COND_NE;
1938
1939 // Optimize conditions coming from a compare if both instructions are in the
1940 // same basic block (values defined in other basic blocks may not have
1941 // initialized registers).
1942 const auto *CI = dyn_cast<CmpInst>(Cond);
1943 if (CI && (CI->getParent() == I->getParent())) {
1944 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1945
1946 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1947 static unsigned SETFOpcTable[2][3] = {
1948 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1949 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1950 };
1951 unsigned *SETFOpc = nullptr;
1952 switch (Predicate) {
1953 default: break;
1954 case CmpInst::FCMP_OEQ:
1955 SETFOpc = &SETFOpcTable[0][0];
1956 Predicate = CmpInst::ICMP_NE;
1957 break;
1958 case CmpInst::FCMP_UNE:
1959 SETFOpc = &SETFOpcTable[1][0];
1960 Predicate = CmpInst::ICMP_NE;
1961 break;
1962 }
1963
1964 bool NeedSwap;
1965 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1966 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1967
1968 const Value *CmpLHS = CI->getOperand(0);
1969 const Value *CmpRHS = CI->getOperand(1);
1970 if (NeedSwap)
1971 std::swap(CmpLHS, CmpRHS);
1972
Mehdi Amini44ede332015-07-09 02:09:04 +00001973 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001974 // Emit a compare of the LHS and RHS, setting the flags.
1975 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1976 return false;
1977
1978 if (SETFOpc) {
1979 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1980 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1981 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1982 FlagReg1);
1983 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1984 FlagReg2);
1985 auto const &II = TII.get(SETFOpc[2]);
1986 if (II.getNumDefs()) {
1987 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1988 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1989 .addReg(FlagReg2).addReg(FlagReg1);
1990 } else {
1991 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1992 .addReg(FlagReg2).addReg(FlagReg1);
1993 }
1994 }
1995 NeedTest = false;
1996 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1997 // Fake request the condition, otherwise the intrinsic might be completely
1998 // optimized away.
1999 unsigned TmpReg = getRegForValue(Cond);
2000 if (TmpReg == 0)
2001 return false;
2002
2003 NeedTest = false;
2004 }
2005
2006 if (NeedTest) {
2007 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2008 // garbage. Indeed, only the less significant bit is supposed to be
2009 // accurate. If we read more than the lsb, we may see non-zero values
2010 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2011 // the select. This is achieved by performing TEST against 1.
2012 unsigned CondReg = getRegForValue(Cond);
2013 if (CondReg == 0)
2014 return false;
2015 bool CondIsKill = hasTrivialKill(Cond);
2016
2017 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2018 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2019 }
2020
2021 const Value *LHS = I->getOperand(1);
2022 const Value *RHS = I->getOperand(2);
2023
2024 unsigned RHSReg = getRegForValue(RHS);
2025 bool RHSIsKill = hasTrivialKill(RHS);
2026
2027 unsigned LHSReg = getRegForValue(LHS);
2028 bool LHSIsKill = hasTrivialKill(LHS);
2029
2030 if (!LHSReg || !RHSReg)
2031 return false;
2032
2033 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
2034 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
2035 LHSReg, LHSIsKill);
2036 updateValueMap(I, ResultReg);
2037 return true;
2038}
2039
Sanjay Patel302404b2015-03-05 21:46:54 +00002040/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002041///
2042/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2043/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00002044/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002045bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2046 // Optimize conditions coming from a compare if both instructions are in the
2047 // same basic block (values defined in other basic blocks may not have
2048 // initialized registers).
2049 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2050 if (!CI || (CI->getParent() != I->getParent()))
2051 return false;
2052
2053 if (I->getType() != CI->getOperand(0)->getType() ||
2054 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2055 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2056 return false;
2057
2058 const Value *CmpLHS = CI->getOperand(0);
2059 const Value *CmpRHS = CI->getOperand(1);
2060 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2061
2062 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2063 // We don't have to materialize a zero constant for this case and can just use
2064 // %x again on the RHS.
2065 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2066 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2067 if (CmpRHSC && CmpRHSC->isNullValue())
2068 CmpRHS = CmpLHS;
2069 }
2070
2071 unsigned CC;
2072 bool NeedSwap;
2073 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2074 if (CC > 7)
2075 return false;
2076
2077 if (NeedSwap)
2078 std::swap(CmpLHS, CmpRHS);
2079
Sanjay Patel302404b2015-03-05 21:46:54 +00002080 // Choose the SSE instruction sequence based on data type (float or double).
2081 static unsigned OpcTable[2][4] = {
2082 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
2083 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002084 };
2085
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002086 unsigned *Opc = nullptr;
2087 switch (RetVT.SimpleTy) {
2088 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00002089 case MVT::f32: Opc = &OpcTable[0][0]; break;
2090 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002091 }
2092
2093 const Value *LHS = I->getOperand(1);
2094 const Value *RHS = I->getOperand(2);
2095
2096 unsigned LHSReg = getRegForValue(LHS);
2097 bool LHSIsKill = hasTrivialKill(LHS);
2098
2099 unsigned RHSReg = getRegForValue(RHS);
2100 bool RHSIsKill = hasTrivialKill(RHS);
2101
2102 unsigned CmpLHSReg = getRegForValue(CmpLHS);
2103 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
2104
2105 unsigned CmpRHSReg = getRegForValue(CmpRHS);
2106 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
2107
2108 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
2109 return false;
2110
2111 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00002112 unsigned ResultReg;
2113
2114 if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00002115 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
2116 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2117
Sanjay Patel302404b2015-03-05 21:46:54 +00002118 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2119 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2120 // uses XMM0 as the selection register. That may need just as many
2121 // instructions as the AND/ANDN/OR sequence due to register moves, so
2122 // don't bother.
2123 unsigned CmpOpcode =
2124 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
2125 unsigned BlendOpcode =
2126 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2127
Matthias Braun818c78d2015-08-31 18:25:11 +00002128 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00002129 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00002130 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2131 LHSReg, LHSIsKill, CmpReg, true);
2132 ResultReg = createResultReg(RC);
2133 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2134 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002135 } else {
2136 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2137 CmpRHSReg, CmpRHSIsKill, CC);
2138 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
2139 LHSReg, LHSIsKill);
2140 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
2141 RHSReg, RHSIsKill);
2142 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
2143 AndReg, /*IsKill=*/true);
2144 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002145 updateValueMap(I, ResultReg);
2146 return true;
2147}
2148
2149bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2150 // These are pseudo CMOV instructions and will be later expanded into control-
2151 // flow.
2152 unsigned Opc;
2153 switch (RetVT.SimpleTy) {
2154 default: return false;
2155 case MVT::i8: Opc = X86::CMOV_GR8; break;
2156 case MVT::i16: Opc = X86::CMOV_GR16; break;
2157 case MVT::i32: Opc = X86::CMOV_GR32; break;
2158 case MVT::f32: Opc = X86::CMOV_FR32; break;
2159 case MVT::f64: Opc = X86::CMOV_FR64; break;
2160 }
2161
2162 const Value *Cond = I->getOperand(0);
2163 X86::CondCode CC = X86::COND_NE;
2164
2165 // Optimize conditions coming from a compare if both instructions are in the
2166 // same basic block (values defined in other basic blocks may not have
2167 // initialized registers).
2168 const auto *CI = dyn_cast<CmpInst>(Cond);
2169 if (CI && (CI->getParent() == I->getParent())) {
2170 bool NeedSwap;
2171 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2172 if (CC > X86::LAST_VALID_COND)
2173 return false;
2174
2175 const Value *CmpLHS = CI->getOperand(0);
2176 const Value *CmpRHS = CI->getOperand(1);
2177
2178 if (NeedSwap)
2179 std::swap(CmpLHS, CmpRHS);
2180
Mehdi Amini44ede332015-07-09 02:09:04 +00002181 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002182 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2183 return false;
2184 } else {
2185 unsigned CondReg = getRegForValue(Cond);
2186 if (CondReg == 0)
2187 return false;
2188 bool CondIsKill = hasTrivialKill(Cond);
2189 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2190 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2191 }
2192
2193 const Value *LHS = I->getOperand(1);
2194 const Value *RHS = I->getOperand(2);
2195
2196 unsigned LHSReg = getRegForValue(LHS);
2197 bool LHSIsKill = hasTrivialKill(LHS);
2198
2199 unsigned RHSReg = getRegForValue(RHS);
2200 bool RHSIsKill = hasTrivialKill(RHS);
2201
2202 if (!LHSReg || !RHSReg)
2203 return false;
2204
2205 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2206
2207 unsigned ResultReg =
2208 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2209 updateValueMap(I, ResultReg);
2210 return true;
2211}
2212
2213bool X86FastISel::X86SelectSelect(const Instruction *I) {
2214 MVT RetVT;
2215 if (!isTypeLegal(I->getType(), RetVT))
2216 return false;
2217
2218 // Check if we can fold the select.
2219 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2220 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2221 const Value *Opnd = nullptr;
2222 switch (Predicate) {
2223 default: break;
2224 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2225 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2226 }
2227 // No need for a select anymore - this is an unconditional move.
2228 if (Opnd) {
2229 unsigned OpReg = getRegForValue(Opnd);
2230 if (OpReg == 0)
2231 return false;
2232 bool OpIsKill = hasTrivialKill(Opnd);
2233 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2234 unsigned ResultReg = createResultReg(RC);
2235 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2236 TII.get(TargetOpcode::COPY), ResultReg)
2237 .addReg(OpReg, getKillRegState(OpIsKill));
2238 updateValueMap(I, ResultReg);
2239 return true;
2240 }
2241 }
2242
2243 // First try to use real conditional move instructions.
2244 if (X86FastEmitCMoveSelect(RetVT, I))
2245 return true;
2246
2247 // Try to use a sequence of SSE instructions to simulate a conditional move.
2248 if (X86FastEmitSSESelect(RetVT, I))
2249 return true;
2250
2251 // Fall-back to pseudo conditional move instructions, which will be later
2252 // converted to control-flow.
2253 if (X86FastEmitPseudoSelect(RetVT, I))
2254 return true;
2255
2256 return false;
2257}
2258
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002259bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002260 // The target-independent selection algorithm in FastISel already knows how
2261 // to select a SINT_TO_FP if the target is SSE but not AVX.
2262 // Early exit if the subtarget doesn't have AVX.
2263 if (!Subtarget->hasAVX())
2264 return false;
2265
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002266 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2267 return false;
2268
2269 // Select integer to float/double conversion.
2270 unsigned OpReg = getRegForValue(I->getOperand(0));
2271 if (OpReg == 0)
2272 return false;
2273
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002274 const TargetRegisterClass *RC = nullptr;
2275 unsigned Opcode;
2276
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002277 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002278 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002279 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002280 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002281 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002282 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002283 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002284 RC = &X86::FR32RegClass;
2285 } else
2286 return false;
2287
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002288 unsigned ImplicitDefReg = createResultReg(RC);
2289 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2290 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2291 unsigned ResultReg =
2292 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002293 updateValueMap(I, ResultReg);
2294 return true;
2295}
2296
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002297// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2298bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2299 unsigned TargetOpc,
2300 const TargetRegisterClass *RC) {
2301 assert((I->getOpcode() == Instruction::FPExt ||
2302 I->getOpcode() == Instruction::FPTrunc) &&
2303 "Instruction must be an FPExt or FPTrunc!");
2304
2305 unsigned OpReg = getRegForValue(I->getOperand(0));
2306 if (OpReg == 0)
2307 return false;
2308
2309 unsigned ResultReg = createResultReg(RC);
2310 MachineInstrBuilder MIB;
2311 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2312 ResultReg);
2313 if (Subtarget->hasAVX())
2314 MIB.addReg(OpReg);
2315 MIB.addReg(OpReg);
2316 updateValueMap(I, ResultReg);
2317 return true;
2318}
2319
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002320bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002321 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2322 I->getOperand(0)->getType()->isFloatTy()) {
2323 // fpext from float to double.
2324 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2325 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002326 }
2327
2328 return false;
2329}
2330
2331bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002332 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2333 I->getOperand(0)->getType()->isDoubleTy()) {
2334 // fptrunc from double to float.
2335 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2336 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002337 }
2338
2339 return false;
2340}
2341
2342bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002343 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2344 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002345
2346 // This code only handles truncation to byte.
2347 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2348 return false;
2349 if (!TLI.isTypeLegal(SrcVT))
2350 return false;
2351
2352 unsigned InputReg = getRegForValue(I->getOperand(0));
2353 if (!InputReg)
2354 // Unhandled operand. Halt "fast" selection and bail.
2355 return false;
2356
2357 if (SrcVT == MVT::i8) {
2358 // Truncate from i8 to i1; no code needed.
2359 updateValueMap(I, InputReg);
2360 return true;
2361 }
2362
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002363 bool KillInputReg = false;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002364 if (!Subtarget->is64Bit()) {
2365 // If we're on x86-32; we can't extract an i8 from a general register.
2366 // First issue a copy to GR16_ABCD or GR32_ABCD.
2367 const TargetRegisterClass *CopyRC =
2368 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2369 unsigned CopyReg = createResultReg(CopyRC);
2370 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2371 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2372 InputReg = CopyReg;
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002373 KillInputReg = true;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002374 }
2375
2376 // Issue an extract_subreg.
2377 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002378 InputReg, KillInputReg,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002379 X86::sub_8bit);
2380 if (!ResultReg)
2381 return false;
2382
2383 updateValueMap(I, ResultReg);
2384 return true;
2385}
2386
2387bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2388 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2389}
2390
2391bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2392 X86AddressMode SrcAM, uint64_t Len) {
2393
2394 // Make sure we don't bloat code by inlining very large memcpy's.
2395 if (!IsMemcpySmall(Len))
2396 return false;
2397
2398 bool i64Legal = Subtarget->is64Bit();
2399
2400 // We don't care about alignment here since we just emit integer accesses.
2401 while (Len) {
2402 MVT VT;
2403 if (Len >= 8 && i64Legal)
2404 VT = MVT::i64;
2405 else if (Len >= 4)
2406 VT = MVT::i32;
2407 else if (Len >= 2)
2408 VT = MVT::i16;
2409 else
2410 VT = MVT::i8;
2411
2412 unsigned Reg;
2413 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2414 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2415 assert(RV && "Failed to emit load or store??");
2416
2417 unsigned Size = VT.getSizeInBits()/8;
2418 Len -= Size;
2419 DestAM.Disp += Size;
2420 SrcAM.Disp += Size;
2421 }
2422
2423 return true;
2424}
2425
2426bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2427 // FIXME: Handle more intrinsics.
2428 switch (II->getIntrinsicID()) {
2429 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002430 case Intrinsic::convert_from_fp16:
2431 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002432 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002433 return false;
2434
2435 const Value *Op = II->getArgOperand(0);
2436 unsigned InputReg = getRegForValue(Op);
2437 if (InputReg == 0)
2438 return false;
2439
2440 // F16C only allows converting from float to half and from half to float.
2441 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2442 if (IsFloatToHalf) {
2443 if (!Op->getType()->isFloatTy())
2444 return false;
2445 } else {
2446 if (!II->getType()->isFloatTy())
2447 return false;
2448 }
2449
2450 unsigned ResultReg = 0;
2451 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2452 if (IsFloatToHalf) {
2453 // 'InputReg' is implicitly promoted from register class FR32 to
2454 // register class VR128 by method 'constrainOperandRegClass' which is
2455 // directly called by 'fastEmitInst_ri'.
2456 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
Ahmed Bougacha68a8efa2016-02-02 01:44:03 +00002457 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2458 // It's consistent with the other FP instructions, which are usually
2459 // controlled by MXCSR.
2460 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
Andrea Di Biagio70351782015-02-20 19:37:14 +00002461
2462 // Move the lower 32-bits of ResultReg to another register of class GR32.
2463 ResultReg = createResultReg(&X86::GR32RegClass);
2464 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2465 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2466 .addReg(InputReg, RegState::Kill);
2467
2468 // The result value is in the lower 16-bits of ResultReg.
2469 unsigned RegIdx = X86::sub_16bit;
2470 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2471 } else {
2472 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2473 // Explicitly sign-extend the input to 32-bit.
2474 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2475 /*Kill=*/false);
2476
2477 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2478 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2479 InputReg, /*Kill=*/true);
2480
2481 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2482
2483 // The result value is in the lower 32-bits of ResultReg.
2484 // Emit an explicit copy from register class VR128 to register class FR32.
2485 ResultReg = createResultReg(&X86::FR32RegClass);
2486 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2487 TII.get(TargetOpcode::COPY), ResultReg)
2488 .addReg(InputReg, RegState::Kill);
2489 }
2490
2491 updateValueMap(II, ResultReg);
2492 return true;
2493 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002494 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002495 MachineFunction *MF = FuncInfo.MF;
2496 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2497 return false;
2498
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002499 Type *RetTy = II->getCalledFunction()->getReturnType();
2500
2501 MVT VT;
2502 if (!isTypeLegal(RetTy, VT))
2503 return false;
2504
2505 unsigned Opc;
2506 const TargetRegisterClass *RC = nullptr;
2507
2508 switch (VT.SimpleTy) {
2509 default: llvm_unreachable("Invalid result type for frameaddress.");
2510 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2511 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2512 }
2513
2514 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2515 // we get the wrong frame register.
David Majnemerca194852015-02-10 22:00:34 +00002516 MachineFrameInfo *MFI = MF->getFrameInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002517 MFI->setFrameAddressIsTaken(true);
2518
Eric Christophera1c535b2015-02-02 23:03:45 +00002519 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002520 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002521 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2522 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2523 "Invalid Frame Register!");
2524
2525 // Always make a copy of the frame register to to a vreg first, so that we
2526 // never directly reference the frame register (the TwoAddressInstruction-
2527 // Pass doesn't like that).
2528 unsigned SrcReg = createResultReg(RC);
2529 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2530 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2531
2532 // Now recursively load from the frame address.
2533 // movq (%rbp), %rax
2534 // movq (%rax), %rax
2535 // movq (%rax), %rax
2536 // ...
2537 unsigned DestReg;
2538 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2539 while (Depth--) {
2540 DestReg = createResultReg(RC);
2541 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2542 TII.get(Opc), DestReg), SrcReg);
2543 SrcReg = DestReg;
2544 }
2545
2546 updateValueMap(II, SrcReg);
2547 return true;
2548 }
2549 case Intrinsic::memcpy: {
2550 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2551 // Don't handle volatile or variable length memcpys.
2552 if (MCI->isVolatile())
2553 return false;
2554
2555 if (isa<ConstantInt>(MCI->getLength())) {
2556 // Small memcpy's are common enough that we want to do them
2557 // without a call if possible.
2558 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2559 if (IsMemcpySmall(Len)) {
2560 X86AddressMode DestAM, SrcAM;
2561 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2562 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2563 return false;
2564 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2565 return true;
2566 }
2567 }
2568
2569 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2570 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2571 return false;
2572
2573 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2574 return false;
2575
Pete Cooper67cf9a72015-11-19 05:56:52 +00002576 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002577 }
2578 case Intrinsic::memset: {
2579 const MemSetInst *MSI = cast<MemSetInst>(II);
2580
2581 if (MSI->isVolatile())
2582 return false;
2583
2584 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2585 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2586 return false;
2587
2588 if (MSI->getDestAddressSpace() > 255)
2589 return false;
2590
Pete Cooper67cf9a72015-11-19 05:56:52 +00002591 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002592 }
2593 case Intrinsic::stackprotector: {
2594 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002595 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002596
2597 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2598 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2599
2600 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2601
2602 // Grab the frame index.
2603 X86AddressMode AM;
2604 if (!X86SelectAddress(Slot, AM)) return false;
2605 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2606 return true;
2607 }
2608 case Intrinsic::dbg_declare: {
2609 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2610 X86AddressMode AM;
2611 assert(DI->getAddress() && "Null address should be checked earlier!");
2612 if (!X86SelectAddress(DI->getAddress(), AM))
2613 return false;
2614 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2615 // FIXME may need to add RegState::Debug to any registers produced,
2616 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002617 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2618 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002619 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2620 .addImm(0)
2621 .addMetadata(DI->getVariable())
2622 .addMetadata(DI->getExpression());
2623 return true;
2624 }
2625 case Intrinsic::trap: {
2626 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2627 return true;
2628 }
2629 case Intrinsic::sqrt: {
2630 if (!Subtarget->hasSSE1())
2631 return false;
2632
2633 Type *RetTy = II->getCalledFunction()->getReturnType();
2634
2635 MVT VT;
2636 if (!isTypeLegal(RetTy, VT))
2637 return false;
2638
2639 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2640 // is not generated by FastISel yet.
2641 // FIXME: Update this code once tablegen can handle it.
Craig Toppercf65c622016-03-02 04:42:31 +00002642 static const uint16_t SqrtOpc[2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002643 {X86::SQRTSSr, X86::VSQRTSSr},
2644 {X86::SQRTSDr, X86::VSQRTSDr}
2645 };
2646 bool HasAVX = Subtarget->hasAVX();
2647 unsigned Opc;
2648 const TargetRegisterClass *RC;
2649 switch (VT.SimpleTy) {
2650 default: return false;
2651 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2652 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2653 }
2654
2655 const Value *SrcVal = II->getArgOperand(0);
2656 unsigned SrcReg = getRegForValue(SrcVal);
2657
2658 if (SrcReg == 0)
2659 return false;
2660
2661 unsigned ImplicitDefReg = 0;
2662 if (HasAVX) {
2663 ImplicitDefReg = createResultReg(RC);
2664 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2665 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2666 }
2667
2668 unsigned ResultReg = createResultReg(RC);
2669 MachineInstrBuilder MIB;
2670 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2671 ResultReg);
2672
2673 if (ImplicitDefReg)
2674 MIB.addReg(ImplicitDefReg);
2675
2676 MIB.addReg(SrcReg);
2677
2678 updateValueMap(II, ResultReg);
2679 return true;
2680 }
2681 case Intrinsic::sadd_with_overflow:
2682 case Intrinsic::uadd_with_overflow:
2683 case Intrinsic::ssub_with_overflow:
2684 case Intrinsic::usub_with_overflow:
2685 case Intrinsic::smul_with_overflow:
2686 case Intrinsic::umul_with_overflow: {
2687 // This implements the basic lowering of the xalu with overflow intrinsics
2688 // into add/sub/mul followed by either seto or setb.
2689 const Function *Callee = II->getCalledFunction();
2690 auto *Ty = cast<StructType>(Callee->getReturnType());
2691 Type *RetTy = Ty->getTypeAtIndex(0U);
2692 Type *CondTy = Ty->getTypeAtIndex(1);
2693
2694 MVT VT;
2695 if (!isTypeLegal(RetTy, VT))
2696 return false;
2697
2698 if (VT < MVT::i8 || VT > MVT::i64)
2699 return false;
2700
2701 const Value *LHS = II->getArgOperand(0);
2702 const Value *RHS = II->getArgOperand(1);
2703
2704 // Canonicalize immediate to the RHS.
2705 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2706 isCommutativeIntrinsic(II))
2707 std::swap(LHS, RHS);
2708
2709 bool UseIncDec = false;
2710 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2711 UseIncDec = true;
2712
2713 unsigned BaseOpc, CondOpc;
2714 switch (II->getIntrinsicID()) {
2715 default: llvm_unreachable("Unexpected intrinsic!");
2716 case Intrinsic::sadd_with_overflow:
2717 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2718 CondOpc = X86::SETOr;
2719 break;
2720 case Intrinsic::uadd_with_overflow:
2721 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2722 case Intrinsic::ssub_with_overflow:
2723 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2724 CondOpc = X86::SETOr;
2725 break;
2726 case Intrinsic::usub_with_overflow:
2727 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2728 case Intrinsic::smul_with_overflow:
2729 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2730 case Intrinsic::umul_with_overflow:
2731 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2732 }
2733
2734 unsigned LHSReg = getRegForValue(LHS);
2735 if (LHSReg == 0)
2736 return false;
2737 bool LHSIsKill = hasTrivialKill(LHS);
2738
2739 unsigned ResultReg = 0;
2740 // Check if we have an immediate version.
2741 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
Craig Topper66111882016-06-02 04:19:42 +00002742 static const uint16_t Opc[2][4] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002743 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2744 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2745 };
2746
2747 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2748 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2749 bool IsDec = BaseOpc == X86ISD::DEC;
2750 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2751 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2752 .addReg(LHSReg, getKillRegState(LHSIsKill));
2753 } else
2754 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2755 CI->getZExtValue());
2756 }
2757
2758 unsigned RHSReg;
2759 bool RHSIsKill;
2760 if (!ResultReg) {
2761 RHSReg = getRegForValue(RHS);
2762 if (RHSReg == 0)
2763 return false;
2764 RHSIsKill = hasTrivialKill(RHS);
2765 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2766 RHSIsKill);
2767 }
2768
2769 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2770 // it manually.
2771 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002772 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002773 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002774 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002775 // First copy the first operand into RAX, which is an implicit input to
2776 // the X86::MUL*r instruction.
2777 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2778 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2779 .addReg(LHSReg, getKillRegState(LHSIsKill));
2780 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2781 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2782 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002783 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002784 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2785 if (VT == MVT::i8) {
2786 // Copy the first operand into AL, which is an implicit input to the
2787 // X86::IMUL8r instruction.
2788 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2789 TII.get(TargetOpcode::COPY), X86::AL)
2790 .addReg(LHSReg, getKillRegState(LHSIsKill));
2791 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2792 RHSIsKill);
2793 } else
2794 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2795 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2796 RHSReg, RHSIsKill);
2797 }
2798
2799 if (!ResultReg)
2800 return false;
2801
2802 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2803 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2804 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2805 ResultReg2);
2806
2807 updateValueMap(II, ResultReg, 2);
2808 return true;
2809 }
2810 case Intrinsic::x86_sse_cvttss2si:
2811 case Intrinsic::x86_sse_cvttss2si64:
2812 case Intrinsic::x86_sse2_cvttsd2si:
2813 case Intrinsic::x86_sse2_cvttsd2si64: {
2814 bool IsInputDouble;
2815 switch (II->getIntrinsicID()) {
2816 default: llvm_unreachable("Unexpected intrinsic.");
2817 case Intrinsic::x86_sse_cvttss2si:
2818 case Intrinsic::x86_sse_cvttss2si64:
2819 if (!Subtarget->hasSSE1())
2820 return false;
2821 IsInputDouble = false;
2822 break;
2823 case Intrinsic::x86_sse2_cvttsd2si:
2824 case Intrinsic::x86_sse2_cvttsd2si64:
2825 if (!Subtarget->hasSSE2())
2826 return false;
2827 IsInputDouble = true;
2828 break;
2829 }
2830
2831 Type *RetTy = II->getCalledFunction()->getReturnType();
2832 MVT VT;
2833 if (!isTypeLegal(RetTy, VT))
2834 return false;
2835
Craig Topper66111882016-06-02 04:19:42 +00002836 static const uint16_t CvtOpc[2][2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002837 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2838 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2839 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2840 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2841 };
2842 bool HasAVX = Subtarget->hasAVX();
2843 unsigned Opc;
2844 switch (VT.SimpleTy) {
2845 default: llvm_unreachable("Unexpected result type.");
2846 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2847 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2848 }
2849
2850 // Check if we can fold insertelement instructions into the convert.
2851 const Value *Op = II->getArgOperand(0);
2852 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2853 const Value *Index = IE->getOperand(2);
2854 if (!isa<ConstantInt>(Index))
2855 break;
2856 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2857
2858 if (Idx == 0) {
2859 Op = IE->getOperand(1);
2860 break;
2861 }
2862 Op = IE->getOperand(0);
2863 }
2864
2865 unsigned Reg = getRegForValue(Op);
2866 if (Reg == 0)
2867 return false;
2868
2869 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2870 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2871 .addReg(Reg);
2872
2873 updateValueMap(II, ResultReg);
2874 return true;
2875 }
2876 }
2877}
2878
2879bool X86FastISel::fastLowerArguments() {
2880 if (!FuncInfo.CanLowerReturn)
2881 return false;
2882
2883 const Function *F = FuncInfo.Fn;
2884 if (F->isVarArg())
2885 return false;
2886
2887 CallingConv::ID CC = F->getCallingConv();
2888 if (CC != CallingConv::C)
2889 return false;
2890
2891 if (Subtarget->isCallingConvWin64(CC))
2892 return false;
2893
2894 if (!Subtarget->is64Bit())
2895 return false;
2896
2897 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2898 unsigned GPRCnt = 0;
2899 unsigned FPRCnt = 0;
2900 unsigned Idx = 0;
2901 for (auto const &Arg : F->args()) {
2902 // The first argument is at index 1.
2903 ++Idx;
2904 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2905 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2906 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
Manman Renf46262e2016-03-29 17:37:21 +00002907 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
Manman Ren57518142016-04-11 21:08:06 +00002908 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002909 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2910 return false;
2911
2912 Type *ArgTy = Arg.getType();
2913 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2914 return false;
2915
Mehdi Amini44ede332015-07-09 02:09:04 +00002916 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002917 if (!ArgVT.isSimple()) return false;
2918 switch (ArgVT.getSimpleVT().SimpleTy) {
2919 default: return false;
2920 case MVT::i32:
2921 case MVT::i64:
2922 ++GPRCnt;
2923 break;
2924 case MVT::f32:
2925 case MVT::f64:
2926 if (!Subtarget->hasSSE1())
2927 return false;
2928 ++FPRCnt;
2929 break;
2930 }
2931
2932 if (GPRCnt > 6)
2933 return false;
2934
2935 if (FPRCnt > 8)
2936 return false;
2937 }
2938
2939 static const MCPhysReg GPR32ArgRegs[] = {
2940 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2941 };
2942 static const MCPhysReg GPR64ArgRegs[] = {
2943 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2944 };
2945 static const MCPhysReg XMMArgRegs[] = {
2946 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2947 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2948 };
2949
2950 unsigned GPRIdx = 0;
2951 unsigned FPRIdx = 0;
2952 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002953 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002954 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2955 unsigned SrcReg;
2956 switch (VT.SimpleTy) {
2957 default: llvm_unreachable("Unexpected value type.");
2958 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2959 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2960 case MVT::f32: // fall-through
2961 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2962 }
2963 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2964 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2965 // Without this, EmitLiveInCopies may eliminate the livein if its only
2966 // use is a bitcast (which isn't turned into an instruction).
2967 unsigned ResultReg = createResultReg(RC);
2968 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2969 TII.get(TargetOpcode::COPY), ResultReg)
2970 .addReg(DstReg, getKillRegState(true));
2971 updateValueMap(&Arg, ResultReg);
2972 }
2973 return true;
2974}
2975
2976static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2977 CallingConv::ID CC,
2978 ImmutableCallSite *CS) {
2979 if (Subtarget->is64Bit())
2980 return 0;
2981 if (Subtarget->getTargetTriple().isOSMSVCRT())
2982 return 0;
2983 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2984 CC == CallingConv::HiPE)
2985 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00002986
2987 if (CS)
2988 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00002989 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00002990 return 0;
2991
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002992 return 4;
2993}
2994
2995bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2996 auto &OutVals = CLI.OutVals;
2997 auto &OutFlags = CLI.OutFlags;
2998 auto &OutRegs = CLI.OutRegs;
2999 auto &Ins = CLI.Ins;
3000 auto &InRegs = CLI.InRegs;
3001 CallingConv::ID CC = CLI.CallConv;
3002 bool &IsTailCall = CLI.IsTailCall;
3003 bool IsVarArg = CLI.IsVarArg;
3004 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003005 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003006
3007 bool Is64Bit = Subtarget->is64Bit();
3008 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3009
3010 // Handle only C, fastcc, and webkit_js calling conventions for now.
3011 switch (CC) {
3012 default: return false;
3013 case CallingConv::C:
3014 case CallingConv::Fast:
3015 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00003016 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003017 case CallingConv::X86_FastCall:
3018 case CallingConv::X86_64_Win64:
3019 case CallingConv::X86_64_SysV:
3020 break;
3021 }
3022
3023 // Allow SelectionDAG isel to handle tail calls.
3024 if (IsTailCall)
3025 return false;
3026
3027 // fastcc with -tailcallopt is intended to provide a guaranteed
3028 // tail call optimization. Fastisel doesn't know how to do that.
3029 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
3030 return false;
3031
3032 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3033 // x86-32. Special handling for x86-64 is implemented.
3034 if (IsVarArg && IsWin64)
3035 return false;
3036
3037 // Don't know about inalloca yet.
3038 if (CLI.CS && CLI.CS->hasInAllocaArgument())
3039 return false;
3040
Manman Ren57518142016-04-11 21:08:06 +00003041 for (auto Flag : CLI.OutFlags)
3042 if (Flag.isSwiftError())
3043 return false;
3044
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003045 // Fast-isel doesn't know about callee-pop yet.
3046 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3047 TM.Options.GuaranteedTailCallOpt))
3048 return false;
3049
3050 SmallVector<MVT, 16> OutVTs;
3051 SmallVector<unsigned, 16> ArgRegs;
3052
3053 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3054 // instruction. This is safe because it is common to all FastISel supported
3055 // calling conventions on x86.
3056 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3057 Value *&Val = OutVals[i];
3058 ISD::ArgFlagsTy Flags = OutFlags[i];
3059 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3060 if (CI->getBitWidth() < 32) {
3061 if (Flags.isSExt())
3062 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
3063 else
3064 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
3065 }
3066 }
3067
3068 // Passing bools around ends up doing a trunc to i1 and passing it.
3069 // Codegen this as an argument + "and 1".
3070 MVT VT;
3071 auto *TI = dyn_cast<TruncInst>(Val);
3072 unsigned ResultReg;
3073 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
3074 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
3075 TI->hasOneUse()) {
3076 Value *PrevVal = TI->getOperand(0);
3077 ResultReg = getRegForValue(PrevVal);
3078
3079 if (!ResultReg)
3080 return false;
3081
3082 if (!isTypeLegal(PrevVal->getType(), VT))
3083 return false;
3084
3085 ResultReg =
3086 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
3087 } else {
3088 if (!isTypeLegal(Val->getType(), VT))
3089 return false;
3090 ResultReg = getRegForValue(Val);
3091 }
3092
3093 if (!ResultReg)
3094 return false;
3095
3096 ArgRegs.push_back(ResultReg);
3097 OutVTs.push_back(VT);
3098 }
3099
3100 // Analyze operands of the call, assigning locations to each operand.
3101 SmallVector<CCValAssign, 16> ArgLocs;
3102 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3103
3104 // Allocate shadow area for Win64
3105 if (IsWin64)
3106 CCInfo.AllocateStack(32, 8);
3107
3108 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
3109
3110 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00003111 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003112
3113 // Issue CALLSEQ_START
3114 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3115 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00003116 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003117
3118 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00003119 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003120 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3121 CCValAssign const &VA = ArgLocs[i];
3122 const Value *ArgVal = OutVals[VA.getValNo()];
3123 MVT ArgVT = OutVTs[VA.getValNo()];
3124
3125 if (ArgVT == MVT::x86mmx)
3126 return false;
3127
3128 unsigned ArgReg = ArgRegs[VA.getValNo()];
3129
3130 // Promote the value if needed.
3131 switch (VA.getLocInfo()) {
3132 case CCValAssign::Full: break;
3133 case CCValAssign::SExt: {
3134 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3135 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003136
3137 if (ArgVT.SimpleTy == MVT::i1)
3138 return false;
3139
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003140 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3141 ArgVT, ArgReg);
3142 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3143 ArgVT = VA.getLocVT();
3144 break;
3145 }
3146 case CCValAssign::ZExt: {
3147 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3148 "Unexpected extend");
David Majnemer2c5aeab2016-05-04 00:22:23 +00003149
3150 // Handle zero-extension from i1 to i8, which is common.
3151 if (ArgVT.SimpleTy == MVT::i1) {
3152 // Set the high bits to zero.
3153 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg, /*TODO: Kill=*/false);
3154 ArgVT = MVT::i8;
3155
3156 if (ArgReg == 0)
3157 return false;
3158 }
3159
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003160 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3161 ArgVT, ArgReg);
3162 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3163 ArgVT = VA.getLocVT();
3164 break;
3165 }
3166 case CCValAssign::AExt: {
3167 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3168 "Unexpected extend");
3169 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3170 ArgVT, ArgReg);
3171 if (!Emitted)
3172 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3173 ArgVT, ArgReg);
3174 if (!Emitted)
3175 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3176 ArgVT, ArgReg);
3177
3178 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3179 ArgVT = VA.getLocVT();
3180 break;
3181 }
3182 case CCValAssign::BCvt: {
3183 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3184 /*TODO: Kill=*/false);
3185 assert(ArgReg && "Failed to emit a bitcast!");
3186 ArgVT = VA.getLocVT();
3187 break;
3188 }
3189 case CCValAssign::VExt:
3190 // VExt has not been implemented, so this should be impossible to reach
3191 // for now. However, fallback to Selection DAG isel once implemented.
3192 return false;
3193 case CCValAssign::AExtUpper:
3194 case CCValAssign::SExtUpper:
3195 case CCValAssign::ZExtUpper:
3196 case CCValAssign::FPExt:
3197 llvm_unreachable("Unexpected loc info!");
3198 case CCValAssign::Indirect:
3199 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3200 // support this.
3201 return false;
3202 }
3203
3204 if (VA.isRegLoc()) {
3205 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3206 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3207 OutRegs.push_back(VA.getLocReg());
3208 } else {
3209 assert(VA.isMemLoc());
3210
3211 // Don't emit stores for undef values.
3212 if (isa<UndefValue>(ArgVal))
3213 continue;
3214
3215 unsigned LocMemOffset = VA.getLocMemOffset();
3216 X86AddressMode AM;
3217 AM.Base.Reg = RegInfo->getStackRegister();
3218 AM.Disp = LocMemOffset;
3219 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3220 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3221 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003222 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3223 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003224 if (Flags.isByVal()) {
3225 X86AddressMode SrcAM;
3226 SrcAM.Base.Reg = ArgReg;
3227 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3228 return false;
3229 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3230 // If this is a really simple value, emit this with the Value* version
3231 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3232 // as it can cause us to reevaluate the argument.
3233 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3234 return false;
3235 } else {
3236 bool ValIsKill = hasTrivialKill(ArgVal);
3237 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3238 return false;
3239 }
3240 }
3241 }
3242
3243 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3244 // GOT pointer.
3245 if (Subtarget->isPICStyleGOT()) {
3246 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3247 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3248 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3249 }
3250
3251 if (Is64Bit && IsVarArg && !IsWin64) {
3252 // From AMD64 ABI document:
3253 // For calls that may call functions that use varargs or stdargs
3254 // (prototype-less calls or calls to functions containing ellipsis (...) in
3255 // the declaration) %al is used as hidden argument to specify the number
3256 // of SSE registers used. The contents of %al do not need to match exactly
3257 // the number of registers, but must be an ubound on the number of SSE
3258 // registers used and is in the range 0 - 8 inclusive.
3259
3260 // Count the number of XMM registers allocated.
3261 static const MCPhysReg XMMArgRegs[] = {
3262 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3263 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3264 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003265 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003266 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3267 && "SSE registers cannot be used when SSE is disabled");
3268 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3269 X86::AL).addImm(NumXMMRegs);
3270 }
3271
3272 // Materialize callee address in a register. FIXME: GV address can be
3273 // handled with a CALLpcrel32 instead.
3274 X86AddressMode CalleeAM;
3275 if (!X86SelectCallAddress(Callee, CalleeAM))
3276 return false;
3277
3278 unsigned CalleeOp = 0;
3279 const GlobalValue *GV = nullptr;
3280 if (CalleeAM.GV != nullptr) {
3281 GV = CalleeAM.GV;
3282 } else if (CalleeAM.Base.Reg != 0) {
3283 CalleeOp = CalleeAM.Base.Reg;
3284 } else
3285 return false;
3286
3287 // Issue the call.
3288 MachineInstrBuilder MIB;
3289 if (CalleeOp) {
3290 // Register-indirect call.
3291 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3292 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3293 .addReg(CalleeOp);
3294 } else {
3295 // Direct call.
3296 assert(GV && "Not a direct call");
3297 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3298
3299 // See if we need any target-specific flags on the GV operand.
Rafael Espindola46107b92016-05-19 18:49:29 +00003300 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
Asaf Badouh89406d12016-04-20 08:32:57 +00003301 // Ignore NonLazyBind attribute in FastISel
3302 if (OpFlags == X86II::MO_GOTPCREL)
3303 OpFlags = 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003304
3305 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003306 if (Symbol)
3307 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003308 else
3309 MIB.addGlobalAddress(GV, 0, OpFlags);
3310 }
3311
3312 // Add a register mask operand representing the call-preserved registers.
3313 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003314 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003315
3316 // Add an implicit use GOT pointer in EBX.
3317 if (Subtarget->isPICStyleGOT())
3318 MIB.addReg(X86::EBX, RegState::Implicit);
3319
3320 if (Is64Bit && IsVarArg && !IsWin64)
3321 MIB.addReg(X86::AL, RegState::Implicit);
3322
3323 // Add implicit physical register uses to the call.
3324 for (auto Reg : OutRegs)
3325 MIB.addReg(Reg, RegState::Implicit);
3326
3327 // Issue CALLSEQ_END
3328 unsigned NumBytesForCalleeToPop =
3329 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3330 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3331 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3332 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3333
3334 // Now handle call return values.
3335 SmallVector<CCValAssign, 16> RVLocs;
3336 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3337 CLI.RetTy->getContext());
3338 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3339
3340 // Copy all of the result registers out of their specified physreg.
3341 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3342 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3343 CCValAssign &VA = RVLocs[i];
3344 EVT CopyVT = VA.getValVT();
3345 unsigned CopyReg = ResultReg + i;
3346
3347 // If this is x86-64, and we disabled SSE, we can't return FP values
3348 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3349 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3350 report_fatal_error("SSE register return with SSE disabled");
3351 }
3352
3353 // If we prefer to use the value in xmm registers, copy it out as f80 and
3354 // use a truncate to move it from fp stack reg to xmm reg.
3355 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3356 isScalarFPTypeInSSEReg(VA.getValVT())) {
3357 CopyVT = MVT::f80;
3358 CopyReg = createResultReg(&X86::RFP80RegClass);
3359 }
3360
3361 // Copy out the result.
3362 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3363 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3364 InRegs.push_back(VA.getLocReg());
3365
3366 // Round the f80 to the right size, which also moves it to the appropriate
3367 // xmm register. This is accomplished by storing the f80 value in memory
3368 // and then loading it back.
3369 if (CopyVT != VA.getValVT()) {
3370 EVT ResVT = VA.getValVT();
3371 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3372 unsigned MemSize = ResVT.getSizeInBits()/8;
3373 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3374 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3375 TII.get(Opc)), FI)
3376 .addReg(CopyReg);
3377 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3378 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3379 TII.get(Opc), ResultReg + i), FI);
3380 }
3381 }
3382
3383 CLI.ResultReg = ResultReg;
3384 CLI.NumResultRegs = RVLocs.size();
3385 CLI.Call = MIB;
3386
3387 return true;
3388}
3389
3390bool
3391X86FastISel::fastSelectInstruction(const Instruction *I) {
3392 switch (I->getOpcode()) {
3393 default: break;
3394 case Instruction::Load:
3395 return X86SelectLoad(I);
3396 case Instruction::Store:
3397 return X86SelectStore(I);
3398 case Instruction::Ret:
3399 return X86SelectRet(I);
3400 case Instruction::ICmp:
3401 case Instruction::FCmp:
3402 return X86SelectCmp(I);
3403 case Instruction::ZExt:
3404 return X86SelectZExt(I);
3405 case Instruction::Br:
3406 return X86SelectBranch(I);
3407 case Instruction::LShr:
3408 case Instruction::AShr:
3409 case Instruction::Shl:
3410 return X86SelectShift(I);
3411 case Instruction::SDiv:
3412 case Instruction::UDiv:
3413 case Instruction::SRem:
3414 case Instruction::URem:
3415 return X86SelectDivRem(I);
3416 case Instruction::Select:
3417 return X86SelectSelect(I);
3418 case Instruction::Trunc:
3419 return X86SelectTrunc(I);
3420 case Instruction::FPExt:
3421 return X86SelectFPExt(I);
3422 case Instruction::FPTrunc:
3423 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003424 case Instruction::SIToFP:
3425 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003426 case Instruction::IntToPtr: // Deliberate fall-through.
3427 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003428 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3429 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003430 if (DstVT.bitsGT(SrcVT))
3431 return X86SelectZExt(I);
3432 if (DstVT.bitsLT(SrcVT))
3433 return X86SelectTrunc(I);
3434 unsigned Reg = getRegForValue(I->getOperand(0));
3435 if (Reg == 0) return false;
3436 updateValueMap(I, Reg);
3437 return true;
3438 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003439 case Instruction::BitCast: {
3440 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3441 if (!Subtarget->hasSSE2())
3442 return false;
3443
3444 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3445 EVT DstVT = TLI.getValueType(DL, I->getType());
3446
3447 if (!SrcVT.isSimple() || !DstVT.isSimple())
3448 return false;
3449
3450 if (!SrcVT.is128BitVector() &&
3451 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3452 return false;
3453
3454 unsigned Reg = getRegForValue(I->getOperand(0));
3455 if (Reg == 0)
3456 return false;
3457
3458 // No instruction is needed for conversion. Reuse the register used by
3459 // the fist operand.
3460 updateValueMap(I, Reg);
3461 return true;
3462 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003463 }
3464
3465 return false;
3466}
3467
3468unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3469 if (VT > MVT::i64)
3470 return 0;
3471
3472 uint64_t Imm = CI->getZExtValue();
3473 if (Imm == 0) {
3474 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3475 switch (VT.SimpleTy) {
3476 default: llvm_unreachable("Unexpected value type");
3477 case MVT::i1:
3478 case MVT::i8:
3479 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3480 X86::sub_8bit);
3481 case MVT::i16:
3482 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3483 X86::sub_16bit);
3484 case MVT::i32:
3485 return SrcReg;
3486 case MVT::i64: {
3487 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3488 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3489 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3490 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3491 return ResultReg;
3492 }
3493 }
3494 }
3495
3496 unsigned Opc = 0;
3497 switch (VT.SimpleTy) {
3498 default: llvm_unreachable("Unexpected value type");
3499 case MVT::i1: VT = MVT::i8; // fall-through
3500 case MVT::i8: Opc = X86::MOV8ri; break;
3501 case MVT::i16: Opc = X86::MOV16ri; break;
3502 case MVT::i32: Opc = X86::MOV32ri; break;
3503 case MVT::i64: {
3504 if (isUInt<32>(Imm))
3505 Opc = X86::MOV32ri;
3506 else if (isInt<32>(Imm))
3507 Opc = X86::MOV64ri32;
3508 else
3509 Opc = X86::MOV64ri;
3510 break;
3511 }
3512 }
3513 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3514 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3515 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3516 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3517 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3518 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3519 return ResultReg;
3520 }
3521 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3522}
3523
3524unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3525 if (CFP->isNullValue())
3526 return fastMaterializeFloatZero(CFP);
3527
3528 // Can't handle alternate code models yet.
3529 CodeModel::Model CM = TM.getCodeModel();
3530 if (CM != CodeModel::Small && CM != CodeModel::Large)
3531 return 0;
3532
3533 // Get opcode and regclass of the output for the given load instruction.
3534 unsigned Opc = 0;
3535 const TargetRegisterClass *RC = nullptr;
3536 switch (VT.SimpleTy) {
3537 default: return 0;
3538 case MVT::f32:
3539 if (X86ScalarSSEf32) {
3540 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3541 RC = &X86::FR32RegClass;
3542 } else {
3543 Opc = X86::LD_Fp32m;
3544 RC = &X86::RFP32RegClass;
3545 }
3546 break;
3547 case MVT::f64:
3548 if (X86ScalarSSEf64) {
3549 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3550 RC = &X86::FR64RegClass;
3551 } else {
3552 Opc = X86::LD_Fp64m;
3553 RC = &X86::RFP64RegClass;
3554 }
3555 break;
3556 case MVT::f80:
3557 // No f80 support yet.
3558 return 0;
3559 }
3560
3561 // MachineConstantPool wants an explicit alignment.
3562 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3563 if (Align == 0) {
3564 // Alignment of vector types. FIXME!
3565 Align = DL.getTypeAllocSize(CFP->getType());
3566 }
3567
3568 // x86-32 PIC requires a PIC base register for constant pools.
3569 unsigned PICBase = 0;
Rafael Espindolac7e98132016-05-20 12:20:10 +00003570 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3571 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003572 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003573 else if (OpFlag == X86II::MO_GOTOFF)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003574 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
Rafael Espindolac7e98132016-05-20 12:20:10 +00003575 else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003576 PICBase = X86::RIP;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003577
3578 // Create the load from the constant pool.
3579 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3580 unsigned ResultReg = createResultReg(RC);
3581
3582 if (CM == CodeModel::Large) {
3583 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3584 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3585 AddrReg)
3586 .addConstantPoolIndex(CPI, 0, OpFlag);
3587 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3588 TII.get(Opc), ResultReg);
3589 addDirectMem(MIB, AddrReg);
3590 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003591 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3592 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003593 MIB->addMemOperand(*FuncInfo.MF, MMO);
3594 return ResultReg;
3595 }
3596
3597 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3598 TII.get(Opc), ResultReg),
3599 CPI, PICBase, OpFlag);
3600 return ResultReg;
3601}
3602
3603unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3604 // Can't handle alternate code models yet.
3605 if (TM.getCodeModel() != CodeModel::Small)
3606 return 0;
3607
3608 // Materialize addresses with LEA/MOV instructions.
3609 X86AddressMode AM;
3610 if (X86SelectAddress(GV, AM)) {
3611 // If the expression is just a basereg, then we're done, otherwise we need
3612 // to emit an LEA.
3613 if (AM.BaseType == X86AddressMode::RegBase &&
3614 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3615 return AM.Base.Reg;
3616
3617 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3618 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003619 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003620 // The displacement code could be more than 32 bits away so we need to use
3621 // an instruction with a 64 bit immediate
3622 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3623 ResultReg)
3624 .addGlobalAddress(GV);
3625 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003626 unsigned Opc =
3627 TLI.getPointerTy(DL) == MVT::i32
3628 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3629 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003630 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3631 TII.get(Opc), ResultReg), AM);
3632 }
3633 return ResultReg;
3634 }
3635 return 0;
3636}
3637
3638unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003639 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003640
3641 // Only handle simple types.
3642 if (!CEVT.isSimple())
3643 return 0;
3644 MVT VT = CEVT.getSimpleVT();
3645
3646 if (const auto *CI = dyn_cast<ConstantInt>(C))
3647 return X86MaterializeInt(CI, VT);
3648 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3649 return X86MaterializeFP(CFP, VT);
3650 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3651 return X86MaterializeGV(GV, VT);
3652
3653 return 0;
3654}
3655
3656unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3657 // Fail on dynamic allocas. At this point, getRegForValue has already
3658 // checked its CSE maps, so if we're here trying to handle a dynamic
3659 // alloca, we're not going to succeed. X86SelectAddress has a
3660 // check for dynamic allocas, because it's called directly from
3661 // various places, but targetMaterializeAlloca also needs a check
3662 // in order to avoid recursion between getRegForValue,
3663 // X86SelectAddrss, and targetMaterializeAlloca.
3664 if (!FuncInfo.StaticAllocaMap.count(C))
3665 return 0;
3666 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3667
3668 X86AddressMode AM;
3669 if (!X86SelectAddress(C, AM))
3670 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003671 unsigned Opc =
3672 TLI.getPointerTy(DL) == MVT::i32
3673 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3674 : X86::LEA64r;
3675 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003676 unsigned ResultReg = createResultReg(RC);
3677 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3678 TII.get(Opc), ResultReg), AM);
3679 return ResultReg;
3680}
3681
3682unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3683 MVT VT;
3684 if (!isTypeLegal(CF->getType(), VT))
3685 return 0;
3686
3687 // Get opcode and regclass for the given zero.
3688 unsigned Opc = 0;
3689 const TargetRegisterClass *RC = nullptr;
3690 switch (VT.SimpleTy) {
3691 default: return 0;
3692 case MVT::f32:
3693 if (X86ScalarSSEf32) {
3694 Opc = X86::FsFLD0SS;
3695 RC = &X86::FR32RegClass;
3696 } else {
3697 Opc = X86::LD_Fp032;
3698 RC = &X86::RFP32RegClass;
3699 }
3700 break;
3701 case MVT::f64:
3702 if (X86ScalarSSEf64) {
3703 Opc = X86::FsFLD0SD;
3704 RC = &X86::FR64RegClass;
3705 } else {
3706 Opc = X86::LD_Fp064;
3707 RC = &X86::RFP64RegClass;
3708 }
3709 break;
3710 case MVT::f80:
3711 // No f80 support yet.
3712 return 0;
3713 }
3714
3715 unsigned ResultReg = createResultReg(RC);
3716 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3717 return ResultReg;
3718}
3719
3720
3721bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3722 const LoadInst *LI) {
3723 const Value *Ptr = LI->getPointerOperand();
3724 X86AddressMode AM;
3725 if (!X86SelectAddress(Ptr, AM))
3726 return false;
3727
3728 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3729
3730 unsigned Size = DL.getTypeAllocSize(LI->getType());
3731 unsigned Alignment = LI->getAlignment();
3732
3733 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3734 Alignment = DL.getABITypeAlignment(LI->getType());
3735
3736 SmallVector<MachineOperand, 8> AddrOps;
3737 AM.getFullAddress(AddrOps);
3738
Keno Fischere70b31f2015-06-08 20:09:58 +00003739 MachineInstr *Result = XII.foldMemoryOperandImpl(
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00003740 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
Keno Fischere70b31f2015-06-08 20:09:58 +00003741 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003742 if (!Result)
3743 return false;
3744
Pete Cooperd31583d2015-05-06 21:37:19 +00003745 // The index register could be in the wrong register class. Unfortunately,
3746 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3747 // to just look at OpNo + the offset to the index reg. We actually need to
3748 // scan the instruction to find the index reg and see if its the correct reg
3749 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003750 unsigned OperandNo = 0;
3751 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3752 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3753 MachineOperand &MO = *I;
3754 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003755 continue;
3756 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003757 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003758 MO.getReg(), OperandNo);
3759 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003760 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003761 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003762 }
3763
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003764 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003765 MI->eraseFromParent();
3766 return true;
3767}
3768
3769
3770namespace llvm {
3771 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3772 const TargetLibraryInfo *libInfo) {
3773 return new X86FastISel(funcInfo, libInfo);
3774 }
3775}