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