blob: 17704da91c2a72d5fb0e5aaac250b8e691fb1d80 [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
301 BasicBlock::const_iterator Start = I;
302 BasicBlock::const_iterator End = II;
303 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) {
436 // Get opcode and regclass of the output for the given store instruction.
437 unsigned Opc = 0;
438 switch (VT.getSimpleVT().SimpleTy) {
439 case MVT::f80: // No f80 support yet.
440 default: return false;
441 case MVT::i1: {
442 // Mask out all but lowest bit.
443 unsigned AndResult = createResultReg(&X86::GR8RegClass);
444 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
445 TII.get(X86::AND8ri), AndResult)
446 .addReg(ValReg, getKillRegState(ValIsKill)).addImm(1);
447 ValReg = AndResult;
448 }
449 // FALLTHROUGH, handling i1 as i8.
450 case MVT::i8: Opc = X86::MOV8mr; break;
451 case MVT::i16: Opc = X86::MOV16mr; break;
452 case MVT::i32: Opc = X86::MOV32mr; break;
453 case MVT::i64: Opc = X86::MOV64mr; break; // Must be in x86-64 mode.
454 case MVT::f32:
455 Opc = X86ScalarSSEf32 ?
456 (Subtarget->hasAVX() ? X86::VMOVSSmr : X86::MOVSSmr) : X86::ST_Fp32m;
457 break;
458 case MVT::f64:
459 Opc = X86ScalarSSEf64 ?
460 (Subtarget->hasAVX() ? X86::VMOVSDmr : X86::MOVSDmr) : X86::ST_Fp64m;
461 break;
462 case MVT::v4f32:
463 if (Aligned)
464 Opc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
465 else
466 Opc = Subtarget->hasAVX() ? X86::VMOVUPSmr : X86::MOVUPSmr;
467 break;
468 case MVT::v2f64:
469 if (Aligned)
470 Opc = Subtarget->hasAVX() ? X86::VMOVAPDmr : X86::MOVAPDmr;
471 else
472 Opc = Subtarget->hasAVX() ? X86::VMOVUPDmr : X86::MOVUPDmr;
473 break;
474 case MVT::v4i32:
475 case MVT::v2i64:
476 case MVT::v8i16:
477 case MVT::v16i8:
478 if (Aligned)
479 Opc = Subtarget->hasAVX() ? X86::VMOVDQAmr : X86::MOVDQAmr;
480 else
481 Opc = Subtarget->hasAVX() ? X86::VMOVDQUmr : X86::MOVDQUmr;
482 break;
483 }
484
485 MachineInstrBuilder MIB =
486 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
487 addFullAddress(MIB, AM).addReg(ValReg, getKillRegState(ValIsKill));
488 if (MMO)
489 MIB->addMemOperand(*FuncInfo.MF, MMO);
490
491 return true;
492}
493
494bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
Pete Cooperd0dae3e2015-05-05 23:41:53 +0000495 X86AddressMode &AM,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000496 MachineMemOperand *MMO, bool Aligned) {
497 // Handle 'null' like i32/i64 0.
498 if (isa<ConstantPointerNull>(Val))
499 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
500
501 // If this is a store of a simple constant, fold the constant into the store.
502 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
503 unsigned Opc = 0;
504 bool Signed = true;
505 switch (VT.getSimpleVT().SimpleTy) {
506 default: break;
507 case MVT::i1: Signed = false; // FALLTHROUGH to handle as i8.
508 case MVT::i8: Opc = X86::MOV8mi; break;
509 case MVT::i16: Opc = X86::MOV16mi; break;
510 case MVT::i32: Opc = X86::MOV32mi; break;
511 case MVT::i64:
512 // Must be a 32-bit sign extended value.
513 if (isInt<32>(CI->getSExtValue()))
514 Opc = X86::MOV64mi32;
515 break;
516 }
517
518 if (Opc) {
519 MachineInstrBuilder MIB =
520 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
521 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
522 : CI->getZExtValue());
523 if (MMO)
524 MIB->addMemOperand(*FuncInfo.MF, MMO);
525 return true;
526 }
527 }
528
529 unsigned ValReg = getRegForValue(Val);
530 if (ValReg == 0)
531 return false;
532
533 bool ValKill = hasTrivialKill(Val);
534 return X86FastEmitStore(VT, ValReg, ValKill, AM, MMO, Aligned);
535}
536
537/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
538/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
539/// ISD::SIGN_EXTEND).
540bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
541 unsigned Src, EVT SrcVT,
542 unsigned &ResultReg) {
543 unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
544 Src, /*TODO: Kill=*/false);
545 if (RR == 0)
546 return false;
547
548 ResultReg = RR;
549 return true;
550}
551
552bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
553 // Handle constant address.
554 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
555 // Can't handle alternate code models yet.
556 if (TM.getCodeModel() != CodeModel::Small)
557 return false;
558
559 // Can't handle TLS yet.
560 if (GV->isThreadLocal())
561 return false;
562
563 // RIP-relative addresses can't have additional register operands, so if
564 // we've already folded stuff into the addressing mode, just force the
565 // global value into its own register, which we can use as the basereg.
566 if (!Subtarget->isPICStyleRIPRel() ||
567 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
568 // Okay, we've committed to selecting this global. Set up the address.
569 AM.GV = GV;
570
571 // Allow the subtarget to classify the global.
572 unsigned char GVFlags = Subtarget->ClassifyGlobalReference(GV, TM);
573
574 // If this reference is relative to the pic base, set it now.
575 if (isGlobalRelativeToPICBase(GVFlags)) {
576 // FIXME: How do we know Base.Reg is free??
577 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
578 }
579
580 // Unless the ABI requires an extra load, return a direct reference to
581 // the global.
582 if (!isGlobalStubReference(GVFlags)) {
583 if (Subtarget->isPICStyleRIPRel()) {
584 // Use rip-relative addressing if we can. Above we verified that the
585 // base and index registers are unused.
586 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
587 AM.Base.Reg = X86::RIP;
588 }
589 AM.GVOpFlags = GVFlags;
590 return true;
591 }
592
593 // Ok, we need to do a load from a stub. If we've already loaded from
594 // this stub, reuse the loaded pointer, otherwise emit the load now.
595 DenseMap<const Value *, unsigned>::iterator I = LocalValueMap.find(V);
596 unsigned LoadReg;
597 if (I != LocalValueMap.end() && I->second != 0) {
598 LoadReg = I->second;
599 } else {
600 // Issue load from stub.
601 unsigned Opc = 0;
602 const TargetRegisterClass *RC = nullptr;
603 X86AddressMode StubAM;
604 StubAM.Base.Reg = AM.Base.Reg;
605 StubAM.GV = GV;
606 StubAM.GVOpFlags = GVFlags;
607
608 // Prepare for inserting code in the local-value area.
609 SavePoint SaveInsertPt = enterLocalValueArea();
610
Mehdi Amini44ede332015-07-09 02:09:04 +0000611 if (TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000612 Opc = X86::MOV64rm;
613 RC = &X86::GR64RegClass;
614
615 if (Subtarget->isPICStyleRIPRel())
616 StubAM.Base.Reg = X86::RIP;
617 } else {
618 Opc = X86::MOV32rm;
619 RC = &X86::GR32RegClass;
620 }
621
622 LoadReg = createResultReg(RC);
623 MachineInstrBuilder LoadMI =
624 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
625 addFullAddress(LoadMI, StubAM);
626
627 // Ok, back to normal mode.
628 leaveLocalValueArea(SaveInsertPt);
629
630 // Prevent loading GV stub multiple times in same MBB.
631 LocalValueMap[V] = LoadReg;
632 }
633
634 // Now construct the final address. Note that the Disp, Scale,
635 // and Index values may already be set here.
636 AM.Base.Reg = LoadReg;
637 AM.GV = nullptr;
638 return true;
639 }
640 }
641
642 // If all else fails, try to materialize the value in a register.
643 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
644 if (AM.Base.Reg == 0) {
645 AM.Base.Reg = getRegForValue(V);
646 return AM.Base.Reg != 0;
647 }
648 if (AM.IndexReg == 0) {
649 assert(AM.Scale == 1 && "Scale with no index!");
650 AM.IndexReg = getRegForValue(V);
651 return AM.IndexReg != 0;
652 }
653 }
654
655 return false;
656}
657
658/// X86SelectAddress - Attempt to fill in an address from the given value.
659///
660bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
661 SmallVector<const Value *, 32> GEPs;
662redo_gep:
663 const User *U = nullptr;
664 unsigned Opcode = Instruction::UserOp1;
665 if (const Instruction *I = dyn_cast<Instruction>(V)) {
666 // Don't walk into other basic blocks; it's possible we haven't
667 // visited them yet, so the instructions may not yet be assigned
668 // virtual registers.
669 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
670 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
671 Opcode = I->getOpcode();
672 U = I;
673 }
674 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
675 Opcode = C->getOpcode();
676 U = C;
677 }
678
679 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
680 if (Ty->getAddressSpace() > 255)
681 // Fast instruction selection doesn't support the special
682 // address spaces.
683 return false;
684
685 switch (Opcode) {
686 default: break;
687 case Instruction::BitCast:
688 // Look past bitcasts.
689 return X86SelectAddress(U->getOperand(0), AM);
690
691 case Instruction::IntToPtr:
692 // Look past no-op inttoptrs.
Mehdi Amini44ede332015-07-09 02:09:04 +0000693 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
694 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000695 return X86SelectAddress(U->getOperand(0), AM);
696 break;
697
698 case Instruction::PtrToInt:
699 // Look past no-op ptrtoints.
Mehdi Amini44ede332015-07-09 02:09:04 +0000700 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000701 return X86SelectAddress(U->getOperand(0), AM);
702 break;
703
704 case Instruction::Alloca: {
705 // Do static allocas.
706 const AllocaInst *A = cast<AllocaInst>(V);
707 DenseMap<const AllocaInst *, int>::iterator SI =
708 FuncInfo.StaticAllocaMap.find(A);
709 if (SI != FuncInfo.StaticAllocaMap.end()) {
710 AM.BaseType = X86AddressMode::FrameIndexBase;
711 AM.Base.FrameIndex = SI->second;
712 return true;
713 }
714 break;
715 }
716
717 case Instruction::Add: {
718 // Adds of constants are common and easy enough.
719 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
720 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
721 // They have to fit in the 32-bit signed displacement field though.
722 if (isInt<32>(Disp)) {
723 AM.Disp = (uint32_t)Disp;
724 return X86SelectAddress(U->getOperand(0), AM);
725 }
726 }
727 break;
728 }
729
730 case Instruction::GetElementPtr: {
731 X86AddressMode SavedAM = AM;
732
733 // Pattern-match simple GEPs.
734 uint64_t Disp = (int32_t)AM.Disp;
735 unsigned IndexReg = AM.IndexReg;
736 unsigned Scale = AM.Scale;
737 gep_type_iterator GTI = gep_type_begin(U);
738 // Iterate through the indices, folding what we can. Constants can be
739 // folded, and one dynamic index can be handled, if the scale is supported.
740 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
741 i != e; ++i, ++GTI) {
742 const Value *Op = *i;
743 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
744 const StructLayout *SL = DL.getStructLayout(STy);
745 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
746 continue;
747 }
748
749 // A array/variable index is always of the form i*S where S is the
750 // constant scale size. See if we can push the scale into immediates.
751 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
752 for (;;) {
753 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
754 // Constant-offset addressing.
755 Disp += CI->getSExtValue() * S;
756 break;
757 }
758 if (canFoldAddIntoGEP(U, Op)) {
759 // A compatible add with a constant operand. Fold the constant.
760 ConstantInt *CI =
761 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
762 Disp += CI->getSExtValue() * S;
763 // Iterate on the other operand.
764 Op = cast<AddOperator>(Op)->getOperand(0);
765 continue;
766 }
767 if (IndexReg == 0 &&
768 (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
769 (S == 1 || S == 2 || S == 4 || S == 8)) {
770 // Scaled-index addressing.
771 Scale = S;
772 IndexReg = getRegForGEPIndex(Op).first;
773 if (IndexReg == 0)
774 return false;
775 break;
776 }
777 // Unsupported.
778 goto unsupported_gep;
779 }
780 }
781
782 // Check for displacement overflow.
783 if (!isInt<32>(Disp))
784 break;
785
786 AM.IndexReg = IndexReg;
787 AM.Scale = Scale;
788 AM.Disp = (uint32_t)Disp;
789 GEPs.push_back(V);
790
791 if (const GetElementPtrInst *GEP =
792 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
793 // Ok, the GEP indices were covered by constant-offset and scaled-index
794 // addressing. Update the address state and move on to examining the base.
795 V = GEP;
796 goto redo_gep;
797 } else if (X86SelectAddress(U->getOperand(0), AM)) {
798 return true;
799 }
800
801 // If we couldn't merge the gep value into this addr mode, revert back to
802 // our address and just match the value instead of completely failing.
803 AM = SavedAM;
804
805 for (SmallVectorImpl<const Value *>::reverse_iterator
806 I = GEPs.rbegin(), E = GEPs.rend(); I != E; ++I)
807 if (handleConstantAddresses(*I, AM))
808 return true;
809
810 return false;
811 unsupported_gep:
812 // Ok, the GEP indices weren't all covered.
813 break;
814 }
815 }
816
817 return handleConstantAddresses(V, AM);
818}
819
820/// X86SelectCallAddress - Attempt to fill in an address from the given value.
821///
822bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
823 const User *U = nullptr;
824 unsigned Opcode = Instruction::UserOp1;
825 const Instruction *I = dyn_cast<Instruction>(V);
826 // Record if the value is defined in the same basic block.
827 //
828 // This information is crucial to know whether or not folding an
829 // operand is valid.
830 // Indeed, FastISel generates or reuses a virtual register for all
831 // operands of all instructions it selects. Obviously, the definition and
832 // its uses must use the same virtual register otherwise the produced
833 // code is incorrect.
834 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
835 // registers for values that are alive across basic blocks. This ensures
836 // that the values are consistently set between across basic block, even
837 // if different instruction selection mechanisms are used (e.g., a mix of
838 // SDISel and FastISel).
839 // For values local to a basic block, the instruction selection process
840 // generates these virtual registers with whatever method is appropriate
841 // for its needs. In particular, FastISel and SDISel do not share the way
842 // local virtual registers are set.
843 // Therefore, this is impossible (or at least unsafe) to share values
844 // between basic blocks unless they use the same instruction selection
845 // method, which is not guarantee for X86.
846 // Moreover, things like hasOneUse could not be used accurately, if we
847 // allow to reference values across basic blocks whereas they are not
848 // alive across basic blocks initially.
849 bool InMBB = true;
850 if (I) {
851 Opcode = I->getOpcode();
852 U = I;
853 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
854 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
855 Opcode = C->getOpcode();
856 U = C;
857 }
858
859 switch (Opcode) {
860 default: break;
861 case Instruction::BitCast:
862 // Look past bitcasts if its operand is in the same BB.
863 if (InMBB)
864 return X86SelectCallAddress(U->getOperand(0), AM);
865 break;
866
867 case Instruction::IntToPtr:
868 // Look past no-op inttoptrs if its operand is in the same BB.
869 if (InMBB &&
Mehdi Amini44ede332015-07-09 02:09:04 +0000870 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
871 TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000872 return X86SelectCallAddress(U->getOperand(0), AM);
873 break;
874
875 case Instruction::PtrToInt:
876 // Look past no-op ptrtoints if its operand is in the same BB.
Mehdi Amini44ede332015-07-09 02:09:04 +0000877 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000878 return X86SelectCallAddress(U->getOperand(0), AM);
879 break;
880 }
881
882 // Handle constant address.
883 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
884 // Can't handle alternate code models yet.
885 if (TM.getCodeModel() != CodeModel::Small)
886 return false;
887
888 // RIP-relative addresses can't have additional register operands.
889 if (Subtarget->isPICStyleRIPRel() &&
890 (AM.Base.Reg != 0 || AM.IndexReg != 0))
891 return false;
892
893 // Can't handle DLL Import.
894 if (GV->hasDLLImportStorageClass())
895 return false;
896
897 // Can't handle TLS.
898 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
899 if (GVar->isThreadLocal())
900 return false;
901
902 // Okay, we've committed to selecting this global. Set up the basic address.
903 AM.GV = GV;
904
905 // No ABI requires an extra load for anything other than DLLImport, which
906 // we rejected above. Return a direct reference to the global.
907 if (Subtarget->isPICStyleRIPRel()) {
908 // Use rip-relative addressing if we can. Above we verified that the
909 // base and index registers are unused.
910 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
911 AM.Base.Reg = X86::RIP;
912 } else if (Subtarget->isPICStyleStubPIC()) {
913 AM.GVOpFlags = X86II::MO_PIC_BASE_OFFSET;
914 } else if (Subtarget->isPICStyleGOT()) {
915 AM.GVOpFlags = X86II::MO_GOTOFF;
916 }
917
918 return true;
919 }
920
921 // If all else fails, try to materialize the value in a register.
922 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
923 if (AM.Base.Reg == 0) {
924 AM.Base.Reg = getRegForValue(V);
925 return AM.Base.Reg != 0;
926 }
927 if (AM.IndexReg == 0) {
928 assert(AM.Scale == 1 && "Scale with no index!");
929 AM.IndexReg = getRegForValue(V);
930 return AM.IndexReg != 0;
931 }
932 }
933
934 return false;
935}
936
937
938/// X86SelectStore - Select and emit code to implement store instructions.
939bool X86FastISel::X86SelectStore(const Instruction *I) {
940 // Atomic stores need special handling.
941 const StoreInst *S = cast<StoreInst>(I);
942
943 if (S->isAtomic())
944 return false;
945
946 const Value *Val = S->getValueOperand();
947 const Value *Ptr = S->getPointerOperand();
948
949 MVT VT;
950 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
951 return false;
952
953 unsigned Alignment = S->getAlignment();
954 unsigned ABIAlignment = DL.getABITypeAlignment(Val->getType());
955 if (Alignment == 0) // Ensure that codegen never sees alignment 0
956 Alignment = ABIAlignment;
957 bool Aligned = Alignment >= ABIAlignment;
958
959 X86AddressMode AM;
960 if (!X86SelectAddress(Ptr, AM))
961 return false;
962
963 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
964}
965
966/// X86SelectRet - Select and emit code to implement ret instructions.
967bool X86FastISel::X86SelectRet(const Instruction *I) {
968 const ReturnInst *Ret = cast<ReturnInst>(I);
969 const Function &F = *I->getParent()->getParent();
970 const X86MachineFunctionInfo *X86MFInfo =
971 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
972
973 if (!FuncInfo.CanLowerReturn)
974 return false;
975
976 CallingConv::ID CC = F.getCallingConv();
977 if (CC != CallingConv::C &&
978 CC != CallingConv::Fast &&
979 CC != CallingConv::X86_FastCall &&
980 CC != CallingConv::X86_64_SysV)
981 return false;
982
983 if (Subtarget->isCallingConvWin64(CC))
984 return false;
985
986 // Don't handle popping bytes on return for now.
987 if (X86MFInfo->getBytesToPopOnReturn() != 0)
988 return false;
989
990 // fastcc with -tailcallopt is intended to provide a guaranteed
991 // tail call optimization. Fastisel doesn't know how to do that.
992 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
993 return false;
994
995 // Let SDISel handle vararg functions.
996 if (F.isVarArg())
997 return false;
998
999 // Build a list of return value registers.
1000 SmallVector<unsigned, 4> RetRegs;
1001
1002 if (Ret->getNumOperands() > 0) {
1003 SmallVector<ISD::OutputArg, 4> Outs;
Mehdi Amini44ede332015-07-09 02:09:04 +00001004 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001005
1006 // Analyze operands of the call, assigning locations to each operand.
1007 SmallVector<CCValAssign, 16> ValLocs;
1008 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1009 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1010
1011 const Value *RV = Ret->getOperand(0);
1012 unsigned Reg = getRegForValue(RV);
1013 if (Reg == 0)
1014 return false;
1015
1016 // Only handle a single return value for now.
1017 if (ValLocs.size() != 1)
1018 return false;
1019
1020 CCValAssign &VA = ValLocs[0];
1021
1022 // Don't bother handling odd stuff for now.
1023 if (VA.getLocInfo() != CCValAssign::Full)
1024 return false;
1025 // Only handle register returns for now.
1026 if (!VA.isRegLoc())
1027 return false;
1028
1029 // The calling-convention tables for x87 returns don't tell
1030 // the whole story.
1031 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1032 return false;
1033
1034 unsigned SrcReg = Reg + VA.getValNo();
Mehdi Amini44ede332015-07-09 02:09:04 +00001035 EVT SrcVT = TLI.getValueType(DL, RV->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001036 EVT DstVT = VA.getValVT();
1037 // Special handling for extended integers.
1038 if (SrcVT != DstVT) {
1039 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1040 return false;
1041
1042 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1043 return false;
1044
1045 assert(DstVT == MVT::i32 && "X86 should always ext to i32");
1046
1047 if (SrcVT == MVT::i1) {
1048 if (Outs[0].Flags.isSExt())
1049 return false;
1050 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg, /*TODO: Kill=*/false);
1051 SrcVT = MVT::i8;
1052 }
1053 unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
1054 ISD::SIGN_EXTEND;
1055 SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op,
1056 SrcReg, /*TODO: Kill=*/false);
1057 }
1058
1059 // Make the copy.
1060 unsigned DstReg = VA.getLocReg();
1061 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1062 // Avoid a cross-class copy. This is very unlikely.
1063 if (!SrcRC->contains(DstReg))
1064 return false;
1065 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1066 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1067
1068 // Add register to return instruction.
1069 RetRegs.push_back(VA.getLocReg());
1070 }
1071
1072 // The x86-64 ABI for returning structs by value requires that we copy
1073 // the sret argument into %rax for the return. We saved the argument into
1074 // a virtual register in the entry block, so now we copy the value out
1075 // and into %rax. We also do the same with %eax for Win32.
1076 if (F.hasStructRetAttr() &&
1077 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1078 unsigned Reg = X86MFInfo->getSRetReturnReg();
1079 assert(Reg &&
1080 "SRetReturnReg should have been set in LowerFormalArguments()!");
1081 unsigned RetReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
1082 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1083 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1084 RetRegs.push_back(RetReg);
1085 }
1086
1087 // Now emit the RET.
1088 MachineInstrBuilder MIB =
1089 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1090 TII.get(Subtarget->is64Bit() ? X86::RETQ : X86::RETL));
1091 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
1092 MIB.addReg(RetRegs[i], RegState::Implicit);
1093 return true;
1094}
1095
1096/// X86SelectLoad - Select and emit code to implement load instructions.
1097///
1098bool X86FastISel::X86SelectLoad(const Instruction *I) {
1099 const LoadInst *LI = cast<LoadInst>(I);
1100
1101 // Atomic loads need special handling.
1102 if (LI->isAtomic())
1103 return false;
1104
1105 MVT VT;
1106 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1107 return false;
1108
1109 const Value *Ptr = LI->getPointerOperand();
1110
1111 X86AddressMode AM;
1112 if (!X86SelectAddress(Ptr, AM))
1113 return false;
1114
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001115 unsigned Alignment = LI->getAlignment();
1116 unsigned ABIAlignment = DL.getABITypeAlignment(LI->getType());
1117 if (Alignment == 0) // Ensure that codegen never sees alignment 0
1118 Alignment = ABIAlignment;
1119
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001120 unsigned ResultReg = 0;
Andrea Di Biagio8f7feec2015-03-26 11:29:02 +00001121 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1122 Alignment))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001123 return false;
1124
1125 updateValueMap(I, ResultReg);
1126 return true;
1127}
1128
1129static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1130 bool HasAVX = Subtarget->hasAVX();
1131 bool X86ScalarSSEf32 = Subtarget->hasSSE1();
1132 bool X86ScalarSSEf64 = Subtarget->hasSSE2();
1133
1134 switch (VT.getSimpleVT().SimpleTy) {
1135 default: return 0;
1136 case MVT::i8: return X86::CMP8rr;
1137 case MVT::i16: return X86::CMP16rr;
1138 case MVT::i32: return X86::CMP32rr;
1139 case MVT::i64: return X86::CMP64rr;
1140 case MVT::f32:
1141 return X86ScalarSSEf32 ? (HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr) : 0;
1142 case MVT::f64:
1143 return X86ScalarSSEf64 ? (HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr) : 0;
1144 }
1145}
1146
Rafael Espindola19141f22015-03-16 14:05:49 +00001147/// If we have a comparison with RHS as the RHS of the comparison, return an
1148/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001149static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
Rafael Espindola933f51a2015-03-16 14:25:08 +00001150 int64_t Val = RHSC->getSExtValue();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001151 switch (VT.getSimpleVT().SimpleTy) {
1152 // Otherwise, we can't fold the immediate into this comparison.
Rafael Espindola19141f22015-03-16 14:05:49 +00001153 default:
1154 return 0;
1155 case MVT::i8:
1156 return X86::CMP8ri;
1157 case MVT::i16:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001158 if (isInt<8>(Val))
1159 return X86::CMP16ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001160 return X86::CMP16ri;
1161 case MVT::i32:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001162 if (isInt<8>(Val))
1163 return X86::CMP32ri8;
Rafael Espindola19141f22015-03-16 14:05:49 +00001164 return X86::CMP32ri;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001165 case MVT::i64:
Rafael Espindola933f51a2015-03-16 14:25:08 +00001166 if (isInt<8>(Val))
1167 return X86::CMP64ri8;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001168 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1169 // field.
Rafael Espindola933f51a2015-03-16 14:25:08 +00001170 if (isInt<32>(Val))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001171 return X86::CMP64ri32;
1172 return 0;
1173 }
1174}
1175
1176bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1,
1177 EVT VT, DebugLoc CurDbgLoc) {
1178 unsigned Op0Reg = getRegForValue(Op0);
1179 if (Op0Reg == 0) return false;
1180
1181 // Handle 'null' like i32/i64 0.
1182 if (isa<ConstantPointerNull>(Op1))
1183 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1184
1185 // We have two options: compare with register or immediate. If the RHS of
1186 // the compare is an immediate that we can fold into this compare, use
1187 // CMPri, otherwise use CMPrr.
1188 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1189 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1190 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
1191 .addReg(Op0Reg)
1192 .addImm(Op1C->getSExtValue());
1193 return true;
1194 }
1195 }
1196
1197 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1198 if (CompareOpc == 0) return false;
1199
1200 unsigned Op1Reg = getRegForValue(Op1);
1201 if (Op1Reg == 0) return false;
1202 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
1203 .addReg(Op0Reg)
1204 .addReg(Op1Reg);
1205
1206 return true;
1207}
1208
1209bool X86FastISel::X86SelectCmp(const Instruction *I) {
1210 const CmpInst *CI = cast<CmpInst>(I);
1211
1212 MVT VT;
1213 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1214 return false;
1215
1216 // Try to optimize or fold the cmp.
1217 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1218 unsigned ResultReg = 0;
1219 switch (Predicate) {
1220 default: break;
1221 case CmpInst::FCMP_FALSE: {
1222 ResultReg = createResultReg(&X86::GR32RegClass);
1223 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
1224 ResultReg);
1225 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, /*Kill=*/true,
1226 X86::sub_8bit);
1227 if (!ResultReg)
1228 return false;
1229 break;
1230 }
1231 case CmpInst::FCMP_TRUE: {
1232 ResultReg = createResultReg(&X86::GR8RegClass);
1233 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
1234 ResultReg).addImm(1);
1235 break;
1236 }
1237 }
1238
1239 if (ResultReg) {
1240 updateValueMap(I, ResultReg);
1241 return true;
1242 }
1243
1244 const Value *LHS = CI->getOperand(0);
1245 const Value *RHS = CI->getOperand(1);
1246
1247 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1248 // We don't have to materialize a zero constant for this case and can just use
1249 // %x again on the RHS.
1250 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1251 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1252 if (RHSC && RHSC->isNullValue())
1253 RHS = LHS;
1254 }
1255
1256 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1257 static unsigned SETFOpcTable[2][3] = {
1258 { X86::SETEr, X86::SETNPr, X86::AND8rr },
1259 { X86::SETNEr, X86::SETPr, X86::OR8rr }
1260 };
1261 unsigned *SETFOpc = nullptr;
1262 switch (Predicate) {
1263 default: break;
1264 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1265 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1266 }
1267
1268 ResultReg = createResultReg(&X86::GR8RegClass);
1269 if (SETFOpc) {
1270 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1271 return false;
1272
1273 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1274 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1275 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1276 FlagReg1);
1277 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1278 FlagReg2);
1279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
1280 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1281 updateValueMap(I, ResultReg);
1282 return true;
1283 }
1284
1285 X86::CondCode CC;
1286 bool SwapArgs;
1287 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1288 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1289 unsigned Opc = X86::getSETFromCond(CC);
1290
1291 if (SwapArgs)
1292 std::swap(LHS, RHS);
1293
1294 // Emit a compare of LHS/RHS.
1295 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1296 return false;
1297
1298 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
1299 updateValueMap(I, ResultReg);
1300 return true;
1301}
1302
1303bool X86FastISel::X86SelectZExt(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001304 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001305 if (!TLI.isTypeLegal(DstVT))
1306 return false;
1307
1308 unsigned ResultReg = getRegForValue(I->getOperand(0));
1309 if (ResultReg == 0)
1310 return false;
1311
1312 // Handle zero-extension from i1 to i8, which is common.
Mehdi Amini44ede332015-07-09 02:09:04 +00001313 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001314 if (SrcVT.SimpleTy == MVT::i1) {
1315 // Set the high bits to zero.
1316 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg, /*TODO: Kill=*/false);
1317 SrcVT = MVT::i8;
1318
1319 if (ResultReg == 0)
1320 return false;
1321 }
1322
1323 if (DstVT == MVT::i64) {
1324 // Handle extension to 64-bits via sub-register shenanigans.
1325 unsigned MovInst;
1326
1327 switch (SrcVT.SimpleTy) {
1328 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1329 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1330 case MVT::i32: MovInst = X86::MOV32rr; break;
1331 default: llvm_unreachable("Unexpected zext to i64 source type");
1332 }
1333
1334 unsigned Result32 = createResultReg(&X86::GR32RegClass);
1335 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
1336 .addReg(ResultReg);
1337
1338 ResultReg = createResultReg(&X86::GR64RegClass);
1339 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
1340 ResultReg)
1341 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1342 } else if (DstVT != MVT::i8) {
1343 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1344 ResultReg, /*Kill=*/true);
1345 if (ResultReg == 0)
1346 return false;
1347 }
1348
1349 updateValueMap(I, ResultReg);
1350 return true;
1351}
1352
1353bool X86FastISel::X86SelectBranch(const Instruction *I) {
1354 // Unconditional branches are selected by tablegen-generated code.
1355 // Handle a conditional branch.
1356 const BranchInst *BI = cast<BranchInst>(I);
1357 MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1358 MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1359
1360 // Fold the common case of a conditional branch with a comparison
1361 // in the same block (values defined on other blocks may not have
1362 // initialized registers).
1363 X86::CondCode CC;
1364 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1365 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00001366 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001367
1368 // Try to optimize or fold the cmp.
1369 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1370 switch (Predicate) {
1371 default: break;
1372 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
1373 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
1374 }
1375
1376 const Value *CmpLHS = CI->getOperand(0);
1377 const Value *CmpRHS = CI->getOperand(1);
1378
1379 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1380 // 0.0.
1381 // We don't have to materialize a zero constant for this case and can just
1382 // use %x again on the RHS.
1383 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1384 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1385 if (CmpRHSC && CmpRHSC->isNullValue())
1386 CmpRHS = CmpLHS;
1387 }
1388
1389 // Try to take advantage of fallthrough opportunities.
1390 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1391 std::swap(TrueMBB, FalseMBB);
1392 Predicate = CmpInst::getInversePredicate(Predicate);
1393 }
1394
1395 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1396 // code check. Instead two branch instructions are required to check all
1397 // the flags. First we change the predicate to a supported condition code,
1398 // which will be the first branch. Later one we will emit the second
1399 // branch.
1400 bool NeedExtraBranch = false;
1401 switch (Predicate) {
1402 default: break;
1403 case CmpInst::FCMP_OEQ:
1404 std::swap(TrueMBB, FalseMBB); // fall-through
1405 case CmpInst::FCMP_UNE:
1406 NeedExtraBranch = true;
1407 Predicate = CmpInst::FCMP_ONE;
1408 break;
1409 }
1410
1411 bool SwapArgs;
1412 unsigned BranchOpc;
1413 std::tie(CC, SwapArgs) = getX86ConditionCode(Predicate);
1414 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1415
1416 BranchOpc = X86::GetCondBranchFromCond(CC);
1417 if (SwapArgs)
1418 std::swap(CmpLHS, CmpRHS);
1419
1420 // Emit a compare of the LHS and RHS, setting the flags.
1421 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1422 return false;
1423
1424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1425 .addMBB(TrueMBB);
1426
1427 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1428 // to UNE above).
1429 if (NeedExtraBranch) {
1430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JP_1))
1431 .addMBB(TrueMBB);
1432 }
1433
Matthias Braun17af6072015-08-26 01:38:00 +00001434 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001435 return true;
1436 }
1437 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1438 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1439 // typically happen for _Bool and C++ bools.
1440 MVT SourceVT;
1441 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1442 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1443 unsigned TestOpc = 0;
1444 switch (SourceVT.SimpleTy) {
1445 default: break;
1446 case MVT::i8: TestOpc = X86::TEST8ri; break;
1447 case MVT::i16: TestOpc = X86::TEST16ri; break;
1448 case MVT::i32: TestOpc = X86::TEST32ri; break;
1449 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1450 }
1451 if (TestOpc) {
1452 unsigned OpReg = getRegForValue(TI->getOperand(0));
1453 if (OpReg == 0) return false;
1454 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
1455 .addReg(OpReg).addImm(1);
1456
1457 unsigned JmpOpc = X86::JNE_1;
1458 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1459 std::swap(TrueMBB, FalseMBB);
1460 JmpOpc = X86::JE_1;
1461 }
1462
1463 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(JmpOpc))
1464 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001465
1466 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001467 return true;
1468 }
1469 }
1470 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1471 // Fake request the condition, otherwise the intrinsic might be completely
1472 // optimized away.
1473 unsigned TmpReg = getRegForValue(BI->getCondition());
1474 if (TmpReg == 0)
1475 return false;
1476
1477 unsigned BranchOpc = X86::GetCondBranchFromCond(CC);
1478
1479 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BranchOpc))
1480 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001481 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001482 return true;
1483 }
1484
1485 // Otherwise do a clumsy setcc and re-test it.
1486 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1487 // in an explicit cast, so make sure to handle that correctly.
1488 unsigned OpReg = getRegForValue(BI->getCondition());
1489 if (OpReg == 0) return false;
1490
1491 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1492 .addReg(OpReg).addImm(1);
1493 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JNE_1))
1494 .addMBB(TrueMBB);
Matthias Braun17af6072015-08-26 01:38:00 +00001495 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001496 return true;
1497}
1498
1499bool X86FastISel::X86SelectShift(const Instruction *I) {
1500 unsigned CReg = 0, OpReg = 0;
1501 const TargetRegisterClass *RC = nullptr;
1502 if (I->getType()->isIntegerTy(8)) {
1503 CReg = X86::CL;
1504 RC = &X86::GR8RegClass;
1505 switch (I->getOpcode()) {
1506 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1507 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1508 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1509 default: return false;
1510 }
1511 } else if (I->getType()->isIntegerTy(16)) {
1512 CReg = X86::CX;
1513 RC = &X86::GR16RegClass;
1514 switch (I->getOpcode()) {
1515 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1516 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1517 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1518 default: return false;
1519 }
1520 } else if (I->getType()->isIntegerTy(32)) {
1521 CReg = X86::ECX;
1522 RC = &X86::GR32RegClass;
1523 switch (I->getOpcode()) {
1524 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1525 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1526 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1527 default: return false;
1528 }
1529 } else if (I->getType()->isIntegerTy(64)) {
1530 CReg = X86::RCX;
1531 RC = &X86::GR64RegClass;
1532 switch (I->getOpcode()) {
1533 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1534 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1535 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1536 default: return false;
1537 }
1538 } else {
1539 return false;
1540 }
1541
1542 MVT VT;
1543 if (!isTypeLegal(I->getType(), VT))
1544 return false;
1545
1546 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1547 if (Op0Reg == 0) return false;
1548
1549 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1550 if (Op1Reg == 0) return false;
1551 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
1552 CReg).addReg(Op1Reg);
1553
1554 // The shift instruction uses X86::CL. If we defined a super-register
1555 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1556 if (CReg != X86::CL)
1557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1558 TII.get(TargetOpcode::KILL), X86::CL)
1559 .addReg(CReg, RegState::Kill);
1560
1561 unsigned ResultReg = createResultReg(RC);
1562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
1563 .addReg(Op0Reg);
1564 updateValueMap(I, ResultReg);
1565 return true;
1566}
1567
1568bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1569 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1570 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1571 const static bool S = true; // IsSigned
1572 const static bool U = false; // !IsSigned
1573 const static unsigned Copy = TargetOpcode::COPY;
1574 // For the X86 DIV/IDIV instruction, in most cases the dividend
1575 // (numerator) must be in a specific register pair highreg:lowreg,
1576 // producing the quotient in lowreg and the remainder in highreg.
1577 // For most data types, to set up the instruction, the dividend is
1578 // copied into lowreg, and lowreg is sign-extended or zero-extended
1579 // into highreg. The exception is i8, where the dividend is defined
1580 // as a single register rather than a register pair, and we
1581 // therefore directly sign-extend or zero-extend the dividend into
1582 // lowreg, instead of copying, and ignore the highreg.
1583 const static struct DivRemEntry {
1584 // The following portion depends only on the data type.
1585 const TargetRegisterClass *RC;
1586 unsigned LowInReg; // low part of the register pair
1587 unsigned HighInReg; // high part of the register pair
1588 // The following portion depends on both the data type and the operation.
1589 struct DivRemResult {
1590 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1591 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1592 // highreg, or copying a zero into highreg.
1593 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1594 // zero/sign-extending into lowreg for i8.
1595 unsigned DivRemResultReg; // Register containing the desired result.
1596 bool IsOpSigned; // Whether to use signed or unsigned form.
1597 } ResultTable[NumOps];
1598 } OpTable[NumTypes] = {
1599 { &X86::GR8RegClass, X86::AX, 0, {
1600 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1601 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1602 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1603 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1604 }
1605 }, // i8
1606 { &X86::GR16RegClass, X86::AX, X86::DX, {
1607 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1608 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1609 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1610 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1611 }
1612 }, // i16
1613 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1614 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1615 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1616 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1617 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1618 }
1619 }, // i32
1620 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1621 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1622 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1623 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1624 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1625 }
1626 }, // i64
1627 };
1628
1629 MVT VT;
1630 if (!isTypeLegal(I->getType(), VT))
1631 return false;
1632
1633 unsigned TypeIndex, OpIndex;
1634 switch (VT.SimpleTy) {
1635 default: return false;
1636 case MVT::i8: TypeIndex = 0; break;
1637 case MVT::i16: TypeIndex = 1; break;
1638 case MVT::i32: TypeIndex = 2; break;
1639 case MVT::i64: TypeIndex = 3;
1640 if (!Subtarget->is64Bit())
1641 return false;
1642 break;
1643 }
1644
1645 switch (I->getOpcode()) {
1646 default: llvm_unreachable("Unexpected div/rem opcode");
1647 case Instruction::SDiv: OpIndex = 0; break;
1648 case Instruction::SRem: OpIndex = 1; break;
1649 case Instruction::UDiv: OpIndex = 2; break;
1650 case Instruction::URem: OpIndex = 3; break;
1651 }
1652
1653 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1654 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1655 unsigned Op0Reg = getRegForValue(I->getOperand(0));
1656 if (Op0Reg == 0)
1657 return false;
1658 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1659 if (Op1Reg == 0)
1660 return false;
1661
1662 // Move op0 into low-order input register.
1663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1664 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1665 // Zero-extend or sign-extend into high-order input register.
1666 if (OpEntry.OpSignExtend) {
1667 if (OpEntry.IsOpSigned)
1668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1669 TII.get(OpEntry.OpSignExtend));
1670 else {
1671 unsigned Zero32 = createResultReg(&X86::GR32RegClass);
1672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1673 TII.get(X86::MOV32r0), Zero32);
1674
1675 // Copy the zero into the appropriate sub/super/identical physical
1676 // register. Unfortunately the operations needed are not uniform enough
1677 // to fit neatly into the table above.
1678 if (VT.SimpleTy == MVT::i16) {
1679 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1680 TII.get(Copy), TypeEntry.HighInReg)
1681 .addReg(Zero32, 0, X86::sub_16bit);
1682 } else if (VT.SimpleTy == MVT::i32) {
1683 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1684 TII.get(Copy), TypeEntry.HighInReg)
1685 .addReg(Zero32);
1686 } else if (VT.SimpleTy == MVT::i64) {
1687 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1688 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1689 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1690 }
1691 }
1692 }
1693 // Generate the DIV/IDIV instruction.
1694 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1695 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1696 // For i8 remainder, we can't reference AH directly, as we'll end
1697 // up with bogus copies like %R9B = COPY %AH. Reference AX
1698 // instead to prevent AH references in a REX instruction.
1699 //
1700 // The current assumption of the fast register allocator is that isel
1701 // won't generate explicit references to the GPR8_NOREX registers. If
1702 // the allocator and/or the backend get enhanced to be more robust in
1703 // that regard, this can be, and should be, removed.
1704 unsigned ResultReg = 0;
1705 if ((I->getOpcode() == Instruction::SRem ||
1706 I->getOpcode() == Instruction::URem) &&
1707 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
1708 unsigned SourceSuperReg = createResultReg(&X86::GR16RegClass);
1709 unsigned ResultSuperReg = createResultReg(&X86::GR16RegClass);
1710 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1711 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
1712
1713 // Shift AX right by 8 bits instead of using AH.
1714 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
1715 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
1716
1717 // Now reference the 8-bit subreg of the result.
1718 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
1719 /*Kill=*/true, X86::sub_8bit);
1720 }
1721 // Copy the result out of the physreg if we haven't already.
1722 if (!ResultReg) {
1723 ResultReg = createResultReg(TypeEntry.RC);
1724 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
1725 .addReg(OpEntry.DivRemResultReg);
1726 }
1727 updateValueMap(I, ResultReg);
1728
1729 return true;
1730}
1731
1732/// \brief Emit a conditional move instruction (if the are supported) to lower
1733/// the select.
1734bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
1735 // Check if the subtarget supports these instructions.
1736 if (!Subtarget->hasCMov())
1737 return false;
1738
1739 // FIXME: Add support for i8.
1740 if (RetVT < MVT::i16 || RetVT > MVT::i64)
1741 return false;
1742
1743 const Value *Cond = I->getOperand(0);
1744 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
1745 bool NeedTest = true;
1746 X86::CondCode CC = X86::COND_NE;
1747
1748 // Optimize conditions coming from a compare if both instructions are in the
1749 // same basic block (values defined in other basic blocks may not have
1750 // initialized registers).
1751 const auto *CI = dyn_cast<CmpInst>(Cond);
1752 if (CI && (CI->getParent() == I->getParent())) {
1753 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1754
1755 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1756 static unsigned SETFOpcTable[2][3] = {
1757 { X86::SETNPr, X86::SETEr , X86::TEST8rr },
1758 { X86::SETPr, X86::SETNEr, X86::OR8rr }
1759 };
1760 unsigned *SETFOpc = nullptr;
1761 switch (Predicate) {
1762 default: break;
1763 case CmpInst::FCMP_OEQ:
1764 SETFOpc = &SETFOpcTable[0][0];
1765 Predicate = CmpInst::ICMP_NE;
1766 break;
1767 case CmpInst::FCMP_UNE:
1768 SETFOpc = &SETFOpcTable[1][0];
1769 Predicate = CmpInst::ICMP_NE;
1770 break;
1771 }
1772
1773 bool NeedSwap;
1774 std::tie(CC, NeedSwap) = getX86ConditionCode(Predicate);
1775 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1776
1777 const Value *CmpLHS = CI->getOperand(0);
1778 const Value *CmpRHS = CI->getOperand(1);
1779 if (NeedSwap)
1780 std::swap(CmpLHS, CmpRHS);
1781
Mehdi Amini44ede332015-07-09 02:09:04 +00001782 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001783 // Emit a compare of the LHS and RHS, setting the flags.
1784 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1785 return false;
1786
1787 if (SETFOpc) {
1788 unsigned FlagReg1 = createResultReg(&X86::GR8RegClass);
1789 unsigned FlagReg2 = createResultReg(&X86::GR8RegClass);
1790 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[0]),
1791 FlagReg1);
1792 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[1]),
1793 FlagReg2);
1794 auto const &II = TII.get(SETFOpc[2]);
1795 if (II.getNumDefs()) {
1796 unsigned TmpReg = createResultReg(&X86::GR8RegClass);
1797 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
1798 .addReg(FlagReg2).addReg(FlagReg1);
1799 } else {
1800 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1801 .addReg(FlagReg2).addReg(FlagReg1);
1802 }
1803 }
1804 NeedTest = false;
1805 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
1806 // Fake request the condition, otherwise the intrinsic might be completely
1807 // optimized away.
1808 unsigned TmpReg = getRegForValue(Cond);
1809 if (TmpReg == 0)
1810 return false;
1811
1812 NeedTest = false;
1813 }
1814
1815 if (NeedTest) {
1816 // Selects operate on i1, however, CondReg is 8 bits width and may contain
1817 // garbage. Indeed, only the less significant bit is supposed to be
1818 // accurate. If we read more than the lsb, we may see non-zero values
1819 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
1820 // the select. This is achieved by performing TEST against 1.
1821 unsigned CondReg = getRegForValue(Cond);
1822 if (CondReg == 0)
1823 return false;
1824 bool CondIsKill = hasTrivialKill(Cond);
1825
1826 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1827 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
1828 }
1829
1830 const Value *LHS = I->getOperand(1);
1831 const Value *RHS = I->getOperand(2);
1832
1833 unsigned RHSReg = getRegForValue(RHS);
1834 bool RHSIsKill = hasTrivialKill(RHS);
1835
1836 unsigned LHSReg = getRegForValue(LHS);
1837 bool LHSIsKill = hasTrivialKill(LHS);
1838
1839 if (!LHSReg || !RHSReg)
1840 return false;
1841
1842 unsigned Opc = X86::getCMovFromCond(CC, RC->getSize());
1843 unsigned ResultReg = fastEmitInst_rr(Opc, RC, RHSReg, RHSIsKill,
1844 LHSReg, LHSIsKill);
1845 updateValueMap(I, ResultReg);
1846 return true;
1847}
1848
Sanjay Patel302404b2015-03-05 21:46:54 +00001849/// \brief Emit SSE or AVX instructions to lower the select.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001850///
1851/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
1852/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
Sanjay Patel302404b2015-03-05 21:46:54 +00001853/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001854bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
1855 // Optimize conditions coming from a compare if both instructions are in the
1856 // same basic block (values defined in other basic blocks may not have
1857 // initialized registers).
1858 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
1859 if (!CI || (CI->getParent() != I->getParent()))
1860 return false;
1861
1862 if (I->getType() != CI->getOperand(0)->getType() ||
1863 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
1864 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
1865 return false;
1866
1867 const Value *CmpLHS = CI->getOperand(0);
1868 const Value *CmpRHS = CI->getOperand(1);
1869 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1870
1871 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1872 // We don't have to materialize a zero constant for this case and can just use
1873 // %x again on the RHS.
1874 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1875 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1876 if (CmpRHSC && CmpRHSC->isNullValue())
1877 CmpRHS = CmpLHS;
1878 }
1879
1880 unsigned CC;
1881 bool NeedSwap;
1882 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
1883 if (CC > 7)
1884 return false;
1885
1886 if (NeedSwap)
1887 std::swap(CmpLHS, CmpRHS);
1888
Sanjay Patel302404b2015-03-05 21:46:54 +00001889 // Choose the SSE instruction sequence based on data type (float or double).
1890 static unsigned OpcTable[2][4] = {
1891 { X86::CMPSSrr, X86::FsANDPSrr, X86::FsANDNPSrr, X86::FsORPSrr },
1892 { X86::CMPSDrr, X86::FsANDPDrr, X86::FsANDNPDrr, X86::FsORPDrr }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001893 };
1894
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001895 unsigned *Opc = nullptr;
1896 switch (RetVT.SimpleTy) {
1897 default: return false;
Sanjay Patel302404b2015-03-05 21:46:54 +00001898 case MVT::f32: Opc = &OpcTable[0][0]; break;
1899 case MVT::f64: Opc = &OpcTable[1][0]; break;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001900 }
1901
1902 const Value *LHS = I->getOperand(1);
1903 const Value *RHS = I->getOperand(2);
1904
1905 unsigned LHSReg = getRegForValue(LHS);
1906 bool LHSIsKill = hasTrivialKill(LHS);
1907
1908 unsigned RHSReg = getRegForValue(RHS);
1909 bool RHSIsKill = hasTrivialKill(RHS);
1910
1911 unsigned CmpLHSReg = getRegForValue(CmpLHS);
1912 bool CmpLHSIsKill = hasTrivialKill(CmpLHS);
1913
1914 unsigned CmpRHSReg = getRegForValue(CmpRHS);
1915 bool CmpRHSIsKill = hasTrivialKill(CmpRHS);
1916
1917 if (!LHSReg || !RHSReg || !CmpLHS || !CmpRHS)
1918 return false;
1919
1920 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
Sanjay Patel302404b2015-03-05 21:46:54 +00001921 unsigned ResultReg;
1922
1923 if (Subtarget->hasAVX()) {
Matthias Braun818c78d2015-08-31 18:25:11 +00001924 const TargetRegisterClass *FR32 = &X86::FR32RegClass;
1925 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
1926
Sanjay Patel302404b2015-03-05 21:46:54 +00001927 // If we have AVX, create 1 blendv instead of 3 logic instructions.
1928 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
1929 // uses XMM0 as the selection register. That may need just as many
1930 // instructions as the AND/ANDN/OR sequence due to register moves, so
1931 // don't bother.
1932 unsigned CmpOpcode =
1933 (RetVT.SimpleTy == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
1934 unsigned BlendOpcode =
1935 (RetVT.SimpleTy == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
1936
Matthias Braun818c78d2015-08-31 18:25:11 +00001937 unsigned CmpReg = fastEmitInst_rri(CmpOpcode, FR32, CmpLHSReg, CmpLHSIsKill,
Sanjay Patel302404b2015-03-05 21:46:54 +00001938 CmpRHSReg, CmpRHSIsKill, CC);
Matthias Braun818c78d2015-08-31 18:25:11 +00001939 unsigned VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, RHSIsKill,
1940 LHSReg, LHSIsKill, CmpReg, true);
1941 ResultReg = createResultReg(RC);
1942 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1943 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
Sanjay Patel302404b2015-03-05 21:46:54 +00001944 } else {
1945 unsigned CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpLHSIsKill,
1946 CmpRHSReg, CmpRHSIsKill, CC);
1947 unsigned AndReg = fastEmitInst_rr(Opc[1], RC, CmpReg, /*IsKill=*/false,
1948 LHSReg, LHSIsKill);
1949 unsigned AndNReg = fastEmitInst_rr(Opc[2], RC, CmpReg, /*IsKill=*/true,
1950 RHSReg, RHSIsKill);
1951 ResultReg = fastEmitInst_rr(Opc[3], RC, AndNReg, /*IsKill=*/true,
1952 AndReg, /*IsKill=*/true);
1953 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001954 updateValueMap(I, ResultReg);
1955 return true;
1956}
1957
1958bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
1959 // These are pseudo CMOV instructions and will be later expanded into control-
1960 // flow.
1961 unsigned Opc;
1962 switch (RetVT.SimpleTy) {
1963 default: return false;
1964 case MVT::i8: Opc = X86::CMOV_GR8; break;
1965 case MVT::i16: Opc = X86::CMOV_GR16; break;
1966 case MVT::i32: Opc = X86::CMOV_GR32; break;
1967 case MVT::f32: Opc = X86::CMOV_FR32; break;
1968 case MVT::f64: Opc = X86::CMOV_FR64; break;
1969 }
1970
1971 const Value *Cond = I->getOperand(0);
1972 X86::CondCode CC = X86::COND_NE;
1973
1974 // Optimize conditions coming from a compare if both instructions are in the
1975 // same basic block (values defined in other basic blocks may not have
1976 // initialized registers).
1977 const auto *CI = dyn_cast<CmpInst>(Cond);
1978 if (CI && (CI->getParent() == I->getParent())) {
1979 bool NeedSwap;
1980 std::tie(CC, NeedSwap) = getX86ConditionCode(CI->getPredicate());
1981 if (CC > X86::LAST_VALID_COND)
1982 return false;
1983
1984 const Value *CmpLHS = CI->getOperand(0);
1985 const Value *CmpRHS = CI->getOperand(1);
1986
1987 if (NeedSwap)
1988 std::swap(CmpLHS, CmpRHS);
1989
Mehdi Amini44ede332015-07-09 02:09:04 +00001990 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001991 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
1992 return false;
1993 } else {
1994 unsigned CondReg = getRegForValue(Cond);
1995 if (CondReg == 0)
1996 return false;
1997 bool CondIsKill = hasTrivialKill(Cond);
1998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
1999 .addReg(CondReg, getKillRegState(CondIsKill)).addImm(1);
2000 }
2001
2002 const Value *LHS = I->getOperand(1);
2003 const Value *RHS = I->getOperand(2);
2004
2005 unsigned LHSReg = getRegForValue(LHS);
2006 bool LHSIsKill = hasTrivialKill(LHS);
2007
2008 unsigned RHSReg = getRegForValue(RHS);
2009 bool RHSIsKill = hasTrivialKill(RHS);
2010
2011 if (!LHSReg || !RHSReg)
2012 return false;
2013
2014 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2015
2016 unsigned ResultReg =
2017 fastEmitInst_rri(Opc, RC, RHSReg, RHSIsKill, LHSReg, LHSIsKill, CC);
2018 updateValueMap(I, ResultReg);
2019 return true;
2020}
2021
2022bool X86FastISel::X86SelectSelect(const Instruction *I) {
2023 MVT RetVT;
2024 if (!isTypeLegal(I->getType(), RetVT))
2025 return false;
2026
2027 // Check if we can fold the select.
2028 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2029 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2030 const Value *Opnd = nullptr;
2031 switch (Predicate) {
2032 default: break;
2033 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2034 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2035 }
2036 // No need for a select anymore - this is an unconditional move.
2037 if (Opnd) {
2038 unsigned OpReg = getRegForValue(Opnd);
2039 if (OpReg == 0)
2040 return false;
2041 bool OpIsKill = hasTrivialKill(Opnd);
2042 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2043 unsigned ResultReg = createResultReg(RC);
2044 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2045 TII.get(TargetOpcode::COPY), ResultReg)
2046 .addReg(OpReg, getKillRegState(OpIsKill));
2047 updateValueMap(I, ResultReg);
2048 return true;
2049 }
2050 }
2051
2052 // First try to use real conditional move instructions.
2053 if (X86FastEmitCMoveSelect(RetVT, I))
2054 return true;
2055
2056 // Try to use a sequence of SSE instructions to simulate a conditional move.
2057 if (X86FastEmitSSESelect(RetVT, I))
2058 return true;
2059
2060 // Fall-back to pseudo conditional move instructions, which will be later
2061 // converted to control-flow.
2062 if (X86FastEmitPseudoSelect(RetVT, I))
2063 return true;
2064
2065 return false;
2066}
2067
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002068bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
Andrea Di Biagio98c36702015-04-20 11:56:59 +00002069 // The target-independent selection algorithm in FastISel already knows how
2070 // to select a SINT_TO_FP if the target is SSE but not AVX.
2071 // Early exit if the subtarget doesn't have AVX.
2072 if (!Subtarget->hasAVX())
2073 return false;
2074
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002075 if (!I->getOperand(0)->getType()->isIntegerTy(32))
2076 return false;
2077
2078 // Select integer to float/double conversion.
2079 unsigned OpReg = getRegForValue(I->getOperand(0));
2080 if (OpReg == 0)
2081 return false;
2082
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002083 const TargetRegisterClass *RC = nullptr;
2084 unsigned Opcode;
2085
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002086 if (I->getType()->isDoubleTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002087 // sitofp int -> double
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002088 Opcode = X86::VCVTSI2SDrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002089 RC = &X86::FR64RegClass;
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002090 } else if (I->getType()->isFloatTy()) {
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002091 // sitofp int -> float
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002092 Opcode = X86::VCVTSI2SSrr;
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002093 RC = &X86::FR32RegClass;
2094 } else
2095 return false;
2096
Andrea Di Biagiodf93ccf2015-03-04 14:23:25 +00002097 unsigned ImplicitDefReg = createResultReg(RC);
2098 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2099 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2100 unsigned ResultReg =
2101 fastEmitInst_rr(Opcode, RC, ImplicitDefReg, true, OpReg, false);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00002102 updateValueMap(I, ResultReg);
2103 return true;
2104}
2105
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002106// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2107bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2108 unsigned TargetOpc,
2109 const TargetRegisterClass *RC) {
2110 assert((I->getOpcode() == Instruction::FPExt ||
2111 I->getOpcode() == Instruction::FPTrunc) &&
2112 "Instruction must be an FPExt or FPTrunc!");
2113
2114 unsigned OpReg = getRegForValue(I->getOperand(0));
2115 if (OpReg == 0)
2116 return false;
2117
2118 unsigned ResultReg = createResultReg(RC);
2119 MachineInstrBuilder MIB;
2120 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
2121 ResultReg);
2122 if (Subtarget->hasAVX())
2123 MIB.addReg(OpReg);
2124 MIB.addReg(OpReg);
2125 updateValueMap(I, ResultReg);
2126 return true;
2127}
2128
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002129bool X86FastISel::X86SelectFPExt(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002130 if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
2131 I->getOperand(0)->getType()->isFloatTy()) {
2132 // fpext from float to double.
2133 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2134 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR64RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002135 }
2136
2137 return false;
2138}
2139
2140bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
Andrea Di Biagio62622d22015-02-10 12:04:41 +00002141 if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
2142 I->getOperand(0)->getType()->isDoubleTy()) {
2143 // fptrunc from double to float.
2144 unsigned Opc = Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2145 return X86SelectFPExtOrFPTrunc(I, Opc, &X86::FR32RegClass);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002146 }
2147
2148 return false;
2149}
2150
2151bool X86FastISel::X86SelectTrunc(const Instruction *I) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002152 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2153 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002154
2155 // This code only handles truncation to byte.
2156 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2157 return false;
2158 if (!TLI.isTypeLegal(SrcVT))
2159 return false;
2160
2161 unsigned InputReg = getRegForValue(I->getOperand(0));
2162 if (!InputReg)
2163 // Unhandled operand. Halt "fast" selection and bail.
2164 return false;
2165
2166 if (SrcVT == MVT::i8) {
2167 // Truncate from i8 to i1; no code needed.
2168 updateValueMap(I, InputReg);
2169 return true;
2170 }
2171
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002172 bool KillInputReg = false;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002173 if (!Subtarget->is64Bit()) {
2174 // If we're on x86-32; we can't extract an i8 from a general register.
2175 // First issue a copy to GR16_ABCD or GR32_ABCD.
2176 const TargetRegisterClass *CopyRC =
2177 (SrcVT == MVT::i16) ? &X86::GR16_ABCDRegClass : &X86::GR32_ABCDRegClass;
2178 unsigned CopyReg = createResultReg(CopyRC);
2179 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2180 TII.get(TargetOpcode::COPY), CopyReg).addReg(InputReg);
2181 InputReg = CopyReg;
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002182 KillInputReg = true;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002183 }
2184
2185 // Issue an extract_subreg.
2186 unsigned ResultReg = fastEmitInst_extractsubreg(MVT::i8,
Pete Cooper7f7c9f12015-05-08 18:29:42 +00002187 InputReg, KillInputReg,
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002188 X86::sub_8bit);
2189 if (!ResultReg)
2190 return false;
2191
2192 updateValueMap(I, ResultReg);
2193 return true;
2194}
2195
2196bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2197 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2198}
2199
2200bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2201 X86AddressMode SrcAM, uint64_t Len) {
2202
2203 // Make sure we don't bloat code by inlining very large memcpy's.
2204 if (!IsMemcpySmall(Len))
2205 return false;
2206
2207 bool i64Legal = Subtarget->is64Bit();
2208
2209 // We don't care about alignment here since we just emit integer accesses.
2210 while (Len) {
2211 MVT VT;
2212 if (Len >= 8 && i64Legal)
2213 VT = MVT::i64;
2214 else if (Len >= 4)
2215 VT = MVT::i32;
2216 else if (Len >= 2)
2217 VT = MVT::i16;
2218 else
2219 VT = MVT::i8;
2220
2221 unsigned Reg;
2222 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2223 RV &= X86FastEmitStore(VT, Reg, /*Kill=*/true, DestAM);
2224 assert(RV && "Failed to emit load or store??");
2225
2226 unsigned Size = VT.getSizeInBits()/8;
2227 Len -= Size;
2228 DestAM.Disp += Size;
2229 SrcAM.Disp += Size;
2230 }
2231
2232 return true;
2233}
2234
2235bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2236 // FIXME: Handle more intrinsics.
2237 switch (II->getIntrinsicID()) {
2238 default: return false;
Andrea Di Biagio70351782015-02-20 19:37:14 +00002239 case Intrinsic::convert_from_fp16:
2240 case Intrinsic::convert_to_fp16: {
Eric Christopher824f42f2015-05-12 01:26:05 +00002241 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
Andrea Di Biagio70351782015-02-20 19:37:14 +00002242 return false;
2243
2244 const Value *Op = II->getArgOperand(0);
2245 unsigned InputReg = getRegForValue(Op);
2246 if (InputReg == 0)
2247 return false;
2248
2249 // F16C only allows converting from float to half and from half to float.
2250 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2251 if (IsFloatToHalf) {
2252 if (!Op->getType()->isFloatTy())
2253 return false;
2254 } else {
2255 if (!II->getType()->isFloatTy())
2256 return false;
2257 }
2258
2259 unsigned ResultReg = 0;
2260 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2261 if (IsFloatToHalf) {
2262 // 'InputReg' is implicitly promoted from register class FR32 to
2263 // register class VR128 by method 'constrainOperandRegClass' which is
2264 // directly called by 'fastEmitInst_ri'.
2265 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2266 // used to provide rounding control.
2267 InputReg = fastEmitInst_ri(X86::VCVTPS2PHrr, RC, InputReg, false, 0);
2268
2269 // Move the lower 32-bits of ResultReg to another register of class GR32.
2270 ResultReg = createResultReg(&X86::GR32RegClass);
2271 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2272 TII.get(X86::VMOVPDI2DIrr), ResultReg)
2273 .addReg(InputReg, RegState::Kill);
2274
2275 // The result value is in the lower 16-bits of ResultReg.
2276 unsigned RegIdx = X86::sub_16bit;
2277 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, true, RegIdx);
2278 } else {
2279 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2280 // Explicitly sign-extend the input to 32-bit.
2281 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::SIGN_EXTEND, InputReg,
2282 /*Kill=*/false);
2283
2284 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2285 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2286 InputReg, /*Kill=*/true);
2287
2288 InputReg = fastEmitInst_r(X86::VCVTPH2PSrr, RC, InputReg, /*Kill=*/true);
2289
2290 // The result value is in the lower 32-bits of ResultReg.
2291 // Emit an explicit copy from register class VR128 to register class FR32.
2292 ResultReg = createResultReg(&X86::FR32RegClass);
2293 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2294 TII.get(TargetOpcode::COPY), ResultReg)
2295 .addReg(InputReg, RegState::Kill);
2296 }
2297
2298 updateValueMap(II, ResultReg);
2299 return true;
2300 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002301 case Intrinsic::frameaddress: {
David Majnemerca194852015-02-10 22:00:34 +00002302 MachineFunction *MF = FuncInfo.MF;
2303 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2304 return false;
2305
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002306 Type *RetTy = II->getCalledFunction()->getReturnType();
2307
2308 MVT VT;
2309 if (!isTypeLegal(RetTy, VT))
2310 return false;
2311
2312 unsigned Opc;
2313 const TargetRegisterClass *RC = nullptr;
2314
2315 switch (VT.SimpleTy) {
2316 default: llvm_unreachable("Invalid result type for frameaddress.");
2317 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2318 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2319 }
2320
2321 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2322 // we get the wrong frame register.
David Majnemerca194852015-02-10 22:00:34 +00002323 MachineFrameInfo *MFI = MF->getFrameInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002324 MFI->setFrameAddressIsTaken(true);
2325
Eric Christophera1c535b2015-02-02 23:03:45 +00002326 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
David Majnemerca194852015-02-10 22:00:34 +00002327 unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002328 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2329 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2330 "Invalid Frame Register!");
2331
2332 // Always make a copy of the frame register to to a vreg first, so that we
2333 // never directly reference the frame register (the TwoAddressInstruction-
2334 // Pass doesn't like that).
2335 unsigned SrcReg = createResultReg(RC);
2336 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2337 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2338
2339 // Now recursively load from the frame address.
2340 // movq (%rbp), %rax
2341 // movq (%rax), %rax
2342 // movq (%rax), %rax
2343 // ...
2344 unsigned DestReg;
2345 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2346 while (Depth--) {
2347 DestReg = createResultReg(RC);
2348 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2349 TII.get(Opc), DestReg), SrcReg);
2350 SrcReg = DestReg;
2351 }
2352
2353 updateValueMap(II, SrcReg);
2354 return true;
2355 }
2356 case Intrinsic::memcpy: {
2357 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2358 // Don't handle volatile or variable length memcpys.
2359 if (MCI->isVolatile())
2360 return false;
2361
2362 if (isa<ConstantInt>(MCI->getLength())) {
2363 // Small memcpy's are common enough that we want to do them
2364 // without a call if possible.
2365 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2366 if (IsMemcpySmall(Len)) {
2367 X86AddressMode DestAM, SrcAM;
2368 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2369 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2370 return false;
2371 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2372 return true;
2373 }
2374 }
2375
2376 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2377 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2378 return false;
2379
2380 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2381 return false;
2382
2383 return lowerCallTo(II, "memcpy", II->getNumArgOperands() - 2);
2384 }
2385 case Intrinsic::memset: {
2386 const MemSetInst *MSI = cast<MemSetInst>(II);
2387
2388 if (MSI->isVolatile())
2389 return false;
2390
2391 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2392 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2393 return false;
2394
2395 if (MSI->getDestAddressSpace() > 255)
2396 return false;
2397
2398 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
2399 }
2400 case Intrinsic::stackprotector: {
2401 // Emit code to store the stack guard onto the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002402 EVT PtrTy = TLI.getPointerTy(DL);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002403
2404 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2405 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2406
2407 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2408
2409 // Grab the frame index.
2410 X86AddressMode AM;
2411 if (!X86SelectAddress(Slot, AM)) return false;
2412 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2413 return true;
2414 }
2415 case Intrinsic::dbg_declare: {
2416 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2417 X86AddressMode AM;
2418 assert(DI->getAddress() && "Null address should be checked earlier!");
2419 if (!X86SelectAddress(DI->getAddress(), AM))
2420 return false;
2421 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2422 // FIXME may need to add RegState::Debug to any registers produced,
2423 // although ESP/EBP should be the only ones at the moment.
Duncan P. N. Exon Smith3bef6a32015-04-03 19:20:26 +00002424 assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
2425 "Expected inlined-at fields to agree");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002426 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
2427 .addImm(0)
2428 .addMetadata(DI->getVariable())
2429 .addMetadata(DI->getExpression());
2430 return true;
2431 }
2432 case Intrinsic::trap: {
2433 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
2434 return true;
2435 }
2436 case Intrinsic::sqrt: {
2437 if (!Subtarget->hasSSE1())
2438 return false;
2439
2440 Type *RetTy = II->getCalledFunction()->getReturnType();
2441
2442 MVT VT;
2443 if (!isTypeLegal(RetTy, VT))
2444 return false;
2445
2446 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2447 // is not generated by FastISel yet.
2448 // FIXME: Update this code once tablegen can handle it.
2449 static const unsigned SqrtOpc[2][2] = {
2450 {X86::SQRTSSr, X86::VSQRTSSr},
2451 {X86::SQRTSDr, X86::VSQRTSDr}
2452 };
2453 bool HasAVX = Subtarget->hasAVX();
2454 unsigned Opc;
2455 const TargetRegisterClass *RC;
2456 switch (VT.SimpleTy) {
2457 default: return false;
2458 case MVT::f32: Opc = SqrtOpc[0][HasAVX]; RC = &X86::FR32RegClass; break;
2459 case MVT::f64: Opc = SqrtOpc[1][HasAVX]; RC = &X86::FR64RegClass; break;
2460 }
2461
2462 const Value *SrcVal = II->getArgOperand(0);
2463 unsigned SrcReg = getRegForValue(SrcVal);
2464
2465 if (SrcReg == 0)
2466 return false;
2467
2468 unsigned ImplicitDefReg = 0;
2469 if (HasAVX) {
2470 ImplicitDefReg = createResultReg(RC);
2471 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2472 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2473 }
2474
2475 unsigned ResultReg = createResultReg(RC);
2476 MachineInstrBuilder MIB;
2477 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
2478 ResultReg);
2479
2480 if (ImplicitDefReg)
2481 MIB.addReg(ImplicitDefReg);
2482
2483 MIB.addReg(SrcReg);
2484
2485 updateValueMap(II, ResultReg);
2486 return true;
2487 }
2488 case Intrinsic::sadd_with_overflow:
2489 case Intrinsic::uadd_with_overflow:
2490 case Intrinsic::ssub_with_overflow:
2491 case Intrinsic::usub_with_overflow:
2492 case Intrinsic::smul_with_overflow:
2493 case Intrinsic::umul_with_overflow: {
2494 // This implements the basic lowering of the xalu with overflow intrinsics
2495 // into add/sub/mul followed by either seto or setb.
2496 const Function *Callee = II->getCalledFunction();
2497 auto *Ty = cast<StructType>(Callee->getReturnType());
2498 Type *RetTy = Ty->getTypeAtIndex(0U);
2499 Type *CondTy = Ty->getTypeAtIndex(1);
2500
2501 MVT VT;
2502 if (!isTypeLegal(RetTy, VT))
2503 return false;
2504
2505 if (VT < MVT::i8 || VT > MVT::i64)
2506 return false;
2507
2508 const Value *LHS = II->getArgOperand(0);
2509 const Value *RHS = II->getArgOperand(1);
2510
2511 // Canonicalize immediate to the RHS.
2512 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
2513 isCommutativeIntrinsic(II))
2514 std::swap(LHS, RHS);
2515
2516 bool UseIncDec = false;
2517 if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isOne())
2518 UseIncDec = true;
2519
2520 unsigned BaseOpc, CondOpc;
2521 switch (II->getIntrinsicID()) {
2522 default: llvm_unreachable("Unexpected intrinsic!");
2523 case Intrinsic::sadd_with_overflow:
2524 BaseOpc = UseIncDec ? unsigned(X86ISD::INC) : unsigned(ISD::ADD);
2525 CondOpc = X86::SETOr;
2526 break;
2527 case Intrinsic::uadd_with_overflow:
2528 BaseOpc = ISD::ADD; CondOpc = X86::SETBr; break;
2529 case Intrinsic::ssub_with_overflow:
2530 BaseOpc = UseIncDec ? unsigned(X86ISD::DEC) : unsigned(ISD::SUB);
2531 CondOpc = X86::SETOr;
2532 break;
2533 case Intrinsic::usub_with_overflow:
2534 BaseOpc = ISD::SUB; CondOpc = X86::SETBr; break;
2535 case Intrinsic::smul_with_overflow:
2536 BaseOpc = X86ISD::SMUL; CondOpc = X86::SETOr; break;
2537 case Intrinsic::umul_with_overflow:
2538 BaseOpc = X86ISD::UMUL; CondOpc = X86::SETOr; break;
2539 }
2540
2541 unsigned LHSReg = getRegForValue(LHS);
2542 if (LHSReg == 0)
2543 return false;
2544 bool LHSIsKill = hasTrivialKill(LHS);
2545
2546 unsigned ResultReg = 0;
2547 // Check if we have an immediate version.
2548 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2549 static const unsigned Opc[2][4] = {
2550 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2551 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2552 };
2553
2554 if (BaseOpc == X86ISD::INC || BaseOpc == X86ISD::DEC) {
2555 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2556 bool IsDec = BaseOpc == X86ISD::DEC;
2557 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2558 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2559 .addReg(LHSReg, getKillRegState(LHSIsKill));
2560 } else
2561 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, LHSIsKill,
2562 CI->getZExtValue());
2563 }
2564
2565 unsigned RHSReg;
2566 bool RHSIsKill;
2567 if (!ResultReg) {
2568 RHSReg = getRegForValue(RHS);
2569 if (RHSReg == 0)
2570 return false;
2571 RHSIsKill = hasTrivialKill(RHS);
2572 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, LHSIsKill, RHSReg,
2573 RHSIsKill);
2574 }
2575
2576 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2577 // it manually.
2578 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2579 static const unsigned MULOpc[] =
2580 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2581 static const unsigned Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2582 // First copy the first operand into RAX, which is an implicit input to
2583 // the X86::MUL*r instruction.
2584 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2585 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2586 .addReg(LHSReg, getKillRegState(LHSIsKill));
2587 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2588 TLI.getRegClassFor(VT), RHSReg, RHSIsKill);
2589 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2590 static const unsigned MULOpc[] =
2591 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2592 if (VT == MVT::i8) {
2593 // Copy the first operand into AL, which is an implicit input to the
2594 // X86::IMUL8r instruction.
2595 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2596 TII.get(TargetOpcode::COPY), X86::AL)
2597 .addReg(LHSReg, getKillRegState(LHSIsKill));
2598 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg,
2599 RHSIsKill);
2600 } else
2601 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2602 TLI.getRegClassFor(VT), LHSReg, LHSIsKill,
2603 RHSReg, RHSIsKill);
2604 }
2605
2606 if (!ResultReg)
2607 return false;
2608
2609 unsigned ResultReg2 = FuncInfo.CreateRegs(CondTy);
2610 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
2611 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CondOpc),
2612 ResultReg2);
2613
2614 updateValueMap(II, ResultReg, 2);
2615 return true;
2616 }
2617 case Intrinsic::x86_sse_cvttss2si:
2618 case Intrinsic::x86_sse_cvttss2si64:
2619 case Intrinsic::x86_sse2_cvttsd2si:
2620 case Intrinsic::x86_sse2_cvttsd2si64: {
2621 bool IsInputDouble;
2622 switch (II->getIntrinsicID()) {
2623 default: llvm_unreachable("Unexpected intrinsic.");
2624 case Intrinsic::x86_sse_cvttss2si:
2625 case Intrinsic::x86_sse_cvttss2si64:
2626 if (!Subtarget->hasSSE1())
2627 return false;
2628 IsInputDouble = false;
2629 break;
2630 case Intrinsic::x86_sse2_cvttsd2si:
2631 case Intrinsic::x86_sse2_cvttsd2si64:
2632 if (!Subtarget->hasSSE2())
2633 return false;
2634 IsInputDouble = true;
2635 break;
2636 }
2637
2638 Type *RetTy = II->getCalledFunction()->getReturnType();
2639 MVT VT;
2640 if (!isTypeLegal(RetTy, VT))
2641 return false;
2642
2643 static const unsigned CvtOpc[2][2][2] = {
2644 { { X86::CVTTSS2SIrr, X86::VCVTTSS2SIrr },
2645 { X86::CVTTSS2SI64rr, X86::VCVTTSS2SI64rr } },
2646 { { X86::CVTTSD2SIrr, X86::VCVTTSD2SIrr },
2647 { X86::CVTTSD2SI64rr, X86::VCVTTSD2SI64rr } }
2648 };
2649 bool HasAVX = Subtarget->hasAVX();
2650 unsigned Opc;
2651 switch (VT.SimpleTy) {
2652 default: llvm_unreachable("Unexpected result type.");
2653 case MVT::i32: Opc = CvtOpc[IsInputDouble][0][HasAVX]; break;
2654 case MVT::i64: Opc = CvtOpc[IsInputDouble][1][HasAVX]; break;
2655 }
2656
2657 // Check if we can fold insertelement instructions into the convert.
2658 const Value *Op = II->getArgOperand(0);
2659 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
2660 const Value *Index = IE->getOperand(2);
2661 if (!isa<ConstantInt>(Index))
2662 break;
2663 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
2664
2665 if (Idx == 0) {
2666 Op = IE->getOperand(1);
2667 break;
2668 }
2669 Op = IE->getOperand(0);
2670 }
2671
2672 unsigned Reg = getRegForValue(Op);
2673 if (Reg == 0)
2674 return false;
2675
2676 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
2677 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2678 .addReg(Reg);
2679
2680 updateValueMap(II, ResultReg);
2681 return true;
2682 }
2683 }
2684}
2685
2686bool X86FastISel::fastLowerArguments() {
2687 if (!FuncInfo.CanLowerReturn)
2688 return false;
2689
2690 const Function *F = FuncInfo.Fn;
2691 if (F->isVarArg())
2692 return false;
2693
2694 CallingConv::ID CC = F->getCallingConv();
2695 if (CC != CallingConv::C)
2696 return false;
2697
2698 if (Subtarget->isCallingConvWin64(CC))
2699 return false;
2700
2701 if (!Subtarget->is64Bit())
2702 return false;
2703
2704 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
2705 unsigned GPRCnt = 0;
2706 unsigned FPRCnt = 0;
2707 unsigned Idx = 0;
2708 for (auto const &Arg : F->args()) {
2709 // The first argument is at index 1.
2710 ++Idx;
2711 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2712 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2713 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2714 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2715 return false;
2716
2717 Type *ArgTy = Arg.getType();
2718 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
2719 return false;
2720
Mehdi Amini44ede332015-07-09 02:09:04 +00002721 EVT ArgVT = TLI.getValueType(DL, ArgTy);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002722 if (!ArgVT.isSimple()) return false;
2723 switch (ArgVT.getSimpleVT().SimpleTy) {
2724 default: return false;
2725 case MVT::i32:
2726 case MVT::i64:
2727 ++GPRCnt;
2728 break;
2729 case MVT::f32:
2730 case MVT::f64:
2731 if (!Subtarget->hasSSE1())
2732 return false;
2733 ++FPRCnt;
2734 break;
2735 }
2736
2737 if (GPRCnt > 6)
2738 return false;
2739
2740 if (FPRCnt > 8)
2741 return false;
2742 }
2743
2744 static const MCPhysReg GPR32ArgRegs[] = {
2745 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
2746 };
2747 static const MCPhysReg GPR64ArgRegs[] = {
2748 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
2749 };
2750 static const MCPhysReg XMMArgRegs[] = {
2751 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2752 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2753 };
2754
2755 unsigned GPRIdx = 0;
2756 unsigned FPRIdx = 0;
2757 for (auto const &Arg : F->args()) {
Mehdi Amini44ede332015-07-09 02:09:04 +00002758 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002759 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2760 unsigned SrcReg;
2761 switch (VT.SimpleTy) {
2762 default: llvm_unreachable("Unexpected value type.");
2763 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
2764 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
2765 case MVT::f32: // fall-through
2766 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
2767 }
2768 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2769 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2770 // Without this, EmitLiveInCopies may eliminate the livein if its only
2771 // use is a bitcast (which isn't turned into an instruction).
2772 unsigned ResultReg = createResultReg(RC);
2773 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2774 TII.get(TargetOpcode::COPY), ResultReg)
2775 .addReg(DstReg, getKillRegState(true));
2776 updateValueMap(&Arg, ResultReg);
2777 }
2778 return true;
2779}
2780
2781static unsigned computeBytesPoppedByCallee(const X86Subtarget *Subtarget,
2782 CallingConv::ID CC,
2783 ImmutableCallSite *CS) {
2784 if (Subtarget->is64Bit())
2785 return 0;
2786 if (Subtarget->getTargetTriple().isOSMSVCRT())
2787 return 0;
2788 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2789 CC == CallingConv::HiPE)
2790 return 0;
2791 if (CS && !CS->paramHasAttr(1, Attribute::StructRet))
2792 return 0;
2793 if (CS && CS->paramHasAttr(1, Attribute::InReg))
2794 return 0;
2795 return 4;
2796}
2797
2798bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2799 auto &OutVals = CLI.OutVals;
2800 auto &OutFlags = CLI.OutFlags;
2801 auto &OutRegs = CLI.OutRegs;
2802 auto &Ins = CLI.Ins;
2803 auto &InRegs = CLI.InRegs;
2804 CallingConv::ID CC = CLI.CallConv;
2805 bool &IsTailCall = CLI.IsTailCall;
2806 bool IsVarArg = CLI.IsVarArg;
2807 const Value *Callee = CLI.Callee;
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00002808 MCSymbol *Symbol = CLI.Symbol;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002809
2810 bool Is64Bit = Subtarget->is64Bit();
2811 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
2812
2813 // Handle only C, fastcc, and webkit_js calling conventions for now.
2814 switch (CC) {
2815 default: return false;
2816 case CallingConv::C:
2817 case CallingConv::Fast:
2818 case CallingConv::WebKit_JS:
2819 case CallingConv::X86_FastCall:
2820 case CallingConv::X86_64_Win64:
2821 case CallingConv::X86_64_SysV:
2822 break;
2823 }
2824
2825 // Allow SelectionDAG isel to handle tail calls.
2826 if (IsTailCall)
2827 return false;
2828
2829 // fastcc with -tailcallopt is intended to provide a guaranteed
2830 // tail call optimization. Fastisel doesn't know how to do that.
2831 if (CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt)
2832 return false;
2833
2834 // Don't know how to handle Win64 varargs yet. Nothing special needed for
2835 // x86-32. Special handling for x86-64 is implemented.
2836 if (IsVarArg && IsWin64)
2837 return false;
2838
2839 // Don't know about inalloca yet.
2840 if (CLI.CS && CLI.CS->hasInAllocaArgument())
2841 return false;
2842
2843 // Fast-isel doesn't know about callee-pop yet.
2844 if (X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
2845 TM.Options.GuaranteedTailCallOpt))
2846 return false;
2847
2848 SmallVector<MVT, 16> OutVTs;
2849 SmallVector<unsigned, 16> ArgRegs;
2850
2851 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
2852 // instruction. This is safe because it is common to all FastISel supported
2853 // calling conventions on x86.
2854 for (int i = 0, e = OutVals.size(); i != e; ++i) {
2855 Value *&Val = OutVals[i];
2856 ISD::ArgFlagsTy Flags = OutFlags[i];
2857 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
2858 if (CI->getBitWidth() < 32) {
2859 if (Flags.isSExt())
2860 Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
2861 else
2862 Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
2863 }
2864 }
2865
2866 // Passing bools around ends up doing a trunc to i1 and passing it.
2867 // Codegen this as an argument + "and 1".
2868 MVT VT;
2869 auto *TI = dyn_cast<TruncInst>(Val);
2870 unsigned ResultReg;
2871 if (TI && TI->getType()->isIntegerTy(1) && CLI.CS &&
2872 (TI->getParent() == CLI.CS->getInstruction()->getParent()) &&
2873 TI->hasOneUse()) {
2874 Value *PrevVal = TI->getOperand(0);
2875 ResultReg = getRegForValue(PrevVal);
2876
2877 if (!ResultReg)
2878 return false;
2879
2880 if (!isTypeLegal(PrevVal->getType(), VT))
2881 return false;
2882
2883 ResultReg =
2884 fastEmit_ri(VT, VT, ISD::AND, ResultReg, hasTrivialKill(PrevVal), 1);
2885 } else {
2886 if (!isTypeLegal(Val->getType(), VT))
2887 return false;
2888 ResultReg = getRegForValue(Val);
2889 }
2890
2891 if (!ResultReg)
2892 return false;
2893
2894 ArgRegs.push_back(ResultReg);
2895 OutVTs.push_back(VT);
2896 }
2897
2898 // Analyze operands of the call, assigning locations to each operand.
2899 SmallVector<CCValAssign, 16> ArgLocs;
2900 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
2901
2902 // Allocate shadow area for Win64
2903 if (IsWin64)
2904 CCInfo.AllocateStack(32, 8);
2905
2906 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
2907
2908 // Get a count of how many bytes are to be pushed on the stack.
Jeroen Ketema740f9d72015-09-29 10:12:57 +00002909 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002910
2911 // Issue CALLSEQ_START
2912 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2913 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
Michael Kuperstein13fbd452015-02-01 16:56:04 +00002914 .addImm(NumBytes).addImm(0);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002915
2916 // Walk the register/memloc assignments, inserting copies/loads.
Eric Christophera1c535b2015-02-02 23:03:45 +00002917 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00002918 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2919 CCValAssign const &VA = ArgLocs[i];
2920 const Value *ArgVal = OutVals[VA.getValNo()];
2921 MVT ArgVT = OutVTs[VA.getValNo()];
2922
2923 if (ArgVT == MVT::x86mmx)
2924 return false;
2925
2926 unsigned ArgReg = ArgRegs[VA.getValNo()];
2927
2928 // Promote the value if needed.
2929 switch (VA.getLocInfo()) {
2930 case CCValAssign::Full: break;
2931 case CCValAssign::SExt: {
2932 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2933 "Unexpected extend");
2934 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2935 ArgVT, ArgReg);
2936 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
2937 ArgVT = VA.getLocVT();
2938 break;
2939 }
2940 case CCValAssign::ZExt: {
2941 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2942 "Unexpected extend");
2943 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2944 ArgVT, ArgReg);
2945 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
2946 ArgVT = VA.getLocVT();
2947 break;
2948 }
2949 case CCValAssign::AExt: {
2950 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
2951 "Unexpected extend");
2952 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
2953 ArgVT, ArgReg);
2954 if (!Emitted)
2955 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
2956 ArgVT, ArgReg);
2957 if (!Emitted)
2958 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
2959 ArgVT, ArgReg);
2960
2961 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
2962 ArgVT = VA.getLocVT();
2963 break;
2964 }
2965 case CCValAssign::BCvt: {
2966 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg,
2967 /*TODO: Kill=*/false);
2968 assert(ArgReg && "Failed to emit a bitcast!");
2969 ArgVT = VA.getLocVT();
2970 break;
2971 }
2972 case CCValAssign::VExt:
2973 // VExt has not been implemented, so this should be impossible to reach
2974 // for now. However, fallback to Selection DAG isel once implemented.
2975 return false;
2976 case CCValAssign::AExtUpper:
2977 case CCValAssign::SExtUpper:
2978 case CCValAssign::ZExtUpper:
2979 case CCValAssign::FPExt:
2980 llvm_unreachable("Unexpected loc info!");
2981 case CCValAssign::Indirect:
2982 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
2983 // support this.
2984 return false;
2985 }
2986
2987 if (VA.isRegLoc()) {
2988 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2989 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2990 OutRegs.push_back(VA.getLocReg());
2991 } else {
2992 assert(VA.isMemLoc());
2993
2994 // Don't emit stores for undef values.
2995 if (isa<UndefValue>(ArgVal))
2996 continue;
2997
2998 unsigned LocMemOffset = VA.getLocMemOffset();
2999 X86AddressMode AM;
3000 AM.Base.Reg = RegInfo->getStackRegister();
3001 AM.Disp = LocMemOffset;
3002 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3003 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
3004 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003005 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3006 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003007 if (Flags.isByVal()) {
3008 X86AddressMode SrcAM;
3009 SrcAM.Base.Reg = ArgReg;
3010 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3011 return false;
3012 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3013 // If this is a really simple value, emit this with the Value* version
3014 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3015 // as it can cause us to reevaluate the argument.
3016 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3017 return false;
3018 } else {
3019 bool ValIsKill = hasTrivialKill(ArgVal);
3020 if (!X86FastEmitStore(ArgVT, ArgReg, ValIsKill, AM, MMO))
3021 return false;
3022 }
3023 }
3024 }
3025
3026 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3027 // GOT pointer.
3028 if (Subtarget->isPICStyleGOT()) {
3029 unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3030 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3031 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3032 }
3033
3034 if (Is64Bit && IsVarArg && !IsWin64) {
3035 // From AMD64 ABI document:
3036 // For calls that may call functions that use varargs or stdargs
3037 // (prototype-less calls or calls to functions containing ellipsis (...) in
3038 // the declaration) %al is used as hidden argument to specify the number
3039 // of SSE registers used. The contents of %al do not need to match exactly
3040 // the number of registers, but must be an ubound on the number of SSE
3041 // registers used and is in the range 0 - 8 inclusive.
3042
3043 // Count the number of XMM registers allocated.
3044 static const MCPhysReg XMMArgRegs[] = {
3045 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3046 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3047 };
Tim Northover3b6b7ca2015-02-21 02:11:17 +00003048 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003049 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3050 && "SSE registers cannot be used when SSE is disabled");
3051 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
3052 X86::AL).addImm(NumXMMRegs);
3053 }
3054
3055 // Materialize callee address in a register. FIXME: GV address can be
3056 // handled with a CALLpcrel32 instead.
3057 X86AddressMode CalleeAM;
3058 if (!X86SelectCallAddress(Callee, CalleeAM))
3059 return false;
3060
3061 unsigned CalleeOp = 0;
3062 const GlobalValue *GV = nullptr;
3063 if (CalleeAM.GV != nullptr) {
3064 GV = CalleeAM.GV;
3065 } else if (CalleeAM.Base.Reg != 0) {
3066 CalleeOp = CalleeAM.Base.Reg;
3067 } else
3068 return false;
3069
3070 // Issue the call.
3071 MachineInstrBuilder MIB;
3072 if (CalleeOp) {
3073 // Register-indirect call.
3074 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3075 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
3076 .addReg(CalleeOp);
3077 } else {
3078 // Direct call.
3079 assert(GV && "Not a direct call");
3080 unsigned CallOpc = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
3081
3082 // See if we need any target-specific flags on the GV operand.
3083 unsigned char OpFlags = 0;
3084
3085 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3086 // external symbols most go through the PLT in PIC mode. If the symbol
3087 // has hidden or protected visibility, or if it is static or local, then
3088 // we don't need to use the PLT - we can directly call it.
3089 if (Subtarget->isTargetELF() &&
3090 TM.getRelocationModel() == Reloc::PIC_ &&
3091 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3092 OpFlags = X86II::MO_PLT;
3093 } else if (Subtarget->isPICStyleStubAny() &&
Peter Collingbourne6a9d1772015-07-05 20:52:35 +00003094 !GV->isStrongDefinitionForLinker() &&
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003095 (!Subtarget->getTargetTriple().isMacOSX() ||
3096 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3097 // PC-relative references to external symbols should go through $stub,
3098 // unless we're building with the leopard linker or later, which
3099 // automatically synthesizes these stubs.
3100 OpFlags = X86II::MO_DARWIN_STUB;
3101 }
3102
3103 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
Rafael Espindolace4c2bc2015-06-23 12:21:54 +00003104 if (Symbol)
3105 MIB.addSym(Symbol, OpFlags);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003106 else
3107 MIB.addGlobalAddress(GV, 0, OpFlags);
3108 }
3109
3110 // Add a register mask operand representing the call-preserved registers.
3111 // Proper defs for return values will be added by setPhysRegsDeadExcept().
Eric Christopher9deb75d2015-03-11 22:42:13 +00003112 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003113
3114 // Add an implicit use GOT pointer in EBX.
3115 if (Subtarget->isPICStyleGOT())
3116 MIB.addReg(X86::EBX, RegState::Implicit);
3117
3118 if (Is64Bit && IsVarArg && !IsWin64)
3119 MIB.addReg(X86::AL, RegState::Implicit);
3120
3121 // Add implicit physical register uses to the call.
3122 for (auto Reg : OutRegs)
3123 MIB.addReg(Reg, RegState::Implicit);
3124
3125 // Issue CALLSEQ_END
3126 unsigned NumBytesForCalleeToPop =
3127 computeBytesPoppedByCallee(Subtarget, CC, CLI.CS);
3128 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3129 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
3130 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3131
3132 // Now handle call return values.
3133 SmallVector<CCValAssign, 16> RVLocs;
3134 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3135 CLI.RetTy->getContext());
3136 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3137
3138 // Copy all of the result registers out of their specified physreg.
3139 unsigned ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3140 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3141 CCValAssign &VA = RVLocs[i];
3142 EVT CopyVT = VA.getValVT();
3143 unsigned CopyReg = ResultReg + i;
3144
3145 // If this is x86-64, and we disabled SSE, we can't return FP values
3146 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3147 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3148 report_fatal_error("SSE register return with SSE disabled");
3149 }
3150
3151 // If we prefer to use the value in xmm registers, copy it out as f80 and
3152 // use a truncate to move it from fp stack reg to xmm reg.
3153 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
3154 isScalarFPTypeInSSEReg(VA.getValVT())) {
3155 CopyVT = MVT::f80;
3156 CopyReg = createResultReg(&X86::RFP80RegClass);
3157 }
3158
3159 // Copy out the result.
3160 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3161 TII.get(TargetOpcode::COPY), CopyReg).addReg(VA.getLocReg());
3162 InRegs.push_back(VA.getLocReg());
3163
3164 // Round the f80 to the right size, which also moves it to the appropriate
3165 // xmm register. This is accomplished by storing the f80 value in memory
3166 // and then loading it back.
3167 if (CopyVT != VA.getValVT()) {
3168 EVT ResVT = VA.getValVT();
3169 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3170 unsigned MemSize = ResVT.getSizeInBits()/8;
3171 int FI = MFI.CreateStackObject(MemSize, MemSize, false);
3172 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3173 TII.get(Opc)), FI)
3174 .addReg(CopyReg);
3175 Opc = ResVT == MVT::f32 ? X86::MOVSSrm : X86::MOVSDrm;
3176 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3177 TII.get(Opc), ResultReg + i), FI);
3178 }
3179 }
3180
3181 CLI.ResultReg = ResultReg;
3182 CLI.NumResultRegs = RVLocs.size();
3183 CLI.Call = MIB;
3184
3185 return true;
3186}
3187
3188bool
3189X86FastISel::fastSelectInstruction(const Instruction *I) {
3190 switch (I->getOpcode()) {
3191 default: break;
3192 case Instruction::Load:
3193 return X86SelectLoad(I);
3194 case Instruction::Store:
3195 return X86SelectStore(I);
3196 case Instruction::Ret:
3197 return X86SelectRet(I);
3198 case Instruction::ICmp:
3199 case Instruction::FCmp:
3200 return X86SelectCmp(I);
3201 case Instruction::ZExt:
3202 return X86SelectZExt(I);
3203 case Instruction::Br:
3204 return X86SelectBranch(I);
3205 case Instruction::LShr:
3206 case Instruction::AShr:
3207 case Instruction::Shl:
3208 return X86SelectShift(I);
3209 case Instruction::SDiv:
3210 case Instruction::UDiv:
3211 case Instruction::SRem:
3212 case Instruction::URem:
3213 return X86SelectDivRem(I);
3214 case Instruction::Select:
3215 return X86SelectSelect(I);
3216 case Instruction::Trunc:
3217 return X86SelectTrunc(I);
3218 case Instruction::FPExt:
3219 return X86SelectFPExt(I);
3220 case Instruction::FPTrunc:
3221 return X86SelectFPTrunc(I);
Andrea Di Biagioe7b58ee2015-02-17 23:40:58 +00003222 case Instruction::SIToFP:
3223 return X86SelectSIToFP(I);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003224 case Instruction::IntToPtr: // Deliberate fall-through.
3225 case Instruction::PtrToInt: {
Mehdi Amini44ede332015-07-09 02:09:04 +00003226 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3227 EVT DstVT = TLI.getValueType(DL, I->getType());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003228 if (DstVT.bitsGT(SrcVT))
3229 return X86SelectZExt(I);
3230 if (DstVT.bitsLT(SrcVT))
3231 return X86SelectTrunc(I);
3232 unsigned Reg = getRegForValue(I->getOperand(0));
3233 if (Reg == 0) return false;
3234 updateValueMap(I, Reg);
3235 return true;
3236 }
Andrea Di Biagio77f62652015-10-02 16:08:05 +00003237 case Instruction::BitCast: {
3238 // Select SSE2/AVX bitcasts between 128/256 bit vector types.
3239 if (!Subtarget->hasSSE2())
3240 return false;
3241
3242 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3243 EVT DstVT = TLI.getValueType(DL, I->getType());
3244
3245 if (!SrcVT.isSimple() || !DstVT.isSimple())
3246 return false;
3247
3248 if (!SrcVT.is128BitVector() &&
3249 !(Subtarget->hasAVX() && SrcVT.is256BitVector()))
3250 return false;
3251
3252 unsigned Reg = getRegForValue(I->getOperand(0));
3253 if (Reg == 0)
3254 return false;
3255
3256 // No instruction is needed for conversion. Reuse the register used by
3257 // the fist operand.
3258 updateValueMap(I, Reg);
3259 return true;
3260 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003261 }
3262
3263 return false;
3264}
3265
3266unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3267 if (VT > MVT::i64)
3268 return 0;
3269
3270 uint64_t Imm = CI->getZExtValue();
3271 if (Imm == 0) {
3272 unsigned SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3273 switch (VT.SimpleTy) {
3274 default: llvm_unreachable("Unexpected value type");
3275 case MVT::i1:
3276 case MVT::i8:
3277 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, /*Kill=*/true,
3278 X86::sub_8bit);
3279 case MVT::i16:
3280 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, /*Kill=*/true,
3281 X86::sub_16bit);
3282 case MVT::i32:
3283 return SrcReg;
3284 case MVT::i64: {
3285 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3286 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3287 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3288 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3289 return ResultReg;
3290 }
3291 }
3292 }
3293
3294 unsigned Opc = 0;
3295 switch (VT.SimpleTy) {
3296 default: llvm_unreachable("Unexpected value type");
3297 case MVT::i1: VT = MVT::i8; // fall-through
3298 case MVT::i8: Opc = X86::MOV8ri; break;
3299 case MVT::i16: Opc = X86::MOV16ri; break;
3300 case MVT::i32: Opc = X86::MOV32ri; break;
3301 case MVT::i64: {
3302 if (isUInt<32>(Imm))
3303 Opc = X86::MOV32ri;
3304 else if (isInt<32>(Imm))
3305 Opc = X86::MOV64ri32;
3306 else
3307 Opc = X86::MOV64ri;
3308 break;
3309 }
3310 }
3311 if (VT == MVT::i64 && Opc == X86::MOV32ri) {
3312 unsigned SrcReg = fastEmitInst_i(Opc, &X86::GR32RegClass, Imm);
3313 unsigned ResultReg = createResultReg(&X86::GR64RegClass);
3314 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3315 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3316 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3317 return ResultReg;
3318 }
3319 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3320}
3321
3322unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3323 if (CFP->isNullValue())
3324 return fastMaterializeFloatZero(CFP);
3325
3326 // Can't handle alternate code models yet.
3327 CodeModel::Model CM = TM.getCodeModel();
3328 if (CM != CodeModel::Small && CM != CodeModel::Large)
3329 return 0;
3330
3331 // Get opcode and regclass of the output for the given load instruction.
3332 unsigned Opc = 0;
3333 const TargetRegisterClass *RC = nullptr;
3334 switch (VT.SimpleTy) {
3335 default: return 0;
3336 case MVT::f32:
3337 if (X86ScalarSSEf32) {
3338 Opc = Subtarget->hasAVX() ? X86::VMOVSSrm : X86::MOVSSrm;
3339 RC = &X86::FR32RegClass;
3340 } else {
3341 Opc = X86::LD_Fp32m;
3342 RC = &X86::RFP32RegClass;
3343 }
3344 break;
3345 case MVT::f64:
3346 if (X86ScalarSSEf64) {
3347 Opc = Subtarget->hasAVX() ? X86::VMOVSDrm : X86::MOVSDrm;
3348 RC = &X86::FR64RegClass;
3349 } else {
3350 Opc = X86::LD_Fp64m;
3351 RC = &X86::RFP64RegClass;
3352 }
3353 break;
3354 case MVT::f80:
3355 // No f80 support yet.
3356 return 0;
3357 }
3358
3359 // MachineConstantPool wants an explicit alignment.
3360 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
3361 if (Align == 0) {
3362 // Alignment of vector types. FIXME!
3363 Align = DL.getTypeAllocSize(CFP->getType());
3364 }
3365
3366 // x86-32 PIC requires a PIC base register for constant pools.
3367 unsigned PICBase = 0;
3368 unsigned char OpFlag = 0;
3369 if (Subtarget->isPICStyleStubPIC()) { // Not dynamic-no-pic
3370 OpFlag = X86II::MO_PIC_BASE_OFFSET;
3371 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3372 } else if (Subtarget->isPICStyleGOT()) {
3373 OpFlag = X86II::MO_GOTOFF;
3374 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3375 } else if (Subtarget->isPICStyleRIPRel() &&
3376 TM.getCodeModel() == CodeModel::Small) {
3377 PICBase = X86::RIP;
3378 }
3379
3380 // Create the load from the constant pool.
3381 unsigned CPI = MCP.getConstantPoolIndex(CFP, Align);
3382 unsigned ResultReg = createResultReg(RC);
3383
3384 if (CM == CodeModel::Large) {
3385 unsigned AddrReg = createResultReg(&X86::GR64RegClass);
3386 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3387 AddrReg)
3388 .addConstantPoolIndex(CPI, 0, OpFlag);
3389 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3390 TII.get(Opc), ResultReg);
3391 addDirectMem(MIB, AddrReg);
3392 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
Alex Lorenze40c8a22015-08-11 23:09:45 +00003393 MachinePointerInfo::getConstantPool(*FuncInfo.MF),
3394 MachineMemOperand::MOLoad, DL.getPointerSize(), Align);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003395 MIB->addMemOperand(*FuncInfo.MF, MMO);
3396 return ResultReg;
3397 }
3398
3399 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3400 TII.get(Opc), ResultReg),
3401 CPI, PICBase, OpFlag);
3402 return ResultReg;
3403}
3404
3405unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3406 // Can't handle alternate code models yet.
3407 if (TM.getCodeModel() != CodeModel::Small)
3408 return 0;
3409
3410 // Materialize addresses with LEA/MOV instructions.
3411 X86AddressMode AM;
3412 if (X86SelectAddress(GV, AM)) {
3413 // If the expression is just a basereg, then we're done, otherwise we need
3414 // to emit an LEA.
3415 if (AM.BaseType == X86AddressMode::RegBase &&
3416 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3417 return AM.Base.Reg;
3418
3419 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3420 if (TM.getRelocationModel() == Reloc::Static &&
Mehdi Amini44ede332015-07-09 02:09:04 +00003421 TLI.getPointerTy(DL) == MVT::i64) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003422 // The displacement code could be more than 32 bits away so we need to use
3423 // an instruction with a 64 bit immediate
3424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
3425 ResultReg)
3426 .addGlobalAddress(GV);
3427 } else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003428 unsigned Opc =
3429 TLI.getPointerTy(DL) == MVT::i32
3430 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3431 : X86::LEA64r;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003432 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3433 TII.get(Opc), ResultReg), AM);
3434 }
3435 return ResultReg;
3436 }
3437 return 0;
3438}
3439
3440unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
Mehdi Amini44ede332015-07-09 02:09:04 +00003441 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003442
3443 // Only handle simple types.
3444 if (!CEVT.isSimple())
3445 return 0;
3446 MVT VT = CEVT.getSimpleVT();
3447
3448 if (const auto *CI = dyn_cast<ConstantInt>(C))
3449 return X86MaterializeInt(CI, VT);
3450 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
3451 return X86MaterializeFP(CFP, VT);
3452 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
3453 return X86MaterializeGV(GV, VT);
3454
3455 return 0;
3456}
3457
3458unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3459 // Fail on dynamic allocas. At this point, getRegForValue has already
3460 // checked its CSE maps, so if we're here trying to handle a dynamic
3461 // alloca, we're not going to succeed. X86SelectAddress has a
3462 // check for dynamic allocas, because it's called directly from
3463 // various places, but targetMaterializeAlloca also needs a check
3464 // in order to avoid recursion between getRegForValue,
3465 // X86SelectAddrss, and targetMaterializeAlloca.
3466 if (!FuncInfo.StaticAllocaMap.count(C))
3467 return 0;
3468 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3469
3470 X86AddressMode AM;
3471 if (!X86SelectAddress(C, AM))
3472 return 0;
Mehdi Amini44ede332015-07-09 02:09:04 +00003473 unsigned Opc =
3474 TLI.getPointerTy(DL) == MVT::i32
3475 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3476 : X86::LEA64r;
3477 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003478 unsigned ResultReg = createResultReg(RC);
3479 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3480 TII.get(Opc), ResultReg), AM);
3481 return ResultReg;
3482}
3483
3484unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3485 MVT VT;
3486 if (!isTypeLegal(CF->getType(), VT))
3487 return 0;
3488
3489 // Get opcode and regclass for the given zero.
3490 unsigned Opc = 0;
3491 const TargetRegisterClass *RC = nullptr;
3492 switch (VT.SimpleTy) {
3493 default: return 0;
3494 case MVT::f32:
3495 if (X86ScalarSSEf32) {
3496 Opc = X86::FsFLD0SS;
3497 RC = &X86::FR32RegClass;
3498 } else {
3499 Opc = X86::LD_Fp032;
3500 RC = &X86::RFP32RegClass;
3501 }
3502 break;
3503 case MVT::f64:
3504 if (X86ScalarSSEf64) {
3505 Opc = X86::FsFLD0SD;
3506 RC = &X86::FR64RegClass;
3507 } else {
3508 Opc = X86::LD_Fp064;
3509 RC = &X86::RFP64RegClass;
3510 }
3511 break;
3512 case MVT::f80:
3513 // No f80 support yet.
3514 return 0;
3515 }
3516
3517 unsigned ResultReg = createResultReg(RC);
3518 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
3519 return ResultReg;
3520}
3521
3522
3523bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
3524 const LoadInst *LI) {
3525 const Value *Ptr = LI->getPointerOperand();
3526 X86AddressMode AM;
3527 if (!X86SelectAddress(Ptr, AM))
3528 return false;
3529
3530 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
3531
3532 unsigned Size = DL.getTypeAllocSize(LI->getType());
3533 unsigned Alignment = LI->getAlignment();
3534
3535 if (Alignment == 0) // Ensure that codegen never sees alignment 0
3536 Alignment = DL.getABITypeAlignment(LI->getType());
3537
3538 SmallVector<MachineOperand, 8> AddrOps;
3539 AM.getFullAddress(AddrOps);
3540
Keno Fischere70b31f2015-06-08 20:09:58 +00003541 MachineInstr *Result = XII.foldMemoryOperandImpl(
3542 *FuncInfo.MF, MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, Alignment,
3543 /*AllowCommute=*/true);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003544 if (!Result)
3545 return false;
3546
Pete Cooperd31583d2015-05-06 21:37:19 +00003547 // The index register could be in the wrong register class. Unfortunately,
3548 // foldMemoryOperandImpl could have commuted the instruction so its not enough
3549 // to just look at OpNo + the offset to the index reg. We actually need to
3550 // scan the instruction to find the index reg and see if its the correct reg
3551 // class.
Matthias Braune41e1462015-05-29 02:56:46 +00003552 unsigned OperandNo = 0;
3553 for (MachineInstr::mop_iterator I = Result->operands_begin(),
3554 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
3555 MachineOperand &MO = *I;
3556 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
Pete Cooperd31583d2015-05-06 21:37:19 +00003557 continue;
3558 // Found the index reg, now try to rewrite it.
Pete Cooperd31583d2015-05-06 21:37:19 +00003559 unsigned IndexReg = constrainOperandRegClass(Result->getDesc(),
Matthias Braune41e1462015-05-29 02:56:46 +00003560 MO.getReg(), OperandNo);
3561 if (IndexReg == MO.getReg())
Pete Cooperd31583d2015-05-06 21:37:19 +00003562 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00003563 MO.setReg(IndexReg);
Pete Cooperd31583d2015-05-06 21:37:19 +00003564 }
3565
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003566 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00003567 MI->eraseFromParent();
3568 return true;
3569}
3570
3571
3572namespace llvm {
3573 FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
3574 const TargetLibraryInfo *libInfo) {
3575 return new X86FastISel(funcInfo, libInfo);
3576 }
3577}