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