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