LLVM 23.0.0git
X86FastISel.cpp
Go to the documentation of this file.
1//===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the X86-specific support for the FastISel class. Much
10// of the target-specific code is generated by tablegen in the file
11// X86GenFastISel.inc, which is #included here.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86.h"
16#include "X86CallingConv.h"
17#include "X86InstrBuilder.h"
18#include "X86InstrInfo.h"
20#include "X86RegisterInfo.h"
21#include "X86Subtarget.h"
22#include "X86TargetMachine.h"
29#include "llvm/IR/CallingConv.h"
30#include "llvm/IR/DebugInfo.h"
36#include "llvm/IR/IntrinsicsX86.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/Operator.h"
39#include "llvm/MC/MCAsmInfo.h"
40#include "llvm/MC/MCSymbol.h"
43using namespace llvm;
44
45namespace {
46
47class X86FastISel final : public FastISel {
48 /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
49 /// make the right decision when generating code for different targets.
50 const X86Subtarget *Subtarget;
51
52public:
53 explicit X86FastISel(FunctionLoweringInfo &funcInfo,
54 const TargetLibraryInfo *libInfo,
55 const LibcallLoweringInfo *libcallLowering)
56 : FastISel(funcInfo, libInfo, libcallLowering) {
57 Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
58 }
59
60 bool fastSelectInstruction(const Instruction *I) override;
61
62 /// The specified machine instr operand is a vreg, and that
63 /// vreg is being provided by the specified load instruction. If possible,
64 /// try to fold the load as an operand to the instruction, returning true if
65 /// possible.
66 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
67 const LoadInst *LI) override;
68
69 bool fastLowerArguments() override;
70 bool fastLowerCall(CallLoweringInfo &CLI) override;
71 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
72
73#include "X86GenFastISel.inc"
74
75private:
76 bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
77 const DebugLoc &DL);
78
79 bool X86FastEmitLoad(MVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
80 Register &ResultReg, unsigned Alignment = 1);
81
82 bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
83 MachineMemOperand *MMO = nullptr, bool Aligned = false);
84 bool X86FastEmitStore(EVT VT, Register ValReg, X86AddressMode &AM,
85 MachineMemOperand *MMO = nullptr, bool Aligned = false);
86
87 bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, Register Src, EVT SrcVT,
88 Register &ResultReg);
89
90 bool X86SelectAddress(const Value *V, X86AddressMode &AM);
91 bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
92
93 bool X86SelectLoad(const Instruction *I);
94
95 bool X86SelectStore(const Instruction *I);
96
97 bool X86SelectRet(const Instruction *I);
98
99 bool X86SelectCmp(const Instruction *I);
100
101 bool X86SelectZExt(const Instruction *I);
102
103 bool X86SelectSExt(const Instruction *I);
104
105 bool X86SelectBranch(const Instruction *I);
106
107 bool X86SelectShift(const Instruction *I);
108
109 bool X86SelectDivRem(const Instruction *I);
110
111 bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
112
113 bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
114
115 bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
116
117 bool X86SelectSelect(const Instruction *I);
118
119 bool X86SelectTrunc(const Instruction *I);
120
121 bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
122 const TargetRegisterClass *RC);
123
124 bool X86SelectFPExt(const Instruction *I);
125 bool X86SelectFPTrunc(const Instruction *I);
126 bool X86SelectSIToFP(const Instruction *I);
127 bool X86SelectUIToFP(const Instruction *I);
128 bool X86SelectIntToFP(const Instruction *I, bool IsSigned);
129 bool X86SelectBitCast(const Instruction *I);
130
131 const X86InstrInfo *getInstrInfo() const {
132 return Subtarget->getInstrInfo();
133 }
134 const X86TargetMachine *getTargetMachine() const {
135 return static_cast<const X86TargetMachine *>(&TM);
136 }
137
138 bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
139
140 Register X86MaterializeInt(const ConstantInt *CI, MVT VT);
141 Register X86MaterializeFP(const ConstantFP *CFP, MVT VT);
142 Register X86MaterializeGV(const GlobalValue *GV, MVT VT);
143 Register fastMaterializeConstant(const Constant *C) override;
144
145 Register fastMaterializeAlloca(const AllocaInst *C) override;
146
147 Register fastMaterializeFloatZero(const ConstantFP *CF) override;
148
149 /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
150 /// computed in an SSE register, not on the X87 floating point stack.
151 bool isScalarFPTypeInSSEReg(EVT VT) const {
152 return (VT == MVT::f64 && Subtarget->hasSSE2()) ||
153 (VT == MVT::f32 && Subtarget->hasSSE1()) || VT == MVT::f16;
154 }
155
156 bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
157
158 bool IsMemcpySmall(uint64_t Len);
159
160 bool TryEmitSmallMemcpy(X86AddressMode DestAM,
161 X86AddressMode SrcAM, uint64_t Len);
162
163 bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
164 const Value *Cond);
165
166 const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
167 X86AddressMode &AM);
168
169 Register fastEmitInst_rrrr(unsigned MachineInstOpcode,
170 const TargetRegisterClass *RC, Register Op0,
171 Register Op1, Register Op2, Register Op3);
172};
173
174} // end anonymous namespace.
175
176static std::pair<unsigned, bool>
178 unsigned CC;
179 bool NeedSwap = false;
180
181 // SSE Condition code mapping:
182 // 0 - EQ
183 // 1 - LT
184 // 2 - LE
185 // 3 - UNORD
186 // 4 - NEQ
187 // 5 - NLT
188 // 6 - NLE
189 // 7 - ORD
190 switch (Predicate) {
191 default: llvm_unreachable("Unexpected predicate");
192 case CmpInst::FCMP_OEQ: CC = 0; break;
193 case CmpInst::FCMP_OGT: NeedSwap = true; [[fallthrough]];
194 case CmpInst::FCMP_OLT: CC = 1; break;
195 case CmpInst::FCMP_OGE: NeedSwap = true; [[fallthrough]];
196 case CmpInst::FCMP_OLE: CC = 2; break;
197 case CmpInst::FCMP_UNO: CC = 3; break;
198 case CmpInst::FCMP_UNE: CC = 4; break;
199 case CmpInst::FCMP_ULE: NeedSwap = true; [[fallthrough]];
200 case CmpInst::FCMP_UGE: CC = 5; break;
201 case CmpInst::FCMP_ULT: NeedSwap = true; [[fallthrough]];
202 case CmpInst::FCMP_UGT: CC = 6; break;
203 case CmpInst::FCMP_ORD: CC = 7; break;
204 case CmpInst::FCMP_UEQ: CC = 8; break;
205 case CmpInst::FCMP_ONE: CC = 12; break;
206 }
207
208 return std::make_pair(CC, NeedSwap);
209}
210
211/// Adds a complex addressing mode to the given machine instr builder.
212/// Note, this will constrain the index register. If its not possible to
213/// constrain the given index register, then a new one will be created. The
214/// IndexReg field of the addressing mode will be updated to match in this case.
216X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
217 X86AddressMode &AM) {
218 // First constrain the index register. It needs to be a GR64_NOSP.
220 MIB->getNumOperands() +
222 return ::addFullAddress(MIB, AM);
223}
224
225/// Check if it is possible to fold the condition from the XALU intrinsic
226/// into the user. The condition code will only be updated on success.
227bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
228 const Value *Cond) {
230 return false;
231
232 const auto *EV = cast<ExtractValueInst>(Cond);
233 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
234 return false;
235
236 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
237 MVT RetVT;
238 const Function *Callee = II->getCalledFunction();
239 Type *RetTy =
240 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
241 if (!isTypeLegal(RetTy, RetVT))
242 return false;
243
244 if (RetVT != MVT::i32 && RetVT != MVT::i64)
245 return false;
246
247 X86::CondCode TmpCC;
248 switch (II->getIntrinsicID()) {
249 default: return false;
250 case Intrinsic::sadd_with_overflow:
251 case Intrinsic::ssub_with_overflow:
252 case Intrinsic::smul_with_overflow:
253 case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
254 case Intrinsic::uadd_with_overflow:
255 case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
256 }
257
258 // Check if both instructions are in the same basic block.
259 if (II->getParent() != I->getParent())
260 return false;
261
262 // Make sure nothing is in the way
265 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
266 // We only expect extractvalue instructions between the intrinsic and the
267 // instruction to be selected.
268 if (!isa<ExtractValueInst>(Itr))
269 return false;
270
271 // Check that the extractvalue operand comes from the intrinsic.
272 const auto *EVI = cast<ExtractValueInst>(Itr);
273 if (EVI->getAggregateOperand() != II)
274 return false;
275 }
276
277 // Make sure no potentially eflags clobbering phi moves can be inserted in
278 // between.
279 auto HasPhis = [](const BasicBlock *Succ) { return !Succ->phis().empty(); };
280 if (I->isTerminator() && llvm::any_of(successors(I), HasPhis))
281 return false;
282
283 // Make sure there are no potentially eflags clobbering constant
284 // materializations in between.
285 if (llvm::any_of(I->operands(), [](Value *V) { return isa<Constant>(V); }))
286 return false;
287
288 CC = TmpCC;
289 return true;
290}
291
292bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
293 EVT evt = TLI.getValueType(DL, Ty, /*AllowUnknown=*/true);
294 if (evt == MVT::Other || !evt.isSimple())
295 // Unhandled type. Halt "fast" selection and bail.
296 return false;
297
298 VT = evt.getSimpleVT();
299 // For now, require SSE/SSE2 for performing floating-point operations,
300 // since x87 requires additional work.
301 if (VT == MVT::f64 && !Subtarget->hasSSE2())
302 return false;
303 if (VT == MVT::f32 && !Subtarget->hasSSE1())
304 return false;
305 // Similarly, no f80 support yet.
306 if (VT == MVT::f80)
307 return false;
308 // We only handle legal types. For example, on x86-32 the instruction
309 // selector contains all of the 64-bit instructions from x86-64,
310 // under the assumption that i64 won't be used if the target doesn't
311 // support it.
312 return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
313}
314
315/// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
316/// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
317/// Return true and the result register by reference if it is possible.
318bool X86FastISel::X86FastEmitLoad(MVT VT, X86AddressMode &AM,
319 MachineMemOperand *MMO, Register &ResultReg,
320 unsigned Alignment) {
321 bool HasSSE1 = Subtarget->hasSSE1();
322 bool HasSSE2 = Subtarget->hasSSE2();
323 bool HasSSE41 = Subtarget->hasSSE41();
324 bool HasAVX = Subtarget->hasAVX();
325 bool HasAVX2 = Subtarget->hasAVX2();
326 bool HasAVX512 = Subtarget->hasAVX512();
327 bool HasVLX = Subtarget->hasVLX();
328 bool IsNonTemporal = MMO && MMO->isNonTemporal();
329
330 // Treat i1 loads the same as i8 loads. Masking will be done when storing.
331 if (VT == MVT::i1)
332 VT = MVT::i8;
333
334 // Get opcode and regclass of the output for the given load instruction.
335 unsigned Opc = 0;
336 switch (VT.SimpleTy) {
337 default: return false;
338 case MVT::i8:
339 Opc = X86::MOV8rm;
340 break;
341 case MVT::i16:
342 Opc = X86::MOV16rm;
343 break;
344 case MVT::i32:
345 Opc = X86::MOV32rm;
346 break;
347 case MVT::i64:
348 // Must be in x86-64 mode.
349 Opc = X86::MOV64rm;
350 break;
351 case MVT::f32:
352 Opc = HasAVX512 ? X86::VMOVSSZrm_alt
353 : HasAVX ? X86::VMOVSSrm_alt
354 : HasSSE1 ? X86::MOVSSrm_alt
355 : X86::LD_Fp32m;
356 break;
357 case MVT::f64:
358 Opc = HasAVX512 ? X86::VMOVSDZrm_alt
359 : HasAVX ? X86::VMOVSDrm_alt
360 : HasSSE2 ? X86::MOVSDrm_alt
361 : X86::LD_Fp64m;
362 break;
363 case MVT::f80:
364 // No f80 support yet.
365 return false;
366 case MVT::v4f32:
367 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
368 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
369 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
370 else if (Alignment >= 16)
371 Opc = HasVLX ? X86::VMOVAPSZ128rm :
372 HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
373 else
374 Opc = HasVLX ? X86::VMOVUPSZ128rm :
375 HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
376 break;
377 case MVT::v2f64:
378 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
379 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
380 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
381 else if (Alignment >= 16)
382 Opc = HasVLX ? X86::VMOVAPDZ128rm :
383 HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
384 else
385 Opc = HasVLX ? X86::VMOVUPDZ128rm :
386 HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
387 break;
388 case MVT::v4i32:
389 case MVT::v2i64:
390 case MVT::v8i16:
391 case MVT::v16i8:
392 if (IsNonTemporal && Alignment >= 16 && HasSSE41)
393 Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
394 HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
395 else if (Alignment >= 16)
396 Opc = HasVLX ? X86::VMOVDQA64Z128rm :
397 HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
398 else
399 Opc = HasVLX ? X86::VMOVDQU64Z128rm :
400 HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
401 break;
402 case MVT::v8f32:
403 assert(HasAVX);
404 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
405 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
406 else if (IsNonTemporal && Alignment >= 16)
407 return false; // Force split for X86::VMOVNTDQArm
408 else if (Alignment >= 32)
409 Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
410 else
411 Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
412 break;
413 case MVT::v4f64:
414 assert(HasAVX);
415 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
416 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
417 else if (IsNonTemporal && Alignment >= 16)
418 return false; // Force split for X86::VMOVNTDQArm
419 else if (Alignment >= 32)
420 Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
421 else
422 Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
423 break;
424 case MVT::v8i32:
425 case MVT::v4i64:
426 case MVT::v16i16:
427 case MVT::v32i8:
428 assert(HasAVX);
429 if (IsNonTemporal && Alignment >= 32 && HasAVX2)
430 Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
431 else if (IsNonTemporal && Alignment >= 16)
432 return false; // Force split for X86::VMOVNTDQArm
433 else if (Alignment >= 32)
434 Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
435 else
436 Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
437 break;
438 case MVT::v16f32:
439 assert(HasAVX512);
440 if (IsNonTemporal && Alignment >= 64)
441 Opc = X86::VMOVNTDQAZrm;
442 else
443 Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
444 break;
445 case MVT::v8f64:
446 assert(HasAVX512);
447 if (IsNonTemporal && Alignment >= 64)
448 Opc = X86::VMOVNTDQAZrm;
449 else
450 Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
451 break;
452 case MVT::v8i64:
453 case MVT::v16i32:
454 case MVT::v32i16:
455 case MVT::v64i8:
456 assert(HasAVX512);
457 // Note: There are a lot more choices based on type with AVX-512, but
458 // there's really no advantage when the load isn't masked.
459 if (IsNonTemporal && Alignment >= 64)
460 Opc = X86::VMOVNTDQAZrm;
461 else
462 Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
463 break;
464 }
465
466 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
467
468 ResultReg = createResultReg(RC);
469 MachineInstrBuilder MIB =
470 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), ResultReg);
471 addFullAddress(MIB, AM);
472 if (MMO)
473 MIB->addMemOperand(*FuncInfo.MF, MMO);
474 return true;
475}
476
477/// X86FastEmitStore - Emit a machine instruction to store a value Val of
478/// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
479/// and a displacement offset, or a GlobalAddress,
480/// i.e. V. Return true if it is possible.
481bool X86FastISel::X86FastEmitStore(EVT VT, Register ValReg, X86AddressMode &AM,
482 MachineMemOperand *MMO, bool Aligned) {
483 bool HasSSE1 = Subtarget->hasSSE1();
484 bool HasSSE2 = Subtarget->hasSSE2();
485 bool HasSSE4A = Subtarget->hasSSE4A();
486 bool HasAVX = Subtarget->hasAVX();
487 bool HasAVX512 = Subtarget->hasAVX512();
488 bool HasVLX = Subtarget->hasVLX();
489 bool IsNonTemporal = MMO && MMO->isNonTemporal();
490
491 // Get opcode and regclass of the output for the given store instruction.
492 unsigned Opc = 0;
493 switch (VT.getSimpleVT().SimpleTy) {
494 case MVT::f80: // No f80 support yet.
495 default: return false;
496 case MVT::i1: {
497 // Mask out all but lowest bit.
498 Register AndResult = createResultReg(&X86::GR8RegClass);
499 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
500 TII.get(X86::AND8ri), AndResult)
501 .addReg(ValReg).addImm(1);
502 ValReg = AndResult;
503 [[fallthrough]]; // handle i1 as i8.
504 }
505 case MVT::i8: Opc = X86::MOV8mr; break;
506 case MVT::i16: Opc = X86::MOV16mr; break;
507 case MVT::i32:
508 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
509 break;
510 case MVT::i64:
511 // Must be in x86-64 mode.
512 Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
513 break;
514 case MVT::f32:
515 if (HasSSE1) {
516 if (IsNonTemporal && HasSSE4A)
517 Opc = X86::MOVNTSS;
518 else
519 Opc = HasAVX512 ? X86::VMOVSSZmr :
520 HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
521 } else
522 Opc = X86::ST_Fp32m;
523 break;
524 case MVT::f64:
525 if (HasSSE2) {
526 if (IsNonTemporal && HasSSE4A)
527 Opc = X86::MOVNTSD;
528 else
529 Opc = HasAVX512 ? X86::VMOVSDZmr :
530 HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
531 } else
532 Opc = X86::ST_Fp64m;
533 break;
534 case MVT::x86mmx:
535 Opc = (IsNonTemporal && HasSSE1) ? X86::MMX_MOVNTQmr : X86::MMX_MOVQ64mr;
536 break;
537 case MVT::v4f32:
538 if (Aligned) {
539 if (IsNonTemporal)
540 Opc = HasVLX ? X86::VMOVNTPSZ128mr :
541 HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
542 else
543 Opc = HasVLX ? X86::VMOVAPSZ128mr :
544 HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
545 } else
546 Opc = HasVLX ? X86::VMOVUPSZ128mr :
547 HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
548 break;
549 case MVT::v2f64:
550 if (Aligned) {
551 if (IsNonTemporal)
552 Opc = HasVLX ? X86::VMOVNTPDZ128mr :
553 HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
554 else
555 Opc = HasVLX ? X86::VMOVAPDZ128mr :
556 HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
557 } else
558 Opc = HasVLX ? X86::VMOVUPDZ128mr :
559 HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
560 break;
561 case MVT::v4i32:
562 case MVT::v2i64:
563 case MVT::v8i16:
564 case MVT::v16i8:
565 if (Aligned) {
566 if (IsNonTemporal)
567 Opc = HasVLX ? X86::VMOVNTDQZ128mr :
568 HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
569 else
570 Opc = HasVLX ? X86::VMOVDQA64Z128mr :
571 HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
572 } else
573 Opc = HasVLX ? X86::VMOVDQU64Z128mr :
574 HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
575 break;
576 case MVT::v8f32:
577 assert(HasAVX);
578 if (Aligned) {
579 if (IsNonTemporal)
580 Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
581 else
582 Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
583 } else
584 Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
585 break;
586 case MVT::v4f64:
587 assert(HasAVX);
588 if (Aligned) {
589 if (IsNonTemporal)
590 Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
591 else
592 Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
593 } else
594 Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
595 break;
596 case MVT::v8i32:
597 case MVT::v4i64:
598 case MVT::v16i16:
599 case MVT::v32i8:
600 assert(HasAVX);
601 if (Aligned) {
602 if (IsNonTemporal)
603 Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
604 else
605 Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
606 } else
607 Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
608 break;
609 case MVT::v16f32:
610 assert(HasAVX512);
611 if (Aligned)
612 Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
613 else
614 Opc = X86::VMOVUPSZmr;
615 break;
616 case MVT::v8f64:
617 assert(HasAVX512);
618 if (Aligned) {
619 Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
620 } else
621 Opc = X86::VMOVUPDZmr;
622 break;
623 case MVT::v8i64:
624 case MVT::v16i32:
625 case MVT::v32i16:
626 case MVT::v64i8:
627 assert(HasAVX512);
628 // Note: There are a lot more choices based on type with AVX-512, but
629 // there's really no advantage when the store isn't masked.
630 if (Aligned)
631 Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
632 else
633 Opc = X86::VMOVDQU64Zmr;
634 break;
635 }
636
637 const MCInstrDesc &Desc = TII.get(Opc);
638 // Some of the instructions in the previous switch use FR128 instead
639 // of FR32 for ValReg. Make sure the register we feed the instruction
640 // matches its register class constraints.
641 // Note: This is fine to do a copy from FR32 to FR128, this is the
642 // same registers behind the scene and actually why it did not trigger
643 // any bugs before.
644 ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
645 MachineInstrBuilder MIB =
646 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, Desc);
647 addFullAddress(MIB, AM).addReg(ValReg);
648 if (MMO)
649 MIB->addMemOperand(*FuncInfo.MF, MMO);
650
651 return true;
652}
653
654bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
655 X86AddressMode &AM,
656 MachineMemOperand *MMO, bool Aligned) {
657 // Handle 'null' like i32/i64 0.
659 Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
660
661 // If this is a store of a simple constant, fold the constant into the store.
662 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
663 unsigned Opc = 0;
664 bool Signed = true;
665 switch (VT.getSimpleVT().SimpleTy) {
666 default: break;
667 case MVT::i1:
668 Signed = false;
669 [[fallthrough]]; // Handle as i8.
670 case MVT::i8: Opc = X86::MOV8mi; break;
671 case MVT::i16: Opc = X86::MOV16mi; break;
672 case MVT::i32: Opc = X86::MOV32mi; break;
673 case MVT::i64:
674 // Must be a 32-bit sign extended value.
675 if (isInt<32>(CI->getSExtValue()))
676 Opc = X86::MOV64mi32;
677 break;
678 }
679
680 if (Opc) {
681 MachineInstrBuilder MIB =
682 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc));
683 addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
684 : CI->getZExtValue());
685 if (MMO)
686 MIB->addMemOperand(*FuncInfo.MF, MMO);
687 return true;
688 }
689 }
690
691 Register ValReg = getRegForValue(Val);
692 if (!ValReg)
693 return false;
694
695 return X86FastEmitStore(VT, ValReg, AM, MMO, Aligned);
696}
697
698/// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
699/// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
700/// ISD::SIGN_EXTEND).
701bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, Register Src,
702 EVT SrcVT, Register &ResultReg) {
703 Register RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src);
704 if (!RR)
705 return false;
706
707 ResultReg = RR;
708 return true;
709}
710
711bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
712 // Handle constant address.
713 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
714 // Can't handle alternate code models yet.
715 if (TM.getCodeModel() != CodeModel::Small &&
716 TM.getCodeModel() != CodeModel::Medium)
717 return false;
718
719 // Can't handle large objects yet.
720 if (TM.isLargeGlobalValue(GV))
721 return false;
722
723 // Can't handle TLS yet.
724 if (GV->isThreadLocal())
725 return false;
726
727 // Can't handle !absolute_symbol references yet.
728 if (GV->isAbsoluteSymbolRef())
729 return false;
730
731 // RIP-relative addresses can't have additional register operands, so if
732 // we've already folded stuff into the addressing mode, just force the
733 // global value into its own register, which we can use as the basereg.
734 if (!Subtarget->isPICStyleRIPRel() ||
735 (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
736 // Okay, we've committed to selecting this global. Set up the address.
737 AM.GV = GV;
738
739 // Allow the subtarget to classify the global.
740 unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
741
742 // If this reference is relative to the pic base, set it now.
743 if (isGlobalRelativeToPICBase(GVFlags)) {
744 // FIXME: How do we know Base.Reg is free??
745 AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
746 }
747
748 // Unless the ABI requires an extra load, return a direct reference to
749 // the global.
750 if (!isGlobalStubReference(GVFlags)) {
751 if (Subtarget->isPICStyleRIPRel()) {
752 // Use rip-relative addressing if we can. Above we verified that the
753 // base and index registers are unused.
754 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
755 AM.Base.Reg = X86::RIP;
756 }
757 AM.GVOpFlags = GVFlags;
758 return true;
759 }
760
761 // Ok, we need to do a load from a stub. If we've already loaded from
762 // this stub, reuse the loaded pointer, otherwise emit the load now.
763 DenseMap<const Value *, Register>::iterator I = LocalValueMap.find(V);
764 Register LoadReg;
765 if (I != LocalValueMap.end() && I->second) {
766 LoadReg = I->second;
767 } else {
768 // Issue load from stub.
769 unsigned Opc = 0;
770 const TargetRegisterClass *RC = nullptr;
771 X86AddressMode StubAM;
772 StubAM.Base.Reg = AM.Base.Reg;
773 StubAM.GV = GV;
774 StubAM.GVOpFlags = GVFlags;
775
776 // Prepare for inserting code in the local-value area.
777 SavePoint SaveInsertPt = enterLocalValueArea();
778
779 if (TLI.getPointerTy(DL) == MVT::i64) {
780 Opc = X86::MOV64rm;
781 RC = &X86::GR64RegClass;
782 } else {
783 Opc = X86::MOV32rm;
784 RC = &X86::GR32RegClass;
785 }
786
787 if (Subtarget->isPICStyleRIPRel() || GVFlags == X86II::MO_GOTPCREL ||
789 StubAM.Base.Reg = X86::RIP;
790
791 LoadReg = createResultReg(RC);
792 MachineInstrBuilder LoadMI =
793 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), LoadReg);
794 addFullAddress(LoadMI, StubAM);
795
796 // Ok, back to normal mode.
797 leaveLocalValueArea(SaveInsertPt);
798
799 // Prevent loading GV stub multiple times in same MBB.
800 LocalValueMap[V] = LoadReg;
801 }
802
803 // Now construct the final address. Note that the Disp, Scale,
804 // and Index values may already be set here.
805 AM.Base.Reg = LoadReg;
806 AM.GV = nullptr;
807 return true;
808 }
809 }
810
811 // If all else fails, try to materialize the value in a register.
812 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
813 if (AM.Base.Reg == 0) {
814 AM.Base.Reg = getRegForValue(V);
815 return AM.Base.Reg != 0;
816 }
817 if (AM.IndexReg == 0) {
818 assert(AM.Scale == 1 && "Scale with no index!");
819 AM.IndexReg = getRegForValue(V);
820 return AM.IndexReg != 0;
821 }
822 }
823
824 return false;
825}
826
827/// X86SelectAddress - Attempt to fill in an address from the given value.
828///
829bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
831redo_gep:
832 const User *U = nullptr;
833 unsigned Opcode = Instruction::UserOp1;
834 if (const Instruction *I = dyn_cast<Instruction>(V)) {
835 // Don't walk into other basic blocks; it's possible we haven't
836 // visited them yet, so the instructions may not yet be assigned
837 // virtual registers.
838 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
839 FuncInfo.getMBB(I->getParent()) == FuncInfo.MBB) {
840 Opcode = I->getOpcode();
841 U = I;
842 }
843 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
844 Opcode = C->getOpcode();
845 U = C;
846 }
847
848 if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
849 if (Ty->getAddressSpace() > 255)
850 // Fast instruction selection doesn't support the special
851 // address spaces.
852 return false;
853
854 switch (Opcode) {
855 default: break;
856 case Instruction::BitCast:
857 // Look past bitcasts.
858 return X86SelectAddress(U->getOperand(0), AM);
859
860 case Instruction::IntToPtr:
861 // Look past no-op inttoptrs.
862 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
863 TLI.getPointerTy(DL))
864 return X86SelectAddress(U->getOperand(0), AM);
865 break;
866
867 case Instruction::PtrToInt:
868 // Look past no-op ptrtoints.
869 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
870 return X86SelectAddress(U->getOperand(0), AM);
871 break;
872
873 case Instruction::Alloca: {
874 // Do static allocas.
875 const AllocaInst *A = cast<AllocaInst>(V);
876 DenseMap<const AllocaInst *, int>::iterator SI =
877 FuncInfo.StaticAllocaMap.find(A);
878 if (SI != FuncInfo.StaticAllocaMap.end()) {
880 AM.Base.FrameIndex = SI->second;
881 return true;
882 }
883 break;
884 }
885
886 case Instruction::Add: {
887 // Adds of constants are common and easy enough.
888 if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
889 uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
890 // They have to fit in the 32-bit signed displacement field though.
891 if (isInt<32>(Disp)) {
892 AM.Disp = (uint32_t)Disp;
893 return X86SelectAddress(U->getOperand(0), AM);
894 }
895 }
896 break;
897 }
898
899 case Instruction::GetElementPtr: {
900 X86AddressMode SavedAM = AM;
901
902 // Pattern-match simple GEPs.
903 uint64_t Disp = (int32_t)AM.Disp;
904 Register IndexReg = AM.IndexReg;
905 unsigned Scale = AM.Scale;
906 MVT PtrVT = TLI.getValueType(DL, U->getType()).getSimpleVT();
907
909 // Iterate through the indices, folding what we can. Constants can be
910 // folded, and one dynamic index can be handled, if the scale is supported.
911 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
912 i != e; ++i, ++GTI) {
913 const Value *Op = *i;
914 if (StructType *STy = GTI.getStructTypeOrNull()) {
915 const StructLayout *SL = DL.getStructLayout(STy);
916 Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
917 continue;
918 }
919
920 // A array/variable index is always of the form i*S where S is the
921 // constant scale size. See if we can push the scale into immediates.
922 uint64_t S = GTI.getSequentialElementStride(DL);
923 for (;;) {
924 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
925 // Constant-offset addressing.
926 Disp += CI->getSExtValue() * S;
927 break;
928 }
929 if (canFoldAddIntoGEP(U, Op)) {
930 // A compatible add with a constant operand. Fold the constant.
931 ConstantInt *CI =
932 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
933 Disp += CI->getSExtValue() * S;
934 // Iterate on the other operand.
935 Op = cast<AddOperator>(Op)->getOperand(0);
936 continue;
937 }
938 if (!IndexReg && (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
939 (S == 1 || S == 2 || S == 4 || S == 8)) {
940 // Scaled-index addressing.
941 Scale = S;
942 IndexReg = getRegForGEPIndex(PtrVT, Op);
943 if (!IndexReg)
944 return false;
945 break;
946 }
947 // Unsupported.
948 goto unsupported_gep;
949 }
950 }
951
952 // Check for displacement overflow.
953 if (!isInt<32>(Disp))
954 break;
955
956 AM.IndexReg = IndexReg;
957 AM.Scale = Scale;
958 AM.Disp = (uint32_t)Disp;
959 GEPs.push_back(V);
960
961 if (const GetElementPtrInst *GEP =
962 dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
963 // Ok, the GEP indices were covered by constant-offset and scaled-index
964 // addressing. Update the address state and move on to examining the base.
965 V = GEP;
966 goto redo_gep;
967 } else if (X86SelectAddress(U->getOperand(0), AM)) {
968 return true;
969 }
970
971 // If we couldn't merge the gep value into this addr mode, revert back to
972 // our address and just match the value instead of completely failing.
973 AM = SavedAM;
974
975 for (const Value *I : reverse(GEPs))
976 if (handleConstantAddresses(I, AM))
977 return true;
978
979 return false;
980 unsupported_gep:
981 // Ok, the GEP indices weren't all covered.
982 break;
983 }
984 }
985
986 return handleConstantAddresses(V, AM);
987}
988
989/// X86SelectCallAddress - Attempt to fill in an address from the given value.
990///
991bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
992 const User *U = nullptr;
993 unsigned Opcode = Instruction::UserOp1;
995 // Record if the value is defined in the same basic block.
996 //
997 // This information is crucial to know whether or not folding an
998 // operand is valid.
999 // Indeed, FastISel generates or reuses a virtual register for all
1000 // operands of all instructions it selects. Obviously, the definition and
1001 // its uses must use the same virtual register otherwise the produced
1002 // code is incorrect.
1003 // Before instruction selection, FunctionLoweringInfo::set sets the virtual
1004 // registers for values that are alive across basic blocks. This ensures
1005 // that the values are consistently set between across basic block, even
1006 // if different instruction selection mechanisms are used (e.g., a mix of
1007 // SDISel and FastISel).
1008 // For values local to a basic block, the instruction selection process
1009 // generates these virtual registers with whatever method is appropriate
1010 // for its needs. In particular, FastISel and SDISel do not share the way
1011 // local virtual registers are set.
1012 // Therefore, this is impossible (or at least unsafe) to share values
1013 // between basic blocks unless they use the same instruction selection
1014 // method, which is not guarantee for X86.
1015 // Moreover, things like hasOneUse could not be used accurately, if we
1016 // allow to reference values across basic blocks whereas they are not
1017 // alive across basic blocks initially.
1018 bool InMBB = true;
1019 if (I) {
1020 Opcode = I->getOpcode();
1021 U = I;
1022 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
1023 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
1024 Opcode = C->getOpcode();
1025 U = C;
1026 }
1027
1028 switch (Opcode) {
1029 default: break;
1030 case Instruction::BitCast:
1031 // Look past bitcasts if its operand is in the same BB.
1032 if (InMBB)
1033 return X86SelectCallAddress(U->getOperand(0), AM);
1034 break;
1035
1036 case Instruction::IntToPtr:
1037 // Look past no-op inttoptrs if its operand is in the same BB.
1038 if (InMBB &&
1039 TLI.getValueType(DL, U->getOperand(0)->getType()) ==
1040 TLI.getPointerTy(DL))
1041 return X86SelectCallAddress(U->getOperand(0), AM);
1042 break;
1043
1044 case Instruction::PtrToInt:
1045 // Look past no-op ptrtoints if its operand is in the same BB.
1046 if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
1047 return X86SelectCallAddress(U->getOperand(0), AM);
1048 break;
1049 }
1050
1051 // Handle constant address.
1052 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
1053 // Can't handle alternate code models yet.
1054 if (TM.getCodeModel() != CodeModel::Small &&
1055 TM.getCodeModel() != CodeModel::Medium)
1056 return false;
1057
1058 // RIP-relative addresses can't have additional register operands.
1059 if (Subtarget->isPICStyleRIPRel() &&
1060 (AM.Base.Reg != 0 || AM.IndexReg != 0))
1061 return false;
1062
1063 // Can't handle TLS.
1064 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
1065 if (GVar->isThreadLocal())
1066 return false;
1067
1068 // Okay, we've committed to selecting this global. Set up the basic address.
1069 AM.GV = GV;
1070
1071 // Return a direct reference to the global. Fastisel can handle calls to
1072 // functions that require loads, such as dllimport and nonlazybind
1073 // functions.
1074 if (Subtarget->isPICStyleRIPRel()) {
1075 // Use rip-relative addressing if we can. Above we verified that the
1076 // base and index registers are unused.
1077 assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
1078 AM.Base.Reg = X86::RIP;
1079 } else {
1080 AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
1081 }
1082
1083 return true;
1084 }
1085
1086 // If all else fails, try to materialize the value in a register.
1087 if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
1088 auto GetCallRegForValue = [this](const Value *V) {
1089 Register Reg = getRegForValue(V);
1090
1091 // In 64-bit mode, we need a 64-bit register even if pointers are 32 bits.
1092 if (Reg && Subtarget->isTarget64BitILP32()) {
1093 Register CopyReg = createResultReg(&X86::GR32RegClass);
1094 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV32rr),
1095 CopyReg)
1096 .addReg(Reg);
1097
1098 Register ExtReg = createResultReg(&X86::GR64RegClass);
1099 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1100 TII.get(TargetOpcode::SUBREG_TO_REG), ExtReg)
1101 .addImm(0)
1102 .addReg(CopyReg)
1103 .addImm(X86::sub_32bit);
1104 Reg = ExtReg;
1105 }
1106
1107 return Reg;
1108 };
1109
1110 if (AM.Base.Reg == 0) {
1111 AM.Base.Reg = GetCallRegForValue(V);
1112 return AM.Base.Reg != 0;
1113 }
1114 if (AM.IndexReg == 0) {
1115 assert(AM.Scale == 1 && "Scale with no index!");
1116 AM.IndexReg = GetCallRegForValue(V);
1117 return AM.IndexReg != 0;
1118 }
1119 }
1120
1121 return false;
1122}
1123
1124
1125/// X86SelectStore - Select and emit code to implement store instructions.
1126bool X86FastISel::X86SelectStore(const Instruction *I) {
1127 // Atomic stores need special handling.
1128 const StoreInst *S = cast<StoreInst>(I);
1129
1130 if (S->isAtomic())
1131 return false;
1132
1133 const Value *PtrV = I->getOperand(1);
1134 if (TLI.supportSwiftError()) {
1135 // Swifterror values can come from either a function parameter with
1136 // swifterror attribute or an alloca with swifterror attribute.
1137 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1138 if (Arg->hasSwiftErrorAttr())
1139 return false;
1140 }
1141
1142 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1143 if (Alloca->isSwiftError())
1144 return false;
1145 }
1146 }
1147
1148 const Value *Val = S->getValueOperand();
1149 const Value *Ptr = S->getPointerOperand();
1150
1151 MVT VT;
1152 if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
1153 return false;
1154
1155 Align Alignment = S->getAlign();
1156 Align ABIAlignment = DL.getABITypeAlign(Val->getType());
1157 bool Aligned = Alignment >= ABIAlignment;
1158
1159 X86AddressMode AM;
1160 if (!X86SelectAddress(Ptr, AM))
1161 return false;
1162
1163 return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
1164}
1165
1166/// X86SelectRet - Select and emit code to implement ret instructions.
1167bool X86FastISel::X86SelectRet(const Instruction *I) {
1168 const ReturnInst *Ret = cast<ReturnInst>(I);
1169 const Function &F = *I->getParent()->getParent();
1170 const X86MachineFunctionInfo *X86MFInfo =
1171 FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
1172
1173 if (!FuncInfo.CanLowerReturn)
1174 return false;
1175
1176 if (TLI.supportSwiftError() &&
1177 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1178 return false;
1179
1180 if (TLI.supportSplitCSR(FuncInfo.MF))
1181 return false;
1182
1183 CallingConv::ID CC = F.getCallingConv();
1184 if (CC != CallingConv::C &&
1185 CC != CallingConv::Fast &&
1186 CC != CallingConv::Tail &&
1187 CC != CallingConv::SwiftTail &&
1188 CC != CallingConv::X86_FastCall &&
1189 CC != CallingConv::X86_StdCall &&
1190 CC != CallingConv::X86_ThisCall &&
1191 CC != CallingConv::X86_64_SysV &&
1192 CC != CallingConv::Win64)
1193 return false;
1194
1195 // Don't handle popping bytes if they don't fit the ret's immediate.
1196 if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
1197 return false;
1198
1199 // fastcc with -tailcallopt is intended to provide a guaranteed
1200 // tail call optimization. Fastisel doesn't know how to do that.
1201 if ((CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) ||
1202 CC == CallingConv::Tail || CC == CallingConv::SwiftTail)
1203 return false;
1204
1205 // Let SDISel handle vararg functions.
1206 if (F.isVarArg())
1207 return false;
1208
1209 // Build a list of return value registers.
1211
1212 if (Ret->getNumOperands() > 0) {
1214 GetReturnInfo(CC, F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
1215
1216 // Analyze operands of the call, assigning locations to each operand.
1218 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
1219 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1220
1221 const Value *RV = Ret->getOperand(0);
1222 Register Reg = getRegForValue(RV);
1223 if (!Reg)
1224 return false;
1225
1226 // Only handle a single return value for now.
1227 if (ValLocs.size() != 1)
1228 return false;
1229
1230 CCValAssign &VA = ValLocs[0];
1231
1232 // Don't bother handling odd stuff for now.
1233 if (VA.getLocInfo() != CCValAssign::Full)
1234 return false;
1235 // Only handle register returns for now.
1236 if (!VA.isRegLoc())
1237 return false;
1238
1239 // The calling-convention tables for x87 returns don't tell
1240 // the whole story.
1241 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
1242 return false;
1243
1244 Register SrcReg = Reg + VA.getValNo();
1245 EVT SrcVT = TLI.getValueType(DL, RV->getType());
1246 EVT DstVT = VA.getValVT();
1247 // Special handling for extended integers.
1248 if (SrcVT != DstVT) {
1249 if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
1250 return false;
1251
1252 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
1253 return false;
1254
1255 if (SrcVT == MVT::i1) {
1256 if (Outs[0].Flags.isSExt())
1257 return false;
1258 SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg);
1259 SrcVT = MVT::i8;
1260 }
1261 if (SrcVT != DstVT) {
1262 unsigned Op =
1263 Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
1264 SrcReg =
1265 fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op, SrcReg);
1266 }
1267 }
1268
1269 // Make the copy.
1270 Register DstReg = VA.getLocReg();
1271 const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
1272 // Avoid a cross-class copy. This is very unlikely.
1273 if (!SrcRC->contains(DstReg))
1274 return false;
1275 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1276 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
1277
1278 // Add register to return instruction.
1279 RetRegs.push_back(VA.getLocReg());
1280 }
1281
1282 // Swift calling convention does not require we copy the sret argument
1283 // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
1284
1285 // All x86 ABIs require that for returning structs by value we copy
1286 // the sret argument into %rax/%eax (depending on ABI) for the return.
1287 // We saved the argument into a virtual register in the entry block,
1288 // so now we copy the value out and into %rax/%eax.
1289 if (F.hasStructRetAttr() && CC != CallingConv::Swift &&
1290 CC != CallingConv::SwiftTail) {
1291 Register Reg = X86MFInfo->getSRetReturnReg();
1292 assert(Reg &&
1293 "SRetReturnReg should have been set in LowerFormalArguments()!");
1294 Register RetReg = Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
1295 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1296 TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
1297 RetRegs.push_back(RetReg);
1298 }
1299
1300 // Now emit the RET.
1301 MachineInstrBuilder MIB;
1302 if (X86MFInfo->getBytesToPopOnReturn()) {
1303 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1304 TII.get(Subtarget->is64Bit() ? X86::RETI64 : X86::RETI32))
1305 .addImm(X86MFInfo->getBytesToPopOnReturn());
1306 } else {
1307 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1308 TII.get(Subtarget->is64Bit() ? X86::RET64 : X86::RET32));
1309 }
1310 for (Register Reg : RetRegs)
1312 return true;
1313}
1314
1315/// X86SelectLoad - Select and emit code to implement load instructions.
1316///
1317bool X86FastISel::X86SelectLoad(const Instruction *I) {
1318 const LoadInst *LI = cast<LoadInst>(I);
1319
1320 // Atomic loads need special handling.
1321 if (LI->isAtomic())
1322 return false;
1323
1324 const Value *SV = I->getOperand(0);
1325 if (TLI.supportSwiftError()) {
1326 // Swifterror values can come from either a function parameter with
1327 // swifterror attribute or an alloca with swifterror attribute.
1328 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1329 if (Arg->hasSwiftErrorAttr())
1330 return false;
1331 }
1332
1333 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1334 if (Alloca->isSwiftError())
1335 return false;
1336 }
1337 }
1338
1339 MVT VT;
1340 if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
1341 return false;
1342
1343 const Value *Ptr = LI->getPointerOperand();
1344
1345 X86AddressMode AM;
1346 if (!X86SelectAddress(Ptr, AM))
1347 return false;
1348
1349 Register ResultReg;
1350 if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
1351 LI->getAlign().value()))
1352 return false;
1353
1354 updateValueMap(I, ResultReg);
1355 return true;
1356}
1357
1358static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
1359 bool HasAVX512 = Subtarget->hasAVX512();
1360 bool HasAVX = Subtarget->hasAVX();
1361 bool HasSSE1 = Subtarget->hasSSE1();
1362 bool HasSSE2 = Subtarget->hasSSE2();
1363
1364 switch (VT.getSimpleVT().SimpleTy) {
1365 default: return 0;
1366 case MVT::i8: return X86::CMP8rr;
1367 case MVT::i16: return X86::CMP16rr;
1368 case MVT::i32: return X86::CMP32rr;
1369 case MVT::i64: return X86::CMP64rr;
1370 case MVT::f32:
1371 return HasAVX512 ? X86::VUCOMISSZrr
1372 : HasAVX ? X86::VUCOMISSrr
1373 : HasSSE1 ? X86::UCOMISSrr
1374 : 0;
1375 case MVT::f64:
1376 return HasAVX512 ? X86::VUCOMISDZrr
1377 : HasAVX ? X86::VUCOMISDrr
1378 : HasSSE2 ? X86::UCOMISDrr
1379 : 0;
1380 }
1381}
1382
1383/// If we have a comparison with RHS as the RHS of the comparison, return an
1384/// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
1385static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
1386 switch (VT.getSimpleVT().SimpleTy) {
1387 // Otherwise, we can't fold the immediate into this comparison.
1388 default:
1389 return 0;
1390 case MVT::i8:
1391 return X86::CMP8ri;
1392 case MVT::i16:
1393 return X86::CMP16ri;
1394 case MVT::i32:
1395 return X86::CMP32ri;
1396 case MVT::i64:
1397 // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
1398 // field.
1399 return isInt<32>(RHSC->getSExtValue()) ? X86::CMP64ri32 : 0;
1400 }
1401}
1402
1403bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
1404 const DebugLoc &CurMIMD) {
1405 Register Op0Reg = getRegForValue(Op0);
1406 if (!Op0Reg)
1407 return false;
1408
1409 // Handle 'null' like i32/i64 0.
1410 if (isa<ConstantPointerNull>(Op1))
1411 Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
1412
1413 // We have two options: compare with register or immediate. If the RHS of
1414 // the compare is an immediate that we can fold into this compare, use
1415 // CMPri, otherwise use CMPrr.
1416 if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
1417 if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
1418 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurMIMD, TII.get(CompareImmOpc))
1419 .addReg(Op0Reg)
1420 .addImm(Op1C->getSExtValue());
1421 return true;
1422 }
1423 }
1424
1425 unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
1426 if (CompareOpc == 0) return false;
1427
1428 Register Op1Reg = getRegForValue(Op1);
1429 if (!Op1Reg)
1430 return false;
1431 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurMIMD, TII.get(CompareOpc))
1432 .addReg(Op0Reg)
1433 .addReg(Op1Reg);
1434
1435 return true;
1436}
1437
1438#define GET_SETCC \
1439 ((!Subtarget->hasZU() || Subtarget->preferLegacySetCC()) ? X86::SETCCr \
1440 : X86::SETZUCCr)
1441
1442bool X86FastISel::X86SelectCmp(const Instruction *I) {
1443 const CmpInst *CI = cast<CmpInst>(I);
1444
1445 MVT VT;
1446 if (!isTypeLegal(I->getOperand(0)->getType(), VT))
1447 return false;
1448
1449 // Below code only works for scalars.
1450 if (VT.isVector())
1451 return false;
1452
1453 // Try to optimize or fold the cmp.
1454 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1455 Register ResultReg;
1456 switch (Predicate) {
1457 default: break;
1458 case CmpInst::FCMP_FALSE: {
1459 ResultReg = createResultReg(&X86::GR32RegClass);
1460 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV32r0),
1461 ResultReg);
1462 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, X86::sub_8bit);
1463 if (!ResultReg)
1464 return false;
1465 break;
1466 }
1467 case CmpInst::FCMP_TRUE: {
1468 ResultReg = createResultReg(&X86::GR8RegClass);
1469 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV8ri),
1470 ResultReg).addImm(1);
1471 break;
1472 }
1473 }
1474
1475 if (ResultReg) {
1476 updateValueMap(I, ResultReg);
1477 return true;
1478 }
1479
1480 const Value *LHS = CI->getOperand(0);
1481 const Value *RHS = CI->getOperand(1);
1482
1483 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
1484 // We don't have to materialize a zero constant for this case and can just use
1485 // %x again on the RHS.
1487 const auto *RHSC = dyn_cast<ConstantFP>(RHS);
1488 if (RHSC && RHSC->isNullValue())
1489 RHS = LHS;
1490 }
1491
1492 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
1493 static const uint16_t SETFOpcTable[2][3] = {
1494 { X86::COND_E, X86::COND_NP, X86::AND8rr },
1495 { X86::COND_NE, X86::COND_P, X86::OR8rr }
1496 };
1497 const uint16_t *SETFOpc = nullptr;
1498 switch (Predicate) {
1499 default: break;
1500 case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
1501 case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
1502 }
1503
1504 ResultReg = createResultReg(&X86::GR8RegClass);
1505 if (SETFOpc) {
1506 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1507 return false;
1508
1509 Register FlagReg1 = createResultReg(&X86::GR8RegClass);
1510 Register FlagReg2 = createResultReg(&X86::GR8RegClass);
1511 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(GET_SETCC),
1512 FlagReg1)
1513 .addImm(SETFOpc[0]);
1514 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(GET_SETCC),
1515 FlagReg2)
1516 .addImm(SETFOpc[1]);
1517 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(SETFOpc[2]),
1518 ResultReg).addReg(FlagReg1).addReg(FlagReg2);
1519 updateValueMap(I, ResultReg);
1520 return true;
1521 }
1522
1523 X86::CondCode CC;
1524 bool SwapArgs;
1525 std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
1526 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1527
1528 if (SwapArgs)
1529 std::swap(LHS, RHS);
1530
1531 // Emit a compare of LHS/RHS.
1532 if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
1533 return false;
1534
1535 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(GET_SETCC), ResultReg)
1536 .addImm(CC);
1537 updateValueMap(I, ResultReg);
1538 return true;
1539}
1540
1541bool X86FastISel::X86SelectZExt(const Instruction *I) {
1542 EVT DstVT = TLI.getValueType(DL, I->getType());
1543 if (!TLI.isTypeLegal(DstVT))
1544 return false;
1545
1546 Register ResultReg = getRegForValue(I->getOperand(0));
1547 if (!ResultReg)
1548 return false;
1549
1550 // Handle zero-extension from i1 to i8, which is common.
1551 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1552 if (SrcVT == MVT::i1) {
1553 // Set the high bits to zero.
1554 ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg);
1555 SrcVT = MVT::i8;
1556
1557 if (!ResultReg)
1558 return false;
1559 }
1560
1561 if (DstVT == MVT::i64) {
1562 // Handle extension to 64-bits via sub-register shenanigans.
1563 unsigned MovInst;
1564
1565 switch (SrcVT.SimpleTy) {
1566 case MVT::i8: MovInst = X86::MOVZX32rr8; break;
1567 case MVT::i16: MovInst = X86::MOVZX32rr16; break;
1568 case MVT::i32: MovInst = X86::MOV32rr; break;
1569 default: llvm_unreachable("Unexpected zext to i64 source type");
1570 }
1571
1572 Register Result32 = createResultReg(&X86::GR32RegClass);
1573 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(MovInst), Result32)
1574 .addReg(ResultReg);
1575
1576 ResultReg = createResultReg(&X86::GR64RegClass);
1577 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::SUBREG_TO_REG),
1578 ResultReg)
1579 .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
1580 } else if (DstVT == MVT::i16) {
1581 // i8->i16 doesn't exist in the autogenerated isel table. Need to zero
1582 // extend to 32-bits and then extract down to 16-bits.
1583 Register Result32 = createResultReg(&X86::GR32RegClass);
1584 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOVZX32rr8),
1585 Result32).addReg(ResultReg);
1586
1587 ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, X86::sub_16bit);
1588 } else if (DstVT != MVT::i8) {
1589 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
1590 ResultReg);
1591 if (!ResultReg)
1592 return false;
1593 }
1594
1595 updateValueMap(I, ResultReg);
1596 return true;
1597}
1598
1599bool X86FastISel::X86SelectSExt(const Instruction *I) {
1600 EVT DstVT = TLI.getValueType(DL, I->getType());
1601 if (!TLI.isTypeLegal(DstVT))
1602 return false;
1603
1604 Register ResultReg = getRegForValue(I->getOperand(0));
1605 if (!ResultReg)
1606 return false;
1607
1608 // Handle sign-extension from i1 to i8.
1609 MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
1610 if (SrcVT == MVT::i1) {
1611 // Set the high bits to zero.
1612 Register ZExtReg = fastEmitZExtFromI1(MVT::i8, ResultReg);
1613 if (!ZExtReg)
1614 return false;
1615
1616 // Negate the result to make an 8-bit sign extended value.
1617 ResultReg = createResultReg(&X86::GR8RegClass);
1618 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::NEG8r),
1619 ResultReg).addReg(ZExtReg);
1620
1621 SrcVT = MVT::i8;
1622 }
1623
1624 if (DstVT == MVT::i16) {
1625 // i8->i16 doesn't exist in the autogenerated isel table. Need to sign
1626 // extend to 32-bits and then extract down to 16-bits.
1627 Register Result32 = createResultReg(&X86::GR32RegClass);
1628 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOVSX32rr8),
1629 Result32).addReg(ResultReg);
1630
1631 ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, X86::sub_16bit);
1632 } else if (DstVT != MVT::i8) {
1633 ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::SIGN_EXTEND,
1634 ResultReg);
1635 if (!ResultReg)
1636 return false;
1637 }
1638
1639 updateValueMap(I, ResultReg);
1640 return true;
1641}
1642
1643bool X86FastISel::X86SelectBranch(const Instruction *I) {
1644 // Unconditional branches are selected by tablegen-generated code.
1645 // Handle a conditional branch.
1646 const BranchInst *BI = cast<BranchInst>(I);
1647 MachineBasicBlock *TrueMBB = FuncInfo.getMBB(BI->getSuccessor(0));
1648 MachineBasicBlock *FalseMBB = FuncInfo.getMBB(BI->getSuccessor(1));
1649
1650 // Fold the common case of a conditional branch with a comparison
1651 // in the same block (values defined on other blocks may not have
1652 // initialized registers).
1653 X86::CondCode CC;
1654 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1655 if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
1656 EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1657
1658 // Try to optimize or fold the cmp.
1659 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
1660 switch (Predicate) {
1661 default: break;
1662 case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, MIMD.getDL()); return true;
1663 case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, MIMD.getDL()); return true;
1664 }
1665
1666 const Value *CmpLHS = CI->getOperand(0);
1667 const Value *CmpRHS = CI->getOperand(1);
1668
1669 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
1670 // 0.0.
1671 // We don't have to materialize a zero constant for this case and can just
1672 // use %x again on the RHS.
1673 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
1674 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
1675 if (CmpRHSC && CmpRHSC->isNullValue())
1676 CmpRHS = CmpLHS;
1677 }
1678
1679 // Try to take advantage of fallthrough opportunities.
1680 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1681 std::swap(TrueMBB, FalseMBB);
1683 }
1684
1685 // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
1686 // code check. Instead two branch instructions are required to check all
1687 // the flags. First we change the predicate to a supported condition code,
1688 // which will be the first branch. Later one we will emit the second
1689 // branch.
1690 bool NeedExtraBranch = false;
1691 switch (Predicate) {
1692 default: break;
1693 case CmpInst::FCMP_OEQ:
1694 std::swap(TrueMBB, FalseMBB);
1695 [[fallthrough]];
1696 case CmpInst::FCMP_UNE:
1697 NeedExtraBranch = true;
1699 break;
1700 }
1701
1702 bool SwapArgs;
1703 std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
1704 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
1705
1706 if (SwapArgs)
1707 std::swap(CmpLHS, CmpRHS);
1708
1709 // Emit a compare of the LHS and RHS, setting the flags.
1710 if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
1711 return false;
1712
1713 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::JCC_1))
1714 .addMBB(TrueMBB).addImm(CC);
1715
1716 // X86 requires a second branch to handle UNE (and OEQ, which is mapped
1717 // to UNE above).
1718 if (NeedExtraBranch) {
1719 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::JCC_1))
1720 .addMBB(TrueMBB).addImm(X86::COND_P);
1721 }
1722
1723 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1724 return true;
1725 }
1726 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1727 // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
1728 // typically happen for _Bool and C++ bools.
1729 MVT SourceVT;
1730 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1731 isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
1732 unsigned TestOpc = 0;
1733 switch (SourceVT.SimpleTy) {
1734 default: break;
1735 case MVT::i8: TestOpc = X86::TEST8ri; break;
1736 case MVT::i16: TestOpc = X86::TEST16ri; break;
1737 case MVT::i32: TestOpc = X86::TEST32ri; break;
1738 case MVT::i64: TestOpc = X86::TEST64ri32; break;
1739 }
1740 if (TestOpc) {
1741 Register OpReg = getRegForValue(TI->getOperand(0));
1742 if (!OpReg)
1743 return false;
1744
1745 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TestOpc))
1746 .addReg(OpReg).addImm(1);
1747
1748 unsigned JmpCond = X86::COND_NE;
1749 if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
1750 std::swap(TrueMBB, FalseMBB);
1751 JmpCond = X86::COND_E;
1752 }
1753
1754 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::JCC_1))
1755 .addMBB(TrueMBB).addImm(JmpCond);
1756
1757 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1758 return true;
1759 }
1760 }
1761 } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
1762 // Fake request the condition, otherwise the intrinsic might be completely
1763 // optimized away.
1764 Register TmpReg = getRegForValue(BI->getCondition());
1765 if (!TmpReg)
1766 return false;
1767
1768 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::JCC_1))
1769 .addMBB(TrueMBB).addImm(CC);
1770 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1771 return true;
1772 }
1773
1774 // Otherwise do a clumsy setcc and re-test it.
1775 // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
1776 // in an explicit cast, so make sure to handle that correctly.
1777 Register OpReg = getRegForValue(BI->getCondition());
1778 if (!OpReg)
1779 return false;
1780
1781 // In case OpReg is a K register, COPY to a GPR
1782 if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) {
1783 Register KOpReg = OpReg;
1784 OpReg = createResultReg(&X86::GR32RegClass);
1785 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1786 TII.get(TargetOpcode::COPY), OpReg)
1787 .addReg(KOpReg);
1788 OpReg = fastEmitInst_extractsubreg(MVT::i8, OpReg, X86::sub_8bit);
1789 }
1790 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::TEST8ri))
1791 .addReg(OpReg)
1792 .addImm(1);
1793 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::JCC_1))
1794 .addMBB(TrueMBB).addImm(X86::COND_NE);
1795 finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
1796 return true;
1797}
1798
1799bool X86FastISel::X86SelectShift(const Instruction *I) {
1800 Register CReg;
1801 unsigned OpReg;
1802 const TargetRegisterClass *RC = nullptr;
1803 if (I->getType()->isIntegerTy(8)) {
1804 CReg = X86::CL;
1805 RC = &X86::GR8RegClass;
1806 switch (I->getOpcode()) {
1807 case Instruction::LShr: OpReg = X86::SHR8rCL; break;
1808 case Instruction::AShr: OpReg = X86::SAR8rCL; break;
1809 case Instruction::Shl: OpReg = X86::SHL8rCL; break;
1810 default: return false;
1811 }
1812 } else if (I->getType()->isIntegerTy(16)) {
1813 CReg = X86::CX;
1814 RC = &X86::GR16RegClass;
1815 switch (I->getOpcode()) {
1816 default: llvm_unreachable("Unexpected shift opcode");
1817 case Instruction::LShr: OpReg = X86::SHR16rCL; break;
1818 case Instruction::AShr: OpReg = X86::SAR16rCL; break;
1819 case Instruction::Shl: OpReg = X86::SHL16rCL; break;
1820 }
1821 } else if (I->getType()->isIntegerTy(32)) {
1822 CReg = X86::ECX;
1823 RC = &X86::GR32RegClass;
1824 switch (I->getOpcode()) {
1825 default: llvm_unreachable("Unexpected shift opcode");
1826 case Instruction::LShr: OpReg = X86::SHR32rCL; break;
1827 case Instruction::AShr: OpReg = X86::SAR32rCL; break;
1828 case Instruction::Shl: OpReg = X86::SHL32rCL; break;
1829 }
1830 } else if (I->getType()->isIntegerTy(64)) {
1831 CReg = X86::RCX;
1832 RC = &X86::GR64RegClass;
1833 switch (I->getOpcode()) {
1834 default: llvm_unreachable("Unexpected shift opcode");
1835 case Instruction::LShr: OpReg = X86::SHR64rCL; break;
1836 case Instruction::AShr: OpReg = X86::SAR64rCL; break;
1837 case Instruction::Shl: OpReg = X86::SHL64rCL; break;
1838 }
1839 } else {
1840 return false;
1841 }
1842
1843 MVT VT;
1844 if (!isTypeLegal(I->getType(), VT))
1845 return false;
1846
1847 Register Op0Reg = getRegForValue(I->getOperand(0));
1848 if (!Op0Reg)
1849 return false;
1850
1851 Register Op1Reg = getRegForValue(I->getOperand(1));
1852 if (!Op1Reg)
1853 return false;
1854 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
1855 CReg).addReg(Op1Reg);
1856
1857 // The shift instruction uses X86::CL. If we defined a super-register
1858 // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
1859 if (CReg != X86::CL)
1860 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1861 TII.get(TargetOpcode::KILL), X86::CL)
1862 .addReg(CReg, RegState::Kill);
1863
1864 Register ResultReg = createResultReg(RC);
1865 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(OpReg), ResultReg)
1866 .addReg(Op0Reg);
1867 updateValueMap(I, ResultReg);
1868 return true;
1869}
1870
1871bool X86FastISel::X86SelectDivRem(const Instruction *I) {
1872 const static unsigned NumTypes = 4; // i8, i16, i32, i64
1873 const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
1874 const static bool S = true; // IsSigned
1875 const static bool U = false; // !IsSigned
1876 const static unsigned Copy = TargetOpcode::COPY;
1877 // For the X86 DIV/IDIV instruction, in most cases the dividend
1878 // (numerator) must be in a specific register pair highreg:lowreg,
1879 // producing the quotient in lowreg and the remainder in highreg.
1880 // For most data types, to set up the instruction, the dividend is
1881 // copied into lowreg, and lowreg is sign-extended or zero-extended
1882 // into highreg. The exception is i8, where the dividend is defined
1883 // as a single register rather than a register pair, and we
1884 // therefore directly sign-extend or zero-extend the dividend into
1885 // lowreg, instead of copying, and ignore the highreg.
1886 const static struct DivRemEntry {
1887 // The following portion depends only on the data type.
1888 const TargetRegisterClass *RC;
1889 unsigned LowInReg; // low part of the register pair
1890 unsigned HighInReg; // high part of the register pair
1891 // The following portion depends on both the data type and the operation.
1892 struct DivRemResult {
1893 unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
1894 unsigned OpSignExtend; // Opcode for sign-extending lowreg into
1895 // highreg, or copying a zero into highreg.
1896 unsigned OpCopy; // Opcode for copying dividend into lowreg, or
1897 // zero/sign-extending into lowreg for i8.
1898 unsigned DivRemResultReg; // Register containing the desired result.
1899 bool IsOpSigned; // Whether to use signed or unsigned form.
1900 } ResultTable[NumOps];
1901 } OpTable[NumTypes] = {
1902 { &X86::GR8RegClass, X86::AX, 0, {
1903 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
1904 { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
1905 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
1906 { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
1907 }
1908 }, // i8
1909 { &X86::GR16RegClass, X86::AX, X86::DX, {
1910 { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
1911 { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
1912 { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
1913 { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
1914 }
1915 }, // i16
1916 { &X86::GR32RegClass, X86::EAX, X86::EDX, {
1917 { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
1918 { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
1919 { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
1920 { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
1921 }
1922 }, // i32
1923 { &X86::GR64RegClass, X86::RAX, X86::RDX, {
1924 { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
1925 { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
1926 { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
1927 { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
1928 }
1929 }, // i64
1930 };
1931
1932 MVT VT;
1933 if (!isTypeLegal(I->getType(), VT))
1934 return false;
1935
1936 unsigned TypeIndex, OpIndex;
1937 switch (VT.SimpleTy) {
1938 default: return false;
1939 case MVT::i8: TypeIndex = 0; break;
1940 case MVT::i16: TypeIndex = 1; break;
1941 case MVT::i32: TypeIndex = 2; break;
1942 case MVT::i64: TypeIndex = 3;
1943 if (!Subtarget->is64Bit())
1944 return false;
1945 break;
1946 }
1947
1948 switch (I->getOpcode()) {
1949 default: llvm_unreachable("Unexpected div/rem opcode");
1950 case Instruction::SDiv: OpIndex = 0; break;
1951 case Instruction::SRem: OpIndex = 1; break;
1952 case Instruction::UDiv: OpIndex = 2; break;
1953 case Instruction::URem: OpIndex = 3; break;
1954 }
1955
1956 const DivRemEntry &TypeEntry = OpTable[TypeIndex];
1957 const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
1958 Register Op0Reg = getRegForValue(I->getOperand(0));
1959 if (!Op0Reg)
1960 return false;
1961 Register Op1Reg = getRegForValue(I->getOperand(1));
1962 if (!Op1Reg)
1963 return false;
1964
1965 // Move op0 into low-order input register.
1966 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1967 TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
1968 // Zero-extend or sign-extend into high-order input register.
1969 if (OpEntry.OpSignExtend) {
1970 if (OpEntry.IsOpSigned)
1971 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1972 TII.get(OpEntry.OpSignExtend));
1973 else {
1974 Register Zero32 = createResultReg(&X86::GR32RegClass);
1975 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1976 TII.get(X86::MOV32r0), Zero32);
1977
1978 // Copy the zero into the appropriate sub/super/identical physical
1979 // register. Unfortunately the operations needed are not uniform enough
1980 // to fit neatly into the table above.
1981 if (VT == MVT::i16) {
1982 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1983 TII.get(Copy), TypeEntry.HighInReg)
1984 .addReg(Zero32, 0, X86::sub_16bit);
1985 } else if (VT == MVT::i32) {
1986 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1987 TII.get(Copy), TypeEntry.HighInReg)
1988 .addReg(Zero32);
1989 } else if (VT == MVT::i64) {
1990 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1991 TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
1992 .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
1993 }
1994 }
1995 }
1996 // Generate the DIV/IDIV instruction.
1997 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
1998 TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
1999 // For i8 remainder, we can't reference ah directly, as we'll end
2000 // up with bogus copies like %r9b = COPY %ah. Reference ax
2001 // instead to prevent ah references in a rex instruction.
2002 //
2003 // The current assumption of the fast register allocator is that isel
2004 // won't generate explicit references to the GR8_NOREX registers. If
2005 // the allocator and/or the backend get enhanced to be more robust in
2006 // that regard, this can be, and should be, removed.
2007 Register ResultReg;
2008 if ((I->getOpcode() == Instruction::SRem ||
2009 I->getOpcode() == Instruction::URem) &&
2010 OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
2011 Register SourceSuperReg = createResultReg(&X86::GR16RegClass);
2012 Register ResultSuperReg = createResultReg(&X86::GR16RegClass);
2013 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2014 TII.get(Copy), SourceSuperReg).addReg(X86::AX);
2015
2016 // Shift AX right by 8 bits instead of using AH.
2017 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::SHR16ri),
2018 ResultSuperReg).addReg(SourceSuperReg).addImm(8);
2019
2020 // Now reference the 8-bit subreg of the result.
2021 ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
2022 X86::sub_8bit);
2023 }
2024 // Copy the result out of the physreg if we haven't already.
2025 if (!ResultReg) {
2026 ResultReg = createResultReg(TypeEntry.RC);
2027 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Copy), ResultReg)
2028 .addReg(OpEntry.DivRemResultReg);
2029 }
2030 updateValueMap(I, ResultReg);
2031
2032 return true;
2033}
2034
2035/// Emit a conditional move instruction (if the are supported) to lower
2036/// the select.
2037bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
2038 // Check if the subtarget supports these instructions.
2039 if (!Subtarget->canUseCMOV())
2040 return false;
2041
2042 // FIXME: Add support for i8.
2043 if (RetVT < MVT::i16 || RetVT > MVT::i64)
2044 return false;
2045
2046 const Value *Cond = I->getOperand(0);
2047 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2048 bool NeedTest = true;
2050
2051 // Optimize conditions coming from a compare if both instructions are in the
2052 // same basic block (values defined in other basic blocks may not have
2053 // initialized registers).
2054 const auto *CI = dyn_cast<CmpInst>(Cond);
2055 if (CI && (CI->getParent() == I->getParent())) {
2056 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2057
2058 // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
2059 static const uint16_t SETFOpcTable[2][3] = {
2060 { X86::COND_NP, X86::COND_E, X86::TEST8rr },
2061 { X86::COND_P, X86::COND_NE, X86::OR8rr }
2062 };
2063 const uint16_t *SETFOpc = nullptr;
2064 switch (Predicate) {
2065 default: break;
2066 case CmpInst::FCMP_OEQ:
2067 SETFOpc = &SETFOpcTable[0][0];
2069 break;
2070 case CmpInst::FCMP_UNE:
2071 SETFOpc = &SETFOpcTable[1][0];
2073 break;
2074 }
2075
2076 bool NeedSwap;
2077 std::tie(CC, NeedSwap) = X86::getX86ConditionCode(Predicate);
2078 assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
2079
2080 const Value *CmpLHS = CI->getOperand(0);
2081 const Value *CmpRHS = CI->getOperand(1);
2082 if (NeedSwap)
2083 std::swap(CmpLHS, CmpRHS);
2084
2085 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2086 // Emit a compare of the LHS and RHS, setting the flags.
2087 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2088 return false;
2089
2090 if (SETFOpc) {
2091 Register FlagReg1 = createResultReg(&X86::GR8RegClass);
2092 Register FlagReg2 = createResultReg(&X86::GR8RegClass);
2093 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(GET_SETCC),
2094 FlagReg1)
2095 .addImm(SETFOpc[0]);
2096 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(GET_SETCC),
2097 FlagReg2)
2098 .addImm(SETFOpc[1]);
2099 auto const &II = TII.get(SETFOpc[2]);
2100 if (II.getNumDefs()) {
2101 Register TmpReg = createResultReg(&X86::GR8RegClass);
2102 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, TmpReg)
2103 .addReg(FlagReg2).addReg(FlagReg1);
2104 } else {
2105 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
2106 .addReg(FlagReg2).addReg(FlagReg1);
2107 }
2108 }
2109 NeedTest = false;
2110 } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
2111 // Fake request the condition, otherwise the intrinsic might be completely
2112 // optimized away.
2113 Register TmpReg = getRegForValue(Cond);
2114 if (!TmpReg)
2115 return false;
2116
2117 NeedTest = false;
2118 }
2119
2120 if (NeedTest) {
2121 // Selects operate on i1, however, CondReg is 8 bits width and may contain
2122 // garbage. Indeed, only the less significant bit is supposed to be
2123 // accurate. If we read more than the lsb, we may see non-zero values
2124 // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
2125 // the select. This is achieved by performing TEST against 1.
2126 Register CondReg = getRegForValue(Cond);
2127 if (!CondReg)
2128 return false;
2129
2130 // In case OpReg is a K register, COPY to a GPR
2131 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2132 Register KCondReg = CondReg;
2133 CondReg = createResultReg(&X86::GR32RegClass);
2134 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2135 TII.get(TargetOpcode::COPY), CondReg)
2136 .addReg(KCondReg);
2137 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, X86::sub_8bit);
2138 }
2139 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::TEST8ri))
2140 .addReg(CondReg)
2141 .addImm(1);
2142 }
2143
2144 const Value *LHS = I->getOperand(1);
2145 const Value *RHS = I->getOperand(2);
2146
2147 Register RHSReg = getRegForValue(RHS);
2148 Register LHSReg = getRegForValue(LHS);
2149 if (!LHSReg || !RHSReg)
2150 return false;
2151
2152 const TargetRegisterInfo &TRI = *Subtarget->getRegisterInfo();
2153 unsigned Opc = X86::getCMovOpcode(TRI.getRegSizeInBits(*RC) / 8, false,
2154 Subtarget->hasNDD());
2155 Register ResultReg = fastEmitInst_rri(Opc, RC, RHSReg, LHSReg, CC);
2156 updateValueMap(I, ResultReg);
2157 return true;
2158}
2159
2160/// Emit SSE or AVX instructions to lower the select.
2161///
2162/// Try to use SSE1/SSE2 instructions to simulate a select without branches.
2163/// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
2164/// SSE instructions are available. If AVX is available, try to use a VBLENDV.
2165bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
2166 // Optimize conditions coming from a compare if both instructions are in the
2167 // same basic block (values defined in other basic blocks may not have
2168 // initialized registers).
2169 const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
2170 if (!CI || (CI->getParent() != I->getParent()))
2171 return false;
2172
2173 if (I->getType() != CI->getOperand(0)->getType() ||
2174 !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
2175 (Subtarget->hasSSE2() && RetVT == MVT::f64)))
2176 return false;
2177
2178 const Value *CmpLHS = CI->getOperand(0);
2179 const Value *CmpRHS = CI->getOperand(1);
2180 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2181
2182 // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
2183 // We don't have to materialize a zero constant for this case and can just use
2184 // %x again on the RHS.
2185 if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
2186 const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
2187 if (CmpRHSC && CmpRHSC->isNullValue())
2188 CmpRHS = CmpLHS;
2189 }
2190
2191 unsigned CC;
2192 bool NeedSwap;
2193 std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
2194 if (CC > 7 && !Subtarget->hasAVX())
2195 return false;
2196
2197 if (NeedSwap)
2198 std::swap(CmpLHS, CmpRHS);
2199
2200 const Value *LHS = I->getOperand(1);
2201 const Value *RHS = I->getOperand(2);
2202
2203 Register LHSReg = getRegForValue(LHS);
2204 Register RHSReg = getRegForValue(RHS);
2205 Register CmpLHSReg = getRegForValue(CmpLHS);
2206 Register CmpRHSReg = getRegForValue(CmpRHS);
2207 if (!LHSReg || !RHSReg || !CmpLHSReg || !CmpRHSReg)
2208 return false;
2209
2210 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2211 Register ResultReg;
2212
2213 if (Subtarget->hasAVX512()) {
2214 // If we have AVX512 we can use a mask compare and masked movss/sd.
2215 const TargetRegisterClass *VR128X = &X86::VR128XRegClass;
2216 const TargetRegisterClass *VK1 = &X86::VK1RegClass;
2217
2218 unsigned CmpOpcode =
2219 (RetVT == MVT::f32) ? X86::VCMPSSZrri : X86::VCMPSDZrri;
2220 Register CmpReg = fastEmitInst_rri(CmpOpcode, VK1, CmpLHSReg, CmpRHSReg,
2221 CC);
2222
2223 // Need an IMPLICIT_DEF for the input that is used to generate the upper
2224 // bits of the result register since its not based on any of the inputs.
2225 Register ImplicitDefReg = createResultReg(VR128X);
2226 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2227 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2228
2229 // Place RHSReg is the passthru of the masked movss/sd operation and put
2230 // LHS in the input. The mask input comes from the compare.
2231 unsigned MovOpcode =
2232 (RetVT == MVT::f32) ? X86::VMOVSSZrrk : X86::VMOVSDZrrk;
2233 Register MovReg = fastEmitInst_rrrr(MovOpcode, VR128X, RHSReg, CmpReg,
2234 ImplicitDefReg, LHSReg);
2235
2236 ResultReg = createResultReg(RC);
2237 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2238 TII.get(TargetOpcode::COPY), ResultReg).addReg(MovReg);
2239
2240 } else if (Subtarget->hasAVX()) {
2241 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2242
2243 // If we have AVX, create 1 blendv instead of 3 logic instructions.
2244 // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
2245 // uses XMM0 as the selection register. That may need just as many
2246 // instructions as the AND/ANDN/OR sequence due to register moves, so
2247 // don't bother.
2248 unsigned CmpOpcode =
2249 (RetVT == MVT::f32) ? X86::VCMPSSrri : X86::VCMPSDrri;
2250 unsigned BlendOpcode =
2251 (RetVT == MVT::f32) ? X86::VBLENDVPSrrr : X86::VBLENDVPDrrr;
2252
2253 Register CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpRHSReg,
2254 CC);
2255 Register VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, LHSReg,
2256 CmpReg);
2257 ResultReg = createResultReg(RC);
2258 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2259 TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
2260 } else {
2261 // Choose the SSE instruction sequence based on data type (float or double).
2262 static const uint16_t OpcTable[2][4] = {
2263 { X86::CMPSSrri, X86::ANDPSrr, X86::ANDNPSrr, X86::ORPSrr },
2264 { X86::CMPSDrri, X86::ANDPDrr, X86::ANDNPDrr, X86::ORPDrr }
2265 };
2266
2267 const uint16_t *Opc = nullptr;
2268 switch (RetVT.SimpleTy) {
2269 default: return false;
2270 case MVT::f32: Opc = &OpcTable[0][0]; break;
2271 case MVT::f64: Opc = &OpcTable[1][0]; break;
2272 }
2273
2274 const TargetRegisterClass *VR128 = &X86::VR128RegClass;
2275 Register CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpRHSReg, CC);
2276 Register AndReg = fastEmitInst_rr(Opc[1], VR128, CmpReg, LHSReg);
2277 Register AndNReg = fastEmitInst_rr(Opc[2], VR128, CmpReg, RHSReg);
2278 Register OrReg = fastEmitInst_rr(Opc[3], VR128, AndNReg, AndReg);
2279 ResultReg = createResultReg(RC);
2280 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2281 TII.get(TargetOpcode::COPY), ResultReg).addReg(OrReg);
2282 }
2283 updateValueMap(I, ResultReg);
2284 return true;
2285}
2286
2287bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
2288 // These are pseudo CMOV instructions and will be later expanded into control-
2289 // flow.
2290 unsigned Opc;
2291 switch (RetVT.SimpleTy) {
2292 default: return false;
2293 case MVT::i8: Opc = X86::CMOV_GR8; break;
2294 case MVT::i16: Opc = X86::CMOV_GR16; break;
2295 case MVT::i32: Opc = X86::CMOV_GR32; break;
2296 case MVT::f16:
2297 Opc = Subtarget->hasAVX512() ? X86::CMOV_FR16X : X86::CMOV_FR16; break;
2298 case MVT::f32:
2299 Opc = Subtarget->hasAVX512() ? X86::CMOV_FR32X : X86::CMOV_FR32; break;
2300 case MVT::f64:
2301 Opc = Subtarget->hasAVX512() ? X86::CMOV_FR64X : X86::CMOV_FR64; break;
2302 }
2303
2304 const Value *Cond = I->getOperand(0);
2306
2307 // Optimize conditions coming from a compare if both instructions are in the
2308 // same basic block (values defined in other basic blocks may not have
2309 // initialized registers).
2310 const auto *CI = dyn_cast<CmpInst>(Cond);
2311 if (CI && (CI->getParent() == I->getParent())) {
2312 bool NeedSwap;
2313 std::tie(CC, NeedSwap) = X86::getX86ConditionCode(CI->getPredicate());
2314 if (CC > X86::LAST_VALID_COND)
2315 return false;
2316
2317 const Value *CmpLHS = CI->getOperand(0);
2318 const Value *CmpRHS = CI->getOperand(1);
2319
2320 if (NeedSwap)
2321 std::swap(CmpLHS, CmpRHS);
2322
2323 EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
2324 if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
2325 return false;
2326 } else {
2327 Register CondReg = getRegForValue(Cond);
2328 if (!CondReg)
2329 return false;
2330
2331 // In case OpReg is a K register, COPY to a GPR
2332 if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
2333 Register KCondReg = CondReg;
2334 CondReg = createResultReg(&X86::GR32RegClass);
2335 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2336 TII.get(TargetOpcode::COPY), CondReg)
2337 .addReg(KCondReg);
2338 CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, X86::sub_8bit);
2339 }
2340 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::TEST8ri))
2341 .addReg(CondReg)
2342 .addImm(1);
2343 }
2344
2345 const Value *LHS = I->getOperand(1);
2346 const Value *RHS = I->getOperand(2);
2347
2348 Register LHSReg = getRegForValue(LHS);
2349 Register RHSReg = getRegForValue(RHS);
2350 if (!LHSReg || !RHSReg)
2351 return false;
2352
2353 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2354
2355 Register ResultReg =
2356 fastEmitInst_rri(Opc, RC, RHSReg, LHSReg, CC);
2357 updateValueMap(I, ResultReg);
2358 return true;
2359}
2360
2361bool X86FastISel::X86SelectSelect(const Instruction *I) {
2362 MVT RetVT;
2363 if (!isTypeLegal(I->getType(), RetVT))
2364 return false;
2365
2366 // Check if we can fold the select.
2367 if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
2368 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2369 const Value *Opnd = nullptr;
2370 switch (Predicate) {
2371 default: break;
2372 case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
2373 case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
2374 }
2375 // No need for a select anymore - this is an unconditional move.
2376 if (Opnd) {
2377 Register OpReg = getRegForValue(Opnd);
2378 if (!OpReg)
2379 return false;
2380 const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
2381 Register ResultReg = createResultReg(RC);
2382 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2383 TII.get(TargetOpcode::COPY), ResultReg)
2384 .addReg(OpReg);
2385 updateValueMap(I, ResultReg);
2386 return true;
2387 }
2388 }
2389
2390 // First try to use real conditional move instructions.
2391 if (X86FastEmitCMoveSelect(RetVT, I))
2392 return true;
2393
2394 // Try to use a sequence of SSE instructions to simulate a conditional move.
2395 if (X86FastEmitSSESelect(RetVT, I))
2396 return true;
2397
2398 // Fall-back to pseudo conditional move instructions, which will be later
2399 // converted to control-flow.
2400 if (X86FastEmitPseudoSelect(RetVT, I))
2401 return true;
2402
2403 return false;
2404}
2405
2406// Common code for X86SelectSIToFP and X86SelectUIToFP.
2407bool X86FastISel::X86SelectIntToFP(const Instruction *I, bool IsSigned) {
2408 // The target-independent selection algorithm in FastISel already knows how
2409 // to select a SINT_TO_FP if the target is SSE but not AVX.
2410 // Early exit if the subtarget doesn't have AVX.
2411 // Unsigned conversion requires avx512.
2412 bool HasAVX512 = Subtarget->hasAVX512();
2413 if (!Subtarget->hasAVX() || (!IsSigned && !HasAVX512))
2414 return false;
2415
2416 // TODO: We could sign extend narrower types.
2417 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2418 if (SrcVT != MVT::i32 && SrcVT != MVT::i64)
2419 return false;
2420
2421 // Select integer to float/double conversion.
2422 Register OpReg = getRegForValue(I->getOperand(0));
2423 if (!OpReg)
2424 return false;
2425
2426 unsigned Opcode;
2427
2428 static const uint16_t SCvtOpc[2][2][2] = {
2429 { { X86::VCVTSI2SSrr, X86::VCVTSI642SSrr },
2430 { X86::VCVTSI2SDrr, X86::VCVTSI642SDrr } },
2431 { { X86::VCVTSI2SSZrr, X86::VCVTSI642SSZrr },
2432 { X86::VCVTSI2SDZrr, X86::VCVTSI642SDZrr } },
2433 };
2434 static const uint16_t UCvtOpc[2][2] = {
2435 { X86::VCVTUSI2SSZrr, X86::VCVTUSI642SSZrr },
2436 { X86::VCVTUSI2SDZrr, X86::VCVTUSI642SDZrr },
2437 };
2438 bool Is64Bit = SrcVT == MVT::i64;
2439
2440 if (I->getType()->isDoubleTy()) {
2441 // s/uitofp int -> double
2442 Opcode = IsSigned ? SCvtOpc[HasAVX512][1][Is64Bit] : UCvtOpc[1][Is64Bit];
2443 } else if (I->getType()->isFloatTy()) {
2444 // s/uitofp int -> float
2445 Opcode = IsSigned ? SCvtOpc[HasAVX512][0][Is64Bit] : UCvtOpc[0][Is64Bit];
2446 } else
2447 return false;
2448
2449 MVT DstVT = TLI.getValueType(DL, I->getType()).getSimpleVT();
2450 const TargetRegisterClass *RC = TLI.getRegClassFor(DstVT);
2451 Register ImplicitDefReg = createResultReg(RC);
2452 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2453 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2454 Register ResultReg = fastEmitInst_rr(Opcode, RC, ImplicitDefReg, OpReg);
2455 updateValueMap(I, ResultReg);
2456 return true;
2457}
2458
2459bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
2460 return X86SelectIntToFP(I, /*IsSigned*/true);
2461}
2462
2463bool X86FastISel::X86SelectUIToFP(const Instruction *I) {
2464 return X86SelectIntToFP(I, /*IsSigned*/false);
2465}
2466
2467// Helper method used by X86SelectFPExt and X86SelectFPTrunc.
2468bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
2469 unsigned TargetOpc,
2470 const TargetRegisterClass *RC) {
2471 assert((I->getOpcode() == Instruction::FPExt ||
2472 I->getOpcode() == Instruction::FPTrunc) &&
2473 "Instruction must be an FPExt or FPTrunc!");
2474 bool HasAVX = Subtarget->hasAVX();
2475
2476 Register OpReg = getRegForValue(I->getOperand(0));
2477 if (!OpReg)
2478 return false;
2479
2480 Register ImplicitDefReg;
2481 if (HasAVX) {
2482 ImplicitDefReg = createResultReg(RC);
2483 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2484 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2485
2486 }
2487
2488 Register ResultReg = createResultReg(RC);
2489 MachineInstrBuilder MIB;
2490 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpc),
2491 ResultReg);
2492
2493 if (HasAVX)
2494 MIB.addReg(ImplicitDefReg);
2495
2496 MIB.addReg(OpReg);
2497 updateValueMap(I, ResultReg);
2498 return true;
2499}
2500
2501bool X86FastISel::X86SelectFPExt(const Instruction *I) {
2502 if (Subtarget->hasSSE2() && I->getType()->isDoubleTy() &&
2503 I->getOperand(0)->getType()->isFloatTy()) {
2504 bool HasAVX512 = Subtarget->hasAVX512();
2505 // fpext from float to double.
2506 unsigned Opc =
2507 HasAVX512 ? X86::VCVTSS2SDZrr
2508 : Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
2509 return X86SelectFPExtOrFPTrunc(I, Opc, TLI.getRegClassFor(MVT::f64));
2510 }
2511
2512 return false;
2513}
2514
2515bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
2516 if (Subtarget->hasSSE2() && I->getType()->isFloatTy() &&
2517 I->getOperand(0)->getType()->isDoubleTy()) {
2518 bool HasAVX512 = Subtarget->hasAVX512();
2519 // fptrunc from double to float.
2520 unsigned Opc =
2521 HasAVX512 ? X86::VCVTSD2SSZrr
2522 : Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
2523 return X86SelectFPExtOrFPTrunc(I, Opc, TLI.getRegClassFor(MVT::f32));
2524 }
2525
2526 return false;
2527}
2528
2529bool X86FastISel::X86SelectTrunc(const Instruction *I) {
2530 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
2531 EVT DstVT = TLI.getValueType(DL, I->getType());
2532
2533 // This code only handles truncation to byte.
2534 if (DstVT != MVT::i8 && DstVT != MVT::i1)
2535 return false;
2536 if (!TLI.isTypeLegal(SrcVT))
2537 return false;
2538
2539 Register InputReg = getRegForValue(I->getOperand(0));
2540 if (!InputReg)
2541 // Unhandled operand. Halt "fast" selection and bail.
2542 return false;
2543
2544 if (SrcVT == MVT::i8) {
2545 // Truncate from i8 to i1; no code needed.
2546 updateValueMap(I, InputReg);
2547 return true;
2548 }
2549
2550 // Issue an extract_subreg.
2551 Register ResultReg = fastEmitInst_extractsubreg(MVT::i8, InputReg,
2552 X86::sub_8bit);
2553 if (!ResultReg)
2554 return false;
2555
2556 updateValueMap(I, ResultReg);
2557 return true;
2558}
2559
2560bool X86FastISel::X86SelectBitCast(const Instruction *I) {
2561 // Select SSE2/AVX bitcasts between 128/256/512 bit vector types.
2562 MVT SrcVT, DstVT;
2563 if (!Subtarget->hasSSE2() ||
2564 !isTypeLegal(I->getOperand(0)->getType(), SrcVT) ||
2565 !isTypeLegal(I->getType(), DstVT))
2566 return false;
2567
2568 // Only allow vectors that use xmm/ymm/zmm.
2569 if (!SrcVT.isVector() || !DstVT.isVector() ||
2570 SrcVT.getVectorElementType() == MVT::i1 ||
2571 DstVT.getVectorElementType() == MVT::i1)
2572 return false;
2573
2574 Register Reg = getRegForValue(I->getOperand(0));
2575 if (!Reg)
2576 return false;
2577
2578 // Emit a reg-reg copy so we don't propagate cached known bits information
2579 // with the wrong VT if we fall out of fast isel after selecting this.
2580 const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
2581 Register ResultReg = createResultReg(DstClass);
2582 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
2583 ResultReg)
2584 .addReg(Reg);
2585
2586 updateValueMap(I, ResultReg);
2587 return true;
2588}
2589
2590bool X86FastISel::IsMemcpySmall(uint64_t Len) {
2591 return Len <= (Subtarget->is64Bit() ? 32 : 16);
2592}
2593
2594bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
2595 X86AddressMode SrcAM, uint64_t Len) {
2596
2597 // Make sure we don't bloat code by inlining very large memcpy's.
2598 if (!IsMemcpySmall(Len))
2599 return false;
2600
2601 bool i64Legal = Subtarget->is64Bit();
2602
2603 // We don't care about alignment here since we just emit integer accesses.
2604 while (Len) {
2605 MVT VT;
2606 if (Len >= 8 && i64Legal)
2607 VT = MVT::i64;
2608 else if (Len >= 4)
2609 VT = MVT::i32;
2610 else if (Len >= 2)
2611 VT = MVT::i16;
2612 else
2613 VT = MVT::i8;
2614
2615 Register Reg;
2616 bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
2617 RV &= X86FastEmitStore(VT, Reg, DestAM);
2618 assert(RV && "Failed to emit load or store??");
2619 (void)RV;
2620
2621 unsigned Size = VT.getSizeInBits()/8;
2622 Len -= Size;
2623 DestAM.Disp += Size;
2624 SrcAM.Disp += Size;
2625 }
2626
2627 return true;
2628}
2629
2630bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
2631 // FIXME: Handle more intrinsics.
2632 switch (II->getIntrinsicID()) {
2633 default: return false;
2634 case Intrinsic::convert_from_fp16:
2635 case Intrinsic::convert_to_fp16: {
2636 if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
2637 return false;
2638
2639 const Value *Op = II->getArgOperand(0);
2640 Register InputReg = getRegForValue(Op);
2641 if (!InputReg)
2642 return false;
2643
2644 // F16C only allows converting from float to half and from half to float.
2645 bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
2646 if (IsFloatToHalf) {
2647 if (!Op->getType()->isFloatTy())
2648 return false;
2649 } else {
2650 if (!II->getType()->isFloatTy())
2651 return false;
2652 }
2653
2654 Register ResultReg;
2655 const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
2656 if (IsFloatToHalf) {
2657 // 'InputReg' is implicitly promoted from register class FR32 to
2658 // register class VR128 by method 'constrainOperandRegClass' which is
2659 // directly called by 'fastEmitInst_ri'.
2660 // Instruction VCVTPS2PHrr takes an extra immediate operand which is
2661 // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
2662 // It's consistent with the other FP instructions, which are usually
2663 // controlled by MXCSR.
2664 unsigned Opc = Subtarget->hasVLX() ? X86::VCVTPS2PHZ128rr
2665 : X86::VCVTPS2PHrr;
2666 InputReg = fastEmitInst_ri(Opc, RC, InputReg, 4);
2667
2668 // Move the lower 32-bits of ResultReg to another register of class GR32.
2669 Opc = Subtarget->hasAVX512() ? X86::VMOVPDI2DIZrr
2670 : X86::VMOVPDI2DIrr;
2671 ResultReg = createResultReg(&X86::GR32RegClass);
2672 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), ResultReg)
2673 .addReg(InputReg, RegState::Kill);
2674
2675 // The result value is in the lower 16-bits of ResultReg.
2676 unsigned RegIdx = X86::sub_16bit;
2677 ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, RegIdx);
2678 } else {
2679 assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
2680 // Explicitly zero-extend the input to 32-bit.
2681 InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::ZERO_EXTEND, InputReg);
2682
2683 // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
2684 InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
2685 InputReg);
2686
2687 unsigned Opc = Subtarget->hasVLX() ? X86::VCVTPH2PSZ128rr
2688 : X86::VCVTPH2PSrr;
2689 InputReg = fastEmitInst_r(Opc, RC, InputReg);
2690
2691 // The result value is in the lower 32-bits of ResultReg.
2692 // Emit an explicit copy from register class VR128 to register class FR32.
2693 ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
2694 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2695 TII.get(TargetOpcode::COPY), ResultReg)
2696 .addReg(InputReg, RegState::Kill);
2697 }
2698
2699 updateValueMap(II, ResultReg);
2700 return true;
2701 }
2702 case Intrinsic::frameaddress: {
2703 MachineFunction *MF = FuncInfo.MF;
2704 if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
2705 return false;
2706
2707 Type *RetTy = II->getCalledFunction()->getReturnType();
2708
2709 MVT VT;
2710 if (!isTypeLegal(RetTy, VT))
2711 return false;
2712
2713 unsigned Opc;
2714 const TargetRegisterClass *RC = nullptr;
2715
2716 switch (VT.SimpleTy) {
2717 default: llvm_unreachable("Invalid result type for frameaddress.");
2718 case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
2719 case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
2720 }
2721
2722 // This needs to be set before we call getPtrSizedFrameRegister, otherwise
2723 // we get the wrong frame register.
2724 MachineFrameInfo &MFI = MF->getFrameInfo();
2725 MFI.setFrameAddressIsTaken(true);
2726
2727 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2728 Register FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
2729 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
2730 (FrameReg == X86::EBP && VT == MVT::i32)) &&
2731 "Invalid Frame Register!");
2732
2733 // Always make a copy of the frame register to a vreg first, so that we
2734 // never directly reference the frame register (the TwoAddressInstruction-
2735 // Pass doesn't like that).
2736 Register SrcReg = createResultReg(RC);
2737 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2738 TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
2739
2740 // Now recursively load from the frame address.
2741 // movq (%rbp), %rax
2742 // movq (%rax), %rax
2743 // movq (%rax), %rax
2744 // ...
2745 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
2746 while (Depth--) {
2747 Register DestReg = createResultReg(RC);
2748 addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2749 TII.get(Opc), DestReg), SrcReg);
2750 SrcReg = DestReg;
2751 }
2752
2753 updateValueMap(II, SrcReg);
2754 return true;
2755 }
2756 case Intrinsic::memcpy: {
2757 const MemCpyInst *MCI = cast<MemCpyInst>(II);
2758 // Don't handle volatile or variable length memcpys.
2759 if (MCI->isVolatile())
2760 return false;
2761
2762 if (isa<ConstantInt>(MCI->getLength())) {
2763 // Small memcpy's are common enough that we want to do them
2764 // without a call if possible.
2765 uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
2766 if (IsMemcpySmall(Len)) {
2767 X86AddressMode DestAM, SrcAM;
2768 if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
2769 !X86SelectAddress(MCI->getRawSource(), SrcAM))
2770 return false;
2771 TryEmitSmallMemcpy(DestAM, SrcAM, Len);
2772 return true;
2773 }
2774 }
2775
2776 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2777 if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
2778 return false;
2779
2780 if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
2781 return false;
2782
2783 return lowerCallTo(II, "memcpy", II->arg_size() - 1);
2784 }
2785 case Intrinsic::memset: {
2786 const MemSetInst *MSI = cast<MemSetInst>(II);
2787
2788 if (MSI->isVolatile())
2789 return false;
2790
2791 unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
2792 if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
2793 return false;
2794
2795 if (MSI->getDestAddressSpace() > 255)
2796 return false;
2797
2798 return lowerCallTo(II, "memset", II->arg_size() - 1);
2799 }
2800 case Intrinsic::stackprotector: {
2801 // Emit code to store the stack guard onto the stack.
2802 EVT PtrTy = TLI.getPointerTy(DL);
2803
2804 const Value *Op1 = II->getArgOperand(0); // The guard's value.
2805 const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
2806
2807 MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
2808
2809 // Grab the frame index.
2810 X86AddressMode AM;
2811 if (!X86SelectAddress(Slot, AM)) return false;
2812 if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
2813 return true;
2814 }
2815 case Intrinsic::dbg_declare: {
2816 const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
2817 X86AddressMode AM;
2818 assert(DI->getAddress() && "Null address should be checked earlier!");
2819 if (!X86SelectAddress(DI->getAddress(), AM))
2820 return false;
2821 const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
2822 assert(DI->getVariable()->isValidLocationForIntrinsic(MIMD.getDL()) &&
2823 "Expected inlined-at fields to agree");
2824 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II), AM)
2825 .addImm(0)
2826 .addMetadata(DI->getVariable())
2827 .addMetadata(DI->getExpression());
2828 return true;
2829 }
2830 case Intrinsic::trap: {
2831 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::TRAP));
2832 return true;
2833 }
2834 case Intrinsic::sqrt: {
2835 if (!Subtarget->hasSSE1())
2836 return false;
2837
2838 Type *RetTy = II->getCalledFunction()->getReturnType();
2839
2840 MVT VT;
2841 if (!isTypeLegal(RetTy, VT))
2842 return false;
2843
2844 // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
2845 // is not generated by FastISel yet.
2846 // FIXME: Update this code once tablegen can handle it.
2847 static const uint16_t SqrtOpc[3][2] = {
2848 { X86::SQRTSSr, X86::SQRTSDr },
2849 { X86::VSQRTSSr, X86::VSQRTSDr },
2850 { X86::VSQRTSSZr, X86::VSQRTSDZr },
2851 };
2852 unsigned AVXLevel = Subtarget->hasAVX512() ? 2 :
2853 Subtarget->hasAVX() ? 1 :
2854 0;
2855 unsigned Opc;
2856 switch (VT.SimpleTy) {
2857 default: return false;
2858 case MVT::f32: Opc = SqrtOpc[AVXLevel][0]; break;
2859 case MVT::f64: Opc = SqrtOpc[AVXLevel][1]; break;
2860 }
2861
2862 const Value *SrcVal = II->getArgOperand(0);
2863 Register SrcReg = getRegForValue(SrcVal);
2864
2865 if (!SrcReg)
2866 return false;
2867
2868 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
2869 Register ImplicitDefReg;
2870 if (AVXLevel > 0) {
2871 ImplicitDefReg = createResultReg(RC);
2872 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2873 TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
2874 }
2875
2876 Register ResultReg = createResultReg(RC);
2877 MachineInstrBuilder MIB;
2878 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc),
2879 ResultReg);
2880
2881 if (ImplicitDefReg)
2882 MIB.addReg(ImplicitDefReg);
2883
2884 MIB.addReg(SrcReg);
2885
2886 updateValueMap(II, ResultReg);
2887 return true;
2888 }
2889 case Intrinsic::sadd_with_overflow:
2890 case Intrinsic::uadd_with_overflow:
2891 case Intrinsic::ssub_with_overflow:
2892 case Intrinsic::usub_with_overflow:
2893 case Intrinsic::smul_with_overflow:
2894 case Intrinsic::umul_with_overflow: {
2895 // This implements the basic lowering of the xalu with overflow intrinsics
2896 // into add/sub/mul followed by either seto or setb.
2897 const Function *Callee = II->getCalledFunction();
2898 auto *Ty = cast<StructType>(Callee->getReturnType());
2899 Type *RetTy = Ty->getTypeAtIndex(0U);
2900 assert(Ty->getTypeAtIndex(1)->isIntegerTy() &&
2901 Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 &&
2902 "Overflow value expected to be an i1");
2903
2904 MVT VT;
2905 if (!isTypeLegal(RetTy, VT))
2906 return false;
2907
2908 if (VT < MVT::i8 || VT > MVT::i64)
2909 return false;
2910
2911 const Value *LHS = II->getArgOperand(0);
2912 const Value *RHS = II->getArgOperand(1);
2913
2914 // Canonicalize immediate to the RHS.
2915 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) && II->isCommutative())
2916 std::swap(LHS, RHS);
2917
2918 unsigned BaseOpc, CondCode;
2919 switch (II->getIntrinsicID()) {
2920 default: llvm_unreachable("Unexpected intrinsic!");
2921 case Intrinsic::sadd_with_overflow:
2922 BaseOpc = ISD::ADD; CondCode = X86::COND_O; break;
2923 case Intrinsic::uadd_with_overflow:
2924 BaseOpc = ISD::ADD; CondCode = X86::COND_B; break;
2925 case Intrinsic::ssub_with_overflow:
2926 BaseOpc = ISD::SUB; CondCode = X86::COND_O; break;
2927 case Intrinsic::usub_with_overflow:
2928 BaseOpc = ISD::SUB; CondCode = X86::COND_B; break;
2929 case Intrinsic::smul_with_overflow:
2930 BaseOpc = X86ISD::SMUL; CondCode = X86::COND_O; break;
2931 case Intrinsic::umul_with_overflow:
2932 BaseOpc = X86ISD::UMUL; CondCode = X86::COND_O; break;
2933 }
2934
2935 Register LHSReg = getRegForValue(LHS);
2936 if (!LHSReg)
2937 return false;
2938
2939 Register ResultReg;
2940 // Check if we have an immediate version.
2941 if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
2942 static const uint16_t Opc[2][4] = {
2943 { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
2944 { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
2945 };
2946
2947 if (CI->isOne() && (BaseOpc == ISD::ADD || BaseOpc == ISD::SUB) &&
2948 CondCode == X86::COND_O) {
2949 // We can use INC/DEC.
2950 ResultReg = createResultReg(TLI.getRegClassFor(VT));
2951 bool IsDec = BaseOpc == ISD::SUB;
2952 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2953 TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
2954 .addReg(LHSReg);
2955 } else
2956 ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, CI->getZExtValue());
2957 }
2958
2959 Register RHSReg;
2960 if (!ResultReg) {
2961 RHSReg = getRegForValue(RHS);
2962 if (!RHSReg)
2963 return false;
2964 ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, RHSReg);
2965 }
2966
2967 // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
2968 // it manually.
2969 if (BaseOpc == X86ISD::UMUL && !ResultReg) {
2970 static const uint16_t MULOpc[] =
2971 { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
2972 static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
2973 // First copy the first operand into RAX, which is an implicit input to
2974 // the X86::MUL*r instruction.
2975 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2976 TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
2977 .addReg(LHSReg);
2978 ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
2979 TLI.getRegClassFor(VT), RHSReg);
2980 } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
2981 static const uint16_t MULOpc[] =
2982 { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
2983 if (VT == MVT::i8) {
2984 // Copy the first operand into AL, which is an implicit input to the
2985 // X86::IMUL8r instruction.
2986 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
2987 TII.get(TargetOpcode::COPY), X86::AL)
2988 .addReg(LHSReg);
2989 ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg);
2990 } else
2991 ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
2992 TLI.getRegClassFor(VT), LHSReg, RHSReg);
2993 }
2994
2995 if (!ResultReg)
2996 return false;
2997
2998 // Assign to a GPR since the overflow return value is lowered to a SETcc.
2999 Register ResultReg2 = createResultReg(&X86::GR8RegClass);
3000 assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
3001 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(GET_SETCC),
3002 ResultReg2)
3003 .addImm(CondCode);
3004
3005 updateValueMap(II, ResultReg, 2);
3006 return true;
3007 }
3008 case Intrinsic::x86_sse_cvttss2si:
3009 case Intrinsic::x86_sse_cvttss2si64:
3010 case Intrinsic::x86_sse2_cvttsd2si:
3011 case Intrinsic::x86_sse2_cvttsd2si64: {
3012 bool IsInputDouble;
3013 switch (II->getIntrinsicID()) {
3014 default: llvm_unreachable("Unexpected intrinsic.");
3015 case Intrinsic::x86_sse_cvttss2si:
3016 case Intrinsic::x86_sse_cvttss2si64:
3017 if (!Subtarget->hasSSE1())
3018 return false;
3019 IsInputDouble = false;
3020 break;
3021 case Intrinsic::x86_sse2_cvttsd2si:
3022 case Intrinsic::x86_sse2_cvttsd2si64:
3023 if (!Subtarget->hasSSE2())
3024 return false;
3025 IsInputDouble = true;
3026 break;
3027 }
3028
3029 Type *RetTy = II->getCalledFunction()->getReturnType();
3030 MVT VT;
3031 if (!isTypeLegal(RetTy, VT))
3032 return false;
3033
3034 static const uint16_t CvtOpc[3][2][2] = {
3035 { { X86::CVTTSS2SIrr, X86::CVTTSS2SI64rr },
3036 { X86::CVTTSD2SIrr, X86::CVTTSD2SI64rr } },
3037 { { X86::VCVTTSS2SIrr, X86::VCVTTSS2SI64rr },
3038 { X86::VCVTTSD2SIrr, X86::VCVTTSD2SI64rr } },
3039 { { X86::VCVTTSS2SIZrr, X86::VCVTTSS2SI64Zrr },
3040 { X86::VCVTTSD2SIZrr, X86::VCVTTSD2SI64Zrr } },
3041 };
3042 unsigned AVXLevel = Subtarget->hasAVX512() ? 2 :
3043 Subtarget->hasAVX() ? 1 :
3044 0;
3045 unsigned Opc;
3046 switch (VT.SimpleTy) {
3047 default: llvm_unreachable("Unexpected result type.");
3048 case MVT::i32: Opc = CvtOpc[AVXLevel][IsInputDouble][0]; break;
3049 case MVT::i64: Opc = CvtOpc[AVXLevel][IsInputDouble][1]; break;
3050 }
3051
3052 // Check if we can fold insertelement instructions into the convert.
3053 const Value *Op = II->getArgOperand(0);
3054 while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
3055 const Value *Index = IE->getOperand(2);
3056 if (!isa<ConstantInt>(Index))
3057 break;
3058 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
3059
3060 if (!Idx) {
3061 Op = IE->getOperand(1);
3062 break;
3063 }
3064 Op = IE->getOperand(0);
3065 }
3066
3067 Register Reg = getRegForValue(Op);
3068 if (!Reg)
3069 return false;
3070
3071 Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
3072 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), ResultReg)
3073 .addReg(Reg);
3074
3075 updateValueMap(II, ResultReg);
3076 return true;
3077 }
3078 case Intrinsic::x86_sse42_crc32_32_8:
3079 case Intrinsic::x86_sse42_crc32_32_16:
3080 case Intrinsic::x86_sse42_crc32_32_32:
3081 case Intrinsic::x86_sse42_crc32_64_64: {
3082 if (!Subtarget->hasCRC32())
3083 return false;
3084
3085 Type *RetTy = II->getCalledFunction()->getReturnType();
3086
3087 MVT VT;
3088 if (!isTypeLegal(RetTy, VT))
3089 return false;
3090
3091 unsigned Opc;
3092 const TargetRegisterClass *RC = nullptr;
3093
3094 switch (II->getIntrinsicID()) {
3095 default:
3096 llvm_unreachable("Unexpected intrinsic.");
3097#define GET_EGPR_IF_ENABLED(OPC) Subtarget->hasEGPR() ? OPC##_EVEX : OPC
3098 case Intrinsic::x86_sse42_crc32_32_8:
3099 Opc = GET_EGPR_IF_ENABLED(X86::CRC32r32r8);
3100 RC = &X86::GR32RegClass;
3101 break;
3102 case Intrinsic::x86_sse42_crc32_32_16:
3103 Opc = GET_EGPR_IF_ENABLED(X86::CRC32r32r16);
3104 RC = &X86::GR32RegClass;
3105 break;
3106 case Intrinsic::x86_sse42_crc32_32_32:
3107 Opc = GET_EGPR_IF_ENABLED(X86::CRC32r32r32);
3108 RC = &X86::GR32RegClass;
3109 break;
3110 case Intrinsic::x86_sse42_crc32_64_64:
3111 Opc = GET_EGPR_IF_ENABLED(X86::CRC32r64r64);
3112 RC = &X86::GR64RegClass;
3113 break;
3114#undef GET_EGPR_IF_ENABLED
3115 }
3116
3117 const Value *LHS = II->getArgOperand(0);
3118 const Value *RHS = II->getArgOperand(1);
3119
3120 Register LHSReg = getRegForValue(LHS);
3121 Register RHSReg = getRegForValue(RHS);
3122 if (!LHSReg || !RHSReg)
3123 return false;
3124
3125 Register ResultReg = fastEmitInst_rr(Opc, RC, LHSReg, RHSReg);
3126 if (!ResultReg)
3127 return false;
3128
3129 updateValueMap(II, ResultReg);
3130 return true;
3131 }
3132 }
3133}
3134
3135bool X86FastISel::fastLowerArguments() {
3136 if (!FuncInfo.CanLowerReturn)
3137 return false;
3138
3139 const Function *F = FuncInfo.Fn;
3140 if (F->isVarArg())
3141 return false;
3142
3143 CallingConv::ID CC = F->getCallingConv();
3144 if (CC != CallingConv::C)
3145 return false;
3146
3147 if (Subtarget->isCallingConvWin64(CC))
3148 return false;
3149
3150 if (!Subtarget->is64Bit())
3151 return false;
3152
3153 if (Subtarget->useSoftFloat())
3154 return false;
3155
3156 // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
3157 unsigned GPRCnt = 0;
3158 unsigned FPRCnt = 0;
3159 for (auto const &Arg : F->args()) {
3160 if (Arg.hasAttribute(Attribute::ByVal) ||
3161 Arg.hasAttribute(Attribute::InReg) ||
3162 Arg.hasAttribute(Attribute::StructRet) ||
3163 Arg.hasAttribute(Attribute::SwiftSelf) ||
3164 Arg.hasAttribute(Attribute::SwiftAsync) ||
3165 Arg.hasAttribute(Attribute::SwiftError) ||
3166 Arg.hasAttribute(Attribute::Nest))
3167 return false;
3168
3169 Type *ArgTy = Arg.getType();
3170 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3171 return false;
3172
3173 EVT ArgVT = TLI.getValueType(DL, ArgTy);
3174 if (!ArgVT.isSimple()) return false;
3175 switch (ArgVT.getSimpleVT().SimpleTy) {
3176 default: return false;
3177 case MVT::i32:
3178 case MVT::i64:
3179 ++GPRCnt;
3180 break;
3181 case MVT::f32:
3182 case MVT::f64:
3183 if (!Subtarget->hasSSE1())
3184 return false;
3185 ++FPRCnt;
3186 break;
3187 }
3188
3189 if (GPRCnt > 6)
3190 return false;
3191
3192 if (FPRCnt > 8)
3193 return false;
3194 }
3195
3196 static const MCPhysReg GPR32ArgRegs[] = {
3197 X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
3198 };
3199 static const MCPhysReg GPR64ArgRegs[] = {
3200 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
3201 };
3202 static const MCPhysReg XMMArgRegs[] = {
3203 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3204 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3205 };
3206
3207 unsigned GPRIdx = 0;
3208 unsigned FPRIdx = 0;
3209 for (auto const &Arg : F->args()) {
3210 MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
3211 const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
3212 MCRegister SrcReg;
3213 switch (VT.SimpleTy) {
3214 default: llvm_unreachable("Unexpected value type.");
3215 case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
3216 case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
3217 case MVT::f32: [[fallthrough]];
3218 case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
3219 }
3220 Register DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3221 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3222 // Without this, EmitLiveInCopies may eliminate the livein if its only
3223 // use is a bitcast (which isn't turned into an instruction).
3224 Register ResultReg = createResultReg(RC);
3225 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3226 TII.get(TargetOpcode::COPY), ResultReg)
3227 .addReg(DstReg, getKillRegState(true));
3228 updateValueMap(&Arg, ResultReg);
3229 }
3230 return true;
3231}
3232
3233static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
3234 CallingConv::ID CC,
3235 const CallBase *CB) {
3236 if (Subtarget->is64Bit())
3237 return 0;
3238 if (Subtarget->getTargetTriple().isOSMSVCRT())
3239 return 0;
3240 if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
3241 CC == CallingConv::HiPE || CC == CallingConv::Tail ||
3243 return 0;
3244
3245 if (CB)
3246 if (CB->arg_empty() || !CB->paramHasAttr(0, Attribute::StructRet) ||
3247 CB->paramHasAttr(0, Attribute::InReg) || Subtarget->isTargetMCU())
3248 return 0;
3249
3250 return 4;
3251}
3252
3253bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
3254 auto &OutVals = CLI.OutVals;
3255 auto &OutFlags = CLI.OutFlags;
3256 auto &OutRegs = CLI.OutRegs;
3257 auto &Ins = CLI.Ins;
3258 auto &InRegs = CLI.InRegs;
3259 CallingConv::ID CC = CLI.CallConv;
3260 bool &IsTailCall = CLI.IsTailCall;
3261 bool IsVarArg = CLI.IsVarArg;
3262 const Value *Callee = CLI.Callee;
3263 MCSymbol *Symbol = CLI.Symbol;
3264 const auto *CB = CLI.CB;
3265
3266 bool Is64Bit = Subtarget->is64Bit();
3267 bool IsWin64 = Subtarget->isCallingConvWin64(CC);
3268
3269 // Call / invoke instructions with NoCfCheck attribute require special
3270 // handling.
3271 if (CB && CB->doesNoCfCheck())
3272 return false;
3273
3274 // Functions with no_caller_saved_registers that need special handling.
3275 if ((CB && isa<CallInst>(CB) && CB->hasFnAttr("no_caller_saved_registers")))
3276 return false;
3277
3278 // Functions with no_callee_saved_registers that need special handling.
3279 if ((CB && CB->hasFnAttr("no_callee_saved_registers")))
3280 return false;
3281
3282 // Indirect calls with CFI checks need special handling.
3283 if (CB && CB->isIndirectCall() && CB->getOperandBundle(LLVMContext::OB_kcfi))
3284 return false;
3285
3286 // Functions using thunks for indirect calls need to use SDISel.
3287 if (Subtarget->useIndirectThunkCalls())
3288 return false;
3289
3290 // Handle only C and fastcc calling conventions for now.
3291 switch (CC) {
3292 default: return false;
3293 case CallingConv::C:
3294 case CallingConv::Fast:
3295 case CallingConv::Tail:
3296 case CallingConv::Swift:
3297 case CallingConv::SwiftTail:
3298 case CallingConv::X86_FastCall:
3299 case CallingConv::X86_StdCall:
3300 case CallingConv::X86_ThisCall:
3301 case CallingConv::Win64:
3302 case CallingConv::X86_64_SysV:
3303 case CallingConv::CFGuard_Check:
3304 break;
3305 }
3306
3307 // Allow SelectionDAG isel to handle tail calls.
3308 if (IsTailCall)
3309 return false;
3310
3311 // fastcc with -tailcallopt is intended to provide a guaranteed
3312 // tail call optimization. Fastisel doesn't know how to do that.
3313 if ((CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) ||
3314 CC == CallingConv::Tail || CC == CallingConv::SwiftTail)
3315 return false;
3316
3317 // Don't know how to handle Win64 varargs yet. Nothing special needed for
3318 // x86-32. Special handling for x86-64 is implemented.
3319 if (IsVarArg && IsWin64)
3320 return false;
3321
3322 // Don't know about inalloca yet.
3323 if (CLI.CB && CLI.CB->hasInAllocaArgument())
3324 return false;
3325
3326 for (auto Flag : CLI.OutFlags)
3327 if (Flag.isSwiftError() || Flag.isPreallocated())
3328 return false;
3329
3330 // Can't handle import call optimization.
3331 if (Is64Bit &&
3332 MF->getFunction().getParent()->getModuleFlag("import-call-optimization"))
3333 return false;
3334
3335 SmallVector<MVT, 16> OutVTs;
3337 SmallVector<Register, 16> ArgRegs;
3338
3339 // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
3340 // instruction. This is safe because it is common to all FastISel supported
3341 // calling conventions on x86.
3342 for (int i = 0, e = OutVals.size(); i != e; ++i) {
3343 Value *&Val = OutVals[i];
3344 ISD::ArgFlagsTy Flags = OutFlags[i];
3345 if (auto *CI = dyn_cast<ConstantInt>(Val)) {
3346 if (CI->getBitWidth() < 32) {
3347 if (Flags.isSExt())
3348 Val = ConstantInt::get(CI->getContext(), CI->getValue().sext(32));
3349 else
3350 Val = ConstantInt::get(CI->getContext(), CI->getValue().zext(32));
3351 }
3352 }
3353
3354 // Passing bools around ends up doing a trunc to i1 and passing it.
3355 // Codegen this as an argument + "and 1".
3356 MVT VT;
3357 auto *TI = dyn_cast<TruncInst>(Val);
3358 Register ResultReg;
3359 if (TI && TI->getType()->isIntegerTy(1) && CLI.CB &&
3360 (TI->getParent() == CLI.CB->getParent()) && TI->hasOneUse()) {
3361 Value *PrevVal = TI->getOperand(0);
3362 ResultReg = getRegForValue(PrevVal);
3363
3364 if (!ResultReg)
3365 return false;
3366
3367 if (!isTypeLegal(PrevVal->getType(), VT))
3368 return false;
3369
3370 ResultReg = fastEmit_ri(VT, VT, ISD::AND, ResultReg, 1);
3371 } else {
3372 if (!isTypeLegal(Val->getType(), VT) ||
3373 (VT.isVector() && VT.getVectorElementType() == MVT::i1))
3374 return false;
3375 ResultReg = getRegForValue(Val);
3376 }
3377
3378 if (!ResultReg)
3379 return false;
3380
3381 ArgRegs.push_back(ResultReg);
3382 OutVTs.push_back(VT);
3383 ArgTys.push_back(Val->getType());
3384 }
3385
3386 // Analyze operands of the call, assigning locations to each operand.
3388 CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
3389
3390 // Allocate shadow area for Win64
3391 if (IsWin64)
3392 CCInfo.AllocateStack(32, Align(8));
3393
3394 CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, ArgTys, CC_X86);
3395
3396 // Get a count of how many bytes are to be pushed on the stack.
3397 unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3398
3399 // Issue CALLSEQ_START
3400 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
3401 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(AdjStackDown))
3402 .addImm(NumBytes).addImm(0).addImm(0);
3403
3404 // Walk the register/memloc assignments, inserting copies/loads.
3405 const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3406 for (const CCValAssign &VA : ArgLocs) {
3407 const Value *ArgVal = OutVals[VA.getValNo()];
3408 MVT ArgVT = OutVTs[VA.getValNo()];
3409
3410 if (ArgVT == MVT::x86mmx)
3411 return false;
3412
3413 Register ArgReg = ArgRegs[VA.getValNo()];
3414
3415 // Promote the value if needed.
3416 switch (VA.getLocInfo()) {
3417 case CCValAssign::Full: break;
3418 case CCValAssign::SExt: {
3419 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3420 "Unexpected extend");
3421
3422 if (ArgVT == MVT::i1)
3423 return false;
3424
3425 bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3426 ArgVT, ArgReg);
3427 assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
3428 ArgVT = VA.getLocVT();
3429 break;
3430 }
3431 case CCValAssign::ZExt: {
3432 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3433 "Unexpected extend");
3434
3435 // Handle zero-extension from i1 to i8, which is common.
3436 if (ArgVT == MVT::i1) {
3437 // Set the high bits to zero.
3438 ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg);
3439 ArgVT = MVT::i8;
3440
3441 if (!ArgReg)
3442 return false;
3443 }
3444
3445 bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3446 ArgVT, ArgReg);
3447 assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
3448 ArgVT = VA.getLocVT();
3449 break;
3450 }
3451 case CCValAssign::AExt: {
3452 assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
3453 "Unexpected extend");
3454 bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
3455 ArgVT, ArgReg);
3456 if (!Emitted)
3457 Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
3458 ArgVT, ArgReg);
3459 if (!Emitted)
3460 Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
3461 ArgVT, ArgReg);
3462
3463 assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
3464 ArgVT = VA.getLocVT();
3465 break;
3466 }
3467 case CCValAssign::BCvt: {
3468 ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg);
3469 assert(ArgReg && "Failed to emit a bitcast!");
3470 ArgVT = VA.getLocVT();
3471 break;
3472 }
3473 case CCValAssign::VExt:
3474 // VExt has not been implemented, so this should be impossible to reach
3475 // for now. However, fallback to Selection DAG isel once implemented.
3476 return false;
3480 case CCValAssign::FPExt:
3481 case CCValAssign::Trunc:
3482 llvm_unreachable("Unexpected loc info!");
3484 // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
3485 // support this.
3486 return false;
3487 }
3488
3489 if (VA.isRegLoc()) {
3490 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3491 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
3492 OutRegs.push_back(VA.getLocReg());
3493 } else {
3494 assert(VA.isMemLoc() && "Unknown value location!");
3495
3496 // Don't emit stores for undef values.
3497 if (isa<UndefValue>(ArgVal))
3498 continue;
3499
3500 unsigned LocMemOffset = VA.getLocMemOffset();
3501 X86AddressMode AM;
3502 AM.Base.Reg = RegInfo->getStackRegister();
3503 AM.Disp = LocMemOffset;
3504 ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
3505 Align Alignment = DL.getABITypeAlign(ArgVal->getType());
3506 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3507 MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
3508 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
3509 if (Flags.isByVal()) {
3510 X86AddressMode SrcAM;
3511 SrcAM.Base.Reg = ArgReg;
3512 if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
3513 return false;
3514 } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
3515 // If this is a really simple value, emit this with the Value* version
3516 // of X86FastEmitStore. If it isn't simple, we don't want to do this,
3517 // as it can cause us to reevaluate the argument.
3518 if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
3519 return false;
3520 } else {
3521 if (!X86FastEmitStore(ArgVT, ArgReg, AM, MMO))
3522 return false;
3523 }
3524 }
3525 }
3526
3527 // ELF / PIC requires GOT in the EBX register before function calls via PLT
3528 // GOT pointer.
3529 if (Subtarget->isPICStyleGOT()) {
3530 Register Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3531 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3532 TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
3533 }
3534
3535 if (Is64Bit && IsVarArg && !IsWin64) {
3536 // From AMD64 ABI document:
3537 // For calls that may call functions that use varargs or stdargs
3538 // (prototype-less calls or calls to functions containing ellipsis (...) in
3539 // the declaration) %al is used as hidden argument to specify the number
3540 // of SSE registers used. The contents of %al do not need to match exactly
3541 // the number of registers, but must be an ubound on the number of SSE
3542 // registers used and is in the range 0 - 8 inclusive.
3543
3544 // Count the number of XMM registers allocated.
3545 static const MCPhysReg XMMArgRegs[] = {
3546 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3547 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3548 };
3549 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3550 assert((Subtarget->hasSSE1() || !NumXMMRegs)
3551 && "SSE registers cannot be used when SSE is disabled");
3552 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV8ri),
3553 X86::AL).addImm(NumXMMRegs);
3554 }
3555
3556 // Materialize callee address in a register. FIXME: GV address can be
3557 // handled with a CALLpcrel32 instead.
3558 X86AddressMode CalleeAM;
3559 if (!X86SelectCallAddress(Callee, CalleeAM))
3560 return false;
3561
3562 Register CalleeOp;
3563 const GlobalValue *GV = nullptr;
3564 if (CalleeAM.GV != nullptr) {
3565 GV = CalleeAM.GV;
3566 } else if (CalleeAM.Base.Reg) {
3567 CalleeOp = CalleeAM.Base.Reg;
3568 } else
3569 return false;
3570
3571 // Issue the call.
3572 MachineInstrBuilder MIB;
3573 if (CalleeOp) {
3574 // Register-indirect call.
3575 unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
3576 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(CallOpc))
3577 .addReg(CalleeOp);
3578 } else {
3579 // Direct call.
3580 assert(GV && "Not a direct call");
3581 // See if we need any target-specific flags on the GV operand.
3582 unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
3583 if (OpFlags == X86II::MO_PLT && !Is64Bit &&
3584 TM.getRelocationModel() == Reloc::Static && isa<Function>(GV) &&
3585 cast<Function>(GV)->isIntrinsic())
3586 OpFlags = X86II::MO_NO_FLAG;
3587
3588 // This will be a direct call, or an indirect call through memory for
3589 // NonLazyBind calls or dllimport calls.
3590 bool NeedLoad = OpFlags == X86II::MO_DLLIMPORT ||
3591 OpFlags == X86II::MO_GOTPCREL ||
3592 OpFlags == X86II::MO_GOTPCREL_NORELAX ||
3593 OpFlags == X86II::MO_COFFSTUB;
3594 unsigned CallOpc = NeedLoad
3595 ? (Is64Bit ? X86::CALL64m : X86::CALL32m)
3596 : (Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32);
3597
3598 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(CallOpc));
3599 if (NeedLoad)
3600 MIB.addReg(Is64Bit ? X86::RIP : X86::NoRegister).addImm(1).addReg(0);
3601 if (Symbol)
3602 MIB.addSym(Symbol, OpFlags);
3603 else
3604 MIB.addGlobalAddress(GV, 0, OpFlags);
3605 if (NeedLoad)
3606 MIB.addReg(0);
3607 }
3608
3609 // Add a register mask operand representing the call-preserved registers.
3610 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3611 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
3612
3613 // Add an implicit use GOT pointer in EBX.
3614 if (Subtarget->isPICStyleGOT())
3615 MIB.addReg(X86::EBX, RegState::Implicit);
3616
3617 if (Is64Bit && IsVarArg && !IsWin64)
3618 MIB.addReg(X86::AL, RegState::Implicit);
3619
3620 // Add implicit physical register uses to the call.
3621 for (auto Reg : OutRegs)
3623
3624 // Issue CALLSEQ_END
3625 unsigned NumBytesForCalleeToPop =
3626 X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
3627 TM.Options.GuaranteedTailCallOpt)
3628 ? NumBytes // Callee pops everything.
3629 : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CB);
3630 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
3631 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(AdjStackUp))
3632 .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
3633
3634 // Now handle call return values.
3636 CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
3637 CLI.RetTy->getContext());
3638 CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
3639
3640 // Copy all of the result registers out of their specified physreg.
3641 Register ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
3642 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3643 CCValAssign &VA = RVLocs[i];
3644 EVT CopyVT = VA.getValVT();
3645 Register CopyReg = ResultReg + i;
3646 Register SrcReg = VA.getLocReg();
3647
3648 // If this is x86-64, and we disabled SSE, we can't return FP values
3649 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
3650 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
3651 report_fatal_error("SSE register return with SSE disabled");
3652 }
3653
3654 // If we prefer to use the value in xmm registers, copy it out as f80 and
3655 // use a truncate to move it from fp stack reg to xmm reg.
3656 if ((SrcReg == X86::FP0 || SrcReg == X86::FP1) &&
3657 isScalarFPTypeInSSEReg(VA.getValVT())) {
3658 CopyVT = MVT::f80;
3659 CopyReg = createResultReg(&X86::RFP80RegClass);
3660 }
3661
3662 // Copy out the result.
3663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3664 TII.get(TargetOpcode::COPY), CopyReg).addReg(SrcReg);
3665 InRegs.push_back(VA.getLocReg());
3666
3667 // Round the f80 to the right size, which also moves it to the appropriate
3668 // xmm register. This is accomplished by storing the f80 value in memory
3669 // and then loading it back.
3670 if (CopyVT != VA.getValVT()) {
3671 EVT ResVT = VA.getValVT();
3672 unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
3673 unsigned MemSize = ResVT.getSizeInBits()/8;
3674 int FI = MFI.CreateStackObject(MemSize, Align(MemSize), false);
3675 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3676 TII.get(Opc)), FI)
3677 .addReg(CopyReg);
3678 Opc = ResVT == MVT::f32 ? X86::MOVSSrm_alt : X86::MOVSDrm_alt;
3679 addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3680 TII.get(Opc), ResultReg + i), FI);
3681 }
3682 }
3683
3684 CLI.ResultReg = ResultReg;
3685 CLI.NumResultRegs = RVLocs.size();
3686 CLI.Call = MIB;
3687
3688 // Add call site info for call graph section.
3689 if (TM.Options.EmitCallGraphSection && CB && CB->isIndirectCall()) {
3690 MachineFunction::CallSiteInfo CSInfo(*CB);
3691 MF->addCallSiteInfo(CLI.Call, std::move(CSInfo));
3692 }
3693
3694 return true;
3695}
3696
3697bool
3698X86FastISel::fastSelectInstruction(const Instruction *I) {
3699 switch (I->getOpcode()) {
3700 default: break;
3701 case Instruction::Load:
3702 return X86SelectLoad(I);
3703 case Instruction::Store:
3704 return X86SelectStore(I);
3705 case Instruction::Ret:
3706 return X86SelectRet(I);
3707 case Instruction::ICmp:
3708 case Instruction::FCmp:
3709 return X86SelectCmp(I);
3710 case Instruction::ZExt:
3711 return X86SelectZExt(I);
3712 case Instruction::SExt:
3713 return X86SelectSExt(I);
3714 case Instruction::Br:
3715 return X86SelectBranch(I);
3716 case Instruction::LShr:
3717 case Instruction::AShr:
3718 case Instruction::Shl:
3719 return X86SelectShift(I);
3720 case Instruction::SDiv:
3721 case Instruction::UDiv:
3722 case Instruction::SRem:
3723 case Instruction::URem:
3724 return X86SelectDivRem(I);
3725 case Instruction::Select:
3726 return X86SelectSelect(I);
3727 case Instruction::Trunc:
3728 return X86SelectTrunc(I);
3729 case Instruction::FPExt:
3730 return X86SelectFPExt(I);
3731 case Instruction::FPTrunc:
3732 return X86SelectFPTrunc(I);
3733 case Instruction::SIToFP:
3734 return X86SelectSIToFP(I);
3735 case Instruction::UIToFP:
3736 return X86SelectUIToFP(I);
3737 case Instruction::IntToPtr: // Deliberate fall-through.
3738 case Instruction::PtrToInt: {
3739 EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
3740 EVT DstVT = TLI.getValueType(DL, I->getType());
3741 if (DstVT.bitsGT(SrcVT))
3742 return X86SelectZExt(I);
3743 if (DstVT.bitsLT(SrcVT))
3744 return X86SelectTrunc(I);
3745 Register Reg = getRegForValue(I->getOperand(0));
3746 if (!Reg)
3747 return false;
3748 updateValueMap(I, Reg);
3749 return true;
3750 }
3751 case Instruction::BitCast:
3752 return X86SelectBitCast(I);
3753 }
3754
3755 return false;
3756}
3757
3758Register X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
3759 if (VT > MVT::i64)
3760 return Register();
3761
3762 uint64_t Imm = CI->getZExtValue();
3763 if (Imm == 0) {
3764 Register SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
3765 switch (VT.SimpleTy) {
3766 default: llvm_unreachable("Unexpected value type");
3767 case MVT::i1:
3768 case MVT::i8:
3769 return fastEmitInst_extractsubreg(MVT::i8, SrcReg, X86::sub_8bit);
3770 case MVT::i16:
3771 return fastEmitInst_extractsubreg(MVT::i16, SrcReg, X86::sub_16bit);
3772 case MVT::i32:
3773 return SrcReg;
3774 case MVT::i64: {
3775 Register ResultReg = createResultReg(&X86::GR64RegClass);
3776 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3777 TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
3778 .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
3779 return ResultReg;
3780 }
3781 }
3782 }
3783
3784 unsigned Opc = 0;
3785 switch (VT.SimpleTy) {
3786 default: llvm_unreachable("Unexpected value type");
3787 case MVT::i1:
3788 VT = MVT::i8;
3789 [[fallthrough]];
3790 case MVT::i8: Opc = X86::MOV8ri; break;
3791 case MVT::i16: Opc = X86::MOV16ri; break;
3792 case MVT::i32: Opc = X86::MOV32ri; break;
3793 case MVT::i64: {
3794 if (isUInt<32>(Imm))
3795 Opc = X86::MOV32ri64;
3796 else if (isInt<32>(Imm))
3797 Opc = X86::MOV64ri32;
3798 else
3799 Opc = X86::MOV64ri;
3800 break;
3801 }
3802 }
3803 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
3804}
3805
3806Register X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
3807 if (CFP->isNullValue())
3808 return fastMaterializeFloatZero(CFP);
3809
3810 // Can't handle alternate code models yet.
3811 CodeModel::Model CM = TM.getCodeModel();
3812 if (CM != CodeModel::Small && CM != CodeModel::Medium &&
3813 CM != CodeModel::Large)
3814 return Register();
3815
3816 // Get opcode and regclass of the output for the given load instruction.
3817 unsigned Opc = 0;
3818 bool HasSSE1 = Subtarget->hasSSE1();
3819 bool HasSSE2 = Subtarget->hasSSE2();
3820 bool HasAVX = Subtarget->hasAVX();
3821 bool HasAVX512 = Subtarget->hasAVX512();
3822 switch (VT.SimpleTy) {
3823 default:
3824 return Register();
3825 case MVT::f32:
3826 Opc = HasAVX512 ? X86::VMOVSSZrm_alt
3827 : HasAVX ? X86::VMOVSSrm_alt
3828 : HasSSE1 ? X86::MOVSSrm_alt
3829 : X86::LD_Fp32m;
3830 break;
3831 case MVT::f64:
3832 Opc = HasAVX512 ? X86::VMOVSDZrm_alt
3833 : HasAVX ? X86::VMOVSDrm_alt
3834 : HasSSE2 ? X86::MOVSDrm_alt
3835 : X86::LD_Fp64m;
3836 break;
3837 case MVT::f80:
3838 // No f80 support yet.
3839 return Register();
3840 }
3841
3842 // MachineConstantPool wants an explicit alignment.
3843 Align Alignment = DL.getPrefTypeAlign(CFP->getType());
3844
3845 // x86-32 PIC requires a PIC base register for constant pools.
3846 Register PICBase;
3847 unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
3848 if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
3849 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3850 else if (OpFlag == X86II::MO_GOTOFF)
3851 PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
3852 else if (Subtarget->is64Bit() && TM.getCodeModel() != CodeModel::Large)
3853 PICBase = X86::RIP;
3854
3855 // Create the load from the constant pool.
3856 unsigned CPI = MCP.getConstantPoolIndex(CFP, Alignment);
3857 Register ResultReg = createResultReg(TLI.getRegClassFor(VT.SimpleTy));
3858
3859 // Large code model only applies to 64-bit mode.
3860 if (Subtarget->is64Bit() && CM == CodeModel::Large) {
3861 Register AddrReg = createResultReg(&X86::GR64RegClass);
3862 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV64ri),
3863 AddrReg)
3864 .addConstantPoolIndex(CPI, 0, OpFlag);
3865 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3866 TII.get(Opc), ResultReg);
3867 addRegReg(MIB, AddrReg, false, X86::NoSubRegister, PICBase, false,
3868 X86::NoSubRegister);
3869 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
3871 MachineMemOperand::MOLoad, DL.getPointerSize(), Alignment);
3872 MIB->addMemOperand(*FuncInfo.MF, MMO);
3873 return ResultReg;
3874 }
3875
3876 addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3877 TII.get(Opc), ResultReg),
3878 CPI, PICBase, OpFlag);
3879 return ResultReg;
3880}
3881
3882Register X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
3883 // Can't handle large GlobalValues yet.
3884 if (TM.getCodeModel() != CodeModel::Small &&
3885 TM.getCodeModel() != CodeModel::Medium)
3886 return Register();
3887 if (TM.isLargeGlobalValue(GV))
3888 return Register();
3889
3890 // Materialize addresses with LEA/MOV instructions.
3891 X86AddressMode AM;
3892 if (X86SelectAddress(GV, AM)) {
3893 // If the expression is just a basereg, then we're done, otherwise we need
3894 // to emit an LEA.
3896 AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
3897 return AM.Base.Reg;
3898
3899 Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
3900 if (TM.getRelocationModel() == Reloc::Static &&
3901 TLI.getPointerTy(DL) == MVT::i64) {
3902 // The displacement code could be more than 32 bits away so we need to use
3903 // an instruction with a 64 bit immediate
3904 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(X86::MOV64ri),
3905 ResultReg)
3906 .addGlobalAddress(GV);
3907 } else {
3908 unsigned Opc =
3909 TLI.getPointerTy(DL) == MVT::i32
3910 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3911 : X86::LEA64r;
3912 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3913 TII.get(Opc), ResultReg), AM);
3914 }
3915 return ResultReg;
3916 }
3917 return Register();
3918}
3919
3920Register X86FastISel::fastMaterializeConstant(const Constant *C) {
3921 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
3922
3923 // Only handle simple types.
3924 if (!CEVT.isSimple())
3925 return Register();
3926 MVT VT = CEVT.getSimpleVT();
3927
3928 if (const auto *CI = dyn_cast<ConstantInt>(C))
3929 return X86MaterializeInt(CI, VT);
3930 if (const auto *CFP = dyn_cast<ConstantFP>(C))
3931 return X86MaterializeFP(CFP, VT);
3932 if (const auto *GV = dyn_cast<GlobalValue>(C))
3933 return X86MaterializeGV(GV, VT);
3934 if (isa<UndefValue>(C)) {
3935 unsigned Opc = 0;
3936 switch (VT.SimpleTy) {
3937 default:
3938 break;
3939 case MVT::f32:
3940 if (!Subtarget->hasSSE1())
3941 Opc = X86::LD_Fp032;
3942 break;
3943 case MVT::f64:
3944 if (!Subtarget->hasSSE2())
3945 Opc = X86::LD_Fp064;
3946 break;
3947 case MVT::f80:
3948 Opc = X86::LD_Fp080;
3949 break;
3950 }
3951
3952 if (Opc) {
3953 Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
3954 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc),
3955 ResultReg);
3956 return ResultReg;
3957 }
3958 }
3959
3960 return Register();
3961}
3962
3963Register X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
3964 // Fail on dynamic allocas. At this point, getRegForValue has already
3965 // checked its CSE maps, so if we're here trying to handle a dynamic
3966 // alloca, we're not going to succeed. X86SelectAddress has a
3967 // check for dynamic allocas, because it's called directly from
3968 // various places, but targetMaterializeAlloca also needs a check
3969 // in order to avoid recursion between getRegForValue,
3970 // X86SelectAddrss, and targetMaterializeAlloca.
3971 if (!FuncInfo.StaticAllocaMap.count(C))
3972 return Register();
3973 assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
3974
3975 X86AddressMode AM;
3976 if (!X86SelectAddress(C, AM))
3977 return Register();
3978 unsigned Opc =
3979 TLI.getPointerTy(DL) == MVT::i32
3980 ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
3981 : X86::LEA64r;
3982 const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
3983 Register ResultReg = createResultReg(RC);
3984 addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD,
3985 TII.get(Opc), ResultReg), AM);
3986 return ResultReg;
3987}
3988
3989Register X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
3990 MVT VT;
3991 if (!isTypeLegal(CF->getType(), VT))
3992 return Register();
3993
3994 // Get opcode and regclass for the given zero.
3995 bool HasSSE1 = Subtarget->hasSSE1();
3996 bool HasSSE2 = Subtarget->hasSSE2();
3997 bool HasAVX512 = Subtarget->hasAVX512();
3998 unsigned Opc = 0;
3999 switch (VT.SimpleTy) {
4000 default: return 0;
4001 case MVT::f16:
4002 Opc = HasAVX512 ? X86::AVX512_FsFLD0SH : X86::FsFLD0SH;
4003 break;
4004 case MVT::f32:
4005 Opc = HasAVX512 ? X86::AVX512_FsFLD0SS
4006 : HasSSE1 ? X86::FsFLD0SS
4007 : X86::LD_Fp032;
4008 break;
4009 case MVT::f64:
4010 Opc = HasAVX512 ? X86::AVX512_FsFLD0SD
4011 : HasSSE2 ? X86::FsFLD0SD
4012 : X86::LD_Fp064;
4013 break;
4014 case MVT::f80:
4015 // No f80 support yet.
4016 return Register();
4017 }
4018
4019 Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
4020 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(Opc), ResultReg);
4021 return ResultReg;
4022}
4023
4024bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
4025 const LoadInst *LI) {
4026 const Value *Ptr = LI->getPointerOperand();
4027 X86AddressMode AM;
4028 if (!X86SelectAddress(Ptr, AM))
4029 return false;
4030
4031 const X86InstrInfo &XII = (const X86InstrInfo &)TII;
4032
4033 unsigned Size = DL.getTypeAllocSize(LI->getType());
4034
4036 AM.getFullAddress(AddrOps);
4037
4038 MachineInstr *Result = XII.foldMemoryOperandImpl(
4039 *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, LI->getAlign(),
4040 /*AllowCommute=*/true);
4041 if (!Result)
4042 return false;
4043
4044 // The index register could be in the wrong register class. Unfortunately,
4045 // foldMemoryOperandImpl could have commuted the instruction so its not enough
4046 // to just look at OpNo + the offset to the index reg. We actually need to
4047 // scan the instruction to find the index reg and see if its the correct reg
4048 // class.
4049 unsigned OperandNo = 0;
4050 for (MachineInstr::mop_iterator I = Result->operands_begin(),
4051 E = Result->operands_end(); I != E; ++I, ++OperandNo) {
4052 MachineOperand &MO = *I;
4053 if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
4054 continue;
4055 // Found the index reg, now try to rewrite it.
4056 Register IndexReg = constrainOperandRegClass(Result->getDesc(),
4057 MO.getReg(), OperandNo);
4058 if (IndexReg == MO.getReg())
4059 continue;
4060 MO.setReg(IndexReg);
4061 }
4062
4063 if (MI->isCall())
4064 FuncInfo.MF->moveAdditionalCallInfo(MI, Result);
4065 Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
4066 Result->cloneInstrSymbols(*FuncInfo.MF, *MI);
4068 removeDeadCode(I, std::next(I));
4069 return true;
4070}
4071
4072Register X86FastISel::fastEmitInst_rrrr(unsigned MachineInstOpcode,
4073 const TargetRegisterClass *RC,
4074 Register Op0, Register Op1,
4075 Register Op2, Register Op3) {
4076 const MCInstrDesc &II = TII.get(MachineInstOpcode);
4077
4078 Register ResultReg = createResultReg(RC);
4079 Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
4080 Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
4081 Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
4082 Op3 = constrainOperandRegClass(II, Op3, II.getNumDefs() + 3);
4083
4084 if (II.getNumDefs() >= 1)
4085 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II, ResultReg)
4086 .addReg(Op0)
4087 .addReg(Op1)
4088 .addReg(Op2)
4089 .addReg(Op3);
4090 else {
4091 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, II)
4092 .addReg(Op0)
4093 .addReg(Op1)
4094 .addReg(Op2)
4095 .addReg(Op3);
4096 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, MIMD, TII.get(TargetOpcode::COPY),
4097 ResultReg)
4098 .addReg(II.implicit_defs()[0]);
4099 }
4100 return ResultReg;
4101}
4102
4103namespace llvm {
4105 const TargetLibraryInfo *libInfo,
4106 const LibcallLoweringInfo *libcallLowering) {
4107 return new X86FastISel(funcInfo, libInfo, libcallLowering);
4108}
4109}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the FastISel class.
Hexagon Common GEP
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
uint64_t IntrinsicInst * II
const SmallVectorImpl< MachineOperand > & Cond
unsigned OpIndex
#define GET_EGPR_IF_ENABLED(OPC)
static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC)
If we have a comparison with RHS as the RHS of the comparison, return an opcode that works for the co...
static std::pair< unsigned, bool > getX86SSEConditionCode(CmpInst::Predicate Predicate)
static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget, CallingConv::ID CC, const CallBase *CB)
#define GET_SETCC
static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget)
static bool X86SelectAddress(MachineInstr &I, const X86TargetMachine &TM, const MachineRegisterInfo &MRI, const X86Subtarget &STI, X86AddressMode &AM)
Value * RHS
Value * LHS
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1023
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:996
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
BasicBlock * getSuccessor(unsigned i) const
Value * getCondition() const
Register getLocReg() const
LocInfo getLocInfo() const
int64_t getLocMemOffset() const
unsigned getValNo() const
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool arg_empty() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:664
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:679
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:693
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:682
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:691
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:680
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:681
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:690
@ FCMP_ONE
0 1 1 0 True if ordered and operands are unequal
Definition InstrTypes.h:684
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:687
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:688
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:683
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:685
@ ICMP_NE
not equal
Definition InstrTypes.h:698
@ FCMP_UNE
1 1 1 0 True if unordered or not equal
Definition InstrTypes.h:692
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:689
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:678
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:686
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:789
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constants.cpp:90
bool isValidLocationForIntrinsic(const DILocation *DL) const
Check that a location is valid for this variable.
Value * getAddress() const
DILocalVariable * getVariable() const
DIExpression * getExpression() const
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:66
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI bool isAtomic() const LLVM_READONLY
Return true if this instruction has an AtomicOrdering of unordered or higher.
Tracks which library functions to use for a particular subtarget.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool usesWindowsCFI() const
Definition MCAsmInfo.h:652
Machine Value Type.
SimpleValueType SimpleTy
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
MVT getVectorElementType() const
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void setFrameAddressIsTaken(bool T)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Function & getFunction()
Return the LLVM function that this machine code represents.
void addCallSiteInfo(const MachineInstr *CallI, CallSiteInfo &&CallInfo)
Start tracking the arguments passed to the call CallI.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMetadata(const MDNode *MD) const
const MachineInstrBuilder & addSym(MCSymbol *Sym, unsigned char TargetFlags=0) const
const MachineInstrBuilder & addConstantPoolIndex(unsigned Idx, int Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) const
const MachineInstrBuilder & addGlobalAddress(const GlobalValue *GV, int64_t Offset=0, unsigned TargetFlags=0) const
const MachineInstrBuilder & addReg(Register RegNo, unsigned Flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
unsigned getNumOperands() const
Retuns the total number of operands.
const MCInstrDesc & getDesc() const
Returns the target instruction descriptor of this MachineInstr.
MachineOperand * mop_iterator
iterator/begin/end - Iterate over all operands of a machine instruction.
LLVM_ABI void addMemOperand(MachineFunction &MF, MachineMemOperand *MO)
Add a MachineMemOperand to the machine instruction.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
Register getReg() const
getReg - Returns the register number.
Value * getLength() const
Value * getRawDest() const
unsigned getDestAddressSpace() const
bool isVolatile() const
Value * getRawSource() const
Return the arguments to the instruction.
unsigned getSourceAddressSpace() const
Metadata * getModuleFlag(StringRef Key) const
Return the corresponding value if Key appears in module flags, otherwise return null.
Definition Module.cpp:358
Wrapper class representing virtual and physical registers.
Definition Register.h:20
void push_back(const T &Elt)
Align getAlign() const
Value * getValueOperand()
Value * getPointerOperand()
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:754
Provides information about what library functions are available for the current target.
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
bool contains(Register Reg) const
Return true if the specified register is included in this register class.
bool isOSMSVCRT() const
Is this a "Windows" OS targeting a "MSVCRT.dll" environment.
Definition Triple.h:743
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:273
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition Type.h:264
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:261
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:230
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
const Use * const_op_iterator
Definition User.h:255
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:259
MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, MachineBasicBlock::iterator InsertPt, int FrameIndex, LiveIntervals *LIS=nullptr, VirtRegMap *VRM=nullptr) const override
Fold a load or store of the specified stack slot into the specified machine instruction for the speci...
Register getPtrSizedFrameRegister(const MachineFunction &MF) const
Register getStackRegister() const
bool hasSSE1() const
bool isTargetMCU() const
const Triple & getTargetTriple() const
bool hasAVX512() const
bool hasSSE2() const
bool hasAVX() const
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ HiPE
Used by the High-Performance Erlang Compiler (HiPE).
Definition CallingConv.h:53
@ GHC
Used by the Glasgow Haskell Compiler (GHC).
Definition CallingConv.h:50
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ Tail
Attemps to make calls as fast as possible while guaranteeing that tail call optimization can always b...
Definition CallingConv.h:76
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:41
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:852
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
Definition ISDOpcodes.h:992
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:843
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:664
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:849
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:738
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
@ Implicit
Not emitted register (e.g. carry, or temporary result).
@ Kill
The last use of a register.
@ X86
Windows x64, Windows Itanium (IA-64)
Definition MCAsmInfo.h:50
@ MO_GOTPCREL_NORELAX
MO_GOTPCREL_NORELAX - Same as MO_GOTPCREL except that R_X86_64_GOTPCREL relocations are guaranteed to...
@ MO_GOTOFF
MO_GOTOFF - On a symbol operand this indicates that the immediate is the offset to the location of th...
@ MO_COFFSTUB
MO_COFFSTUB - On a symbol operand "FOO", this indicates that the reference is actually to the "....
@ MO_PLT
MO_PLT - On a symbol operand this indicates that the immediate is offset to the PLT entry of symbol n...
@ MO_NO_FLAG
MO_NO_FLAG - No flag for the operand.
@ MO_DLLIMPORT
MO_DLLIMPORT - On a symbol operand "FOO", this indicates that the reference is actually to the "__imp...
@ MO_PIC_BASE_OFFSET
MO_PIC_BASE_OFFSET - On a symbol operand this indicates that the immediate should get the value of th...
@ MO_GOTPCREL
MO_GOTPCREL - On a symbol operand this indicates that the immediate is offset to the GOT entry for th...
@ LAST_VALID_COND
Definition X86BaseInfo.h:94
FastISel * createFastISel(FunctionLoweringInfo &funcInfo, const TargetLibraryInfo *libInfo, const LibcallLoweringInfo *libcallLowering)
std::pair< CondCode, bool > getX86ConditionCode(CmpInst::Predicate Predicate)
Return a pair of condition code for the given predicate and whether the instruction operands should b...
bool isCalleePop(CallingConv::ID CallingConv, bool is64Bit, bool IsVarArg, bool GuaranteeTCO)
Determines whether the callee is required to pop its own arguments.
unsigned getCMovOpcode(unsigned RegBytes, bool HasMemoryOperand=false, bool HasNDD=false)
Return a cmov opcode for the given register size in bytes, and operand type.
StringMapEntry< std::atomic< TypeEntryBody * > > TypeEntry
Definition TypePool.h:27
@ User
could "use" a pointer
@ Emitted
Assigned address, still materializing.
Definition Core.h:794
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
static bool isGlobalStubReference(unsigned char TargetFlag)
isGlobalStubReference - Return true if the specified TargetFlag operand is a reference to a stub for ...
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
static bool isGlobalRelativeToPICBase(unsigned char TargetFlag)
isGlobalRelativeToPICBase - Return true if the specified global value reference is relative to a 32-b...
LLVM_ABI Register constrainOperandRegClass(const MachineFunction &MF, const TargetRegisterInfo &TRI, MachineRegisterInfo &MRI, const TargetInstrInfo &TII, const RegisterBankInfo &RBI, MachineInstr &InsertPt, const TargetRegisterClass &RegClass, MachineOperand &RegMO)
Constrain the Register operand OpIdx, so that it is now constrained to the TargetRegisterClass passed...
Definition Utils.cpp:56
LLVM_ABI void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr, SmallVectorImpl< ISD::OutputArg > &Outs, const TargetLowering &TLI, const DataLayout &DL)
Given an LLVM IR type and return type attributes, compute the return value EVTs and flags,...
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr unsigned getKillRegState(bool B)
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
static const MachineInstrBuilder & addConstantPoolReference(const MachineInstrBuilder &MIB, unsigned CPI, Register GlobalBaseReg, unsigned char OpFlags)
addConstantPoolReference - This function is used to add a reference to the base of a constant value s...
static const MachineInstrBuilder & addRegReg(const MachineInstrBuilder &MIB, Register Reg1, bool isKill1, unsigned SubReg1, Register Reg2, bool isKill2, unsigned SubReg2)
addRegReg - This function is used to add a memory reference of the form: [Reg + Reg].
static const MachineInstrBuilder & addFrameReference(const MachineInstrBuilder &MIB, int FI, int Offset=0, bool mem=true)
addFrameReference - This function is used to add a reference to the base of an abstract object on the...
static const MachineInstrBuilder & addFullAddress(const MachineInstrBuilder &MIB, const X86AddressMode &AM)
Op::Description Desc
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1744
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
generic_gep_type_iterator<> gep_type_iterator
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:189
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
bool CC_X86(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
bool RetCC_X86(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
static const MachineInstrBuilder & addDirectMem(const MachineInstrBuilder &MIB, Register Reg)
addDirectMem - This function is used to add a direct memory reference to the current instruction – th...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:872
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
Extended Value Type.
Definition ValueTypes.h:35
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:137
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:284
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:300
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:373
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:316
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
static LLVM_ABI MachinePointerInfo getConstantPool(MachineFunction &MF)
Return a MachinePointerInfo record that refers to the constant pool.
X86AddressMode - This struct holds a generalized full x86 address mode.
void getFullAddress(SmallVectorImpl< MachineOperand > &MO)
const GlobalValue * GV
union llvm::X86AddressMode::BaseUnion Base
enum llvm::X86AddressMode::@202116273335065351270200035056227005202106004277 BaseType