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