blob: 8aab37666b00b961eae79de3f991fef55030f09e [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"
25#include "llvm/CodeGen/Analysis.h"
26#include "llvm/CodeGen/FastISel.h"
27#include "llvm/CodeGen/FunctionLoweringInfo.h"
28#include "llvm/CodeGen/MachineConstantPool.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineRegisterInfo.h"
31#include "llvm/IR/CallSite.h"
32#include "llvm/IR/CallingConv.h"
33#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:
85 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT, DebugLoc DL);
86
Pete Cooperd0dae3e2015-05-05 23:41:53 +000087 bool X86FastEmitLoad(EVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +000088 unsigned &ResultReg, unsigned Alignment = 1);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000089
Pete Cooperd0dae3e2015-05-05 23:41:53 +000090 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000091 MachineMemOperand *MMO = nullptr, bool Aligned = false);
92 bool X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +000093 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000094 MachineMemOperand *MMO = nullptr, bool Aligned = false);
95
96 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
97 unsigned &ResultReg);
98
99 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
100 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
101
102 bool X86SelectLoad(const Instruction *I);
103
104 bool X86SelectStore(const Instruction *I);
105
106 bool X86SelectRet(const Instruction *I);
107
108 bool X86SelectCmp(const Instruction *I);
109
110 bool X86SelectZExt(const Instruction *I);
111
112 bool X86SelectBranch(const Instruction *I);
113
114 bool X86SelectShift(const Instruction *I);
115
116 bool X86SelectDivRem(const Instruction *I);
117
118 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
119
120 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
121
122 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
123
124 bool X86SelectSelect(const Instruction *I);
125
126 bool X86SelectTrunc(const Instruction *I);
127
Andrea Di Biagio62622d22015-02-10 12:04:41 +0000128 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
129 const TargetRegisterClass *RC);
130
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000131 bool X86SelectFPExt(const Instruction *I);
132 bool X86SelectFPTrunc(const Instruction *I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +0000133 bool X86SelectSIToFP(const Instruction *I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000134
135 const X86InstrInfo *getInstrInfo() const {
Eric Christophera1c535b2015-02-02 23:03:45 +0000136 return Subtarget->getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000137 }
138 const X86TargetMachine *getTargetMachine() const {
139 return static_cast<const X86TargetMachine *>(&TM);
140 }
141
142 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
143
144 unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
145 unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
146 unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
147 unsigned fastMaterializeConstant(const Constant *C) override;
148
149 unsigned fastMaterializeAlloca(const AllocaInst *C) override;
150
151 unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
152
153 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
154 /// computed in an SSE register, not on the X87 floating point stack.
155 bool isScalarFPTypeInSSEReg(EVT VT) const {
156 return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
157 (VT == MVT::f32 && X86ScalarSSEf32); // f32 is when SSE1
158 }
159
160 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
161
162 bool IsMemcpySmall(uint64_t Len);
163
164 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
165 X86AddressMode SrcAM, uint64_t Len);
166
167 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
168 const Value *Cond);
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000169
170 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
171 X86AddressMode &AM);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000172};
173
174} // end anonymous namespace.
175
176static std::pair<X86::CondCode, bool>
177getX86ConditionCode(CmpInst::Predicate Predicate) {
178 X86::CondCode CC = X86::COND_INVALID;
179 bool NeedSwap = false;
180 switch (Predicate) {
181 default: break;
182 // Floating-point Predicates
183 case CmpInst::FCMP_UEQ: CC = X86::COND_E; break;
184 case CmpInst::FCMP_OLT: NeedSwap = true; // fall-through
185 case CmpInst::FCMP_OGT: CC = X86::COND_A; break;
186 case CmpInst::FCMP_OLE: NeedSwap = true; // fall-through
187 case CmpInst::FCMP_OGE: CC = X86::COND_AE; break;
188 case CmpInst::FCMP_UGT: NeedSwap = true; // fall-through
189 case CmpInst::FCMP_ULT: CC = X86::COND_B; break;
190 case CmpInst::FCMP_UGE: NeedSwap = true; // fall-through
191 case CmpInst::FCMP_ULE: CC = X86::COND_BE; break;
192 case CmpInst::FCMP_ONE: CC = X86::COND_NE; break;
193 case CmpInst::FCMP_UNO: CC = X86::COND_P; break;
194 case CmpInst::FCMP_ORD: CC = X86::COND_NP; break;
195 case CmpInst::FCMP_OEQ: // fall-through
196 case CmpInst::FCMP_UNE: CC = X86::COND_INVALID; break;
197
198 // Integer Predicates
199 case CmpInst::ICMP_EQ: CC = X86::COND_E; break;
200 case CmpInst::ICMP_NE: CC = X86::COND_NE; break;
201 case CmpInst::ICMP_UGT: CC = X86::COND_A; break;
202 case CmpInst::ICMP_UGE: CC = X86::COND_AE; break;
203 case CmpInst::ICMP_ULT: CC = X86::COND_B; break;
204 case CmpInst::ICMP_ULE: CC = X86::COND_BE; break;
205 case CmpInst::ICMP_SGT: CC = X86::COND_G; break;
206 case CmpInst::ICMP_SGE: CC = X86::COND_GE; break;
207 case CmpInst::ICMP_SLT: CC = X86::COND_L; break;
208 case CmpInst::ICMP_SLE: CC = X86::COND_LE; break;
209 }
210
211 return std::make_pair(CC, NeedSwap);
212}
213
214static std::pair<unsigned, bool>
215getX86SSEConditionCode(CmpInst::Predicate Predicate) {
216 unsigned CC;
217 bool NeedSwap = false;
218
219 // SSE Condition code mapping:
220 // 0 - EQ
221 // 1 - LT
222 // 2 - LE
223 // 3 - UNORD
224 // 4 - NEQ
225 // 5 - NLT
226 // 6 - NLE
227 // 7 - ORD
228 switch (Predicate) {
229 default: llvm_unreachable("Unexpected predicate");
230 case CmpInst::FCMP_OEQ: CC = 0; break;
231 case CmpInst::FCMP_OGT: NeedSwap = true; // fall-through
232 case CmpInst::FCMP_OLT: CC = 1; break;
233 case CmpInst::FCMP_OGE: NeedSwap = true; // fall-through
234 case CmpInst::FCMP_OLE: CC = 2; break;
235 case CmpInst::FCMP_UNO: CC = 3; break;
236 case CmpInst::FCMP_UNE: CC = 4; break;
237 case CmpInst::FCMP_ULE: NeedSwap = true; // fall-through
238 case CmpInst::FCMP_UGE: CC = 5; break;
239 case CmpInst::FCMP_ULT: NeedSwap = true; // fall-through
240 case CmpInst::FCMP_UGT: CC = 6; break;
241 case CmpInst::FCMP_ORD: CC = 7; break;
242 case CmpInst::FCMP_UEQ:
243 case CmpInst::FCMP_ONE: CC = 8; break;
244 }
245
246 return std::make_pair(CC, NeedSwap);
247}
248
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000249/// \brief Adds a complex addressing mode to the given machine instr builder.
250/// Note, this will constrain the index register. If its not possible to
251/// constrain the given index register, then a new one will be created. The
252/// IndexReg field of the addressing mode will be updated to match in this case.
253const MachineInstrBuilder &
254X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
255 X86AddressMode &AM) {
256 // First constrain the index register. It needs to be a GR64_NOSP.
257 AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
258 MIB->getNumOperands() +
259 X86::AddrIndexReg);
260 return ::addFullAddress(MIB, AM);
261}
262
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000263/// \brief Check if it is possible to fold the condition from the XALU intrinsic
264/// into the user. The condition code will only be updated on success.
265bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
266 const Value *Cond) {
267 if (!isa<ExtractValueInst>(Cond))
268 return false;
269
270 const auto *EV = cast<ExtractValueInst>(Cond);
271 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
272 return false;
273
274 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
275 MVT RetVT;
276 const Function *Callee = II->getCalledFunction();
277 Type *RetTy =
278 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
279 if (!isTypeLegal(RetTy, RetVT))
280 return false;
281
282 if (RetVT != MVT::i32 && RetVT != MVT::i64)
283 return false;
284
285 X86::CondCode TmpCC;
286 switch (II->getIntrinsicID()) {
287 default: return false;
288 case Intrinsic::sadd_with_overflow:
289 case Intrinsic::ssub_with_overflow:
290 case Intrinsic::smul_with_overflow:
291 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
292 case Intrinsic::uadd_with_overflow:
293 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
294 }
295
296 // Check if both instructions are in the same basic block.
297 if (II->getParent() != I->getParent())
298 return false;
299
300 // Make sure nothing is in the way
Duncan P. N. Exon Smithd77de642015-10-19 21:48:29 +0000301 BasicBlock::const_iterator Start(I);
302 BasicBlock::const_iterator End(II);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000303 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
304 // We only expect extractvalue instructions between the intrinsic and the
305 // instruction to be selected.
306 if (!isa<ExtractValueInst>(Itr))
307 return false;
308
309 // Check that the extractvalue operand comes from the intrinsic.
310 const auto *EVI = cast<ExtractValueInst>(Itr);
311 if (EVI->getAggregateOperand() != II)
312 return false;
313 }
314
315 CC = TmpCC;
316 return true;
317}
318
319bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
Mehdi Amini44ede332015-07-09 02:09:04 +0000320 EVT evt = TLI.getValueType(DL, Ty, /*HandleUnknown=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000321 if (evt == MVT::Other || !evt.isSimple())
322 // Unhandled type. Halt "fast" selection and bail.
323 return false;
324
325 VT = evt.getSimpleVT();
326 // For now, require SSE/SSE2 for performing floating-point operations,
327 // since x87 requires additional work.
328 if (VT == MVT::f64 && !X86ScalarSSEf64)
329 return false;
330 if (VT == MVT::f32 && !X86ScalarSSEf32)
331 return false;
332 // Similarly, no f80 support yet.
333 if (VT == MVT::f80)
334 return false;
335 // We only handle legal types. For example, on x86-32 the instruction
336 // selector contains all of the 64-bit instructions from x86-64,
337 // under the assumption that i64 won't be used if the target doesn't
338 // support it.
339 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
340}
341
342#include "X86GenCallingConv.inc"
343
344/// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
345/// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
346/// Return true and the result register by reference if it is possible.
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000347bool X86FastISel::X86FastEmitLoad(EVT VT, X86AddressMode &AM,
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000348 MachineMemOperand *MMO, unsigned &ResultReg,
349 unsigned Alignment) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000350 // Get opcode and regclass of the output for the given load instruction.
351 unsigned Opc = 0;
352 const TargetRegisterClass *RC = nullptr;
353 switch (VT.getSimpleVT().SimpleTy) {
354 default: return false;
355 case MVT::i1:
356 case MVT::i8:
357 Opc = X86::MOV8rm;
358 RC = &X86::GR8RegClass;
359 break;
360 case MVT::i16:
361 Opc = X86::MOV16rm;
362 RC = &X86::GR16RegClass;
363 break;
364 case MVT::i32:
365 Opc = X86::MOV32rm;
366 RC = &X86::GR32RegClass;
367 break;
368 case MVT::i64:
369 // Must be in x86-64 mode.
370 Opc = X86::MOV64rm;
371 RC = &X86::GR64RegClass;
372 break;
373 case MVT::f32:
374 if (X86ScalarSSEf32) {
375 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
376 RC = &X86::FR32RegClass;
377 } else {
378 Opc = X86::LD_Fp32m;
379 RC = &X86::RFP32RegClass;
380 }
381 break;
382 case MVT::f64:
383 if (X86ScalarSSEf64) {
384 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
385 RC = &X86::FR64RegClass;
386 } else {
387 Opc = X86::LD_Fp64m;
388 RC = &X86::RFP64RegClass;
389 }
390 break;
391 case MVT::f80:
392 // No f80 support yet.
393 return false;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +0000394 case MVT::v4f32:
395 if (Alignment >= 16)
396 Opc = Subtarget->hasAVX() ? X86::VMOVAPSrm : X86::MOVAPSrm;
397 else
398 Opc = Subtarget->hasAVX() ? X86::VMOVUPSrm : X86::MOVUPSrm;
399 RC = &X86::VR128RegClass;
400 break;
401 case MVT::v2f64:
402 if (Alignment >= 16)
403 Opc = Subtarget->hasAVX() ? X86::VMOVAPDrm : X86::MOVAPDrm;
404 else
405 Opc = Subtarget->hasAVX() ? X86::VMOVUPDrm : X86::MOVUPDrm;
406 RC = &X86::VR128RegClass;
407 break;
408 case MVT::v4i32:
409 case MVT::v2i64:
410 case MVT::v8i16:
411 case MVT::v16i8:
412 if (Alignment >= 16)
413 Opc = Subtarget->hasAVX() ? X86::VMOVDQArm : X86::MOVDQArm;
414 else
415 Opc = Subtarget->hasAVX() ? X86::VMOVDQUrm : X86::MOVDQUrm;
416 RC = &X86::VR128RegClass;
417 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000418 }
419
420 ResultReg = createResultReg(RC);
421 MachineInstrBuilder MIB =
422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
423 addFullAddress(MIB, AM);
424 if (MMO)
425 MIB->addMemOperand(*FuncInfo.MF, MMO);
426 return true;
427}
428
429/// X86FastEmitStore - Emit a machine instruction to store a value Val of
430/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
431/// and a displacement offset, or a GlobalAddress,
432/// i.e. V. Return true if it is possible.
433bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, bool ValIsKill,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000434 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000435 MachineMemOperand *MMO, bool Aligned) {
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000436 bool HasSSE2 = Subtarget->hasSSE2();
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000437 bool HasSSE4A = Subtarget->hasSSE4A();
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000438 bool HasAVX = Subtarget->hasAVX();
439 bool IsNonTemporal = MMO && MMO->isNonTemporal();
440
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000441 // Get opcode and regclass of the output for the given store instruction.
442 unsigned Opc = 0;
443 switch (VT.getSimpleVT().SimpleTy) {
444 case MVT::f80: // No f80 support yet.
445 default: return false;
446 case MVT::i1: {
447 // Mask out all but lowest bit.
448 unsigned AndResult = createResultReg(&X86::GR8RegClass);
449 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
450 TII.get(X86::AND8ri), AndResult)
451 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
452 ValReg = AndResult;
453 }
454 // FALLTHROUGH, handling i1 as i8.
455 case MVT::i8: Opc = X86::MOV8mr; break;
456 case MVT::i16: Opc = X86::MOV16mr; break;
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000457 case MVT::i32:
458 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
459 break;
460 case MVT::i64:
461 // Must be in x86-64 mode.
462 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
463 break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000464 case MVT::f32:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000465 if (X86ScalarSSEf32) {
466 if (IsNonTemporal && HasSSE4A)
467 Opc = X86::MOVNTSS;
468 else
469 Opc = HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
470 } else
471 Opc = X86::ST_Fp32m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000472 break;
473 case MVT::f64:
Simon Pilgrim5b65f282015-10-17 13:04:42 +0000474 if (X86ScalarSSEf32) {
475 if (IsNonTemporal && HasSSE4A)
476 Opc = X86::MOVNTSD;
477 else
478 Opc = HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
479 } else
480 Opc = X86::ST_Fp64m;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000481 break;
482 case MVT::v4f32:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000483 if (Aligned) {
484 if (IsNonTemporal)
485 Opc = HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
486 else
487 Opc = HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
488 } else
489 Opc = HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000490 break;
491 case MVT::v2f64:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000492 if (Aligned) {
493 if (IsNonTemporal)
494 Opc = HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
495 else
496 Opc = HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
497 } else
498 Opc = HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000499 break;
500 case MVT::v4i32:
501 case MVT::v2i64:
502 case MVT::v8i16:
503 case MVT::v16i8:
Andrea Di Biagioc47edbe2015-10-14 10:03:13 +0000504 if (Aligned) {
505 if (IsNonTemporal)
506 Opc = HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
507 else
508 Opc = HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
509 } else
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000510 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
511 break;
512 }
513
514 MachineInstrBuilder MIB =
515 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
516 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
517 if (MMO)
518 MIB->addMemOperand(*FuncInfo.MF, MMO);
519
520 return true;
521}
522
523bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000524 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000525 MachineMemOperand *MMO, bool Aligned) {
526 // Handle 'null' like i32/i64 0.
527 if (isa<ConstantPointerNull>(Val))
528 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
529
530 // If this is a store of a simple constant, fold the constant into the store.
531 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
532 unsigned Opc = 0;
533 bool Signed = true;
534 switch (VT.getSimpleVT().SimpleTy) {
535 default: break;
536 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
537 case MVT::i8: Opc = X86::MOV8mi; break;
538 case MVT::i16: Opc = X86::MOV16mi; break;
539 case MVT::i32: Opc = X86::MOV32mi; break;
540 case MVT::i64:
541 // Must be a 32-bit sign extended value.
542 if (isInt<32>(CI->getSExtValue()))
543 Opc = X86::MOV64mi32;
544 break;
545 }
546
547 if (Opc) {
548 MachineInstrBuilder MIB =
549 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
550 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
551 : CI->getZExtValue());
552 if (MMO)
553 MIB->addMemOperand(*FuncInfo.MF, MMO);
554 return true;
555 }
556 }
557
558 unsigned ValReg = getRegForValue(Val);
559 if (ValReg == 0)
560 return false;
561
562 bool ValKill = hasTrivialKill(Val);
563 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
564}
565
566/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
567/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
568/// ISD::SIGN_EXTEND).
569bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
570 unsigned Src, EVT SrcVT,
571 unsigned &ResultReg) {
572 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
573 Src, /*TODO: Kill=*/false);
574 if (RR == 0)
575 return false;
576
577 ResultReg = RR;
578 return true;
579}
580
581bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
582 // Handle constant address.
583 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
584 // Can't handle alternate code models yet.
585 if (TM.getCodeModel() != CodeModel::Small)
586 return false;
587
588 // Can't handle TLS yet.
589 if (GV->isThreadLocal())
590 return false;
591
592 // RIP-relative addresses can't have additional register operands, so if
593 // we've already folded stuff into the addressing mode, just force the
594 // global value into its own register, which we can use as the basereg.
595 if (!Subtarget->isPICStyleRIPRel() ||
596 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
597 // Okay, we've committed to selecting this global. Set up the address.
598 AM.GV = GV;
599
600 // Allow the subtarget to classify the global.
601 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
602
603 // If this reference is relative to the pic base, set it now.
604 if (isGlobalRelativeToPICBase(GVFlags)) {
605 // FIXME: How do we know Base.Reg is free??
606 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
607 }
608
609 // Unless the ABI requires an extra load, return a direct reference to
610 // the global.
611 if (!isGlobalStubReference(GVFlags)) {
612 if (Subtarget->isPICStyleRIPRel()) {
613 // Use rip-relative addressing if we can. Above we verified that the
614 // base and index registers are unused.
615 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
616 AM.Base.Reg = X86::RIP;
617 }
618 AM.GVOpFlags = GVFlags;
619 return true;
620 }
621
622 // Ok, we need to do a load from a stub. If we've already loaded from
623 // this stub, reuse the loaded pointer, otherwise emit the load now.
624 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
625 unsigned LoadReg;
626 if (I != LocalValueMap.end() && I->second != 0) {
627 LoadReg = I->second;
628 } else {
629 // Issue load from stub.
630 unsigned Opc = 0;
631 const TargetRegisterClass *RC = nullptr;
632 X86AddressMode StubAM;
633 StubAM.Base.Reg = AM.Base.Reg;
634 StubAM.GV = GV;
635 StubAM.GVOpFlags = GVFlags;
636
637 // Prepare for inserting code in the local-value area.
638 SavePoint SaveInsertPt = enterLocalValueArea();
639
Mehdi Amini44ede332015-07-09 02:09:04 +0000640 if (TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000641 Opc = X86::MOV64rm;
642 RC = &X86::GR64RegClass;
643
644 if (Subtarget->isPICStyleRIPRel())
645 StubAM.Base.Reg = X86::RIP;
646 } else {
647 Opc = X86::MOV32rm;
648 RC = &X86::GR32RegClass;
649 }
650
651 LoadReg = createResultReg(RC);
652 MachineInstrBuilder LoadMI =
653 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
654 addFullAddress(LoadMI, StubAM);
655
656 // Ok, back to normal mode.
657 leaveLocalValueArea(SaveInsertPt);
658
659 // Prevent loading GV stub multiple times in same MBB.
660 LocalValueMap[V] = LoadReg;
661 }
662
663 // Now construct the final address. Note that the Disp, Scale,
664 // and Index values may already be set here.
665 AM.Base.Reg = LoadReg;
666 AM.GV = nullptr;
667 return true;
668 }
669 }
670
671 // If all else fails, try to materialize the value in a register.
672 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
673 if (AM.Base.Reg == 0) {
674 AM.Base.Reg = getRegForValue(V);
675 return AM.Base.Reg != 0;
676 }
677 if (AM.IndexReg == 0) {
678 assert(AM.Scale == 1 && "Scale with no index!");
679 AM.IndexReg = getRegForValue(V);
680 return AM.IndexReg != 0;
681 }
682 }
683
684 return false;
685}
686
687/// X86SelectAddress - Attempt to fill in an address from the given value.
688///
689bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
690 SmallVector<const Value *, 32> GEPs;
691redo_gep:
692 const User *U = nullptr;
693 unsigned Opcode = Instruction::UserOp1;
694 if (const Instruction *I = dyn_cast<Instruction>(V)) {
695 // Don't walk into other basic blocks; it's possible we haven't
696 // visited them yet, so the instructions may not yet be assigned
697 // virtual registers.
698 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
699 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
700 Opcode = I->getOpcode();
701 U = I;
702 }
703 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
704 Opcode = C->getOpcode();
705 U = C;
706 }
707
708 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
709 if (Ty->getAddressSpace() > 255)
710 // Fast instruction selection doesn't support the special
711 // address spaces.
712 return false;
713
714 switch (Opcode) {
715 default: break;
716 case Instruction::BitCast:
717 // Look past bitcasts.
718 return X86SelectAddress(U->getOperand(0), AM);
719
720 case Instruction::IntToPtr:
721 // Look past no-op inttoptrs.
Mehdi Amini44ede332015-07-09 02:09:04 +0000722 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
723 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000724 return X86SelectAddress(U->getOperand(0), AM);
725 break;
726
727 case Instruction::PtrToInt:
728 // Look past no-op ptrtoints.
Mehdi Amini44ede332015-07-09 02:09:04 +0000729 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000730 return X86SelectAddress(U->getOperand(0), AM);
731 break;
732
733 case Instruction::Alloca: {
734 // Do static allocas.
735 const AllocaInst *A = cast<AllocaInst>(V);
736 DenseMap<const AllocaInst *, int>::iterator SI =
737 FuncInfo.StaticAllocaMap.find(A);
738 if (SI != FuncInfo.StaticAllocaMap.end()) {
739 AM.BaseType = X86AddressMode::FrameIndexBase;
740 AM.Base.FrameIndex = SI->second;
741 return true;
742 }
743 break;
744 }
745
746 case Instruction::Add: {
747 // Adds of constants are common and easy enough.
748 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
749 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
750 // They have to fit in the 32-bit signed displacement field though.
751 if (isInt<32>(Disp)) {
752 AM.Disp = (uint32_t)Disp;
753 return X86SelectAddress(U->getOperand(0), AM);
754 }
755 }
756 break;
757 }
758
759 case Instruction::GetElementPtr: {
760 X86AddressMode SavedAM = AM;
761
762 // Pattern-match simple GEPs.
763 uint64_t Disp = (int32_t)AM.Disp;
764 unsigned IndexReg = AM.IndexReg;
765 unsigned Scale = AM.Scale;
766 gep_type_iterator GTI = gep_type_begin(U);
767 // Iterate through the indices, folding what we can. Constants can be
768 // folded, and one dynamic index can be handled, if the scale is supported.
769 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
770 i != e; ++i, ++GTI) {
771 const Value *Op = *i;
772 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
773 const StructLayout *SL = DL.getStructLayout(STy);
774 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
775 continue;
776 }
777
778 // A array/variable index is always of the form i*S where S is the
779 // constant scale size. See if we can push the scale into immediates.
780 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
781 for (;;) {
782 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
783 // Constant-offset addressing.
784 Disp += CI->getSExtValue() * S;
785 break;
786 }
787 if (canFoldAddIntoGEP(U, Op)) {
788 // A compatible add with a constant operand. Fold the constant.
789 ConstantInt *CI =
790 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
791 Disp += CI->getSExtValue() * S;
792 // Iterate on the other operand.
793 Op = cast<AddOperator>(Op)->getOperand(0);
794 continue;
795 }
796 if (IndexReg == 0 &&
797 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
798 (S == 1 || S == 2 || S == 4 || S == 8)) {
799 // Scaled-index addressing.
800 Scale = S;
801 IndexReg = getRegForGEPIndex(Op).first;
802 if (IndexReg == 0)
803 return false;
804 break;
805 }
806 // Unsupported.
807 goto unsupported_gep;
808 }
809 }
810
811 // Check for displacement overflow.
812 if (!isInt<32>(Disp))
813 break;
814
815 AM.IndexReg = IndexReg;
816 AM.Scale = Scale;
817 AM.Disp = (uint32_t)Disp;
818 GEPs.push_back(V);
819
820 if (const GetElementPtrInst *GEP =
821 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
822 // Ok, the GEP indices were covered by constant-offset and scaled-index
823 // addressing. Update the address state and move on to examining the base.
824 V = GEP;
825 goto redo_gep;
826 } else if (X86SelectAddress(U->getOperand(0), AM)) {
827 return true;
828 }
829
830 // If we couldn't merge the gep value into this addr mode, revert back to
831 // our address and just match the value instead of completely failing.
832 AM = SavedAM;
833
834 for (SmallVectorImpl<const Value *>::reverse_iterator
835 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
836 if (handleConstantAddresses(*I, AM))
837 return true;
838
839 return false;
840 unsupported_gep:
841 // Ok, the GEP indices weren't all covered.
842 break;
843 }
844 }
845
846 return handleConstantAddresses(V, AM);
847}
848
849/// X86SelectCallAddress - Attempt to fill in an address from the given value.
850///
851bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
852 const User *U = nullptr;
853 unsigned Opcode = Instruction::UserOp1;
854 const Instruction *I = dyn_cast<Instruction>(V);
855 // Record if the value is defined in the same basic block.
856 //
857 // This information is crucial to know whether or not folding an
858 // operand is valid.
859 // Indeed, FastISel generates or reuses a virtual register for all
860 // operands of all instructions it selects. Obviously, the definition and
861 // its uses must use the same virtual register otherwise the produced
862 // code is incorrect.
863 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
864 // registers for values that are alive across basic blocks. This ensures
865 // that the values are consistently set between across basic block, even
866 // if different instruction selection mechanisms are used (e.g., a mix of
867 // SDISel and FastISel).
868 // For values local to a basic block, the instruction selection process
869 // generates these virtual registers with whatever method is appropriate
870 // for its needs. In particular, FastISel and SDISel do not share the way
871 // local virtual registers are set.
872 // Therefore, this is impossible (or at least unsafe) to share values
873 // between basic blocks unless they use the same instruction selection
874 // method, which is not guarantee for X86.
875 // Moreover, things like hasOneUse could not be used accurately, if we
876 // allow to reference values across basic blocks whereas they are not
877 // alive across basic blocks initially.
878 bool InMBB = true;
879 if (I) {
880 Opcode = I->getOpcode();
881 U = I;
882 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
883 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
884 Opcode = C->getOpcode();
885 U = C;
886 }
887
888 switch (Opcode) {
889 default: break;
890 case Instruction::BitCast:
891 // Look past bitcasts if its operand is in the same BB.
892 if (InMBB)
893 return X86SelectCallAddress(U->getOperand(0), AM);
894 break;
895
896 case Instruction::IntToPtr:
897 // Look past no-op inttoptrs if its operand is in the same BB.
898 if (InMBB &&
Mehdi Amini44ede332015-07-09 02:09:04 +0000899 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
900 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000901 return X86SelectCallAddress(U->getOperand(0), AM);
902 break;
903
904 case Instruction::PtrToInt:
905 // Look past no-op ptrtoints if its operand is in the same BB.
Mehdi Amini44ede332015-07-09 02:09:04 +0000906 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000907 return X86SelectCallAddress(U->getOperand(0), AM);
908 break;
909 }
910
911 // Handle constant address.
912 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
913 // Can't handle alternate code models yet.
914 if (TM.getCodeModel() != CodeModel::Small)
915 return false;
916
917 // RIP-relative addresses can't have additional register operands.
918 if (Subtarget->isPICStyleRIPRel() &&
919 (AM.Base.Reg != 0 || AM.IndexReg != 0))
920 return false;
921
922 // Can't handle DLL Import.
923 if (GV->hasDLLImportStorageClass())
924 return false;
925
926 // Can't handle TLS.
927 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
928 if (GVar->isThreadLocal())
929 return false;
930
931 // Okay, we've committed to selecting this global. Set up the basic address.
932 AM.GV = GV;
933
934 // No ABI requires an extra load for anything other than DLLImport, which
935 // we rejected above. Return a direct reference to the global.
936 if (Subtarget->isPICStyleRIPRel()) {
937 // Use rip-relative addressing if we can. Above we verified that the
938 // base and index registers are unused.
939 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
940 AM.Base.Reg = X86::RIP;
941 } else if (Subtarget->isPICStyleStubPIC()) {
942 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
943 } else if (Subtarget->isPICStyleGOT()) {
944 AM.GVOpFlags = X86II::MO_GOTOFF;
945 }
946
947 return true;
948 }
949
950 // If all else fails, try to materialize the value in a register.
951 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
952 if (AM.Base.Reg == 0) {
953 AM.Base.Reg = getRegForValue(V);
954 return AM.Base.Reg != 0;
955 }
956 if (AM.IndexReg == 0) {
957 assert(AM.Scale == 1 && "Scale with no index!");
958 AM.IndexReg = getRegForValue(V);
959 return AM.IndexReg != 0;
960 }
961 }
962
963 return false;
964}
965
966
967/// X86SelectStore - Select and emit code to implement store instructions.
968bool X86FastISel::X86SelectStore(const Instruction *I) {
969 // Atomic stores need special handling.
970 const StoreInst *S = cast<StoreInst>(I);
971
972 if (S->isAtomic())
973 return false;
974
Manman Ren57518142016-04-11 21:08:06 +0000975 const Value *PtrV = I->getOperand(1);
976 if (TLI.supportSwiftError()) {
977 // Swifterror values can come from either a function parameter with
978 // swifterror attribute or an alloca with swifterror attribute.
979 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
980 if (Arg->hasSwiftErrorAttr())
981 return false;
982 }
983
984 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
985 if (Alloca->isSwiftError())
986 return false;
987 }
988 }
989
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000990 const Value *Val = S->getValueOperand();
991 const Value *Ptr = S->getPointerOperand();
992
993 MVT VT;
994 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
995 return false;
996
997 unsigned Alignment = S->getAlignment();
998 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
999 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1000 Alignment = ABIAlignment;
1001 bool Aligned = Alignment >= ABIAlignment;
1002
1003 X86AddressMode AM;
1004 if (!X86SelectAddress(Ptr, AM))
1005 return false;
1006
1007 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1008}
1009
1010/// X86SelectRet - Select and emit code to implement ret instructions.
1011bool X86FastISel::X86SelectRet(const Instruction *I) {
1012 const ReturnInst *Ret = cast<ReturnInst>(I);
1013 const Function &F = *I->getParent()->getParent();
1014 const X86MachineFunctionInfo *X86MFInfo =
1015 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1016
1017 if (!FuncInfo.CanLowerReturn)
1018 return false;
1019
Manman Ren57518142016-04-11 21:08:06 +00001020 if (TLI.supportSwiftError() &&
1021 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1022 return false;
1023
Manman Rened967f32016-01-12 01:08:46 +00001024 if (TLI.supportSplitCSR(FuncInfo.MF))
1025 return false;
1026
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001027 CallingConv::ID CC = F.getCallingConv();
1028 if (CC != CallingConv::C &&
1029 CC != CallingConv::Fast &&
1030 CC != CallingConv::X86_FastCall &&
1031 CC != CallingConv::X86_64_SysV)
1032 return false;
1033
1034 if (Subtarget->isCallingConvWin64(CC))
1035 return false;
1036
1037 // Don't handle popping bytes on return for now.
1038 if (X86MFInfo->getBytesToPopOnReturn() != 0)
1039 return false;
1040
1041 // fastcc with -tailcallopt is intended to provide a guaranteed
1042 // tail call optimization. Fastisel doesn't know how to do that.
1043 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
1044 return false;
1045
1046 // Let SDISel handle vararg functions.
1047 if (F.isVarArg())
1048 return false;
1049
1050 // Build a list of return value registers.
1051 SmallVector<unsigned, 4> RetRegs;
1052
1053 if (Ret->getNumOperands() > 0) {
1054 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001055 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001056
1057 // Analyze operands of the call, assigning locations to each operand.
1058 SmallVector<CCValAssign, 16> ValLocs;
1059 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1060 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1061
1062 const Value *RV = Ret->getOperand(0);
1063 unsigned Reg = getRegForValue(RV);
1064 if (Reg == 0)
1065 return false;
1066
1067 // Only handle a single return value for now.
1068 if (ValLocs.size() != 1)
1069 return false;
1070
1071 CCValAssign &VA = ValLocs[0];
1072
1073 // Don't bother handling odd stuff for now.
1074 if (VA.getLocInfo() != CCValAssign::Full)
1075 return false;
1076 // Only handle register returns for now.
1077 if (!VA.isRegLoc())
1078 return false;
1079
1080 // The calling-convention tables for x87 returns don't tell
1081 // the whole story.
1082 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1083 return false;
1084
1085 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001086 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001087 EVT DstVT = VA.getValVT();
1088 // Special handling for extended integers.
1089 if (SrcVT != DstVT) {
1090 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1091 return false;
1092
1093 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1094 return false;
1095
1096 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1097
1098 if (SrcVT == MVT::i1) {
1099 if (Outs[0].Flags.isSExt())
1100 return false;
1101 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1102 SrcVT = MVT::i8;
1103 }
1104 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1105 ISD::SIGN_EXTEND;
1106 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1107 SrcReg, /*TODO: Kill=*/false);
1108 }
1109
1110 // Make the copy.
1111 unsigned DstReg = VA.getLocReg();
1112 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1113 // Avoid a cross-class copy. This is very unlikely.
1114 if (!SrcRC->contains(DstReg))
1115 return false;
1116 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1117 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1118
1119 // Add register to return instruction.
1120 RetRegs.push_back(VA.getLocReg());
1121 }
1122
Dimitry Andric227b9282016-01-03 17:22:03 +00001123 // All x86 ABIs require that for returning structs by value we copy
1124 // the sret argument into %rax/%eax (depending on ABI) for the return.
1125 // We saved the argument into a virtual register in the entry block,
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00001126 // so now we copy the value out and into %rax/%eax.
1127 if (F.hasStructRetAttr()) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001128 unsigned Reg = X86MFInfo->getSRetReturnReg();
1129 assert(Reg &&
1130 "SRetReturnReg should have been set in LowerFormalArguments()!");
1131 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1132 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1133 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1134 RetRegs.push_back(RetReg);
1135 }
1136
1137 // Now emit the RET.
1138 MachineInstrBuilder MIB =
1139 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1140 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1141 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1142 MIB.addReg(RetRegs[i], RegState::Implicit);
1143 return true;
1144}
1145
1146/// X86SelectLoad - Select and emit code to implement load instructions.
1147///
1148bool X86FastISel::X86SelectLoad(const Instruction *I) {
1149 const LoadInst *LI = cast<LoadInst>(I);
1150
1151 // Atomic loads need special handling.
1152 if (LI->isAtomic())
1153 return false;
1154
Manman Ren57518142016-04-11 21:08:06 +00001155 const Value *SV = I->getOperand(0);
1156 if (TLI.supportSwiftError()) {
1157 // Swifterror values can come from either a function parameter with
1158 // swifterror attribute or an alloca with swifterror attribute.
1159 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1160 if (Arg->hasSwiftErrorAttr())
1161 return false;
1162 }
1163
1164 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1165 if (Alloca->isSwiftError())
1166 return false;
1167 }
1168 }
1169
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001170 MVT VT;
1171 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1172 return false;
1173
1174 const Value *Ptr = LI->getPointerOperand();
1175
1176 X86AddressMode AM;
1177 if (!X86SelectAddress(Ptr, AM))
1178 return false;
1179
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001180 unsigned Alignment = LI->getAlignment();
1181 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1182 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1183 Alignment = ABIAlignment;
1184
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001185 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001186 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1187 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001188 return false;
1189
1190 updateValueMap(I, ResultReg);
1191 return true;
1192}
1193
1194static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1195 bool HasAVX = Subtarget->hasAVX();
1196 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1197 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1198
1199 switch (VT.getSimpleVT().SimpleTy) {
1200 default: return 0;
1201 case MVT::i8: return X86::CMP8rr;
1202 case MVT::i16: return X86::CMP16rr;
1203 case MVT::i32: return X86::CMP32rr;
1204 case MVT::i64: return X86::CMP64rr;
1205 case MVT::f32:
1206 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1207 case MVT::f64:
1208 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1209 }
1210}
1211
Rafael Espindola19141f22015-03-16 14:05:49 +00001212/// If we have a comparison with RHS as the RHS of the comparison, return an
1213/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001214static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001215 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001216 switch (VT.getSimpleVT().SimpleTy) {
1217 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001218 default:
1219 return 0;
1220 case MVT::i8:
1221 return X86::CMP8ri;
1222 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001223 if (isInt<8>(Val))
1224 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001225 return X86::CMP16ri;
1226 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001227 if (isInt<8>(Val))
1228 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001229 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001230 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001231 if (isInt<8>(Val))
1232 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001233 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1234 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001235 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001236 return X86::CMP64ri32;
1237 return 0;
1238 }
1239}
1240
1241bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1242 EVT VT, DebugLoc CurDbgLoc) {
1243 unsigned Op0Reg = getRegForValue(Op0);
1244 if (Op0Reg == 0) return false;
1245
1246 // Handle 'null' like i32/i64 0.
1247 if (isa<ConstantPointerNull>(Op1))
1248 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1249
1250 // We have two options: compare with register or immediate. If the RHS of
1251 // the compare is an immediate that we can fold into this compare, use
1252 // CMPri, otherwise use CMPrr.
1253 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1254 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1255 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1256 .addReg(Op0Reg)
1257 .addImm(Op1C->getSExtValue());
1258 return true;
1259 }
1260 }
1261
1262 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1263 if (CompareOpc == 0) return false;
1264
1265 unsigned Op1Reg = getRegForValue(Op1);
1266 if (Op1Reg == 0) return false;
1267 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1268 .addReg(Op0Reg)
1269 .addReg(Op1Reg);
1270
1271 return true;
1272}
1273
1274bool X86FastISel::X86SelectCmp(const Instruction *I) {
1275 const CmpInst *CI = cast<CmpInst>(I);
1276
1277 MVT VT;
1278 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1279 return false;
1280
1281 // Try to optimize or fold the cmp.
1282 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1283 unsigned ResultReg = 0;
1284 switch (Predicate) {
1285 default: break;
1286 case CmpInst::FCMP_FALSE: {
1287 ResultReg = createResultReg(&X86::GR32RegClass);
1288 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1289 ResultReg);
1290 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1291 X86::sub_8bit);
1292 if (!ResultReg)
1293 return false;
1294 break;
1295 }
1296 case CmpInst::FCMP_TRUE: {
1297 ResultReg = createResultReg(&X86::GR8RegClass);
1298 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1299 ResultReg).addImm(1);
1300 break;
1301 }
1302 }
1303
1304 if (ResultReg) {
1305 updateValueMap(I, ResultReg);
1306 return true;
1307 }
1308
1309 const Value *LHS = CI->getOperand(0);
1310 const Value *RHS = CI->getOperand(1);
1311
1312 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1313 // We don't have to materialize a zero constant for this case and can just use
1314 // %x again on the RHS.
1315 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1316 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1317 if (RHSC && RHSC->isNullValue())
1318 RHS = LHS;
1319 }
1320
1321 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1322 static unsigned SETFOpcTable[2][3] = {
1323 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1324 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1325 };
1326 unsigned *SETFOpc = nullptr;
1327 switch (Predicate) {
1328 default: break;
1329 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1330 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1331 }
1332
1333 ResultReg = createResultReg(&X86::GR8RegClass);
1334 if (SETFOpc) {
1335 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1336 return false;
1337
1338 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1339 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1340 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1341 FlagReg1);
1342 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1343 FlagReg2);
1344 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1345 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1346 updateValueMap(I, ResultReg);
1347 return true;
1348 }
1349
1350 X86::CondCode CC;
1351 bool SwapArgs;
1352 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1353 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1354 unsigned Opc = X86::getSETFromCond(CC);
1355
1356 if (SwapArgs)
1357 std::swap(LHS, RHS);
1358
1359 // Emit a compare of LHS/RHS.
1360 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1361 return false;
1362
1363 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1364 updateValueMap(I, ResultReg);
1365 return true;
1366}
1367
1368bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001369 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001370 if (!TLI.isTypeLegal(DstVT))
1371 return false;
1372
1373 unsigned ResultReg = getRegForValue(I->getOperand(0));
1374 if (ResultReg == 0)
1375 return false;
1376
1377 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001378 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001379 if (SrcVT.SimpleTy == MVT::i1) {
1380 // Set the high bits to zero.
1381 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1382 SrcVT = MVT::i8;
1383
1384 if (ResultReg == 0)
1385 return false;
1386 }
1387
1388 if (DstVT == MVT::i64) {
1389 // Handle extension to 64-bits via sub-register shenanigans.
1390 unsigned MovInst;
1391
1392 switch (SrcVT.SimpleTy) {
1393 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1394 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1395 case MVT::i32: MovInst = X86::MOV32rr; break;
1396 default: llvm_unreachable("Unexpected zext to i64 source type");
1397 }
1398
1399 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1400 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1401 .addReg(ResultReg);
1402
1403 ResultReg = createResultReg(&X86::GR64RegClass);
1404 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1405 ResultReg)
1406 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1407 } else if (DstVT != MVT::i8) {
1408 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1409 ResultReg, /*Kill=*/true);
1410 if (ResultReg == 0)
1411 return false;
1412 }
1413
1414 updateValueMap(I, ResultReg);
1415 return true;
1416}
1417
1418bool X86FastISel::X86SelectBranch(const Instruction *I) {
1419 // Unconditional branches are selected by tablegen-generated code.
1420 // Handle a conditional branch.
1421 const BranchInst *BI = cast<BranchInst>(I);
1422 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1423 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1424
1425 // Fold the common case of a conditional branch with a comparison
1426 // in the same block (values defined on other blocks may not have
1427 // initialized registers).
1428 X86::CondCode CC;
1429 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1430 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001431 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001432
1433 // Try to optimize or fold the cmp.
1434 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1435 switch (Predicate) {
1436 default: break;
1437 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1438 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1439 }
1440
1441 const Value *CmpLHS = CI->getOperand(0);
1442 const Value *CmpRHS = CI->getOperand(1);
1443
1444 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1445 // 0.0.
1446 // We don't have to materialize a zero constant for this case and can just
1447 // use %x again on the RHS.
1448 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1449 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1450 if (CmpRHSC && CmpRHSC->isNullValue())
1451 CmpRHS = CmpLHS;
1452 }
1453
1454 // Try to take advantage of fallthrough opportunities.
1455 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1456 std::swap(TrueMBB, FalseMBB);
1457 Predicate = CmpInst::getInversePredicate(Predicate);
1458 }
1459
1460 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1461 // code check. Instead two branch instructions are required to check all
1462 // the flags. First we change the predicate to a supported condition code,
1463 // which will be the first branch. Later one we will emit the second
1464 // branch.
1465 bool NeedExtraBranch = false;
1466 switch (Predicate) {
1467 default: break;
1468 case CmpInst::FCMP_OEQ:
1469 std::swap(TrueMBB, FalseMBB); // fall-through
1470 case CmpInst::FCMP_UNE:
1471 NeedExtraBranch = true;
1472 Predicate = CmpInst::FCMP_ONE;
1473 break;
1474 }
1475
1476 bool SwapArgs;
1477 unsigned BranchOpc;
1478 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1479 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1480
1481 BranchOpc = X86::GetCondBranchFromCond(CC);
1482 if (SwapArgs)
1483 std::swap(CmpLHS, CmpRHS);
1484
1485 // Emit a compare of the LHS and RHS, setting the flags.
1486 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1487 return false;
1488
1489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1490 .addMBB(TrueMBB);
1491
1492 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1493 // to UNE above).
1494 if (NeedExtraBranch) {
1495 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1496 .addMBB(TrueMBB);
1497 }
1498
Matthias Braun17af6072015-08-26 01:38:00 +00001499 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001500 return true;
1501 }
1502 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1503 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1504 // typically happen for _Bool and C++ bools.
1505 MVT SourceVT;
1506 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1507 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1508 unsigned TestOpc = 0;
1509 switch (SourceVT.SimpleTy) {
1510 default: break;
1511 case MVT::i8: TestOpc = X86::TEST8ri; break;
1512 case MVT::i16: TestOpc = X86::TEST16ri; break;
1513 case MVT::i32: TestOpc = X86::TEST32ri; break;
1514 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1515 }
1516 if (TestOpc) {
1517 unsigned OpReg = getRegForValue(TI->getOperand(0));
1518 if (OpReg == 0) return false;
1519 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1520 .addReg(OpReg).addImm(1);
1521
1522 unsigned JmpOpc = X86::JNE_1;
1523 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1524 std::swap(TrueMBB, FalseMBB);
1525 JmpOpc = X86::JE_1;
1526 }
1527
1528 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1529 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001530
1531 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001532 return true;
1533 }
1534 }
1535 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1536 // Fake request the condition, otherwise the intrinsic might be completely
1537 // optimized away.
1538 unsigned TmpReg = getRegForValue(BI->getCondition());
1539 if (TmpReg == 0)
1540 return false;
1541
1542 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1543
1544 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1545 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001546 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001547 return true;
1548 }
1549
1550 // Otherwise do a clumsy setcc and re-test it.
1551 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1552 // in an explicit cast, so make sure to handle that correctly.
1553 unsigned OpReg = getRegForValue(BI->getCondition());
1554 if (OpReg == 0) return false;
1555
1556 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1557 .addReg(OpReg).addImm(1);
1558 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1559 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001560 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001561 return true;
1562}
1563
1564bool X86FastISel::X86SelectShift(const Instruction *I) {
1565 unsigned CReg = 0, OpReg = 0;
1566 const TargetRegisterClass *RC = nullptr;
1567 if (I->getType()->isIntegerTy(8)) {
1568 CReg = X86::CL;
1569 RC = &X86::GR8RegClass;
1570 switch (I->getOpcode()) {
1571 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1572 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1573 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1574 default: return false;
1575 }
1576 } else if (I->getType()->isIntegerTy(16)) {
1577 CReg = X86::CX;
1578 RC = &X86::GR16RegClass;
1579 switch (I->getOpcode()) {
1580 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1581 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1582 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1583 default: return false;
1584 }
1585 } else if (I->getType()->isIntegerTy(32)) {
1586 CReg = X86::ECX;
1587 RC = &X86::GR32RegClass;
1588 switch (I->getOpcode()) {
1589 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1590 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1591 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1592 default: return false;
1593 }
1594 } else if (I->getType()->isIntegerTy(64)) {
1595 CReg = X86::RCX;
1596 RC = &X86::GR64RegClass;
1597 switch (I->getOpcode()) {
1598 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1599 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1600 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1601 default: return false;
1602 }
1603 } else {
1604 return false;
1605 }
1606
1607 MVT VT;
1608 if (!isTypeLegal(I->getType(), VT))
1609 return false;
1610
1611 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1612 if (Op0Reg == 0) return false;
1613
1614 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1615 if (Op1Reg == 0) return false;
1616 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1617 CReg).addReg(Op1Reg);
1618
1619 // The shift instruction uses X86::CL. If we defined a super-register
1620 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1621 if (CReg != X86::CL)
1622 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1623 TII.get(TargetOpcode::KILL), X86::CL)
1624 .addReg(CReg, RegState::Kill);
1625
1626 unsigned ResultReg = createResultReg(RC);
1627 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1628 .addReg(Op0Reg);
1629 updateValueMap(I, ResultReg);
1630 return true;
1631}
1632
1633bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1634 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1635 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1636 const static bool S = true; // IsSigned
1637 const static bool U = false; // !IsSigned
1638 const static unsigned Copy = TargetOpcode::COPY;
1639 // For the X86 DIV/IDIV instruction, in most cases the dividend
1640 // (numerator) must be in a specific register pair highreg:lowreg,
1641 // producing the quotient in lowreg and the remainder in highreg.
1642 // For most data types, to set up the instruction, the dividend is
1643 // copied into lowreg, and lowreg is sign-extended or zero-extended
1644 // into highreg. The exception is i8, where the dividend is defined
1645 // as a single register rather than a register pair, and we
1646 // therefore directly sign-extend or zero-extend the dividend into
1647 // lowreg, instead of copying, and ignore the highreg.
1648 const static struct DivRemEntry {
1649 // The following portion depends only on the data type.
1650 const TargetRegisterClass *RC;
1651 unsigned LowInReg; // low part of the register pair
1652 unsigned HighInReg; // high part of the register pair
1653 // The following portion depends on both the data type and the operation.
1654 struct DivRemResult {
1655 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1656 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1657 // highreg, or copying a zero into highreg.
1658 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1659 // zero/sign-extending into lowreg for i8.
1660 unsigned DivRemResultReg; // Register containing the desired result.
1661 bool IsOpSigned; // Whether to use signed or unsigned form.
1662 } ResultTable[NumOps];
1663 } OpTable[NumTypes] = {
1664 { &X86::GR8RegClass, X86::AX, 0, {
1665 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1666 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1667 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1668 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1669 }
1670 }, // i8
1671 { &X86::GR16RegClass, X86::AX, X86::DX, {
1672 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1673 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1674 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1675 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1676 }
1677 }, // i16
1678 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1679 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1680 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1681 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1682 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1683 }
1684 }, // i32
1685 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1686 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1687 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1688 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1689 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1690 }
1691 }, // i64
1692 };
1693
1694 MVT VT;
1695 if (!isTypeLegal(I->getType(), VT))
1696 return false;
1697
1698 unsigned TypeIndex, OpIndex;
1699 switch (VT.SimpleTy) {
1700 default: return false;
1701 case MVT::i8: TypeIndex = 0; break;
1702 case MVT::i16: TypeIndex = 1; break;
1703 case MVT::i32: TypeIndex = 2; break;
1704 case MVT::i64: TypeIndex = 3;
1705 if (!Subtarget->is64Bit())
1706 return false;
1707 break;
1708 }
1709
1710 switch (I->getOpcode()) {
1711 default: llvm_unreachable("Unexpected div/rem opcode");
1712 case Instruction::SDiv: OpIndex = 0; break;
1713 case Instruction::SRem: OpIndex = 1; break;
1714 case Instruction::UDiv: OpIndex = 2; break;
1715 case Instruction::URem: OpIndex = 3; break;
1716 }
1717
1718 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1719 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1720 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1721 if (Op0Reg == 0)
1722 return false;
1723 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1724 if (Op1Reg == 0)
1725 return false;
1726
1727 // Move op0 into low-order input register.
1728 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1729 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1730 // Zero-extend or sign-extend into high-order input register.
1731 if (OpEntry.OpSignExtend) {
1732 if (OpEntry.IsOpSigned)
1733 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1734 TII.get(OpEntry.OpSignExtend));
1735 else {
1736 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1737 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1738 TII.get(X86::MOV32r0), Zero32);
1739
1740 // Copy the zero into the appropriate sub/super/identical physical
1741 // register. Unfortunately the operations needed are not uniform enough
1742 // to fit neatly into the table above.
1743 if (VT.SimpleTy == MVT::i16) {
1744 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1745 TII.get(Copy), TypeEntry.HighInReg)
1746 .addReg(Zero32, 0, X86::sub_16bit);
1747 } else if (VT.SimpleTy == MVT::i32) {
1748 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1749 TII.get(Copy), TypeEntry.HighInReg)
1750 .addReg(Zero32);
1751 } else if (VT.SimpleTy == MVT::i64) {
1752 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1753 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1754 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1755 }
1756 }
1757 }
1758 // Generate the DIV/IDIV instruction.
1759 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1760 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1761 // For i8 remainder, we can't reference AH directly, as we'll end
1762 // up with bogus copies like %R9B = COPY %AH. Reference AX
1763 // instead to prevent AH references in a REX instruction.
1764 //
1765 // The current assumption of the fast register allocator is that isel
1766 // won't generate explicit references to the GPR8_NOREX registers. If
1767 // the allocator and/or the backend get enhanced to be more robust in
1768 // that regard, this can be, and should be, removed.
1769 unsigned ResultReg = 0;
1770 if ((I->getOpcode() == Instruction::SRem ||
1771 I->getOpcode() == Instruction::URem) &&
1772 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1773 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1774 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1775 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1776 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1777
1778 // Shift AX right by 8 bits instead of using AH.
1779 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1780 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1781
1782 // Now reference the 8-bit subreg of the result.
1783 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1784 /*Kill=*/true, X86::sub_8bit);
1785 }
1786 // Copy the result out of the physreg if we haven't already.
1787 if (!ResultReg) {
1788 ResultReg = createResultReg(TypeEntry.RC);
1789 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1790 .addReg(OpEntry.DivRemResultReg);
1791 }
1792 updateValueMap(I, ResultReg);
1793
1794 return true;
1795}
1796
1797/// \brief Emit a conditional move instruction (if the are supported) to lower
1798/// the select.
1799bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1800 // Check if the subtarget supports these instructions.
1801 if (!Subtarget->hasCMov())
1802 return false;
1803
1804 // FIXME: Add support for i8.
1805 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1806 return false;
1807
1808 const Value *Cond = I->getOperand(0);
1809 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1810 bool NeedTest = true;
1811 X86::CondCode CC = X86::COND_NE;
1812
1813 // Optimize conditions coming from a compare if both instructions are in the
1814 // same basic block (values defined in other basic blocks may not have
1815 // initialized registers).
1816 const auto *CI = dyn_cast<CmpInst>(Cond);
1817 if (CI && (CI->getParent() == I->getParent())) {
1818 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1819
1820 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1821 static unsigned SETFOpcTable[2][3] = {
1822 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1823 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1824 };
1825 unsigned *SETFOpc = nullptr;
1826 switch (Predicate) {
1827 default: break;
1828 case CmpInst::FCMP_OEQ:
1829 SETFOpc = &SETFOpcTable[0][0];
1830 Predicate = CmpInst::ICMP_NE;
1831 break;
1832 case CmpInst::FCMP_UNE:
1833 SETFOpc = &SETFOpcTable[1][0];
1834 Predicate = CmpInst::ICMP_NE;
1835 break;
1836 }
1837
1838 bool NeedSwap;
1839 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1840 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1841
1842 const Value *CmpLHS = CI->getOperand(0);
1843 const Value *CmpRHS = CI->getOperand(1);
1844 if (NeedSwap)
1845 std::swap(CmpLHS, CmpRHS);
1846
Mehdi Amini44ede332015-07-09 02:09:04 +00001847 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001848 // Emit a compare of the LHS and RHS, setting the flags.
1849 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1850 return false;
1851
1852 if (SETFOpc) {
1853 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1854 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1855 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1856 FlagReg1);
1857 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1858 FlagReg2);
1859 auto const &II = TII.get(SETFOpc[2]);
1860 if (II.getNumDefs()) {
1861 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1862 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1863 .addReg(FlagReg2).addReg(FlagReg1);
1864 } else {
1865 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1866 .addReg(FlagReg2).addReg(FlagReg1);
1867 }
1868 }
1869 NeedTest = false;
1870 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1871 // Fake request the condition, otherwise the intrinsic might be completely
1872 // optimized away.
1873 unsigned TmpReg = getRegForValue(Cond);
1874 if (TmpReg == 0)
1875 return false;
1876
1877 NeedTest = false;
1878 }
1879
1880 if (NeedTest) {
1881 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1882 // garbage. Indeed, only the less significant bit is supposed to be
1883 // accurate. If we read more than the lsb, we may see non-zero values
1884 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1885 // the select. This is achieved by performing TEST against 1.
1886 unsigned CondReg = getRegForValue(Cond);
1887 if (CondReg == 0)
1888 return false;
1889 bool CondIsKill = hasTrivialKill(Cond);
1890
1891 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1892 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1893 }
1894
1895 const Value *LHS = I->getOperand(1);
1896 const Value *RHS = I->getOperand(2);
1897
1898 unsigned RHSReg = getRegForValue(RHS);
1899 bool RHSIsKill = hasTrivialKill(RHS);
1900
1901 unsigned LHSReg = getRegForValue(LHS);
1902 bool LHSIsKill = hasTrivialKill(LHS);
1903
1904 if (!LHSReg || !RHSReg)
1905 return false;
1906
1907 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1908 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1909 LHSReg, LHSIsKill);
1910 updateValueMap(I, ResultReg);
1911 return true;
1912}
1913
Sanjay Patel302404b2015-03-05 21:46:54 +00001914/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001915///
1916/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1917/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00001918/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001919bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1920 // Optimize conditions coming from a compare if both instructions are in the
1921 // same basic block (values defined in other basic blocks may not have
1922 // initialized registers).
1923 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1924 if (!CI || (CI->getParent() != I->getParent()))
1925 return false;
1926
1927 if (I->getType() != CI->getOperand(0)->getType() ||
1928 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1929 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1930 return false;
1931
1932 const Value *CmpLHS = CI->getOperand(0);
1933 const Value *CmpRHS = CI->getOperand(1);
1934 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1935
1936 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1937 // We don't have to materialize a zero constant for this case and can just use
1938 // %x again on the RHS.
1939 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1940 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1941 if (CmpRHSC && CmpRHSC->isNullValue())
1942 CmpRHS = CmpLHS;
1943 }
1944
1945 unsigned CC;
1946 bool NeedSwap;
1947 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1948 if (CC > 7)
1949 return false;
1950
1951 if (NeedSwap)
1952 std::swap(CmpLHS, CmpRHS);
1953
Sanjay Patel302404b2015-03-05 21:46:54 +00001954 // Choose the SSE instruction sequence based on data type (float or double).
1955 static unsigned OpcTable[2][4] = {
1956 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1957 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001958 };
1959
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001960 unsigned *Opc = nullptr;
1961 switch (RetVT.SimpleTy) {
1962 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00001963 case MVT::f32: Opc = &OpcTable[0][0]; break;
1964 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001965 }
1966
1967 const Value *LHS = I->getOperand(1);
1968 const Value *RHS = I->getOperand(2);
1969
1970 unsigned LHSReg = getRegForValue(LHS);
1971 bool LHSIsKill = hasTrivialKill(LHS);
1972
1973 unsigned RHSReg = getRegForValue(RHS);
1974 bool RHSIsKill = hasTrivialKill(RHS);
1975
1976 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1977 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1978
1979 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1980 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1981
1982 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1983 return false;
1984
1985 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00001986 unsigned ResultReg;
1987
1988 if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00001989 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
1990 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
1991
Sanjay Patel302404b2015-03-05 21:46:54 +00001992 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1993 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1994 // uses XMM0 as the selection register. That may need just as many
1995 // instructions as the AND/ANDN/OR sequence due to register moves, so
1996 // don't bother.
1997 unsigned CmpOpcode =
1998 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
1999 unsigned BlendOpcode =
2000 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
2001
Matthias Braun818c78d2015-08-31 18:25:11 +00002002 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00002003 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00002004 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
2005 LHSReg, LHSIsKill, CmpReg, true);
2006 ResultReg = createResultReg(RC);
2007 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2008 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00002009 } else {
2010 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
2011 CmpRHSReg, CmpRHSIsKill, CC);
2012 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
2013 LHSReg, LHSIsKill);
2014 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
2015 RHSReg, RHSIsKill);
2016 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
2017 AndReg, /*IsKill=*/true);
2018 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002019 updateValueMap(I, ResultReg);
2020 return true;
2021}
2022
2023bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2024 // These are pseudo CMOV instructions and will be later expanded into control-
2025 // flow.
2026 unsigned Opc;
2027 switch (RetVT.SimpleTy) {
2028 default: return false;
2029 case MVT::i8: Opc = X86::CMOV_GR8; break;
2030 case MVT::i16: Opc = X86::CMOV_GR16; break;
2031 case MVT::i32: Opc = X86::CMOV_GR32; break;
2032 case MVT::f32: Opc = X86::CMOV_FR32; break;
2033 case MVT::f64: Opc = X86::CMOV_FR64; break;
2034 }
2035
2036 const Value *Cond = I->getOperand(0);
2037 X86::CondCode CC = X86::COND_NE;
2038
2039 // Optimize conditions coming from a compare if both instructions are in the
2040 // same basic block (values defined in other basic blocks may not have
2041 // initialized registers).
2042 const auto *CI = dyn_cast<CmpInst>(Cond);
2043 if (CI && (CI->getParent() == I->getParent())) {
2044 bool NeedSwap;
2045 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
2046 if (CC > X86::LAST_VALID_COND)
2047 return false;
2048
2049 const Value *CmpLHS = CI->getOperand(0);
2050 const Value *CmpRHS = CI->getOperand(1);
2051
2052 if (NeedSwap)
2053 std::swap(CmpLHS, CmpRHS);
2054
Mehdi Amini44ede332015-07-09 02:09:04 +00002055 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002056 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2057 return false;
2058 } else {
2059 unsigned CondReg = getRegForValue(Cond);
2060 if (CondReg == 0)
2061 return false;
2062 bool CondIsKill = hasTrivialKill(Cond);
2063 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
2064 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2065 }
2066
2067 const Value *LHS = I->getOperand(1);
2068 const Value *RHS = I->getOperand(2);
2069
2070 unsigned LHSReg = getRegForValue(LHS);
2071 bool LHSIsKill = hasTrivialKill(LHS);
2072
2073 unsigned RHSReg = getRegForValue(RHS);
2074 bool RHSIsKill = hasTrivialKill(RHS);
2075
2076 if (!LHSReg || !RHSReg)
2077 return false;
2078
2079 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2080
2081 unsigned ResultReg =
2082 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2083 updateValueMap(I, ResultReg);
2084 return true;
2085}
2086
2087bool X86FastISel::X86SelectSelect(const Instruction *I) {
2088 MVT RetVT;
2089 if (!isTypeLegal(I->getType(), RetVT))
2090 return false;
2091
2092 // Check if we can fold the select.
2093 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2094 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2095 const Value *Opnd = nullptr;
2096 switch (Predicate) {
2097 default: break;
2098 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2099 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2100 }
2101 // No need for a select anymore - this is an unconditional move.
2102 if (Opnd) {
2103 unsigned OpReg = getRegForValue(Opnd);
2104 if (OpReg == 0)
2105 return false;
2106 bool OpIsKill = hasTrivialKill(Opnd);
2107 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2108 unsigned ResultReg = createResultReg(RC);
2109 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2110 TII.get(TargetOpcode::COPY), ResultReg)
2111 .addReg(OpReg, getKillRegState(OpIsKill));
2112 updateValueMap(I, ResultReg);
2113 return true;
2114 }
2115 }
2116
2117 // First try to use real conditional move instructions.
2118 if (X86FastEmitCMoveSelect(RetVT, I))
2119 return true;
2120
2121 // Try to use a sequence of SSE instructions to simulate a conditional move.
2122 if (X86FastEmitSSESelect(RetVT, I))
2123 return true;
2124
2125 // Fall-back to pseudo conditional move instructions, which will be later
2126 // converted to control-flow.
2127 if (X86FastEmitPseudoSelect(RetVT, I))
2128 return true;
2129
2130 return false;
2131}
2132
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002133bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002134 // The target-independent selection algorithm in FastISel already knows how
2135 // to select a SINT_TO_FP if the target is SSE but not AVX.
2136 // Early exit if the subtarget doesn't have AVX.
2137 if (!Subtarget->hasAVX())
2138 return false;
2139
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002140 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2141 return false;
2142
2143 // Select integer to float/double conversion.
2144 unsigned OpReg = getRegForValue(I->getOperand(0));
2145 if (OpReg == 0)
2146 return false;
2147
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002148 const TargetRegisterClass *RC = nullptr;
2149 unsigned Opcode;
2150
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002151 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002152 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002153 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002154 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002155 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002156 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002157 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002158 RC = &X86::FR32RegClass;
2159 } else
2160 return false;
2161
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002162 unsigned ImplicitDefReg = createResultReg(RC);
2163 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2164 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2165 unsigned ResultReg =
2166 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002167 updateValueMap(I, ResultReg);
2168 return true;
2169}
2170
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002171// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2172bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2173 unsigned TargetOpc,
2174 const TargetRegisterClass *RC) {
2175 assert((I->getOpcode() == Instruction::FPExt ||
2176 I->getOpcode() == Instruction::FPTrunc) &&
2177 "Instruction must be an FPExt or FPTrunc!");
2178
2179 unsigned OpReg = getRegForValue(I->getOperand(0));
2180 if (OpReg == 0)
2181 return false;
2182
2183 unsigned ResultReg = createResultReg(RC);
2184 MachineInstrBuilder MIB;
2185 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2186 ResultReg);
2187 if (Subtarget->hasAVX())
2188 MIB.addReg(OpReg);
2189 MIB.addReg(OpReg);
2190 updateValueMap(I, ResultReg);
2191 return true;
2192}
2193
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002194bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002195 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2196 I->getOperand(0)->getType()->isFloatTy()) {
2197 // fpext from float to double.
2198 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2199 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002200 }
2201
2202 return false;
2203}
2204
2205bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002206 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2207 I->getOperand(0)->getType()->isDoubleTy()) {
2208 // fptrunc from double to float.
2209 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2210 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002211 }
2212
2213 return false;
2214}
2215
2216bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002217 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2218 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002219
2220 // This code only handles truncation to byte.
2221 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2222 return false;
2223 if (!TLI.isTypeLegal(SrcVT))
2224 return false;
2225
2226 unsigned InputReg = getRegForValue(I->getOperand(0));
2227 if (!InputReg)
2228 // Unhandled operand. Halt "fast" selection and bail.
2229 return false;
2230
2231 if (SrcVT == MVT::i8) {
2232 // Truncate from i8 to i1; no code needed.
2233 updateValueMap(I, InputReg);
2234 return true;
2235 }
2236
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002237 bool KillInputReg = false;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002238 if (!Subtarget->is64Bit()) {
2239 // If we're on x86-32; we can't extract an i8 from a general register.
2240 // First issue a copy to GR16_ABCD or GR32_ABCD.
2241 const TargetRegisterClass *CopyRC =
2242 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2243 unsigned CopyReg = createResultReg(CopyRC);
2244 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2245 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2246 InputReg = CopyReg;
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002247 KillInputReg = true;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002248 }
2249
2250 // Issue an extract_subreg.
2251 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002252 InputReg, KillInputReg,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002253 X86::sub_8bit);
2254 if (!ResultReg)
2255 return false;
2256
2257 updateValueMap(I, ResultReg);
2258 return true;
2259}
2260
2261bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2262 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2263}
2264
2265bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2266 X86AddressMode SrcAM, uint64_t Len) {
2267
2268 // Make sure we don't bloat code by inlining very large memcpy's.
2269 if (!IsMemcpySmall(Len))
2270 return false;
2271
2272 bool i64Legal = Subtarget->is64Bit();
2273
2274 // We don't care about alignment here since we just emit integer accesses.
2275 while (Len) {
2276 MVT VT;
2277 if (Len >= 8 && i64Legal)
2278 VT = MVT::i64;
2279 else if (Len >= 4)
2280 VT = MVT::i32;
2281 else if (Len >= 2)
2282 VT = MVT::i16;
2283 else
2284 VT = MVT::i8;
2285
2286 unsigned Reg;
2287 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2288 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2289 assert(RV && "Failed to emit load or store??");
2290
2291 unsigned Size = VT.getSizeInBits()/8;
2292 Len -= Size;
2293 DestAM.Disp += Size;
2294 SrcAM.Disp += Size;
2295 }
2296
2297 return true;
2298}
2299
2300bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2301 // FIXME: Handle more intrinsics.
2302 switch (II->getIntrinsicID()) {
2303 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002304 case Intrinsic::convert_from_fp16:
2305 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002306 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002307 return false;
2308
2309 const Value *Op = II->getArgOperand(0);
2310 unsigned InputReg = getRegForValue(Op);
2311 if (InputReg == 0)
2312 return false;
2313
2314 // F16C only allows converting from float to half and from half to float.
2315 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2316 if (IsFloatToHalf) {
2317 if (!Op->getType()->isFloatTy())
2318 return false;
2319 } else {
2320 if (!II->getType()->isFloatTy())
2321 return false;
2322 }
2323
2324 unsigned ResultReg = 0;
2325 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2326 if (IsFloatToHalf) {
2327 // 'InputReg' is implicitly promoted from register class FR32 to
2328 // register class VR128 by method 'constrainOperandRegClass' which is
2329 // directly called by 'fastEmitInst_ri'.
2330 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
Ahmed Bougacha68a8efa2016-02-02 01:44:03 +00002331 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2332 // It's consistent with the other FP instructions, which are usually
2333 // controlled by MXCSR.
2334 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 4);
Andrea Di Biagio70351782015-02-20 19:37:14 +00002335
2336 // Move the lower 32-bits of ResultReg to another register of class GR32.
2337 ResultReg = createResultReg(&X86::GR32RegClass);
2338 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2339 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2340 .addReg(InputReg, RegState::Kill);
2341
2342 // The result value is in the lower 16-bits of ResultReg.
2343 unsigned RegIdx = X86::sub_16bit;
2344 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2345 } else {
2346 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2347 // Explicitly sign-extend the input to 32-bit.
2348 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2349 /*Kill=*/false);
2350
2351 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2352 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2353 InputReg, /*Kill=*/true);
2354
2355 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2356
2357 // The result value is in the lower 32-bits of ResultReg.
2358 // Emit an explicit copy from register class VR128 to register class FR32.
2359 ResultReg = createResultReg(&X86::FR32RegClass);
2360 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2361 TII.get(TargetOpcode::COPY), ResultReg)
2362 .addReg(InputReg, RegState::Kill);
2363 }
2364
2365 updateValueMap(II, ResultReg);
2366 return true;
2367 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002368 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002369 MachineFunction *MF = FuncInfo.MF;
2370 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2371 return false;
2372
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002373 Type *RetTy = II->getCalledFunction()->getReturnType();
2374
2375 MVT VT;
2376 if (!isTypeLegal(RetTy, VT))
2377 return false;
2378
2379 unsigned Opc;
2380 const TargetRegisterClass *RC = nullptr;
2381
2382 switch (VT.SimpleTy) {
2383 default: llvm_unreachable("Invalid result type for frameaddress.");
2384 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2385 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2386 }
2387
2388 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2389 // we get the wrong frame register.
David Majnemerca194852015-02-10 22:00:34 +00002390 MachineFrameInfo *MFI = MF->getFrameInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002391 MFI->setFrameAddressIsTaken(true);
2392
Eric Christophera1c535b2015-02-02 23:03:45 +00002393 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002394 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002395 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2396 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2397 "Invalid Frame Register!");
2398
2399 // Always make a copy of the frame register to to a vreg first, so that we
2400 // never directly reference the frame register (the TwoAddressInstruction-
2401 // Pass doesn't like that).
2402 unsigned SrcReg = createResultReg(RC);
2403 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2404 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2405
2406 // Now recursively load from the frame address.
2407 // movq (%rbp), %rax
2408 // movq (%rax), %rax
2409 // movq (%rax), %rax
2410 // ...
2411 unsigned DestReg;
2412 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2413 while (Depth--) {
2414 DestReg = createResultReg(RC);
2415 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2416 TII.get(Opc), DestReg), SrcReg);
2417 SrcReg = DestReg;
2418 }
2419
2420 updateValueMap(II, SrcReg);
2421 return true;
2422 }
2423 case Intrinsic::memcpy: {
2424 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2425 // Don't handle volatile or variable length memcpys.
2426 if (MCI->isVolatile())
2427 return false;
2428
2429 if (isa<ConstantInt>(MCI->getLength())) {
2430 // Small memcpy's are common enough that we want to do them
2431 // without a call if possible.
2432 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2433 if (IsMemcpySmall(Len)) {
2434 X86AddressMode DestAM, SrcAM;
2435 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2436 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2437 return false;
2438 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2439 return true;
2440 }
2441 }
2442
2443 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2444 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2445 return false;
2446
2447 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2448 return false;
2449
Pete Cooper67cf9a72015-11-19 05:56:52 +00002450 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002451 }
2452 case Intrinsic::memset: {
2453 const MemSetInst *MSI = cast<MemSetInst>(II);
2454
2455 if (MSI->isVolatile())
2456 return false;
2457
2458 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2459 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2460 return false;
2461
2462 if (MSI->getDestAddressSpace() > 255)
2463 return false;
2464
Pete Cooper67cf9a72015-11-19 05:56:52 +00002465 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002466 }
2467 case Intrinsic::stackprotector: {
2468 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002469 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002470
2471 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2472 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2473
2474 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2475
2476 // Grab the frame index.
2477 X86AddressMode AM;
2478 if (!X86SelectAddress(Slot, AM)) return false;
2479 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2480 return true;
2481 }
2482 case Intrinsic::dbg_declare: {
2483 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2484 X86AddressMode AM;
2485 assert(DI->getAddress() && "Null address should be checked earlier!");
2486 if (!X86SelectAddress(DI->getAddress(), AM))
2487 return false;
2488 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2489 // FIXME may need to add RegState::Debug to any registers produced,
2490 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002491 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2492 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002493 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2494 .addImm(0)
2495 .addMetadata(DI->getVariable())
2496 .addMetadata(DI->getExpression());
2497 return true;
2498 }
2499 case Intrinsic::trap: {
2500 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2501 return true;
2502 }
2503 case Intrinsic::sqrt: {
2504 if (!Subtarget->hasSSE1())
2505 return false;
2506
2507 Type *RetTy = II->getCalledFunction()->getReturnType();
2508
2509 MVT VT;
2510 if (!isTypeLegal(RetTy, VT))
2511 return false;
2512
2513 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2514 // is not generated by FastISel yet.
2515 // FIXME: Update this code once tablegen can handle it.
Craig Toppercf65c622016-03-02 04:42:31 +00002516 static const uint16_t SqrtOpc[2][2] = {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002517 {X86::SQRTSSr, X86::VSQRTSSr},
2518 {X86::SQRTSDr, X86::VSQRTSDr}
2519 };
2520 bool HasAVX = Subtarget->hasAVX();
2521 unsigned Opc;
2522 const TargetRegisterClass *RC;
2523 switch (VT.SimpleTy) {
2524 default: return false;
2525 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2526 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2527 }
2528
2529 const Value *SrcVal = II->getArgOperand(0);
2530 unsigned SrcReg = getRegForValue(SrcVal);
2531
2532 if (SrcReg == 0)
2533 return false;
2534
2535 unsigned ImplicitDefReg = 0;
2536 if (HasAVX) {
2537 ImplicitDefReg = createResultReg(RC);
2538 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2539 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2540 }
2541
2542 unsigned ResultReg = createResultReg(RC);
2543 MachineInstrBuilder MIB;
2544 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2545 ResultReg);
2546
2547 if (ImplicitDefReg)
2548 MIB.addReg(ImplicitDefReg);
2549
2550 MIB.addReg(SrcReg);
2551
2552 updateValueMap(II, ResultReg);
2553 return true;
2554 }
2555 case Intrinsic::sadd_with_overflow:
2556 case Intrinsic::uadd_with_overflow:
2557 case Intrinsic::ssub_with_overflow:
2558 case Intrinsic::usub_with_overflow:
2559 case Intrinsic::smul_with_overflow:
2560 case Intrinsic::umul_with_overflow: {
2561 // This implements the basic lowering of the xalu with overflow intrinsics
2562 // into add/sub/mul followed by either seto or setb.
2563 const Function *Callee = II->getCalledFunction();
2564 auto *Ty = cast<StructType>(Callee->getReturnType());
2565 Type *RetTy = Ty->getTypeAtIndex(0U);
2566 Type *CondTy = Ty->getTypeAtIndex(1);
2567
2568 MVT VT;
2569 if (!isTypeLegal(RetTy, VT))
2570 return false;
2571
2572 if (VT < MVT::i8 || VT > MVT::i64)
2573 return false;
2574
2575 const Value *LHS = II->getArgOperand(0);
2576 const Value *RHS = II->getArgOperand(1);
2577
2578 // Canonicalize immediate to the RHS.
2579 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2580 isCommutativeIntrinsic(II))
2581 std::swap(LHS, RHS);
2582
2583 bool UseIncDec = false;
2584 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2585 UseIncDec = true;
2586
2587 unsigned BaseOpc, CondOpc;
2588 switch (II->getIntrinsicID()) {
2589 default: llvm_unreachable("Unexpected intrinsic!");
2590 case Intrinsic::sadd_with_overflow:
2591 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2592 CondOpc = X86::SETOr;
2593 break;
2594 case Intrinsic::uadd_with_overflow:
2595 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2596 case Intrinsic::ssub_with_overflow:
2597 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2598 CondOpc = X86::SETOr;
2599 break;
2600 case Intrinsic::usub_with_overflow:
2601 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2602 case Intrinsic::smul_with_overflow:
2603 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2604 case Intrinsic::umul_with_overflow:
2605 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2606 }
2607
2608 unsigned LHSReg = getRegForValue(LHS);
2609 if (LHSReg == 0)
2610 return false;
2611 bool LHSIsKill = hasTrivialKill(LHS);
2612
2613 unsigned ResultReg = 0;
2614 // Check if we have an immediate version.
2615 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2616 static const unsigned Opc[2][4] = {
2617 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2618 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2619 };
2620
2621 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2622 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2623 bool IsDec = BaseOpc == X86ISD::DEC;
2624 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2625 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2626 .addReg(LHSReg, getKillRegState(LHSIsKill));
2627 } else
2628 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2629 CI->getZExtValue());
2630 }
2631
2632 unsigned RHSReg;
2633 bool RHSIsKill;
2634 if (!ResultReg) {
2635 RHSReg = getRegForValue(RHS);
2636 if (RHSReg == 0)
2637 return false;
2638 RHSIsKill = hasTrivialKill(RHS);
2639 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2640 RHSIsKill);
2641 }
2642
2643 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2644 // it manually.
2645 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002646 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002647 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
Craig Toppercf65c622016-03-02 04:42:31 +00002648 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002649 // First copy the first operand into RAX, which is an implicit input to
2650 // the X86::MUL*r instruction.
2651 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2652 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2653 .addReg(LHSReg, getKillRegState(LHSIsKill));
2654 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2655 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2656 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
Craig Toppercf65c622016-03-02 04:42:31 +00002657 static const uint16_t MULOpc[] =
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002658 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2659 if (VT == MVT::i8) {
2660 // Copy the first operand into AL, which is an implicit input to the
2661 // X86::IMUL8r instruction.
2662 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2663 TII.get(TargetOpcode::COPY), X86::AL)
2664 .addReg(LHSReg, getKillRegState(LHSIsKill));
2665 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2666 RHSIsKill);
2667 } else
2668 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2669 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2670 RHSReg, RHSIsKill);
2671 }
2672
2673 if (!ResultReg)
2674 return false;
2675
2676 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2677 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2678 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2679 ResultReg2);
2680
2681 updateValueMap(II, ResultReg, 2);
2682 return true;
2683 }
2684 case Intrinsic::x86_sse_cvttss2si:
2685 case Intrinsic::x86_sse_cvttss2si64:
2686 case Intrinsic::x86_sse2_cvttsd2si:
2687 case Intrinsic::x86_sse2_cvttsd2si64: {
2688 bool IsInputDouble;
2689 switch (II->getIntrinsicID()) {
2690 default: llvm_unreachable("Unexpected intrinsic.");
2691 case Intrinsic::x86_sse_cvttss2si:
2692 case Intrinsic::x86_sse_cvttss2si64:
2693 if (!Subtarget->hasSSE1())
2694 return false;
2695 IsInputDouble = false;
2696 break;
2697 case Intrinsic::x86_sse2_cvttsd2si:
2698 case Intrinsic::x86_sse2_cvttsd2si64:
2699 if (!Subtarget->hasSSE2())
2700 return false;
2701 IsInputDouble = true;
2702 break;
2703 }
2704
2705 Type *RetTy = II->getCalledFunction()->getReturnType();
2706 MVT VT;
2707 if (!isTypeLegal(RetTy, VT))
2708 return false;
2709
2710 static const unsigned CvtOpc[2][2][2] = {
2711 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2712 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2713 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2714 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2715 };
2716 bool HasAVX = Subtarget->hasAVX();
2717 unsigned Opc;
2718 switch (VT.SimpleTy) {
2719 default: llvm_unreachable("Unexpected result type.");
2720 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2721 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2722 }
2723
2724 // Check if we can fold insertelement instructions into the convert.
2725 const Value *Op = II->getArgOperand(0);
2726 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2727 const Value *Index = IE->getOperand(2);
2728 if (!isa<ConstantInt>(Index))
2729 break;
2730 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2731
2732 if (Idx == 0) {
2733 Op = IE->getOperand(1);
2734 break;
2735 }
2736 Op = IE->getOperand(0);
2737 }
2738
2739 unsigned Reg = getRegForValue(Op);
2740 if (Reg == 0)
2741 return false;
2742
2743 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2744 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2745 .addReg(Reg);
2746
2747 updateValueMap(II, ResultReg);
2748 return true;
2749 }
2750 }
2751}
2752
2753bool X86FastISel::fastLowerArguments() {
2754 if (!FuncInfo.CanLowerReturn)
2755 return false;
2756
2757 const Function *F = FuncInfo.Fn;
2758 if (F->isVarArg())
2759 return false;
2760
2761 CallingConv::ID CC = F->getCallingConv();
2762 if (CC != CallingConv::C)
2763 return false;
2764
2765 if (Subtarget->isCallingConvWin64(CC))
2766 return false;
2767
2768 if (!Subtarget->is64Bit())
2769 return false;
2770
2771 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2772 unsigned GPRCnt = 0;
2773 unsigned FPRCnt = 0;
2774 unsigned Idx = 0;
2775 for (auto const &Arg : F->args()) {
2776 // The first argument is at index 1.
2777 ++Idx;
2778 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2779 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2780 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
Manman Renf46262e2016-03-29 17:37:21 +00002781 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
Manman Ren57518142016-04-11 21:08:06 +00002782 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002783 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2784 return false;
2785
2786 Type *ArgTy = Arg.getType();
2787 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2788 return false;
2789
Mehdi Amini44ede332015-07-09 02:09:04 +00002790 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002791 if (!ArgVT.isSimple()) return false;
2792 switch (ArgVT.getSimpleVT().SimpleTy) {
2793 default: return false;
2794 case MVT::i32:
2795 case MVT::i64:
2796 ++GPRCnt;
2797 break;
2798 case MVT::f32:
2799 case MVT::f64:
2800 if (!Subtarget->hasSSE1())
2801 return false;
2802 ++FPRCnt;
2803 break;
2804 }
2805
2806 if (GPRCnt > 6)
2807 return false;
2808
2809 if (FPRCnt > 8)
2810 return false;
2811 }
2812
2813 static const MCPhysReg GPR32ArgRegs[] = {
2814 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2815 };
2816 static const MCPhysReg GPR64ArgRegs[] = {
2817 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2818 };
2819 static const MCPhysReg XMMArgRegs[] = {
2820 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2821 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2822 };
2823
2824 unsigned GPRIdx = 0;
2825 unsigned FPRIdx = 0;
2826 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002827 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002828 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2829 unsigned SrcReg;
2830 switch (VT.SimpleTy) {
2831 default: llvm_unreachable("Unexpected value type.");
2832 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2833 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2834 case MVT::f32: // fall-through
2835 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2836 }
2837 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2838 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2839 // Without this, EmitLiveInCopies may eliminate the livein if its only
2840 // use is a bitcast (which isn't turned into an instruction).
2841 unsigned ResultReg = createResultReg(RC);
2842 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2843 TII.get(TargetOpcode::COPY), ResultReg)
2844 .addReg(DstReg, getKillRegState(true));
2845 updateValueMap(&Arg, ResultReg);
2846 }
2847 return true;
2848}
2849
2850static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2851 CallingConv::ID CC,
2852 ImmutableCallSite *CS) {
2853 if (Subtarget->is64Bit())
2854 return 0;
2855 if (Subtarget->getTargetTriple().isOSMSVCRT())
2856 return 0;
2857 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2858 CC == CallingConv::HiPE)
2859 return 0;
Sanjoy Dasb11b4402015-11-04 20:33:45 +00002860
2861 if (CS)
2862 if (CS->arg_empty() || !CS->paramHasAttr(1, Attribute::StructRet) ||
Michael Kuperstein2ea81ba2015-12-28 14:39:21 +00002863 CS->paramHasAttr(1, Attribute::InReg) || Subtarget->isTargetMCU())
Sanjoy Dasb11b4402015-11-04 20:33:45 +00002864 return 0;
2865
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002866 return 4;
2867}
2868
2869bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2870 auto &OutVals = CLI.OutVals;
2871 auto &OutFlags = CLI.OutFlags;
2872 auto &OutRegs = CLI.OutRegs;
2873 auto &Ins = CLI.Ins;
2874 auto &InRegs = CLI.InRegs;
2875 CallingConv::ID CC = CLI.CallConv;
2876 bool &IsTailCall = CLI.IsTailCall;
2877 bool IsVarArg = CLI.IsVarArg;
2878 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00002879 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002880
2881 bool Is64Bit = Subtarget->is64Bit();
2882 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2883
2884 // Handle only C, fastcc, and webkit_js calling conventions for now.
2885 switch (CC) {
2886 default: return false;
2887 case CallingConv::C:
2888 case CallingConv::Fast:
2889 case CallingConv::WebKit_JS:
Manman Renf8bdd882016-04-05 22:41:47 +00002890 case CallingConv::Swift:
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002891 case CallingConv::X86_FastCall:
2892 case CallingConv::X86_64_Win64:
2893 case CallingConv::X86_64_SysV:
2894 break;
2895 }
2896
2897 // Allow SelectionDAG isel to handle tail calls.
2898 if (IsTailCall)
2899 return false;
2900
2901 // fastcc with -tailcallopt is intended to provide a guaranteed
2902 // tail call optimization. Fastisel doesn't know how to do that.
2903 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2904 return false;
2905
2906 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2907 // x86-32. Special handling for x86-64 is implemented.
2908 if (IsVarArg && IsWin64)
2909 return false;
2910
2911 // Don't know about inalloca yet.
2912 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2913 return false;
2914
Manman Ren57518142016-04-11 21:08:06 +00002915 for (auto Flag : CLI.OutFlags)
2916 if (Flag.isSwiftError())
2917 return false;
2918
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002919 // Fast-isel doesn't know about callee-pop yet.
2920 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2921 TM.Options.GuaranteedTailCallOpt))
2922 return false;
2923
2924 SmallVector<MVT, 16> OutVTs;
2925 SmallVector<unsigned, 16> ArgRegs;
2926
2927 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2928 // instruction. This is safe because it is common to all FastISel supported
2929 // calling conventions on x86.
2930 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2931 Value *&Val = OutVals[i];
2932 ISD::ArgFlagsTy Flags = OutFlags[i];
2933 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2934 if (CI->getBitWidth() < 32) {
2935 if (Flags.isSExt())
2936 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2937 else
2938 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2939 }
2940 }
2941
2942 // Passing bools around ends up doing a trunc to i1 and passing it.
2943 // Codegen this as an argument + "and 1".
2944 MVT VT;
2945 auto *TI = dyn_cast<TruncInst>(Val);
2946 unsigned ResultReg;
2947 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2948 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2949 TI->hasOneUse()) {
2950 Value *PrevVal = TI->getOperand(0);
2951 ResultReg = getRegForValue(PrevVal);
2952
2953 if (!ResultReg)
2954 return false;
2955
2956 if (!isTypeLegal(PrevVal->getType(), VT))
2957 return false;
2958
2959 ResultReg =
2960 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2961 } else {
2962 if (!isTypeLegal(Val->getType(), VT))
2963 return false;
2964 ResultReg = getRegForValue(Val);
2965 }
2966
2967 if (!ResultReg)
2968 return false;
2969
2970 ArgRegs.push_back(ResultReg);
2971 OutVTs.push_back(VT);
2972 }
2973
2974 // Analyze operands of the call, assigning locations to each operand.
2975 SmallVector<CCValAssign, 16> ArgLocs;
2976 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2977
2978 // Allocate shadow area for Win64
2979 if (IsWin64)
2980 CCInfo.AllocateStack(32, 8);
2981
2982 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2983
2984 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00002985 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002986
2987 // Issue CALLSEQ_START
2988 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2989 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002990 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002991
2992 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00002993 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002994 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2995 CCValAssign const &VA = ArgLocs[i];
2996 const Value *ArgVal = OutVals[VA.getValNo()];
2997 MVT ArgVT = OutVTs[VA.getValNo()];
2998
2999 if (ArgVT == MVT::x86mmx)
3000 return false;
3001
3002 unsigned ArgReg = ArgRegs[VA.getValNo()];
3003
3004 // Promote the value if needed.
3005 switch (VA.getLocInfo()) {
3006 case CCValAssign::Full: break;
3007 case CCValAssign::SExt: {
3008 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3009 "Unexpected extend");
3010 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3011 ArgVT, ArgReg);
3012 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3013 ArgVT = VA.getLocVT();
3014 break;
3015 }
3016 case CCValAssign::ZExt: {
3017 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3018 "Unexpected extend");
3019 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3020 ArgVT, ArgReg);
3021 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3022 ArgVT = VA.getLocVT();
3023 break;
3024 }
3025 case CCValAssign::AExt: {
3026 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3027 "Unexpected extend");
3028 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3029 ArgVT, ArgReg);
3030 if (!Emitted)
3031 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3032 ArgVT, ArgReg);
3033 if (!Emitted)
3034 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3035 ArgVT, ArgReg);
3036
3037 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3038 ArgVT = VA.getLocVT();
3039 break;
3040 }
3041 case CCValAssign::BCvt: {
3042 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
3043 /*TODO: Kill=*/false);
3044 assert(ArgReg && "Failed to emit a bitcast!");
3045 ArgVT = VA.getLocVT();
3046 break;
3047 }
3048 case CCValAssign::VExt:
3049 // VExt has not been implemented, so this should be impossible to reach
3050 // for now. However, fallback to Selection DAG isel once implemented.
3051 return false;
3052 case CCValAssign::AExtUpper:
3053 case CCValAssign::SExtUpper:
3054 case CCValAssign::ZExtUpper:
3055 case CCValAssign::FPExt:
3056 llvm_unreachable("Unexpected loc info!");
3057 case CCValAssign::Indirect:
3058 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3059 // support this.
3060 return false;
3061 }
3062
3063 if (VA.isRegLoc()) {
3064 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3065 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3066 OutRegs.push_back(VA.getLocReg());
3067 } else {
3068 assert(VA.isMemLoc());
3069
3070 // Don't emit stores for undef values.
3071 if (isa<UndefValue>(ArgVal))
3072 continue;
3073
3074 unsigned LocMemOffset = VA.getLocMemOffset();
3075 X86AddressMode AM;
3076 AM.Base.Reg = RegInfo->getStackRegister();
3077 AM.Disp = LocMemOffset;
3078 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3079 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3080 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003081 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3082 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003083 if (Flags.isByVal()) {
3084 X86AddressMode SrcAM;
3085 SrcAM.Base.Reg = ArgReg;
3086 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3087 return false;
3088 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3089 // If this is a really simple value, emit this with the Value* version
3090 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3091 // as it can cause us to reevaluate the argument.
3092 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3093 return false;
3094 } else {
3095 bool ValIsKill = hasTrivialKill(ArgVal);
3096 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3097 return false;
3098 }
3099 }
3100 }
3101
3102 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3103 // GOT pointer.
3104 if (Subtarget->isPICStyleGOT()) {
3105 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3106 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3107 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3108 }
3109
3110 if (Is64Bit && IsVarArg && !IsWin64) {
3111 // From AMD64 ABI document:
3112 // For calls that may call functions that use varargs or stdargs
3113 // (prototype-less calls or calls to functions containing ellipsis (...) in
3114 // the declaration) %al is used as hidden argument to specify the number
3115 // of SSE registers used. The contents of %al do not need to match exactly
3116 // the number of registers, but must be an ubound on the number of SSE
3117 // registers used and is in the range 0 - 8 inclusive.
3118
3119 // Count the number of XMM registers allocated.
3120 static const MCPhysReg XMMArgRegs[] = {
3121 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3122 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3123 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003124 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003125 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3126 && "SSE registers cannot be used when SSE is disabled");
3127 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3128 X86::AL).addImm(NumXMMRegs);
3129 }
3130
3131 // Materialize callee address in a register. FIXME: GV address can be
3132 // handled with a CALLpcrel32 instead.
3133 X86AddressMode CalleeAM;
3134 if (!X86SelectCallAddress(Callee, CalleeAM))
3135 return false;
3136
3137 unsigned CalleeOp = 0;
3138 const GlobalValue *GV = nullptr;
3139 if (CalleeAM.GV != nullptr) {
3140 GV = CalleeAM.GV;
3141 } else if (CalleeAM.Base.Reg != 0) {
3142 CalleeOp = CalleeAM.Base.Reg;
3143 } else
3144 return false;
3145
3146 // Issue the call.
3147 MachineInstrBuilder MIB;
3148 if (CalleeOp) {
3149 // Register-indirect call.
3150 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3151 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3152 .addReg(CalleeOp);
3153 } else {
3154 // Direct call.
3155 assert(GV && "Not a direct call");
3156 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3157
3158 // See if we need any target-specific flags on the GV operand.
3159 unsigned char OpFlags = 0;
3160
3161 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3162 // external symbols most go through the PLT in PIC mode. If the symbol
3163 // has hidden or protected visibility, or if it is static or local, then
3164 // we don't need to use the PLT - we can directly call it.
3165 if (Subtarget->isTargetELF() &&
3166 TM.getRelocationModel() == Reloc::PIC_ &&
3167 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3168 OpFlags = X86II::MO_PLT;
3169 } else if (Subtarget->isPICStyleStubAny() &&
Peter Collingbourne6a9d1772015-07-05 20:52:35 +00003170 !GV->isStrongDefinitionForLinker() &&
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003171 (!Subtarget->getTargetTriple().isMacOSX() ||
3172 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3173 // PC-relative references to external symbols should go through $stub,
3174 // unless we're building with the leopard linker or later, which
3175 // automatically synthesizes these stubs.
3176 OpFlags = X86II::MO_DARWIN_STUB;
3177 }
3178
3179 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003180 if (Symbol)
3181 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003182 else
3183 MIB.addGlobalAddress(GV, 0, OpFlags);
3184 }
3185
3186 // Add a register mask operand representing the call-preserved registers.
3187 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003188 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003189
3190 // Add an implicit use GOT pointer in EBX.
3191 if (Subtarget->isPICStyleGOT())
3192 MIB.addReg(X86::EBX, RegState::Implicit);
3193
3194 if (Is64Bit && IsVarArg && !IsWin64)
3195 MIB.addReg(X86::AL, RegState::Implicit);
3196
3197 // Add implicit physical register uses to the call.
3198 for (auto Reg : OutRegs)
3199 MIB.addReg(Reg, RegState::Implicit);
3200
3201 // Issue CALLSEQ_END
3202 unsigned NumBytesForCalleeToPop =
3203 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3204 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3205 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3206 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3207
3208 // Now handle call return values.
3209 SmallVector<CCValAssign, 16> RVLocs;
3210 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3211 CLI.RetTy->getContext());
3212 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3213
3214 // Copy all of the result registers out of their specified physreg.
3215 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3216 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3217 CCValAssign &VA = RVLocs[i];
3218 EVT CopyVT = VA.getValVT();
3219 unsigned CopyReg = ResultReg + i;
3220
3221 // If this is x86-64, and we disabled SSE, we can't return FP values
3222 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3223 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3224 report_fatal_error("SSE register return with SSE disabled");
3225 }
3226
3227 // If we prefer to use the value in xmm registers, copy it out as f80 and
3228 // use a truncate to move it from fp stack reg to xmm reg.
3229 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3230 isScalarFPTypeInSSEReg(VA.getValVT())) {
3231 CopyVT = MVT::f80;
3232 CopyReg = createResultReg(&X86::RFP80RegClass);
3233 }
3234
3235 // Copy out the result.
3236 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3237 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3238 InRegs.push_back(VA.getLocReg());
3239
3240 // Round the f80 to the right size, which also moves it to the appropriate
3241 // xmm register. This is accomplished by storing the f80 value in memory
3242 // and then loading it back.
3243 if (CopyVT != VA.getValVT()) {
3244 EVT ResVT = VA.getValVT();
3245 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3246 unsigned MemSize = ResVT.getSizeInBits()/8;
3247 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3248 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3249 TII.get(Opc)), FI)
3250 .addReg(CopyReg);
3251 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3252 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3253 TII.get(Opc), ResultReg + i), FI);
3254 }
3255 }
3256
3257 CLI.ResultReg = ResultReg;
3258 CLI.NumResultRegs = RVLocs.size();
3259 CLI.Call = MIB;
3260
3261 return true;
3262}
3263
3264bool
3265X86FastISel::fastSelectInstruction(const Instruction *I) {
3266 switch (I->getOpcode()) {
3267 default: break;
3268 case Instruction::Load:
3269 return X86SelectLoad(I);
3270 case Instruction::Store:
3271 return X86SelectStore(I);
3272 case Instruction::Ret:
3273 return X86SelectRet(I);
3274 case Instruction::ICmp:
3275 case Instruction::FCmp:
3276 return X86SelectCmp(I);
3277 case Instruction::ZExt:
3278 return X86SelectZExt(I);
3279 case Instruction::Br:
3280 return X86SelectBranch(I);
3281 case Instruction::LShr:
3282 case Instruction::AShr:
3283 case Instruction::Shl:
3284 return X86SelectShift(I);
3285 case Instruction::SDiv:
3286 case Instruction::UDiv:
3287 case Instruction::SRem:
3288 case Instruction::URem:
3289 return X86SelectDivRem(I);
3290 case Instruction::Select:
3291 return X86SelectSelect(I);
3292 case Instruction::Trunc:
3293 return X86SelectTrunc(I);
3294 case Instruction::FPExt:
3295 return X86SelectFPExt(I);
3296 case Instruction::FPTrunc:
3297 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003298 case Instruction::SIToFP:
3299 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003300 case Instruction::IntToPtr: // Deliberate fall-through.
3301 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003302 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3303 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003304 if (DstVT.bitsGT(SrcVT))
3305 return X86SelectZExt(I);
3306 if (DstVT.bitsLT(SrcVT))
3307 return X86SelectTrunc(I);
3308 unsigned Reg = getRegForValue(I->getOperand(0));
3309 if (Reg == 0) return false;
3310 updateValueMap(I, Reg);
3311 return true;
3312 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003313 case Instruction::BitCast: {
3314 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3315 if (!Subtarget->hasSSE2())
3316 return false;
3317
3318 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3319 EVT DstVT = TLI.getValueType(DL, I->getType());
3320
3321 if (!SrcVT.isSimple() || !DstVT.isSimple())
3322 return false;
3323
3324 if (!SrcVT.is128BitVector() &&
3325 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3326 return false;
3327
3328 unsigned Reg = getRegForValue(I->getOperand(0));
3329 if (Reg == 0)
3330 return false;
3331
3332 // No instruction is needed for conversion. Reuse the register used by
3333 // the fist operand.
3334 updateValueMap(I, Reg);
3335 return true;
3336 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003337 }
3338
3339 return false;
3340}
3341
3342unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3343 if (VT > MVT::i64)
3344 return 0;
3345
3346 uint64_t Imm = CI->getZExtValue();
3347 if (Imm == 0) {
3348 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3349 switch (VT.SimpleTy) {
3350 default: llvm_unreachable("Unexpected value type");
3351 case MVT::i1:
3352 case MVT::i8:
3353 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3354 X86::sub_8bit);
3355 case MVT::i16:
3356 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3357 X86::sub_16bit);
3358 case MVT::i32:
3359 return SrcReg;
3360 case MVT::i64: {
3361 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3362 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3363 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3364 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3365 return ResultReg;
3366 }
3367 }
3368 }
3369
3370 unsigned Opc = 0;
3371 switch (VT.SimpleTy) {
3372 default: llvm_unreachable("Unexpected value type");
3373 case MVT::i1: VT = MVT::i8; // fall-through
3374 case MVT::i8: Opc = X86::MOV8ri; break;
3375 case MVT::i16: Opc = X86::MOV16ri; break;
3376 case MVT::i32: Opc = X86::MOV32ri; break;
3377 case MVT::i64: {
3378 if (isUInt<32>(Imm))
3379 Opc = X86::MOV32ri;
3380 else if (isInt<32>(Imm))
3381 Opc = X86::MOV64ri32;
3382 else
3383 Opc = X86::MOV64ri;
3384 break;
3385 }
3386 }
3387 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3388 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3389 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3390 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3391 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3392 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3393 return ResultReg;
3394 }
3395 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3396}
3397
3398unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3399 if (CFP->isNullValue())
3400 return fastMaterializeFloatZero(CFP);
3401
3402 // Can't handle alternate code models yet.
3403 CodeModel::Model CM = TM.getCodeModel();
3404 if (CM != CodeModel::Small && CM != CodeModel::Large)
3405 return 0;
3406
3407 // Get opcode and regclass of the output for the given load instruction.
3408 unsigned Opc = 0;
3409 const TargetRegisterClass *RC = nullptr;
3410 switch (VT.SimpleTy) {
3411 default: return 0;
3412 case MVT::f32:
3413 if (X86ScalarSSEf32) {
3414 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3415 RC = &X86::FR32RegClass;
3416 } else {
3417 Opc = X86::LD_Fp32m;
3418 RC = &X86::RFP32RegClass;
3419 }
3420 break;
3421 case MVT::f64:
3422 if (X86ScalarSSEf64) {
3423 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3424 RC = &X86::FR64RegClass;
3425 } else {
3426 Opc = X86::LD_Fp64m;
3427 RC = &X86::RFP64RegClass;
3428 }
3429 break;
3430 case MVT::f80:
3431 // No f80 support yet.
3432 return 0;
3433 }
3434
3435 // MachineConstantPool wants an explicit alignment.
3436 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3437 if (Align == 0) {
3438 // Alignment of vector types. FIXME!
3439 Align = DL.getTypeAllocSize(CFP->getType());
3440 }
3441
3442 // x86-32 PIC requires a PIC base register for constant pools.
3443 unsigned PICBase = 0;
3444 unsigned char OpFlag = 0;
3445 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3446 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3447 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3448 } else if (Subtarget->isPICStyleGOT()) {
3449 OpFlag = X86II::MO_GOTOFF;
3450 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3451 } else if (Subtarget->isPICStyleRIPRel() &&
3452 TM.getCodeModel() == CodeModel::Small) {
3453 PICBase = X86::RIP;
3454 }
3455
3456 // Create the load from the constant pool.
3457 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3458 unsigned ResultReg = createResultReg(RC);
3459
3460 if (CM == CodeModel::Large) {
3461 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3462 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3463 AddrReg)
3464 .addConstantPoolIndex(CPI, 0, OpFlag);
3465 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3466 TII.get(Opc), ResultReg);
3467 addDirectMem(MIB, AddrReg);
3468 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003469 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3470 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003471 MIB->addMemOperand(*FuncInfo.MF, MMO);
3472 return ResultReg;
3473 }
3474
3475 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3476 TII.get(Opc), ResultReg),
3477 CPI, PICBase, OpFlag);
3478 return ResultReg;
3479}
3480
3481unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3482 // Can't handle alternate code models yet.
3483 if (TM.getCodeModel() != CodeModel::Small)
3484 return 0;
3485
3486 // Materialize addresses with LEA/MOV instructions.
3487 X86AddressMode AM;
3488 if (X86SelectAddress(GV, AM)) {
3489 // If the expression is just a basereg, then we're done, otherwise we need
3490 // to emit an LEA.
3491 if (AM.BaseType == X86AddressMode::RegBase &&
3492 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3493 return AM.Base.Reg;
3494
3495 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3496 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003497 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003498 // The displacement code could be more than 32 bits away so we need to use
3499 // an instruction with a 64 bit immediate
3500 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3501 ResultReg)
3502 .addGlobalAddress(GV);
3503 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003504 unsigned Opc =
3505 TLI.getPointerTy(DL) == MVT::i32
3506 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3507 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003508 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3509 TII.get(Opc), ResultReg), AM);
3510 }
3511 return ResultReg;
3512 }
3513 return 0;
3514}
3515
3516unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003517 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003518
3519 // Only handle simple types.
3520 if (!CEVT.isSimple())
3521 return 0;
3522 MVT VT = CEVT.getSimpleVT();
3523
3524 if (const auto *CI = dyn_cast<ConstantInt>(C))
3525 return X86MaterializeInt(CI, VT);
3526 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3527 return X86MaterializeFP(CFP, VT);
3528 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3529 return X86MaterializeGV(GV, VT);
3530
3531 return 0;
3532}
3533
3534unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3535 // Fail on dynamic allocas. At this point, getRegForValue has already
3536 // checked its CSE maps, so if we're here trying to handle a dynamic
3537 // alloca, we're not going to succeed. X86SelectAddress has a
3538 // check for dynamic allocas, because it's called directly from
3539 // various places, but targetMaterializeAlloca also needs a check
3540 // in order to avoid recursion between getRegForValue,
3541 // X86SelectAddrss, and targetMaterializeAlloca.
3542 if (!FuncInfo.StaticAllocaMap.count(C))
3543 return 0;
3544 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3545
3546 X86AddressMode AM;
3547 if (!X86SelectAddress(C, AM))
3548 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003549 unsigned Opc =
3550 TLI.getPointerTy(DL) == MVT::i32
3551 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3552 : X86::LEA64r;
3553 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003554 unsigned ResultReg = createResultReg(RC);
3555 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3556 TII.get(Opc), ResultReg), AM);
3557 return ResultReg;
3558}
3559
3560unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3561 MVT VT;
3562 if (!isTypeLegal(CF->getType(), VT))
3563 return 0;
3564
3565 // Get opcode and regclass for the given zero.
3566 unsigned Opc = 0;
3567 const TargetRegisterClass *RC = nullptr;
3568 switch (VT.SimpleTy) {
3569 default: return 0;
3570 case MVT::f32:
3571 if (X86ScalarSSEf32) {
3572 Opc = X86::FsFLD0SS;
3573 RC = &X86::FR32RegClass;
3574 } else {
3575 Opc = X86::LD_Fp032;
3576 RC = &X86::RFP32RegClass;
3577 }
3578 break;
3579 case MVT::f64:
3580 if (X86ScalarSSEf64) {
3581 Opc = X86::FsFLD0SD;
3582 RC = &X86::FR64RegClass;
3583 } else {
3584 Opc = X86::LD_Fp064;
3585 RC = &X86::RFP64RegClass;
3586 }
3587 break;
3588 case MVT::f80:
3589 // No f80 support yet.
3590 return 0;
3591 }
3592
3593 unsigned ResultReg = createResultReg(RC);
3594 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3595 return ResultReg;
3596}
3597
3598
3599bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3600 const LoadInst *LI) {
3601 const Value *Ptr = LI->getPointerOperand();
3602 X86AddressMode AM;
3603 if (!X86SelectAddress(Ptr, AM))
3604 return false;
3605
3606 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3607
3608 unsigned Size = DL.getTypeAllocSize(LI->getType());
3609 unsigned Alignment = LI->getAlignment();
3610
3611 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3612 Alignment = DL.getABITypeAlignment(LI->getType());
3613
3614 SmallVector<MachineOperand, 8> AddrOps;
3615 AM.getFullAddress(AddrOps);
3616
Keno Fischere70b31f2015-06-08 20:09:58 +00003617 MachineInstr *Result = XII.foldMemoryOperandImpl(
3618 *FuncInfo.MF, MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3619 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003620 if (!Result)
3621 return false;
3622
Pete Cooperd31583d2015-05-06 21:37:19 +00003623 // The index register could be in the wrong register class. Unfortunately,
3624 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3625 // to just look at OpNo + the offset to the index reg. We actually need to
3626 // scan the instruction to find the index reg and see if its the correct reg
3627 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003628 unsigned OperandNo = 0;
3629 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3630 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3631 MachineOperand &MO = *I;
3632 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003633 continue;
3634 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003635 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003636 MO.getReg(), OperandNo);
3637 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003638 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003639 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003640 }
3641
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003642 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003643 MI->eraseFromParent();
3644 return true;
3645}
3646
3647
3648namespace llvm {
3649 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3650 const TargetLibraryInfo *libInfo) {
3651 return new X86FastISel(funcInfo, libInfo);
3652 }
3653}