LLVM 24.0.0git
X86ISelDAGToDAG.cpp
Go to the documentation of this file.
1//===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
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 a DAG pattern matching instruction selector for X86,
10// converting from a legalized dag to a X86 dag.
11//
12//===----------------------------------------------------------------------===//
13
14#include "X86.h"
16#include "X86Subtarget.h"
17#include "X86TargetMachine.h"
18#include "llvm/ADT/Statistic.h"
21#include "llvm/Config/llvm-config.h"
23#include "llvm/IR/Function.h"
25#include "llvm/IR/Intrinsics.h"
26#include "llvm/IR/IntrinsicsX86.h"
27#include "llvm/IR/Module.h"
28#include "llvm/IR/Type.h"
29#include "llvm/Support/Debug.h"
33#include <cstdint>
34#include <optional>
35
36using namespace llvm;
37
38#define DEBUG_TYPE "x86-isel"
39#define PASS_NAME "X86 DAG->DAG Instruction Selection"
40
41STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
42
43static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true),
44 cl::desc("Enable setting constant bits to reduce size of mask immediates"),
46
48 "x86-promote-anyext-load", cl::init(true),
49 cl::desc("Enable promoting aligned anyext load to wider load"), cl::Hidden);
50
52
53//===----------------------------------------------------------------------===//
54// Pattern Matcher Implementation
55//===----------------------------------------------------------------------===//
56
57namespace {
58 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
59 /// numbers for the leaves of the matched tree.
60 struct X86ISelAddressMode {
61 enum {
62 RegBase,
63 FrameIndexBase
64 } BaseType = RegBase;
65
66 // This is really a union, discriminated by BaseType!
67 SDValue Base_Reg;
68 int Base_FrameIndex = 0;
69
70 unsigned Scale = 1;
71 SDValue IndexReg;
72 int32_t Disp = 0;
73 SDValue Segment;
74 const GlobalValue *GV = nullptr;
75 const Constant *CP = nullptr;
76 const BlockAddress *BlockAddr = nullptr;
77 const char *ES = nullptr;
78 MCSymbol *MCSym = nullptr;
79 int JT = -1;
80 Align Alignment; // CP alignment.
81 unsigned char SymbolFlags = X86II::MO_NO_FLAG; // X86II::MO_*
82 bool NegateIndex = false;
83 // True when this address is being matched to be emitted as a LEA rather
84 // than folded into a memory operand. Unlike a memory operand, a LEA turns
85 // the folded arithmetic into real instructions, so it is not profitable to
86 // split an already-materialized (multi-use) value here. (Issue #51707)
87 bool IsForLEA = false;
88
89 X86ISelAddressMode() = default;
90
91 bool hasSymbolicDisplacement() const {
92 return GV != nullptr || CP != nullptr || ES != nullptr ||
93 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
94 }
95
96 bool hasBaseOrIndexReg() const {
97 return BaseType == FrameIndexBase ||
98 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
99 }
100
101 /// Return true if this addressing mode is already RIP-relative.
102 bool isRIPRelative() const {
103 if (BaseType != RegBase) return false;
104 if (RegisterSDNode *RegNode =
105 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
106 return RegNode->getReg() == X86::RIP;
107 return false;
108 }
109
110 void setBaseReg(SDValue Reg) {
111 BaseType = RegBase;
112 Base_Reg = Reg;
113 }
114
115#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
116 void dump(SelectionDAG *DAG = nullptr) {
117 dbgs() << "X86ISelAddressMode " << this << '\n';
118 dbgs() << "Base_Reg ";
119 if (Base_Reg.getNode())
120 Base_Reg.getNode()->dump(DAG);
121 else
122 dbgs() << "nul\n";
123 if (BaseType == FrameIndexBase)
124 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n';
125 dbgs() << " Scale " << Scale << '\n'
126 << "IndexReg ";
127 if (NegateIndex)
128 dbgs() << "negate ";
129 if (IndexReg.getNode())
130 IndexReg.getNode()->dump(DAG);
131 else
132 dbgs() << "nul\n";
133 dbgs() << " Disp " << Disp << '\n'
134 << "GV ";
135 if (GV)
136 GV->dump();
137 else
138 dbgs() << "nul";
139 dbgs() << " CP ";
140 if (CP)
141 CP->dump();
142 else
143 dbgs() << "nul";
144 dbgs() << '\n'
145 << "ES ";
146 if (ES)
147 dbgs() << ES;
148 else
149 dbgs() << "nul";
150 dbgs() << " MCSym ";
151 if (MCSym)
152 dbgs() << MCSym;
153 else
154 dbgs() << "nul";
155 dbgs() << " JT" << JT << " Align" << Alignment.value() << '\n';
156 }
157#endif
158 };
159}
160
161namespace {
162 //===--------------------------------------------------------------------===//
163 /// ISel - X86-specific code to select X86 machine instructions for
164 /// SelectionDAG operations.
165 ///
166 class X86DAGToDAGISel final : public SelectionDAGISel {
167 /// Keep a pointer to the X86Subtarget around so that we can
168 /// make the right decision when generating code for different targets.
169 const X86Subtarget *Subtarget;
170
171 /// If true, selector should try to optimize for minimum code size.
172 bool OptForMinSize;
173
174 /// Disable direct TLS access through segment registers.
175 bool IndirectTlsSegRefs;
176
177 public:
178 X86DAGToDAGISel() = delete;
179
180 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOptLevel OptLevel)
181 : SelectionDAGISel(tm, OptLevel), Subtarget(nullptr),
182 OptForMinSize(false), IndirectTlsSegRefs(false) {}
183
184 bool runOnMachineFunction(MachineFunction &MF) override {
185 // Reset the subtarget each time through.
186 Subtarget = &MF.getSubtarget<X86Subtarget>();
187 IndirectTlsSegRefs = MF.getFunction().hasFnAttribute(
188 "indirect-tls-seg-refs");
189
190 // OptFor[Min]Size are used in pattern predicates that isel is matching.
191 OptForMinSize = MF.getFunction().hasMinSize();
193 }
194
195 void emitFunctionEntryCode() override;
196
197 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
198
199 void PreprocessISelDAG() override;
200 void PostprocessISelDAG() override;
201
202// Include the pieces autogenerated from the target description.
203#include "X86GenDAGISel.inc"
204
205 private:
206 void Select(SDNode *N) override;
207
208 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
209 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM,
210 bool AllowSegmentRegForX32 = false);
211 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
212 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
213 bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
214 bool matchAdd(SDValue &N, X86ISelAddressMode &AM, unsigned Depth);
215 bool hasMaterializingUse(SDValue V) const;
216 SDValue matchIndexRecursively(SDValue N, X86ISelAddressMode &AM,
217 unsigned Depth);
218 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
219 unsigned Depth);
220 bool matchVectorAddressRecursively(SDValue N, X86ISelAddressMode &AM,
221 unsigned Depth);
222 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
223 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Scale,
224 SDValue &Index, SDValue &Disp, SDValue &Segment,
225 bool HasNDDM = true);
226 bool selectNDDAddr(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Scale,
227 SDValue &Index, SDValue &Disp, SDValue &Segment);
228 bool selectVectorAddr(MemSDNode *Parent, SDValue BasePtr, SDValue IndexOp,
229 SDValue ScaleOp, SDValue &Base, SDValue &Scale,
230 SDValue &Index, SDValue &Disp, SDValue &Segment);
231 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
232 bool selectLEAAddr(SDValue N, SDValue &Base,
233 SDValue &Scale, SDValue &Index, SDValue &Disp,
234 SDValue &Segment);
235 bool selectLEA64_Addr(SDValue N, SDValue &Base, SDValue &Scale,
236 SDValue &Index, SDValue &Disp, SDValue &Segment);
237 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
238 SDValue &Scale, SDValue &Index, SDValue &Disp,
239 SDValue &Segment);
240 bool selectRelocImm(SDValue N, SDValue &Op);
241
242 bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
243 SDValue &Base, SDValue &Scale,
244 SDValue &Index, SDValue &Disp,
245 SDValue &Segment);
246
247 // Convenience method where P is also root.
248 bool tryFoldLoad(SDNode *P, SDValue N,
249 SDValue &Base, SDValue &Scale,
250 SDValue &Index, SDValue &Disp,
251 SDValue &Segment) {
252 return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
253 }
254
255 bool tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,
256 SDValue &Base, SDValue &Scale,
257 SDValue &Index, SDValue &Disp,
258 SDValue &Segment);
259
260 bool isProfitableToFormMaskedOp(SDNode *N) const;
261
262 /// Implement addressing mode selection for inline asm expressions.
263 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
264 InlineAsm::ConstraintCode ConstraintID,
265 std::vector<SDValue> &OutOps) override;
266
267 void emitSpecialCodeForMain();
268
269 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
270 MVT VT, SDValue &Base, SDValue &Scale,
271 SDValue &Index, SDValue &Disp,
272 SDValue &Segment) {
273 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
274 Base = CurDAG->getTargetFrameIndex(
275 AM.Base_FrameIndex, TLI->getPointerTy(CurDAG->getDataLayout()));
276 else if (AM.Base_Reg.getNode())
277 Base = AM.Base_Reg;
278 else
279 Base = CurDAG->getRegister(0, VT);
280
281 Scale = getI8Imm(AM.Scale, DL);
282
283#define GET_ND_IF_ENABLED(OPC) (Subtarget->hasNDD() ? OPC##_ND : OPC)
284#define GET_NDM_IF_ENABLED(OPC) \
285 (Subtarget->hasNDD() && Subtarget->hasNDDM() ? OPC##_ND : OPC)
286 // Negate the index if needed.
287 if (AM.NegateIndex) {
288 unsigned NegOpc;
289 switch (VT.SimpleTy) {
290 default:
291 llvm_unreachable("Unsupported VT!");
292 case MVT::i64:
293 NegOpc = GET_ND_IF_ENABLED(X86::NEG64r);
294 break;
295 case MVT::i32:
296 NegOpc = GET_ND_IF_ENABLED(X86::NEG32r);
297 break;
298 case MVT::i16:
299 NegOpc = GET_ND_IF_ENABLED(X86::NEG16r);
300 break;
301 case MVT::i8:
302 NegOpc = GET_ND_IF_ENABLED(X86::NEG8r);
303 break;
304 }
305 SDValue Neg = SDValue(CurDAG->getMachineNode(NegOpc, DL, VT, MVT::i32,
306 AM.IndexReg), 0);
307 AM.IndexReg = Neg;
308 }
309
310 if (AM.IndexReg.getNode())
311 Index = AM.IndexReg;
312 else
313 Index = CurDAG->getRegister(0, VT);
314
315 // These are 32-bit even in 64-bit mode since RIP-relative offset
316 // is 32-bit.
317 if (AM.GV)
318 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
319 MVT::i32, AM.Disp,
320 AM.SymbolFlags);
321 else if (AM.CP)
322 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Alignment,
323 AM.Disp, AM.SymbolFlags);
324 else if (AM.ES) {
325 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
326 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
327 } else if (AM.MCSym) {
328 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
329 assert(AM.SymbolFlags == 0 && "oo");
330 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
331 } else if (AM.JT != -1) {
332 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
333 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
334 } else if (AM.BlockAddr)
335 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
336 AM.SymbolFlags);
337 else
338 Disp = CurDAG->getSignedTargetConstant(AM.Disp, DL, MVT::i32);
339
340 if (AM.Segment.getNode())
341 Segment = AM.Segment;
342 else
343 Segment = CurDAG->getRegister(0, MVT::i16);
344 }
345
346 // Utility function to determine whether it is AMX SDNode right after
347 // lowering but before ISEL.
348 bool isAMXSDNode(SDNode *N) const {
349 // Check if N is AMX SDNode:
350 // 1. check result type;
351 // 2. check operand type;
352 for (unsigned Idx = 0, E = N->getNumValues(); Idx != E; ++Idx) {
353 if (N->getValueType(Idx) == MVT::x86amx)
354 return true;
355 }
356 for (unsigned Idx = 0, E = N->getNumOperands(); Idx != E; ++Idx) {
357 SDValue Op = N->getOperand(Idx);
358 if (Op.getValueType() == MVT::x86amx)
359 return true;
360 }
361 return false;
362 }
363
364 // Utility function to determine whether we should avoid selecting
365 // immediate forms of instructions for better code size or not.
366 // At a high level, we'd like to avoid such instructions when
367 // we have similar constants used within the same basic block
368 // that can be kept in a register.
369 //
370 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
371 uint32_t UseCount = 0;
372
373 // Do not want to hoist if we're not optimizing for size.
374 // TODO: We'd like to remove this restriction.
375 // See the comment in X86InstrInfo.td for more info.
376 if (!CurDAG->shouldOptForSize())
377 return false;
378
379 // Walk all the users of the immediate.
380 for (const SDNode *User : N->users()) {
381 if (UseCount >= 2)
382 break;
383
384 // This user is already selected. Count it as a legitimate use and
385 // move on.
386 if (User->isMachineOpcode()) {
387 UseCount++;
388 continue;
389 }
390
391 // We want to count stores of immediates as real uses.
392 if (User->getOpcode() == ISD::STORE &&
393 User->getOperand(1).getNode() == N) {
394 UseCount++;
395 continue;
396 }
397
398 // We don't currently match users that have > 2 operands (except
399 // for stores, which are handled above)
400 // Those instruction won't match in ISEL, for now, and would
401 // be counted incorrectly.
402 // This may change in the future as we add additional instruction
403 // types.
404 if (User->getNumOperands() != 2)
405 continue;
406
407 // If this is a sign-extended 8-bit integer immediate used in an ALU
408 // instruction, there is probably an opcode encoding to save space.
410 if (C && isInt<8>(C->getSExtValue()))
411 continue;
412
413 // Immediates that are used for offsets as part of stack
414 // manipulation should be left alone. These are typically
415 // used to indicate SP offsets for argument passing and
416 // will get pulled into stores/pushes (implicitly).
417 if (User->getOpcode() == X86ISD::ADD ||
418 User->getOpcode() == ISD::ADD ||
419 User->getOpcode() == X86ISD::SUB ||
420 User->getOpcode() == ISD::SUB) {
421
422 // Find the other operand of the add/sub.
423 SDValue OtherOp = User->getOperand(0);
424 if (OtherOp.getNode() == N)
425 OtherOp = User->getOperand(1);
426
427 // Don't count if the other operand is SP.
428 RegisterSDNode *RegNode;
429 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
431 OtherOp->getOperand(1).getNode())))
432 if ((RegNode->getReg() == X86::ESP) ||
433 (RegNode->getReg() == X86::RSP))
434 continue;
435 }
436
437 // ... otherwise, count this and move on.
438 UseCount++;
439 }
440
441 // If we have more than 1 use, then recommend for hoisting.
442 return (UseCount > 1);
443 }
444
445 /// Return a target constant with the specified value of type i8.
446 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
447 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
448 }
449
450 /// Return a target constant with the specified value, of type i32.
451 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
452 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
453 }
454
455 /// Return a target constant with the specified value, of type i64.
456 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
457 return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
458 }
459
460 SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
461 const SDLoc &DL) {
462 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
463 uint64_t Index = N->getConstantOperandVal(1);
464 MVT VecVT = N->getOperand(0).getSimpleValueType();
465 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
466 }
467
468 SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
469 const SDLoc &DL) {
470 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
471 uint64_t Index = N->getConstantOperandVal(2);
472 MVT VecVT = N->getSimpleValueType(0);
473 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
474 }
475
476 SDValue getPermuteVINSERTCommutedImmediate(SDNode *N, unsigned VecWidth,
477 const SDLoc &DL) {
478 assert(VecWidth == 128 && "Unexpected vector width");
479 uint64_t Index = N->getConstantOperandVal(2);
480 MVT VecVT = N->getSimpleValueType(0);
481 uint64_t InsertIdx = (Index * VecVT.getScalarSizeInBits()) / VecWidth;
482 assert((InsertIdx == 0 || InsertIdx == 1) && "Bad insertf128 index");
483 // vinsert(0,sub,vec) -> [sub0][vec1] -> vperm2x128(0x30,vec,sub)
484 // vinsert(1,sub,vec) -> [vec0][sub0] -> vperm2x128(0x02,vec,sub)
485 return getI8Imm(InsertIdx ? 0x02 : 0x30, DL);
486 }
487
488 SDValue getSBBZero(SDNode *N) {
489 SDLoc dl(N);
490 MVT VT = N->getSimpleValueType(0);
491
492 // Create zero.
493 SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);
494 SDValue Zero =
495 SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, {}), 0);
496 if (VT == MVT::i64) {
497 Zero = SDValue(
498 CurDAG->getMachineNode(
499 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64, Zero,
500 CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
501 0);
502 }
503
504 // Copy flags to the EFLAGS register and glue it to next node.
505 unsigned Opcode = N->getOpcode();
506 assert((Opcode == X86ISD::SBB || Opcode == X86ISD::SETCC_CARRY) &&
507 "Unexpected opcode for SBB materialization");
508 unsigned FlagOpIndex = Opcode == X86ISD::SBB ? 2 : 1;
509 SDValue EFLAGS =
510 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,
511 N->getOperand(FlagOpIndex), SDValue());
512
513 // Create a 64-bit instruction if the result is 64-bits otherwise use the
514 // 32-bit version.
515 unsigned Opc = VT == MVT::i64 ? X86::SBB64rr : X86::SBB32rr;
516 MVT SBBVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;
517 VTs = CurDAG->getVTList(SBBVT, MVT::i32);
518 return SDValue(
519 CurDAG->getMachineNode(Opc, dl, VTs,
520 {Zero, Zero, EFLAGS, EFLAGS.getValue(1)}),
521 0);
522 }
523
524 // Helper to detect unneeded and instructions on shift amounts. Called
525 // from PatFrags in tablegen.
526 bool isUnneededShiftMask(SDNode *N, unsigned Width) const {
527 assert(N->getOpcode() == ISD::AND && "Unexpected opcode");
528 const APInt &Val = N->getConstantOperandAPInt(1);
529
530 if (Val.countr_one() >= Width)
531 return true;
532
533 APInt Mask = Val | CurDAG->computeKnownBits(N->getOperand(0)).Zero;
534 return Mask.countr_one() >= Width;
535 }
536
537 /// Return an SDNode that returns the value of the global base register.
538 /// Output instructions required to initialize the global base register,
539 /// if necessary.
540 SDNode *getGlobalBaseReg();
541
542 /// Return a reference to the TargetMachine, casted to the target-specific
543 /// type.
544 const X86TargetMachine &getTargetMachine() const {
545 return static_cast<const X86TargetMachine &>(TM);
546 }
547
548 /// Return a reference to the TargetInstrInfo, casted to the target-specific
549 /// type.
550 const X86InstrInfo *getInstrInfo() const {
551 return Subtarget->getInstrInfo();
552 }
553
554 /// Return a condition code of the given SDNode
555 X86::CondCode getCondFromNode(SDNode *N) const;
556
557 /// Address-mode matching performs shift-of-and to and-of-shift
558 /// reassociation in order to expose more scaled addressing
559 /// opportunities.
560 bool ComplexPatternFuncMutatesDAG() const override {
561 return true;
562 }
563
564 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
565
566 // Indicates we should prefer to use a non-temporal load for this load.
567 bool useNonTemporalLoad(LoadSDNode *N) const {
568 if (!N->isNonTemporal())
569 return false;
570
571 unsigned StoreSize = N->getMemoryVT().getStoreSize();
572
573 if (N->getAlign().value() < StoreSize)
574 return false;
575
576 switch (StoreSize) {
577 default: llvm_unreachable("Unsupported store size");
578 case 4:
579 case 8:
580 return false;
581 case 16:
582 return Subtarget->hasSSE41();
583 case 32:
584 return Subtarget->hasAVX2();
585 case 64:
586 return Subtarget->hasAVX512();
587 }
588 }
589
590 bool foldLoadStoreIntoMemOperand(SDNode *Node);
591 MachineSDNode *matchBEXTRFromAndImm(SDNode *Node);
592 bool matchBitExtract(SDNode *Node);
593 bool shrinkAndImmediate(SDNode *N);
594 bool isMaskZeroExtended(SDNode *N) const;
595 bool tryShiftAmountMod(SDNode *N);
596 bool tryShrinkShlLogicImm(SDNode *N);
597 bool tryVPTERNLOG(SDNode *N);
598 bool matchVPTERNLOG(SDNode *Root, SDNode *ParentA, SDNode *ParentB,
599 SDNode *ParentC, SDValue A, SDValue B, SDValue C,
600 uint8_t Imm);
601 bool tryVPTESTM(SDNode *Root, SDValue Setcc, SDValue Mask);
602 bool tryMatchBitSelect(SDNode *N);
603
604 MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
605 const SDLoc &dl, MVT VT, SDNode *Node);
606 MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
607 const SDLoc &dl, MVT VT, SDNode *Node,
608 SDValue &InGlue);
609
610 bool tryOptimizeRem8Extend(SDNode *N);
611
612 bool onlyUsesZeroFlag(SDValue Flags) const;
613 bool hasNoSignFlagUses(SDValue Flags) const;
614 bool hasNoCarryFlagUses(SDValue Flags) const;
615 bool checkTCRetEnoughRegs(SDNode *N) const;
616 };
617
618 class X86DAGToDAGISelLegacy : public SelectionDAGISelLegacy {
619 public:
620 static char ID;
621 explicit X86DAGToDAGISelLegacy(X86TargetMachine &tm,
622 CodeGenOptLevel OptLevel)
623 : SelectionDAGISelLegacy(
624 ID, std::make_unique<X86DAGToDAGISel>(tm, OptLevel)) {}
625 };
626}
627
628char X86DAGToDAGISelLegacy::ID = 0;
629
630INITIALIZE_PASS(X86DAGToDAGISelLegacy, DEBUG_TYPE, PASS_NAME, false, false)
631
632// Returns true if this masked compare can be implemented legally with this
633// type.
634static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
635 unsigned Opcode = N->getOpcode();
636 if (Opcode == X86ISD::CMPM || Opcode == X86ISD::CMPMM ||
637 Opcode == X86ISD::STRICT_CMPM || Opcode == ISD::SETCC ||
638 Opcode == X86ISD::CMPMM_SAE || Opcode == X86ISD::VFPCLASS) {
639 // We can get 256-bit 8 element types here without VLX being enabled. When
640 // this happens we will use 512-bit operations and the mask will not be
641 // zero extended.
642 EVT OpVT = N->getOperand(0).getValueType();
643 // The first operand of X86ISD::STRICT_CMPM is chain, so we need to get the
644 // second operand.
645 if (Opcode == X86ISD::STRICT_CMPM)
646 OpVT = N->getOperand(1).getValueType();
647 if (OpVT.is256BitVector() || OpVT.is128BitVector())
648 return Subtarget->hasVLX();
649
650 return true;
651 }
652 // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
653 if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
654 Opcode == X86ISD::FSETCCM_SAE)
655 return true;
656
657 return false;
658}
659
660// Returns true if we can assume the writer of the mask has zero extended it
661// for us.
662bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
663 // If this is an AND, check if we have a compare on either side. As long as
664 // one side guarantees the mask is zero extended, the AND will preserve those
665 // zeros.
666 if (N->getOpcode() == ISD::AND)
667 return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
668 isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
669
670 return isLegalMaskCompare(N, Subtarget);
671}
672
673bool
674X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
675 if (OptLevel == CodeGenOptLevel::None)
676 return false;
677
678 if (!N.hasOneUse())
679 return false;
680
681 if (N.getOpcode() != ISD::LOAD)
682 return true;
683
684 // Don't fold non-temporal loads if we have an instruction for them.
685 if (useNonTemporalLoad(cast<LoadSDNode>(N)))
686 return false;
687
688 // If N is a load, do additional profitability checks.
689 if (U == Root) {
690 switch (U->getOpcode()) {
691 default: break;
692 case X86ISD::ADD:
693 case X86ISD::ADC:
694 case X86ISD::SUB:
695 case X86ISD::SBB:
696 case X86ISD::AND:
697 case X86ISD::XOR:
698 case X86ISD::OR:
699 case ISD::ADD:
700 case ISD::UADDO_CARRY:
701 case ISD::AND:
702 case ISD::OR:
703 case ISD::XOR: {
704 SDValue Op1 = U->getOperand(1);
705
706 // If the other operand is a 8-bit immediate we should fold the immediate
707 // instead. This reduces code size.
708 // e.g.
709 // movl 4(%esp), %eax
710 // addl $4, %eax
711 // vs.
712 // movl $4, %eax
713 // addl 4(%esp), %eax
714 // The former is 2 bytes shorter. In case where the increment is 1, then
715 // the saving can be 4 bytes (by using incl %eax).
716 if (auto *Imm = dyn_cast<ConstantSDNode>(Op1)) {
717 if (Imm->getAPIntValue().isSignedIntN(8))
718 return false;
719
720 // If this is a 64-bit AND with an immediate that fits in 32-bits,
721 // prefer using the smaller and over folding the load. This is needed to
722 // make sure immediates created by shrinkAndImmediate are always folded.
723 // Ideally we would narrow the load during DAG combine and get the
724 // best of both worlds.
725 if (U->getOpcode() == ISD::AND &&
726 Imm->getAPIntValue().getBitWidth() == 64 &&
727 Imm->getAPIntValue().isIntN(32))
728 return false;
729
730 // If this really a zext_inreg that can be represented with a movzx
731 // instruction, prefer that.
732 // TODO: We could shrink the load and fold if it is non-volatile.
733 if (U->getOpcode() == ISD::AND &&
734 (Imm->getAPIntValue() == UINT8_MAX ||
735 Imm->getAPIntValue() == UINT16_MAX ||
736 Imm->getAPIntValue() == UINT32_MAX))
737 return false;
738
739 // ADD/SUB with can negate the immediate and use the opposite operation
740 // to fit 128 into a sign extended 8 bit immediate.
741 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB) &&
742 (-Imm->getAPIntValue()).isSignedIntN(8))
743 return false;
744
745 if ((U->getOpcode() == X86ISD::ADD || U->getOpcode() == X86ISD::SUB) &&
746 (-Imm->getAPIntValue()).isSignedIntN(8) &&
747 hasNoCarryFlagUses(SDValue(U, 1)))
748 return false;
749 }
750
751 // If the other operand is a TLS address, we should fold it instead.
752 // This produces
753 // movl %gs:0, %eax
754 // leal i@NTPOFF(%eax), %eax
755 // instead of
756 // movl $i@NTPOFF, %eax
757 // addl %gs:0, %eax
758 // if the block also has an access to a second TLS address this will save
759 // a load.
760 // FIXME: This is probably also true for non-TLS addresses.
761 if (Op1.getOpcode() == X86ISD::Wrapper) {
762 SDValue Val = Op1.getOperand(0);
764 return false;
765 }
766
767 // Don't fold load if this matches the BTS/BTR/BTC patterns.
768 // BTS: (or X, (shl 1, n))
769 // BTR: (and X, (rotl -2, n))
770 // BTC: (xor X, (shl 1, n))
771 if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {
772 if (U->getOperand(0).getOpcode() == ISD::SHL &&
773 isOneConstant(U->getOperand(0).getOperand(0)))
774 return false;
775
776 if (U->getOperand(1).getOpcode() == ISD::SHL &&
777 isOneConstant(U->getOperand(1).getOperand(0)))
778 return false;
779 }
780 if (U->getOpcode() == ISD::AND) {
781 SDValue U0 = U->getOperand(0);
782 SDValue U1 = U->getOperand(1);
783 if (U0.getOpcode() == ISD::ROTL) {
785 if (C && C->getSExtValue() == -2)
786 return false;
787 }
788
789 if (U1.getOpcode() == ISD::ROTL) {
791 if (C && C->getSExtValue() == -2)
792 return false;
793 }
794 }
795
796 break;
797 }
798 case ISD::SHL:
799 case ISD::SRA:
800 case ISD::SRL:
801 // Don't fold a load into a shift by immediate. The BMI2 instructions
802 // support folding a load, but not an immediate. The legacy instructions
803 // support folding an immediate, but can't fold a load. Folding an
804 // immediate is preferable to folding a load.
805 if (isa<ConstantSDNode>(U->getOperand(1)))
806 return false;
807
808 break;
809 }
810 }
811
812 // Prevent folding a load if this can implemented with an insert_subreg or
813 // a move that implicitly zeroes.
814 if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&
815 isNullConstant(Root->getOperand(2)) &&
816 (Root->getOperand(0).isUndef() ||
818 return false;
819
820 return true;
821}
822
823// Indicates it is profitable to form an AVX512 masked operation. Returning
824// false will favor a masked register-register masked move or vblendm and the
825// operation will be selected separately.
826bool X86DAGToDAGISel::isProfitableToFormMaskedOp(SDNode *N) const {
827 assert(
828 (N->getOpcode() == ISD::VSELECT || N->getOpcode() == X86ISD::SELECTS) &&
829 "Unexpected opcode!");
830
831 // If the operation has additional users, the operation will be duplicated.
832 // Check the use count to prevent that.
833 // FIXME: Are there cheap opcodes we might want to duplicate?
834 return N->getOperand(1).hasOneUse();
835}
836
837/// Replace the original chain operand of the call with
838/// load's chain operand and move load below the call's chain operand.
840 SDValue Call, SDValue OrigChain) {
842 SDValue Chain = OrigChain.getOperand(0);
843 if (Chain.getNode() == Load.getNode())
844 Ops.push_back(Load.getOperand(0));
845 else {
846 assert(Chain.getOpcode() == ISD::TokenFactor &&
847 "Unexpected chain operand");
848 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
849 if (Chain.getOperand(i).getNode() == Load.getNode())
850 Ops.push_back(Load.getOperand(0));
851 else
852 Ops.push_back(Chain.getOperand(i));
853 SDValue NewChain =
854 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
855 Ops.clear();
856 Ops.push_back(NewChain);
857 }
858 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
859 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
860 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
861 Load.getOperand(1), Load.getOperand(2));
862
863 Ops.clear();
864 Ops.push_back(SDValue(Load.getNode(), 1));
865 Ops.append(Call->op_begin() + 1, Call->op_end());
866 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
867}
868
869/// Return true if call address is a load and it can be
870/// moved below CALLSEQ_START and the chains leading up to the call.
871/// Return the CALLSEQ_START by reference as a second output.
872/// In the case of a tail call, there isn't a callseq node between the call
873/// chain and the load.
874static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
875 // The transformation is somewhat dangerous if the call's chain was glued to
876 // the call. After MoveBelowOrigChain the load is moved between the call and
877 // the chain, this can create a cycle if the load is not folded. So it is
878 // *really* important that we are sure the load will be folded.
879 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
880 return false;
881 auto *LD = dyn_cast<LoadSDNode>(Callee.getNode());
882 if (!LD ||
883 !LD->isSimple() ||
884 LD->getAddressingMode() != ISD::UNINDEXED ||
885 LD->getExtensionType() != ISD::NON_EXTLOAD)
886 return false;
887
888 // If the load's outgoing chain has more than one use, we can't (currently)
889 // move the load since we'd most likely create a loop. TODO: Maybe it could
890 // work if moveBelowOrigChain() updated *all* the chain users.
891 if (!Callee.getValue(1).hasOneUse())
892 return false;
893
894 // Now let's find the callseq_start.
895 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
896 if (!Chain.hasOneUse())
897 return false;
898 Chain = Chain.getOperand(0);
899 }
900
901 while (true) {
902 if (!Chain.getNumOperands())
903 return false;
904
905 // It's not safe to move the callee (a load) across e.g. a store.
906 // Conservatively abort if the chain contains a node other than the ones
907 // below.
908 switch (Chain.getNode()->getOpcode()) {
910 case ISD::CopyToReg:
911 case ISD::LOAD:
912 break;
913 default:
914 return false;
915 }
916
917 if (Chain.getOperand(0).getNode() == Callee.getNode())
918 return true;
919 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
920 Chain.getOperand(0).getValue(0).hasOneUse() &&
921 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
922 Callee.getValue(1).hasOneUse())
923 return true;
924
925 // Look past CopyToRegs. We only walk one path, so the chain mustn't branch.
926 if (Chain.getOperand(0).getOpcode() == ISD::CopyToReg &&
927 Chain.getOperand(0).getValue(0).hasOneUse()) {
928 Chain = Chain.getOperand(0);
929 continue;
930 }
931
932 return false;
933 }
934}
935
936static bool isEndbrImm(uint64_t Imm, unsigned BitWidth) {
937 if (BitWidth > 64 || BitWidth % 8 != 0)
938 return false;
939
940 const unsigned NumBytes = BitWidth / 8;
941 if (NumBytes < 4)
942 return false;
943
944 const uint8_t OptionalPrefixBytes[] = {0x26, 0x2e, 0x36, 0x3e, 0x64,
945 0x65, 0x66, 0x67, 0xf0, 0xf2};
946 uint8_t Bytes[8];
947 for (unsigned I = 0; I != NumBytes; ++I)
948 Bytes[I] = (Imm >> (I * 8)) & 0xFF;
949
950 for (unsigned I = 0; I + 3 < NumBytes; ++I) {
951 if (Bytes[I] != 0xf3)
952 continue;
953
954 unsigned J = I + 1;
955 while (J < NumBytes && llvm::is_contained(OptionalPrefixBytes, Bytes[J]))
956 ++J;
957
958 if (J + 2 < NumBytes && Bytes[J] == 0x0f && Bytes[J + 1] == 0x1e &&
959 (Bytes[J + 2] == 0xfa || Bytes[J + 2] == 0xfb))
960 return true;
961 }
962
963 return false;
964}
965
966static bool needBWI(MVT VT) {
967 return (VT == MVT::v32i16 || VT == MVT::v32f16 || VT == MVT::v64i8);
968}
969
970void X86DAGToDAGISel::PreprocessISelDAG() {
971 bool MadeChange = false;
972 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
973 E = CurDAG->allnodes_end(); I != E; ) {
974 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
975
976 // This is for CET enhancement.
977 //
978 // ENDBR32 and ENDBR64 have specific opcodes:
979 // ENDBR32: F3 0F 1E FB
980 // ENDBR64: F3 0F 1E FA
981 // We want to prevent attackers from finding unintended ENDBR32/64 opcode
982 // matches in executable code. Here's an example:
983 // If the compiler had to generate asm for the following code:
984 // a = 0xFA1E0FF3
985 // it could, for example, generate:
986 // mov 0xFA1E0FF3, dword ptr[a]
987 // In such a case, the binary would include a gadget that starts with a
988 // fake ENDBR64 opcode. Split such constants into multiple operations so
989 // the byte sequence does not appear in executable code.
990 if (N->getOpcode() == ISD::Constant) {
991 MVT VT = N->getSimpleValueType(0);
992 assert(VT.isScalarInteger() &&
993 "ISD::Constant must have a scalar integer type");
994 if (!VT.isScalarInteger() || VT.getSizeInBits() > 64)
995 continue;
996
997 uint64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
998 if (isEndbrImm(Imm, VT.getSizeInBits())) {
999 // Check that the cf-protection-branch is enabled.
1000 Metadata *CFProtectionBranch =
1002 "cf-protection-branch");
1003 if (CFProtectionBranch || IndirectBranchTracking) {
1004 SDLoc dl(N);
1005 uint64_t ComplementImm =
1007 SDValue Complement =
1008 CurDAG->getConstant(ComplementImm, dl, VT, false, true);
1009 Complement = CurDAG->getNOT(dl, Complement, VT);
1010 --I;
1011 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Complement);
1012 ++I;
1013 MadeChange = true;
1014 continue;
1015 }
1016 }
1017 }
1018
1019 // If this is a target specific AND node with no flag usages, turn it back
1020 // into ISD::AND to enable test instruction matching.
1021 if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
1022 SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
1023 N->getOperand(0), N->getOperand(1));
1024 --I;
1025 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1026 ++I;
1027 MadeChange = true;
1028 continue;
1029 }
1030
1031 // Convert vector increment or decrement to sub/add with an all-ones
1032 // constant:
1033 // add X, <1, 1...> --> sub X, <-1, -1...>
1034 // sub X, <1, 1...> --> add X, <-1, -1...>
1035 // The all-ones vector constant can be materialized using a pcmpeq
1036 // instruction that is commonly recognized as an idiom (has no register
1037 // dependency), so that's better/smaller than loading a splat 1 constant.
1038 //
1039 // But don't do this if it would inhibit a potentially profitable load
1040 // folding opportunity for the other operand. That only occurs with the
1041 // intersection of:
1042 // (1) The other operand (op0) is load foldable.
1043 // (2) The op is an add (otherwise, we are *creating* an add and can still
1044 // load fold the other op).
1045 // (3) The target has AVX (otherwise, we have a destructive add and can't
1046 // load fold the other op without killing the constant op).
1047 // (4) The constant 1 vector has multiple uses (so it is profitable to load
1048 // into a register anyway).
1049 auto mayPreventLoadFold = [&]() {
1050 return X86::mayFoldLoad(N->getOperand(0), *Subtarget) &&
1051 N->getOpcode() == ISD::ADD && Subtarget->hasAVX() &&
1052 !N->getOperand(1).hasOneUse();
1053 };
1054 if ((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
1055 N->getSimpleValueType(0).isVector() && !mayPreventLoadFold()) {
1056 APInt SplatVal;
1058 peekThroughBitcasts(N->getOperand(0)).getNode()) &&
1059 X86::isConstantSplat(N->getOperand(1), SplatVal) &&
1060 SplatVal.isOne()) {
1061 SDLoc DL(N);
1062
1063 MVT VT = N->getSimpleValueType(0);
1064 unsigned NumElts = VT.getSizeInBits() / 32;
1066 CurDAG->getAllOnesConstant(DL, MVT::getVectorVT(MVT::i32, NumElts));
1067 AllOnes = CurDAG->getBitcast(VT, AllOnes);
1068
1069 unsigned NewOpcode = N->getOpcode() == ISD::ADD ? ISD::SUB : ISD::ADD;
1070 SDValue Res =
1071 CurDAG->getNode(NewOpcode, DL, VT, N->getOperand(0), AllOnes);
1072 --I;
1073 CurDAG->ReplaceAllUsesWith(N, Res.getNode());
1074 ++I;
1075 MadeChange = true;
1076 continue;
1077 }
1078 }
1079
1080 switch (N->getOpcode()) {
1081 case X86ISD::VBROADCAST: {
1082 MVT VT = N->getSimpleValueType(0);
1083 // Emulate v32i16/v64i8 broadcast without BWI.
1084 if (!Subtarget->hasBWI() && needBWI(VT)) {
1085 MVT NarrowVT = VT.getHalfNumVectorElementsVT();
1086 SDLoc dl(N);
1087 SDValue NarrowBCast =
1088 CurDAG->getNode(X86ISD::VBROADCAST, dl, NarrowVT, N->getOperand(0));
1089 SDValue Res =
1090 CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),
1091 NarrowBCast, CurDAG->getIntPtrConstant(0, dl));
1092 unsigned Index = NarrowVT.getVectorMinNumElements();
1093 Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,
1094 CurDAG->getIntPtrConstant(Index, dl));
1095
1096 --I;
1097 CurDAG->ReplaceAllUsesWith(N, Res.getNode());
1098 ++I;
1099 MadeChange = true;
1100 continue;
1101 }
1102
1103 break;
1104 }
1105 case X86ISD::VBROADCAST_LOAD: {
1106 MVT VT = N->getSimpleValueType(0);
1107 // Emulate v32i16/v64i8 broadcast without BWI.
1108 if (!Subtarget->hasBWI() && needBWI(VT)) {
1109 MVT NarrowVT = VT.getHalfNumVectorElementsVT();
1110 auto *MemNode = cast<MemSDNode>(N);
1111 SDLoc dl(N);
1112 SDVTList VTs = CurDAG->getVTList(NarrowVT, MVT::Other);
1113 SDValue Ops[] = {MemNode->getChain(), MemNode->getBasePtr()};
1114 SDValue NarrowBCast = CurDAG->getMemIntrinsicNode(
1115 X86ISD::VBROADCAST_LOAD, dl, VTs, Ops, MemNode->getMemoryVT(),
1116 MemNode->getMemOperand());
1117 SDValue Res =
1118 CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),
1119 NarrowBCast, CurDAG->getIntPtrConstant(0, dl));
1120 unsigned Index = NarrowVT.getVectorMinNumElements();
1121 Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,
1122 CurDAG->getIntPtrConstant(Index, dl));
1123
1124 --I;
1125 SDValue To[] = {Res, NarrowBCast.getValue(1)};
1126 CurDAG->ReplaceAllUsesWith(N, To);
1127 ++I;
1128 MadeChange = true;
1129 continue;
1130 }
1131
1132 break;
1133 }
1134 case ISD::LOAD: {
1135 // If this is a XMM/YMM load of the same lower bits as another YMM/ZMM
1136 // load, then just extract the lower subvector and avoid the second load.
1137 auto *Ld = cast<LoadSDNode>(N);
1138 MVT VT = N->getSimpleValueType(0);
1139 if (!ISD::isNormalLoad(Ld) || !Ld->isSimple() ||
1140 !(VT.is128BitVector() || VT.is256BitVector()))
1141 break;
1142
1143 MVT MaxVT = VT;
1144 SDNode *MaxLd = nullptr;
1145 SDValue Ptr = Ld->getBasePtr();
1146 SDValue Chain = Ld->getChain();
1147 for (SDNode *User : Ptr->users()) {
1148 auto *UserLd = dyn_cast<LoadSDNode>(User);
1149 MVT UserVT = User->getSimpleValueType(0);
1150 if (User != N && UserLd && ISD::isNormalLoad(User) &&
1151 UserLd->getBasePtr() == Ptr && UserLd->getChain() == Chain &&
1152 !User->hasAnyUseOfValue(1) &&
1153 (UserVT.is256BitVector() || UserVT.is512BitVector()) &&
1154 UserVT.getSizeInBits() > VT.getSizeInBits() &&
1155 (!MaxLd || UserVT.getSizeInBits() > MaxVT.getSizeInBits())) {
1156 MaxLd = User;
1157 MaxVT = UserVT;
1158 }
1159 }
1160 if (MaxLd) {
1161 SDLoc dl(N);
1162 unsigned NumSubElts = VT.getSizeInBits() / MaxVT.getScalarSizeInBits();
1163 MVT SubVT = MVT::getVectorVT(MaxVT.getScalarType(), NumSubElts);
1164 SDValue Extract = CurDAG->getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT,
1165 SDValue(MaxLd, 0),
1166 CurDAG->getIntPtrConstant(0, dl));
1167 SDValue Res = CurDAG->getBitcast(VT, Extract);
1168
1169 --I;
1170 SDValue To[] = {Res, SDValue(MaxLd, 1)};
1171 CurDAG->ReplaceAllUsesWith(N, To);
1172 ++I;
1173 MadeChange = true;
1174 continue;
1175 }
1176 break;
1177 }
1178 case ISD::VSELECT: {
1179 // Replace VSELECT with non-mask conditions with with BLENDV/VPTERNLOG.
1180 EVT EleVT = N->getOperand(0).getValueType().getVectorElementType();
1181 if (EleVT == MVT::i1)
1182 break;
1183
1184 assert(Subtarget->hasSSE41() && "Expected SSE4.1 support!");
1185 assert(N->getValueType(0).getVectorElementType() != MVT::i16 &&
1186 "We can't replace VSELECT with BLENDV in vXi16!");
1187 SDValue R;
1188 if (Subtarget->hasVLX() && CurDAG->ComputeNumSignBits(N->getOperand(0)) ==
1189 EleVT.getSizeInBits()) {
1190 R = CurDAG->getNode(X86ISD::VPTERNLOG, SDLoc(N), N->getValueType(0),
1191 N->getOperand(0), N->getOperand(1), N->getOperand(2),
1192 CurDAG->getTargetConstant(0xCA, SDLoc(N), MVT::i8));
1193 } else {
1194 R = CurDAG->getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0),
1195 N->getOperand(0), N->getOperand(1),
1196 N->getOperand(2));
1197 }
1198 --I;
1199 CurDAG->ReplaceAllUsesWith(N, R.getNode());
1200 ++I;
1201 MadeChange = true;
1202 continue;
1203 }
1204 case ISD::FP_ROUND:
1206 case ISD::FP_TO_SINT:
1207 case ISD::FP_TO_UINT:
1210 // Replace vector fp_to_s/uint with their X86 specific equivalent so we
1211 // don't need 2 sets of patterns.
1212 if (!N->getSimpleValueType(0).isVector())
1213 break;
1214
1215 unsigned NewOpc;
1216 switch (N->getOpcode()) {
1217 default: llvm_unreachable("Unexpected opcode!");
1218 case ISD::FP_ROUND: NewOpc = X86ISD::VFPROUND; break;
1219 case ISD::STRICT_FP_ROUND: NewOpc = X86ISD::STRICT_VFPROUND; break;
1220 case ISD::STRICT_FP_TO_SINT: NewOpc = X86ISD::STRICT_CVTTP2SI; break;
1221 case ISD::FP_TO_SINT: NewOpc = X86ISD::CVTTP2SI; break;
1222 case ISD::STRICT_FP_TO_UINT: NewOpc = X86ISD::STRICT_CVTTP2UI; break;
1223 case ISD::FP_TO_UINT: NewOpc = X86ISD::CVTTP2UI; break;
1224 }
1225 SDValue Res;
1226 if (N->isStrictFPOpcode())
1227 Res =
1228 CurDAG->getNode(NewOpc, SDLoc(N), {N->getValueType(0), MVT::Other},
1229 {N->getOperand(0), N->getOperand(1)});
1230 else
1231 Res =
1232 CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
1233 N->getOperand(0));
1234 --I;
1235 CurDAG->ReplaceAllUsesWith(N, Res.getNode());
1236 ++I;
1237 MadeChange = true;
1238 continue;
1239 }
1240 case ISD::SHL:
1241 case ISD::SRA:
1242 case ISD::SRL: {
1243 // Replace vector shifts with their X86 specific equivalent so we don't
1244 // need 2 sets of patterns.
1245 if (!N->getValueType(0).isVector())
1246 break;
1247
1248 unsigned NewOpc;
1249 switch (N->getOpcode()) {
1250 default: llvm_unreachable("Unexpected opcode!");
1251 case ISD::SHL: NewOpc = X86ISD::VSHLV; break;
1252 case ISD::SRA: NewOpc = X86ISD::VSRAV; break;
1253 case ISD::SRL: NewOpc = X86ISD::VSRLV; break;
1254 }
1255 SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
1256 N->getOperand(0), N->getOperand(1));
1257 --I;
1258 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1259 ++I;
1260 MadeChange = true;
1261 continue;
1262 }
1263 case ISD::ANY_EXTEND:
1265 // Replace vector any extend with the zero extend equivalents so we don't
1266 // need 2 sets of patterns. Ignore vXi1 extensions.
1267 if (!N->getValueType(0).isVector())
1268 break;
1269
1270 unsigned NewOpc;
1271 if (N->getOperand(0).getScalarValueSizeInBits() == 1) {
1272 assert(N->getOpcode() == ISD::ANY_EXTEND &&
1273 "Unexpected opcode for mask vector!");
1274 NewOpc = ISD::SIGN_EXTEND;
1275 } else {
1276 NewOpc = N->getOpcode() == ISD::ANY_EXTEND
1279 }
1280
1281 SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
1282 N->getOperand(0));
1283 --I;
1284 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1285 ++I;
1286 MadeChange = true;
1287 continue;
1288 }
1289 case ISD::FCEIL:
1290 case ISD::STRICT_FCEIL:
1291 case ISD::FFLOOR:
1292 case ISD::STRICT_FFLOOR:
1293 case ISD::FTRUNC:
1294 case ISD::STRICT_FTRUNC:
1295 case ISD::FROUNDEVEN:
1297 case ISD::FNEARBYINT:
1299 case ISD::FRINT:
1300 case ISD::STRICT_FRINT: {
1301 // Replace fp rounding with their X86 specific equivalent so we don't
1302 // need 2 sets of patterns.
1303 unsigned Imm;
1304 switch (N->getOpcode()) {
1305 default: llvm_unreachable("Unexpected opcode!");
1306 case ISD::STRICT_FCEIL:
1307 case ISD::FCEIL: Imm = 0xA; break;
1308 case ISD::STRICT_FFLOOR:
1309 case ISD::FFLOOR: Imm = 0x9; break;
1310 case ISD::STRICT_FTRUNC:
1311 case ISD::FTRUNC: Imm = 0xB; break;
1313 case ISD::FROUNDEVEN: Imm = 0x8; break;
1315 case ISD::FNEARBYINT: Imm = 0xC; break;
1316 case ISD::STRICT_FRINT:
1317 case ISD::FRINT: Imm = 0x4; break;
1318 }
1319 SDLoc dl(N);
1320 bool IsStrict = N->isStrictFPOpcode();
1321 SDValue Res;
1322 if (IsStrict)
1323 Res = CurDAG->getNode(X86ISD::STRICT_VRNDSCALE, dl,
1324 {N->getValueType(0), MVT::Other},
1325 {N->getOperand(0), N->getOperand(1),
1326 CurDAG->getTargetConstant(Imm, dl, MVT::i32)});
1327 else
1328 Res = CurDAG->getNode(X86ISD::VRNDSCALE, dl, N->getValueType(0),
1329 N->getOperand(0),
1330 CurDAG->getTargetConstant(Imm, dl, MVT::i32));
1331 --I;
1332 CurDAG->ReplaceAllUsesWith(N, Res.getNode());
1333 ++I;
1334 MadeChange = true;
1335 continue;
1336 }
1337 case X86ISD::FANDN:
1338 case X86ISD::FAND:
1339 case X86ISD::FOR:
1340 case X86ISD::FXOR: {
1341 // Widen scalar fp logic ops to vector to reduce isel patterns.
1342 // FIXME: Can we do this during lowering/combine.
1343 MVT VT = N->getSimpleValueType(0);
1344 if (VT.isVector() || VT == MVT::f128)
1345 break;
1346
1347 MVT VecVT = VT == MVT::f64 ? MVT::v2f64
1348 : VT == MVT::f32 ? MVT::v4f32
1349 : MVT::v8f16;
1350
1351 SDLoc dl(N);
1352 SDValue Op0 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,
1353 N->getOperand(0));
1354 SDValue Op1 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,
1355 N->getOperand(1));
1356
1357 SDValue Res;
1358 if (Subtarget->hasSSE2()) {
1359 EVT IntVT = EVT(VecVT).changeVectorElementTypeToInteger();
1360 Op0 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op0);
1361 Op1 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op1);
1362 unsigned Opc;
1363 switch (N->getOpcode()) {
1364 default: llvm_unreachable("Unexpected opcode!");
1365 case X86ISD::FANDN: Opc = X86ISD::ANDNP; break;
1366 case X86ISD::FAND: Opc = ISD::AND; break;
1367 case X86ISD::FOR: Opc = ISD::OR; break;
1368 case X86ISD::FXOR: Opc = ISD::XOR; break;
1369 }
1370 Res = CurDAG->getNode(Opc, dl, IntVT, Op0, Op1);
1371 Res = CurDAG->getNode(ISD::BITCAST, dl, VecVT, Res);
1372 } else {
1373 Res = CurDAG->getNode(N->getOpcode(), dl, VecVT, Op0, Op1);
1374 }
1375 Res = CurDAG->getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res,
1376 CurDAG->getIntPtrConstant(0, dl));
1377 --I;
1378 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1379 ++I;
1380 MadeChange = true;
1381 continue;
1382 }
1383 }
1384
1385 if (OptLevel != CodeGenOptLevel::None &&
1386 // Only do this when the target can fold the load into the call or
1387 // jmp.
1388 !Subtarget->useIndirectThunkCalls() &&
1389 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps() &&
1390 !Subtarget->slowIndirectCall()) ||
1391 (N->getOpcode() == X86ISD::TC_RETURN &&
1392 (Subtarget->is64Bit() ||
1393 !getTargetMachine().isPositionIndependent())))) {
1394 /// Also try moving call address load from outside callseq_start to just
1395 /// before the call to allow it to be folded.
1396 ///
1397 /// [Load chain]
1398 /// ^
1399 /// |
1400 /// [Load]
1401 /// ^ ^
1402 /// | |
1403 /// / \--
1404 /// / |
1405 ///[CALLSEQ_START] |
1406 /// ^ |
1407 /// | |
1408 /// [LOAD/C2Reg] |
1409 /// | |
1410 /// \ /
1411 /// \ /
1412 /// [CALL]
1413 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
1414 SDValue Chain = N->getOperand(0);
1415 SDValue Load = N->getOperand(1);
1416 if (!isCalleeLoad(Load, Chain, HasCallSeq))
1417 continue;
1418 if (N->getOpcode() == X86ISD::TC_RETURN && !checkTCRetEnoughRegs(N))
1419 continue;
1420 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
1421 ++NumLoadMoved;
1422 MadeChange = true;
1423 continue;
1424 }
1425
1426 // Lower fpround and fpextend nodes that target the FP stack to be store and
1427 // load to the stack. This is a gross hack. We would like to simply mark
1428 // these as being illegal, but when we do that, legalize produces these when
1429 // it expands calls, then expands these in the same legalize pass. We would
1430 // like dag combine to be able to hack on these between the call expansion
1431 // and the node legalization. As such this pass basically does "really
1432 // late" legalization of these inline with the X86 isel pass.
1433 // FIXME: This should only happen when not compiled with -O0.
1434 switch (N->getOpcode()) {
1435 default: continue;
1436 case ISD::FP_ROUND:
1437 case ISD::FP_EXTEND:
1438 {
1439 MVT SrcVT = N->getOperand(0).getSimpleValueType();
1440 MVT DstVT = N->getSimpleValueType(0);
1441
1442 // If any of the sources are vectors, no fp stack involved.
1443 if (SrcVT.isVector() || DstVT.isVector())
1444 continue;
1445
1446 // If the source and destination are SSE registers, then this is a legal
1447 // conversion that should not be lowered.
1448 const X86TargetLowering *X86Lowering =
1449 static_cast<const X86TargetLowering *>(TLI);
1450 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
1451 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
1452 if (SrcIsSSE && DstIsSSE)
1453 continue;
1454
1455 if (!SrcIsSSE && !DstIsSSE) {
1456 // If this is an FPStack extension, it is a noop.
1457 if (N->getOpcode() == ISD::FP_EXTEND)
1458 continue;
1459 // If this is a value-preserving FPStack truncation, it is a noop.
1460 if (N->getConstantOperandVal(1))
1461 continue;
1462 }
1463
1464 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
1465 // FPStack has extload and truncstore. SSE can fold direct loads into other
1466 // operations. Based on this, decide what we want to do.
1467 MVT MemVT = (N->getOpcode() == ISD::FP_ROUND) ? DstVT : SrcVT;
1468 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
1469 int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();
1470 MachinePointerInfo MPI =
1471 MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);
1472 SDLoc dl(N);
1473
1474 // FIXME: optimize the case where the src/dest is a load or store?
1475
1476 SDValue Store = CurDAG->getTruncStore(
1477 CurDAG->getEntryNode(), dl, N->getOperand(0), MemTmp, MPI, MemVT);
1478 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store,
1479 MemTmp, MPI, MemVT);
1480
1481 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
1482 // extload we created. This will cause general havok on the dag because
1483 // anything below the conversion could be folded into other existing nodes.
1484 // To avoid invalidating 'I', back it up to the convert node.
1485 --I;
1486 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1487 break;
1488 }
1489
1490 //The sequence of events for lowering STRICT_FP versions of these nodes requires
1491 //dealing with the chain differently, as there is already a preexisting chain.
1494 {
1495 MVT SrcVT = N->getOperand(1).getSimpleValueType();
1496 MVT DstVT = N->getSimpleValueType(0);
1497
1498 // If any of the sources are vectors, no fp stack involved.
1499 if (SrcVT.isVector() || DstVT.isVector())
1500 continue;
1501
1502 // If the source and destination are SSE registers, then this is a legal
1503 // conversion that should not be lowered.
1504 const X86TargetLowering *X86Lowering =
1505 static_cast<const X86TargetLowering *>(TLI);
1506 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
1507 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
1508 if (SrcIsSSE && DstIsSSE)
1509 continue;
1510
1511 if (!SrcIsSSE && !DstIsSSE) {
1512 // If this is an FPStack extension, it is a noop.
1513 if (N->getOpcode() == ISD::STRICT_FP_EXTEND)
1514 continue;
1515 // If this is a value-preserving FPStack truncation, it is a noop.
1516 if (N->getConstantOperandVal(2))
1517 continue;
1518 }
1519
1520 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
1521 // FPStack has extload and truncstore. SSE can fold direct loads into other
1522 // operations. Based on this, decide what we want to do.
1523 MVT MemVT = (N->getOpcode() == ISD::STRICT_FP_ROUND) ? DstVT : SrcVT;
1524 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
1525 int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();
1526 MachinePointerInfo MPI =
1527 MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);
1528 SDLoc dl(N);
1529
1530 // FIXME: optimize the case where the src/dest is a load or store?
1531
1532 //Since the operation is StrictFP, use the preexisting chain.
1534 if (!SrcIsSSE) {
1535 SDVTList VTs = CurDAG->getVTList(MVT::Other);
1536 SDValue Ops[] = {N->getOperand(0), N->getOperand(1), MemTmp};
1537 Store = CurDAG->getMemIntrinsicNode(X86ISD::FST, dl, VTs, Ops, MemVT,
1538 MPI, /*Align*/ std::nullopt,
1540 if (N->getFlags().hasNoFPExcept()) {
1541 SDNodeFlags Flags = Store->getFlags();
1542 Flags.setNoFPExcept(true);
1543 Store->setFlags(Flags);
1544 }
1545 } else {
1546 assert(SrcVT == MemVT && "Unexpected VT!");
1547 Store = CurDAG->getStore(N->getOperand(0), dl, N->getOperand(1), MemTmp,
1548 MPI);
1549 }
1550
1551 if (!DstIsSSE) {
1552 SDVTList VTs = CurDAG->getVTList(DstVT, MVT::Other);
1553 SDValue Ops[] = {Store, MemTmp};
1554 Result = CurDAG->getMemIntrinsicNode(
1555 X86ISD::FLD, dl, VTs, Ops, MemVT, MPI,
1556 /*Align*/ std::nullopt, MachineMemOperand::MOLoad);
1557 if (N->getFlags().hasNoFPExcept()) {
1558 SDNodeFlags Flags = Result->getFlags();
1559 Flags.setNoFPExcept(true);
1560 Result->setFlags(Flags);
1561 }
1562 } else {
1563 assert(DstVT == MemVT && "Unexpected VT!");
1564 Result = CurDAG->getLoad(DstVT, dl, Store, MemTmp, MPI);
1565 }
1566
1567 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
1568 // extload we created. This will cause general havok on the dag because
1569 // anything below the conversion could be folded into other existing nodes.
1570 // To avoid invalidating 'I', back it up to the convert node.
1571 --I;
1572 CurDAG->ReplaceAllUsesWith(N, Result.getNode());
1573 break;
1574 }
1575 }
1576
1577
1578 // Now that we did that, the node is dead. Increment the iterator to the
1579 // next node to process, then delete N.
1580 ++I;
1581 MadeChange = true;
1582 }
1583
1584 // Remove any dead nodes that may have been left behind.
1585 if (MadeChange)
1586 CurDAG->RemoveDeadNodes();
1587}
1588
1589// Look for a redundant movzx/movsx that can occur after an 8-bit divrem.
1590bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) {
1591 unsigned Opc = N->getMachineOpcode();
1592 if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 &&
1593 Opc != X86::MOVSX64rr8)
1594 return false;
1595
1596 SDValue N0 = N->getOperand(0);
1597
1598 // We need to be extracting the lower bit of an extend.
1599 if (!N0.isMachineOpcode() ||
1600 N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG ||
1601 N0.getConstantOperandVal(1) != X86::sub_8bit)
1602 return false;
1603
1604 // We're looking for either a movsx or movzx to match the original opcode.
1605 unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX
1606 : X86::MOVSX32rr8_NOREX;
1607 SDValue N00 = N0.getOperand(0);
1608 if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc)
1609 return false;
1610
1611 if (Opc == X86::MOVSX64rr8) {
1612 // If we had a sign extend from 8 to 64 bits. We still need to go from 32
1613 // to 64.
1614 MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N),
1615 MVT::i64, N00);
1616 ReplaceUses(N, Extend);
1617 } else {
1618 // Ok we can drop this extend and just use the original extend.
1619 ReplaceUses(N, N00.getNode());
1620 }
1621
1622 return true;
1623}
1624
1625void X86DAGToDAGISel::PostprocessISelDAG() {
1626 // Skip peepholes at -O0.
1627 if (TM.getOptLevel() == CodeGenOptLevel::None)
1628 return;
1629
1630 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
1631
1632 bool MadeChange = false;
1633 while (Position != CurDAG->allnodes_begin()) {
1634 SDNode *N = &*--Position;
1635 // Skip dead nodes and any non-machine opcodes.
1636 if (N->use_empty() || !N->isMachineOpcode())
1637 continue;
1638
1639 if (tryOptimizeRem8Extend(N)) {
1640 MadeChange = true;
1641 continue;
1642 }
1643
1644 unsigned Opc = N->getMachineOpcode();
1645 switch (Opc) {
1646 default:
1647 continue;
1648 // ANDrr/rm + TESTrr+ -> TESTrr/TESTmr
1649 case X86::TEST8rr:
1650 case X86::TEST16rr:
1651 case X86::TEST32rr:
1652 case X86::TEST64rr:
1653 // ANDrr/rm + CTESTrr -> CTESTrr/CTESTmr
1654 case X86::CTEST8rr:
1655 case X86::CTEST16rr:
1656 case X86::CTEST32rr:
1657 case X86::CTEST64rr: {
1658 auto &Op0 = N->getOperand(0);
1659 if (Op0 != N->getOperand(1) || !Op0->hasNUsesOfValue(2, Op0.getResNo()) ||
1660 !Op0.isMachineOpcode())
1661 continue;
1662 SDValue And = N->getOperand(0);
1663#define CASE_ND(OP) \
1664 case X86::OP: \
1665 case X86::OP##_ND:
1666 switch (And.getMachineOpcode()) {
1667 default:
1668 continue;
1669 CASE_ND(AND8rr)
1670 CASE_ND(AND16rr)
1671 CASE_ND(AND32rr)
1672 CASE_ND(AND64rr) {
1673 if (And->hasAnyUseOfValue(1))
1674 continue;
1675 SmallVector<SDValue> Ops(N->op_values());
1676 Ops[0] = And.getOperand(0);
1677 Ops[1] = And.getOperand(1);
1678 MachineSDNode *Test =
1679 CurDAG->getMachineNode(Opc, SDLoc(N), MVT::i32, Ops);
1680 ReplaceUses(N, Test);
1681 MadeChange = true;
1682 continue;
1683 }
1684 CASE_ND(AND8rm)
1685 CASE_ND(AND16rm)
1686 CASE_ND(AND32rm)
1687 CASE_ND(AND64rm) {
1688 if (And->hasAnyUseOfValue(1))
1689 continue;
1690 unsigned NewOpc;
1691 bool IsCTESTCC = X86::isCTESTCC(Opc);
1692#define FROM_TO(A, B) \
1693 CASE_ND(A) NewOpc = IsCTESTCC ? X86::C##B : X86::B; \
1694 break;
1695 switch (And.getMachineOpcode()) {
1696 FROM_TO(AND8rm, TEST8mr);
1697 FROM_TO(AND16rm, TEST16mr);
1698 FROM_TO(AND32rm, TEST32mr);
1699 FROM_TO(AND64rm, TEST64mr);
1700 }
1701#undef FROM_TO
1702#undef CASE_ND
1703 // Need to swap the memory and register operand.
1704 SmallVector<SDValue> Ops = {And.getOperand(1), And.getOperand(2),
1705 And.getOperand(3), And.getOperand(4),
1706 And.getOperand(5), And.getOperand(0)};
1707 // CC, Cflags.
1708 if (IsCTESTCC) {
1709 Ops.push_back(N->getOperand(2));
1710 Ops.push_back(N->getOperand(3));
1711 }
1712 // Chain of memory load
1713 Ops.push_back(And.getOperand(6));
1714 // Glue
1715 if (IsCTESTCC)
1716 Ops.push_back(N->getOperand(4));
1717
1718 MachineSDNode *Test = CurDAG->getMachineNode(
1719 NewOpc, SDLoc(N), MVT::i32, MVT::Other, Ops);
1720 CurDAG->setNodeMemRefs(
1721 Test, cast<MachineSDNode>(And.getNode())->memoperands());
1722 ReplaceUses(And.getValue(2), SDValue(Test, 1));
1723 ReplaceUses(SDValue(N, 0), SDValue(Test, 0));
1724 MadeChange = true;
1725 continue;
1726 }
1727 }
1728 }
1729 // Look for a KAND+KORTEST and turn it into KTEST if only the zero flag is
1730 // used. We're doing this late so we can prefer to fold the AND into masked
1731 // comparisons. Doing that can be better for the live range of the mask
1732 // register.
1733 case X86::KORTESTBkk:
1734 case X86::KORTESTWkk:
1735 case X86::KORTESTDkk:
1736 case X86::KORTESTQkk: {
1737 SDValue Op0 = N->getOperand(0);
1738 if (Op0 != N->getOperand(1) || !N->isOnlyUserOf(Op0.getNode()) ||
1739 !Op0.isMachineOpcode() || !onlyUsesZeroFlag(SDValue(N, 0)))
1740 continue;
1741#define CASE(A) \
1742 case X86::A: \
1743 break;
1744 switch (Op0.getMachineOpcode()) {
1745 default:
1746 continue;
1747 CASE(KANDBkk)
1748 CASE(KANDWkk)
1749 CASE(KANDDkk)
1750 CASE(KANDQkk)
1751 }
1752 unsigned NewOpc;
1753#define FROM_TO(A, B) \
1754 case X86::A: \
1755 NewOpc = X86::B; \
1756 break;
1757 switch (Opc) {
1758 FROM_TO(KORTESTBkk, KTESTBkk)
1759 FROM_TO(KORTESTWkk, KTESTWkk)
1760 FROM_TO(KORTESTDkk, KTESTDkk)
1761 FROM_TO(KORTESTQkk, KTESTQkk)
1762 }
1763 // KANDW is legal with AVX512F, but KTESTW requires AVX512DQ. The other
1764 // KAND instructions and KTEST use the same ISA feature.
1765 if (NewOpc == X86::KTESTWkk && !Subtarget->hasDQI())
1766 continue;
1767#undef FROM_TO
1768 MachineSDNode *KTest = CurDAG->getMachineNode(
1769 NewOpc, SDLoc(N), MVT::i32, Op0.getOperand(0), Op0.getOperand(1));
1770 ReplaceUses(N, KTest);
1771 MadeChange = true;
1772 continue;
1773 }
1774 // Attempt to remove vectors moves that were inserted to zero upper bits.
1775 case TargetOpcode::SUBREG_TO_REG: {
1776 unsigned SubRegIdx = N->getConstantOperandVal(1);
1777 if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
1778 continue;
1779
1780 SDValue Move = N->getOperand(0);
1781 if (!Move.isMachineOpcode())
1782 continue;
1783
1784 // Make sure its one of the move opcodes we recognize.
1785 switch (Move.getMachineOpcode()) {
1786 default:
1787 continue;
1788 CASE(VMOVAPDrr) CASE(VMOVUPDrr)
1789 CASE(VMOVAPSrr) CASE(VMOVUPSrr)
1790 CASE(VMOVDQArr) CASE(VMOVDQUrr)
1791 CASE(VMOVAPDYrr) CASE(VMOVUPDYrr)
1792 CASE(VMOVAPSYrr) CASE(VMOVUPSYrr)
1793 CASE(VMOVDQAYrr) CASE(VMOVDQUYrr)
1794 CASE(VMOVAPDZ128rr) CASE(VMOVUPDZ128rr)
1795 CASE(VMOVAPSZ128rr) CASE(VMOVUPSZ128rr)
1796 CASE(VMOVDQA32Z128rr) CASE(VMOVDQU32Z128rr)
1797 CASE(VMOVDQA64Z128rr) CASE(VMOVDQU64Z128rr)
1798 CASE(VMOVAPDZ256rr) CASE(VMOVUPDZ256rr)
1799 CASE(VMOVAPSZ256rr) CASE(VMOVUPSZ256rr)
1800 CASE(VMOVDQA32Z256rr) CASE(VMOVDQU32Z256rr)
1801 CASE(VMOVDQA64Z256rr) CASE(VMOVDQU64Z256rr)
1802 }
1803#undef CASE
1804
1805 SDValue In = Move.getOperand(0);
1806 if (!In.isMachineOpcode() ||
1807 In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
1808 continue;
1809
1810 // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers
1811 // the SHA instructions which use a legacy encoding.
1812 uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags;
1813 if ((TSFlags & X86II::EncodingMask) != X86II::VEX &&
1814 (TSFlags & X86II::EncodingMask) != X86II::EVEX &&
1815 (TSFlags & X86II::EncodingMask) != X86II::XOP)
1816 continue;
1817
1818 // Producing instruction is another vector instruction. We can drop the
1819 // move.
1820 CurDAG->UpdateNodeOperands(N, In, N->getOperand(1));
1821 MadeChange = true;
1822 }
1823 }
1824 }
1825
1826 if (MadeChange)
1827 CurDAG->RemoveDeadNodes();
1828}
1829
1830
1831/// Emit any code that needs to be executed only in the main function.
1832void X86DAGToDAGISel::emitSpecialCodeForMain() {
1833 if (Subtarget->isTargetCygMing()) {
1834 TargetLowering::ArgListTy Args;
1835 auto &DL = CurDAG->getDataLayout();
1836
1837 TargetLowering::CallLoweringInfo CLI(*CurDAG);
1838 CLI.setChain(CurDAG->getRoot())
1839 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
1840 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
1841 std::move(Args));
1842 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
1843 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
1844 CurDAG->setRoot(Result.second);
1845 }
1846}
1847
1848void X86DAGToDAGISel::emitFunctionEntryCode() {
1849 // If this is main, emit special code for main.
1850 const Function &F = MF->getFunction();
1851 if (F.hasExternalLinkage() && F.getName() == "main")
1852 emitSpecialCodeForMain();
1853}
1854
1855static bool isDispSafeForFrameIndexOrRegBase(int64_t Val) {
1856 // We can run into an issue where a frame index or a register base
1857 // includes a displacement that, when added to the explicit displacement,
1858 // will overflow the displacement field. Assuming that the
1859 // displacement fits into a 31-bit integer (which is only slightly more
1860 // aggressive than the current fundamental assumption that it fits into
1861 // a 32-bit integer), a 31-bit disp should always be safe.
1862 return isInt<31>(Val);
1863}
1864
1865bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
1866 X86ISelAddressMode &AM) {
1867 // We may have already matched a displacement and the caller just added the
1868 // symbolic displacement. So we still need to do the checks even if Offset
1869 // is zero.
1870
1871 int64_t Val = AM.Disp + Offset;
1872
1873 // Cannot combine ExternalSymbol displacements with integer offsets.
1874 if (Val != 0 && (AM.ES || AM.MCSym))
1875 return true;
1876
1877 CodeModel::Model M = TM.getCodeModel();
1878 if (Subtarget->is64Bit()) {
1879 if (Val != 0 &&
1881 AM.hasSymbolicDisplacement()))
1882 return true;
1883 // In addition to the checks required for a register base, check that
1884 // we do not try to use an unsafe Disp with a frame index.
1885 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
1887 return true;
1888 // In ILP32 (x32) mode, pointers are 32 bits and need to be zero-extended to
1889 // 64 bits. Instructions with 32-bit register addresses perform this zero
1890 // extension for us and we can safely ignore the high bits of Offset.
1891 // Instructions with only a 32-bit immediate address do not, though: they
1892 // sign extend instead. This means only address the low 2GB of address space
1893 // is directly addressable, we need indirect addressing for the high 2GB of
1894 // address space.
1895 // TODO: Some of the earlier checks may be relaxed for ILP32 mode as the
1896 // implicit zero extension of instructions would cover up any problem.
1897 // However, we have asserts elsewhere that get triggered if we do, so keep
1898 // the checks for now.
1899 // TODO: We would actually be able to accept these, as well as the same
1900 // addresses in LP64 mode, by adding the EIZ pseudo-register as an operand
1901 // to get an address size override to be emitted. However, this
1902 // pseudo-register is not part of any register class and therefore causes
1903 // MIR verification to fail.
1904 if (Subtarget->isTarget64BitILP32() &&
1905 !isDispSafeForFrameIndexOrRegBase((uint32_t)Val) &&
1906 !AM.hasBaseOrIndexReg())
1907 return true;
1908 } else if (Subtarget->is16Bit()) {
1909 // In 16-bit mode, displacements are limited to [-65535,65535] for FK_Data_2
1910 // fixups of unknown signedness. See X86AsmBackend::applyFixup.
1911 if (Val < -(int64_t)UINT16_MAX || Val > (int64_t)UINT16_MAX)
1912 return true;
1913 } else if (AM.hasBaseOrIndexReg() && !isDispSafeForFrameIndexOrRegBase(Val))
1914 // For 32-bit X86, make sure the displacement still isn't close to the
1915 // expressible limit.
1916 return true;
1917 AM.Disp = Val;
1918 return false;
1919}
1920
1921bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM,
1922 bool AllowSegmentRegForX32) {
1923 SDValue Address = N->getOperand(1);
1924
1925 // load gs:0 -> GS segment register.
1926 // load fs:0 -> FS segment register.
1927 //
1928 // This optimization is generally valid because the GNU TLS model defines that
1929 // gs:0 (or fs:0 on X86-64) contains its own address. However, for X86-64 mode
1930 // with 32-bit registers, as we get in ILP32 mode, those registers are first
1931 // zero-extended to 64 bits and then added it to the base address, which gives
1932 // unwanted results when the register holds a negative value.
1933 // For more information see http://people.redhat.com/drepper/tls.pdf
1934 if (isNullConstant(Address) && AM.Segment.getNode() == nullptr &&
1935 !IndirectTlsSegRefs &&
1936 (Subtarget->isTargetGlibc() || Subtarget->isTargetMusl() ||
1937 Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())) {
1938 if (Subtarget->isTarget64BitILP32() && !AllowSegmentRegForX32)
1939 return true;
1940 switch (N->getPointerInfo().getAddrSpace()) {
1941 case X86AS::GS:
1942 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1943 return false;
1944 case X86AS::FS:
1945 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1946 return false;
1947 // Address space X86AS::SS is not handled here, because it is not used to
1948 // address TLS areas.
1949 }
1950 }
1951
1952 return true;
1953}
1954
1955/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
1956/// mode. These wrap things that will resolve down into a symbol reference.
1957/// If no match is possible, this returns true, otherwise it returns false.
1958bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
1959 // If the addressing mode already has a symbol as the displacement, we can
1960 // never match another symbol.
1961 if (AM.hasSymbolicDisplacement())
1962 return true;
1963
1964 bool IsRIPRelTLS = false;
1965 bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;
1966 if (IsRIPRel) {
1967 SDValue Val = N.getOperand(0);
1969 IsRIPRelTLS = true;
1970 }
1971
1972 // We can't use an addressing mode in the 64-bit large code model.
1973 // Global TLS addressing is an exception. In the medium code model,
1974 // we use can use a mode when RIP wrappers are present.
1975 // That signifies access to globals that are known to be "near",
1976 // such as the GOT itself.
1977 CodeModel::Model M = TM.getCodeModel();
1978 if (Subtarget->is64Bit() && M == CodeModel::Large && !IsRIPRelTLS)
1979 return true;
1980
1981 // Base and index reg must be 0 in order to use %rip as base.
1982 if (IsRIPRel && AM.hasBaseOrIndexReg())
1983 return true;
1984
1985 // Make a local copy in case we can't do this fold.
1986 X86ISelAddressMode Backup = AM;
1987
1988 int64_t Offset = 0;
1989 SDValue N0 = N.getOperand(0);
1990 if (auto *G = dyn_cast<GlobalAddressSDNode>(N0)) {
1991 AM.GV = G->getGlobal();
1992 AM.SymbolFlags = G->getTargetFlags();
1993 Offset = G->getOffset();
1994 } else if (auto *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
1995 AM.CP = CP->getConstVal();
1996 AM.Alignment = CP->getAlign();
1997 AM.SymbolFlags = CP->getTargetFlags();
1998 Offset = CP->getOffset();
1999 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
2000 AM.ES = S->getSymbol();
2001 AM.SymbolFlags = S->getTargetFlags();
2002 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
2003 AM.MCSym = S->getMCSymbol();
2004 } else if (auto *J = dyn_cast<JumpTableSDNode>(N0)) {
2005 AM.JT = J->getIndex();
2006 AM.SymbolFlags = J->getTargetFlags();
2007 } else if (auto *BA = dyn_cast<BlockAddressSDNode>(N0)) {
2008 AM.BlockAddr = BA->getBlockAddress();
2009 AM.SymbolFlags = BA->getTargetFlags();
2010 Offset = BA->getOffset();
2011 } else
2012 llvm_unreachable("Unhandled symbol reference node.");
2013
2014 // Can't use an addressing mode with large globals.
2015 if (Subtarget->is64Bit() && !IsRIPRel && AM.GV &&
2016 TM.isLargeGlobalValue(AM.GV)) {
2017 AM = Backup;
2018 return true;
2019 }
2020
2021 if (foldOffsetIntoAddress(Offset, AM)) {
2022 AM = Backup;
2023 return true;
2024 }
2025
2026 if (IsRIPRel)
2027 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
2028
2029 // Commit the changes now that we know this fold is safe.
2030 return false;
2031}
2032
2033/// Add the specified node to the specified addressing mode, returning true if
2034/// it cannot be done. This just pattern matches for the addressing mode.
2035bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
2036 if (matchAddressRecursively(N, AM, 0))
2037 return true;
2038
2039 // Post-processing: Make a second attempt to fold a load, if we now know
2040 // that there will not be any other register. This is only performed for
2041 // 64-bit ILP32 mode since 32-bit mode and 64-bit LP64 mode will have folded
2042 // any foldable load the first time.
2043 if (Subtarget->isTarget64BitILP32() &&
2044 AM.BaseType == X86ISelAddressMode::RegBase &&
2045 AM.Base_Reg.getNode() != nullptr && AM.IndexReg.getNode() == nullptr) {
2046 SDValue Save_Base_Reg = AM.Base_Reg;
2047 if (auto *LoadN = dyn_cast<LoadSDNode>(Save_Base_Reg)) {
2048 AM.Base_Reg = SDValue();
2049 if (matchLoadInAddress(LoadN, AM, /*AllowSegmentRegForX32=*/true))
2050 AM.Base_Reg = Save_Base_Reg;
2051 }
2052 }
2053
2054 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
2055 // a smaller encoding and avoids a scaled-index. Not valid when the index is
2056 // negated: this copies the index into the base, but only the index is negated
2057 // when the address is emitted, so the result would be index + (-index) - that
2058 // is, zero - rather than (-index) * 2.
2059 if (AM.Scale == 2 && !AM.NegateIndex &&
2060 AM.BaseType == X86ISelAddressMode::RegBase &&
2061 AM.Base_Reg.getNode() == nullptr) {
2062 AM.Base_Reg = AM.IndexReg;
2063 AM.Scale = 1;
2064 }
2065
2066 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
2067 // because it has a smaller encoding.
2068 if (TM.getCodeModel() != CodeModel::Large &&
2069 (!AM.GV || !TM.isLargeGlobalValue(AM.GV)) && Subtarget->is64Bit() &&
2070 AM.Scale == 1 && AM.BaseType == X86ISelAddressMode::RegBase &&
2071 AM.Base_Reg.getNode() == nullptr && AM.IndexReg.getNode() == nullptr &&
2072 AM.SymbolFlags == X86II::MO_NO_FLAG && AM.hasSymbolicDisplacement()) {
2073 // However, when GV is a local function symbol and in the same section as
2074 // the current instruction, and AM.Disp is negative and near INT32_MIN,
2075 // referencing GV+Disp generates a relocation referencing the section symbol
2076 // with an even smaller offset, which might underflow. We should bail out if
2077 // the negative offset is too close to INT32_MIN. Actually, we are more
2078 // conservative here, using a smaller magic number also used by
2079 // isOffsetSuitableForCodeModel.
2080 if (isa_and_nonnull<Function>(AM.GV) && AM.Disp < -16 * 1024 * 1024)
2081 return true;
2082
2083 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
2084 }
2085
2086 return false;
2087}
2088
2089// Returns true if V has a use that materializes it in a register as a value -
2090// a stored value operand or a CopyToReg (a return value, call argument, or a
2091// value that is live out of the block). Such a use means V will be in a
2092// register regardless, so reusing it when forming an LEA is free. Uses where V
2093// is only an address (a load/store pointer, or folded into another address
2094// computation) do not materialize it. This is a more precise replacement for
2095// the !hasOneUse() proxy: an address-only multi-use value is not materialized.
2096bool X86DAGToDAGISel::hasMaterializingUse(SDValue V) const {
2097 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2098 for (SDUse &U : V->uses()) {
2099 if (U.getResNo() != V.getResNo())
2100 continue;
2101 SDNode *User = U.getUser();
2102 // A return value, call argument, or a value live out of the block.
2103 if (User->getOpcode() == ISD::CopyToReg)
2104 return true;
2105 // A stored value materializes V (V as a store *address* does not).
2106 if (auto *St = dyn_cast<StoreSDNode>(User)) {
2107 if (St->getValue() == V)
2108 return true;
2109 continue;
2110 }
2111 // Selection may already have turned the ISD::STORE into a machine store by
2112 // the time we get here. V materializes it if it is a stored value, i.e. an
2113 // operand that is neither part of the memory reference (the address
2114 // operands) nor the chain/glue. The memory reference is not always the
2115 // first operand, so locate it via the instruction's memory-operand info
2116 // rather than assuming a fixed layout. (No getOperandBias() is needed:
2117 // unlike a MachineInstr, an SDNode's operand list has no leading defs.)
2118 if (!User->isMachineOpcode())
2119 continue;
2120 const MCInstrDesc &Desc = TII->get(User->getMachineOpcode());
2121 if (!Desc.mayStore())
2122 continue;
2123 int MemRefBegin = X86II::getMemoryOperandNo(Desc.TSFlags);
2124 if (MemRefBegin < 0)
2125 continue;
2126 unsigned MemRefEnd = MemRefBegin + X86::AddrNumOperands;
2127 for (unsigned I = 0, E = User->getNumOperands(); I != E; ++I) {
2128 if (I >= static_cast<unsigned>(MemRefBegin) && I < MemRefEnd)
2129 continue; // an address operand
2130 SDValue Opnd = User->getOperand(I);
2131 if (Opnd.getValueType() == MVT::Other || Opnd.getValueType() == MVT::Glue)
2132 continue; // chain / glue
2133 if (Opnd == V)
2134 return true; // a stored value operand
2135 }
2136 }
2137 return false;
2138}
2139
2140bool X86DAGToDAGISel::matchAdd(SDValue &N, X86ISelAddressMode &AM,
2141 unsigned Depth) {
2142 // Add an artificial use to this node so that we can keep track of
2143 // it if it gets CSE'd with a different node.
2144 HandleSDNode Handle(N);
2145
2146 auto IsAddOrAddLike = [&](SDValue V) {
2147 return V.getOpcode() == ISD::ADD || CurDAG->isADDLike(V);
2148 };
2149
2150 // When forming a LEA, avoid splitting an already-materialized value: use the
2151 // operand directly as a base/index register instead. hasMaterializingUse()
2152 // decides whether the operand is genuinely materialized - it has a use that
2153 // puts it in a register as a value. A value used only as an address is not
2154 // materialized, and splitting it there would only add a redundant
2155 // materialization (see the two_ptrs test).
2156 auto SplitsMaterializedValue = [&](SDValue Op) {
2157 if (!AM.IsForLEA || !hasMaterializingUse(Op))
2158 return false;
2159
2160 // add-like: decomposes to base + index (+ disp)
2161 if (IsAddOrAddLike(Op))
2162 return IsAddOrAddLike(Op.getOperand(0)) ||
2163 IsAddOrAddLike(Op.getOperand(1));
2164
2165 // shl by 1/2/3 folds to a scaled index
2166 if (Op.getOpcode() == ISD::SHL)
2167 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2168 return C->getZExtValue() >= 1 && C->getZExtValue() <= 3 &&
2169 IsAddOrAddLike(Op.getOperand(0));
2170
2171 return false;
2172 };
2173
2174 // The check is applied here, per add operand, rather than inside
2175 // matchAddressRecursively, so that it only fires when an add directly
2176 // consumes the value. matchAddressRecursively is also entered for the LEA
2177 // root itself and from the SUB case's operand fold.
2178 // Firing there produces worse code.
2179 auto MatchOperand = [&](SDValue Op) {
2180 // The reuse shortcut places Op directly as a base/index register via
2181 // matchAddressBase. That is illegal once AM is already %rip-relative:
2182 // [%rip + disp32] takes no register beyond RIP itself (its implicit base) -
2183 // no additional base and no index - so adding one would form an invalid
2184 // address (folding a RIP-relative global and a materialized value into a
2185 // single LEA, which asserts "Invalid rip-relative address" in the MC
2186 // encoder). matchAddressRecursively correctly refuses to fold a register
2187 // into a %rip-relative address, so fall back to it and let matchAdd keep
2188 // the operands separate.
2189 if (SplitsMaterializedValue(Op) && !AM.isRIPRelative())
2190 return matchAddressBase(Op, AM);
2191 return matchAddressRecursively(Op, AM, Depth + 1);
2192 };
2193
2194 X86ISelAddressMode Backup = AM;
2195 if (!MatchOperand(N.getOperand(0)) &&
2196 !MatchOperand(Handle.getValue().getOperand(1)))
2197 return false;
2198 AM = Backup;
2199
2200 // Try again after commutating the operands.
2201 if (!MatchOperand(Handle.getValue().getOperand(1)) &&
2202 !MatchOperand(Handle.getValue().getOperand(0)))
2203 return false;
2204 AM = Backup;
2205
2206 // If we couldn't fold both operands into the address at the same time,
2207 // see if we can just put each operand into a register and fold at least
2208 // the add.
2209 if (AM.BaseType == X86ISelAddressMode::RegBase &&
2210 !AM.Base_Reg.getNode() &&
2211 !AM.IndexReg.getNode()) {
2212 N = Handle.getValue();
2213 AM.Base_Reg = N.getOperand(0);
2214 AM.IndexReg = N.getOperand(1);
2215 AM.Scale = 1;
2216 return false;
2217 }
2218 N = Handle.getValue();
2219 return true;
2220}
2221
2222// Insert a node into the DAG at least before the Pos node's position. This
2223// will reposition the node as needed, and will assign it a node ID that is <=
2224// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
2225// IDs! The selection DAG must no longer depend on their uniqueness when this
2226// is used.
2227static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
2228 if (N->getNodeId() == -1 ||
2231 DAG.RepositionNode(Pos->getIterator(), N.getNode());
2232 // Mark Node as invalid for pruning as after this it may be a successor to a
2233 // selected node but otherwise be in the same position of Pos.
2234 // Conservatively mark it with the same -abs(Id) to assure node id
2235 // invariant is preserved.
2236 N->setNodeId(Pos->getNodeId());
2238 }
2239}
2240
2241// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
2242// safe. This allows us to convert the shift and and into an h-register
2243// extract and a scaled index. Returns false if the simplification is
2244// performed.
2246 uint64_t Mask,
2247 SDValue Shift, SDValue X,
2248 X86ISelAddressMode &AM) {
2249 if (Shift.getOpcode() != ISD::SRL ||
2250 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
2251 !Shift.hasOneUse())
2252 return true;
2253
2254 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
2255 if (ScaleLog <= 0 || ScaleLog >= 4 ||
2256 Mask != (0xffu << ScaleLog))
2257 return true;
2258
2259 MVT XVT = X.getSimpleValueType();
2260 MVT VT = N.getSimpleValueType();
2261 SDLoc DL(N);
2262 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
2263 SDValue NewMask = DAG.getConstant(0xff, DL, XVT);
2264 SDValue Srl = DAG.getNode(ISD::SRL, DL, XVT, X, Eight);
2265 SDValue And = DAG.getNode(ISD::AND, DL, XVT, Srl, NewMask);
2266 SDValue Ext = DAG.getZExtOrTrunc(And, DL, VT);
2267 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
2268 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Ext, ShlCount);
2269
2270 // Insert the new nodes into the topological ordering. We must do this in
2271 // a valid topological ordering as nothing is going to go back and re-sort
2272 // these nodes. We continually insert before 'N' in sequence as this is
2273 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
2274 // hierarchy left to express.
2275 insertDAGNode(DAG, N, Eight);
2276 insertDAGNode(DAG, N, NewMask);
2277 insertDAGNode(DAG, N, Srl);
2278 insertDAGNode(DAG, N, And);
2279 insertDAGNode(DAG, N, Ext);
2280 insertDAGNode(DAG, N, ShlCount);
2281 insertDAGNode(DAG, N, Shl);
2282 DAG.ReplaceAllUsesWith(N, Shl);
2283 DAG.RemoveDeadNode(N.getNode());
2284 AM.IndexReg = Ext;
2285 AM.Scale = (1 << ScaleLog);
2286 return false;
2287}
2288
2289// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
2290// allows us to fold the shift into this addressing mode. Returns false if the
2291// transform succeeded.
2293 X86ISelAddressMode &AM) {
2294 SDValue Shift = N.getOperand(0);
2295
2296 // Use a signed mask so that shifting right will insert sign bits. These
2297 // bits will be removed when we shift the result left so it doesn't matter
2298 // what we use. This might allow a smaller immediate encoding.
2299 int64_t Mask = cast<ConstantSDNode>(N->getOperand(1))->getSExtValue();
2300
2301 // If we have an any_extend feeding the AND, look through it to see if there
2302 // is a shift behind it. But only if the AND doesn't use the extended bits.
2303 // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
2304 bool FoundAnyExtend = false;
2305 if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
2306 Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
2307 isUInt<32>(Mask)) {
2308 FoundAnyExtend = true;
2309 Shift = Shift.getOperand(0);
2310 }
2311
2312 if (Shift.getOpcode() != ISD::SHL ||
2314 return true;
2315
2316 SDValue X = Shift.getOperand(0);
2317
2318 // Not likely to be profitable if either the AND or SHIFT node has more
2319 // than one use (unless all uses are for address computation). Besides,
2320 // isel mechanism requires their node ids to be reused.
2321 if (!N.hasOneUse() || !Shift.hasOneUse())
2322 return true;
2323
2324 // Verify that the shift amount is something we can fold.
2325 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
2326 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
2327 return true;
2328
2329 MVT VT = N.getSimpleValueType();
2330 SDLoc DL(N);
2331 if (FoundAnyExtend) {
2332 SDValue NewX = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
2333 insertDAGNode(DAG, N, NewX);
2334 X = NewX;
2335 }
2336
2337 SDValue NewMask = DAG.getSignedConstant(Mask >> ShiftAmt, DL, VT);
2338 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
2339 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
2340
2341 // Insert the new nodes into the topological ordering. We must do this in
2342 // a valid topological ordering as nothing is going to go back and re-sort
2343 // these nodes. We continually insert before 'N' in sequence as this is
2344 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
2345 // hierarchy left to express.
2346 insertDAGNode(DAG, N, NewMask);
2347 insertDAGNode(DAG, N, NewAnd);
2348 insertDAGNode(DAG, N, NewShift);
2349 DAG.ReplaceAllUsesWith(N, NewShift);
2350 DAG.RemoveDeadNode(N.getNode());
2351
2352 AM.Scale = 1 << ShiftAmt;
2353 AM.IndexReg = NewAnd;
2354 return false;
2355}
2356
2357// Implement some heroics to detect shifts of masked values where the mask can
2358// be replaced by extending the shift and undoing that in the addressing mode
2359// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
2360// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
2361// the addressing mode. This results in code such as:
2362//
2363// int f(short *y, int *lookup_table) {
2364// ...
2365// return *y + lookup_table[*y >> 11];
2366// }
2367//
2368// Turning into:
2369// movzwl (%rdi), %eax
2370// movl %eax, %ecx
2371// shrl $11, %ecx
2372// addl (%rsi,%rcx,4), %eax
2373//
2374// Instead of:
2375// movzwl (%rdi), %eax
2376// movl %eax, %ecx
2377// shrl $9, %ecx
2378// andl $124, %rcx
2379// addl (%rsi,%rcx), %eax
2380//
2381// Note that this function assumes the mask is provided as a mask *after* the
2382// value is shifted. The input chain may or may not match that, but computing
2383// such a mask is trivial.
2385 uint64_t Mask,
2386 SDValue Shift, SDValue X,
2387 X86ISelAddressMode &AM) {
2388 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
2390 return true;
2391
2392 // We need to ensure that mask is a continuous run of bits.
2393 unsigned MaskIdx, MaskLen;
2394 if (!isShiftedMask_64(Mask, MaskIdx, MaskLen))
2395 return true;
2396 unsigned MaskLZ = 64 - (MaskIdx + MaskLen);
2397
2398 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
2399
2400 // The amount of shift we're trying to fit into the addressing mode is taken
2401 // from the shifted mask index (number of trailing zeros of the mask).
2402 unsigned AMShiftAmt = MaskIdx;
2403
2404 // There is nothing we can do here unless the mask is removing some bits.
2405 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
2406 if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;
2407
2408 // Scale the leading zero count down based on the actual size of the value.
2409 // Also scale it down based on the size of the shift.
2410 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
2411 if (MaskLZ < ScaleDown)
2412 return true;
2413 MaskLZ -= ScaleDown;
2414
2415 // The final check is to ensure that any masked out high bits of X are
2416 // already known to be zero. Otherwise, the mask has a semantic impact
2417 // other than masking out a couple of low bits. Unfortunately, because of
2418 // the mask, zero extensions will be removed from operands in some cases.
2419 // This code works extra hard to look through extensions because we can
2420 // replace them with zero extensions cheaply if necessary.
2421 bool ReplacingAnyExtend = false;
2422 if (X.getOpcode() == ISD::ANY_EXTEND) {
2423 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
2424 X.getOperand(0).getSimpleValueType().getSizeInBits();
2425 // Assume that we'll replace the any-extend with a zero-extend, and
2426 // narrow the search to the extended value.
2427 X = X.getOperand(0);
2428 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
2429 ReplacingAnyExtend = true;
2430 }
2431 APInt MaskedHighBits =
2432 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
2433 if (!DAG.MaskedValueIsZero(X, MaskedHighBits))
2434 return true;
2435
2436 // We've identified a pattern that can be transformed into a single shift
2437 // and an addressing mode. Make it so.
2438 MVT VT = N.getSimpleValueType();
2439 if (ReplacingAnyExtend) {
2440 assert(X.getValueType() != VT);
2441 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
2442 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
2443 insertDAGNode(DAG, N, NewX);
2444 X = NewX;
2445 }
2446
2447 MVT XVT = X.getSimpleValueType();
2448 SDLoc DL(N);
2449 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
2450 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, XVT, X, NewSRLAmt);
2451 SDValue NewExt = DAG.getZExtOrTrunc(NewSRL, DL, VT);
2452 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
2453 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewExt, NewSHLAmt);
2454
2455 // Insert the new nodes into the topological ordering. We must do this in
2456 // a valid topological ordering as nothing is going to go back and re-sort
2457 // these nodes. We continually insert before 'N' in sequence as this is
2458 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
2459 // hierarchy left to express.
2460 insertDAGNode(DAG, N, NewSRLAmt);
2461 insertDAGNode(DAG, N, NewSRL);
2462 insertDAGNode(DAG, N, NewExt);
2463 insertDAGNode(DAG, N, NewSHLAmt);
2464 insertDAGNode(DAG, N, NewSHL);
2465 DAG.ReplaceAllUsesWith(N, NewSHL);
2466 DAG.RemoveDeadNode(N.getNode());
2467
2468 AM.Scale = 1 << AMShiftAmt;
2469 AM.IndexReg = NewExt;
2470 return false;
2471}
2472
2473// Transform "(X >> SHIFT) & (MASK << C1)" to
2474// "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be
2475// matched to a BEXTR later. Returns false if the simplification is performed.
2477 uint64_t Mask,
2478 SDValue Shift, SDValue X,
2479 X86ISelAddressMode &AM,
2480 const X86Subtarget &Subtarget) {
2481 if (Shift.getOpcode() != ISD::SRL ||
2482 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
2483 !Shift.hasOneUse() || !N.hasOneUse())
2484 return true;
2485
2486 // Only do this if BEXTR will be matched by matchBEXTRFromAndImm.
2487 if (!Subtarget.hasTBM() &&
2488 !(Subtarget.hasBMI() && Subtarget.hasFastBEXTR()))
2489 return true;
2490
2491 // We need to ensure that mask is a continuous run of bits.
2492 unsigned MaskIdx, MaskLen;
2493 if (!isShiftedMask_64(Mask, MaskIdx, MaskLen))
2494 return true;
2495
2496 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
2497
2498 // The amount of shift we're trying to fit into the addressing mode is taken
2499 // from the shifted mask index (number of trailing zeros of the mask).
2500 unsigned AMShiftAmt = MaskIdx;
2501
2502 // There is nothing we can do here unless the mask is removing some bits.
2503 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
2504 if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;
2505
2506 MVT XVT = X.getSimpleValueType();
2507 MVT VT = N.getSimpleValueType();
2508 SDLoc DL(N);
2509 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
2510 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, XVT, X, NewSRLAmt);
2511 SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, XVT);
2512 SDValue NewAnd = DAG.getNode(ISD::AND, DL, XVT, NewSRL, NewMask);
2513 SDValue NewExt = DAG.getZExtOrTrunc(NewAnd, DL, VT);
2514 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
2515 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewExt, NewSHLAmt);
2516
2517 // Insert the new nodes into the topological ordering. We must do this in
2518 // a valid topological ordering as nothing is going to go back and re-sort
2519 // these nodes. We continually insert before 'N' in sequence as this is
2520 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
2521 // hierarchy left to express.
2522 insertDAGNode(DAG, N, NewSRLAmt);
2523 insertDAGNode(DAG, N, NewSRL);
2524 insertDAGNode(DAG, N, NewMask);
2525 insertDAGNode(DAG, N, NewAnd);
2526 insertDAGNode(DAG, N, NewExt);
2527 insertDAGNode(DAG, N, NewSHLAmt);
2528 insertDAGNode(DAG, N, NewSHL);
2529 DAG.ReplaceAllUsesWith(N, NewSHL);
2530 DAG.RemoveDeadNode(N.getNode());
2531
2532 AM.Scale = 1 << AMShiftAmt;
2533 AM.IndexReg = NewExt;
2534 return false;
2535}
2536
2537// Attempt to peek further into a scaled index register, collecting additional
2538// extensions / offsets / etc. Returns /p N if we can't peek any further.
2539SDValue X86DAGToDAGISel::matchIndexRecursively(SDValue N,
2540 X86ISelAddressMode &AM,
2541 unsigned Depth) {
2542 assert(AM.IndexReg.getNode() == nullptr && "IndexReg already matched");
2543 assert((AM.Scale == 1 || AM.Scale == 2 || AM.Scale == 4 || AM.Scale == 8) &&
2544 "Illegal index scale");
2545
2546 // Limit recursion.
2548 return N;
2549
2550 EVT VT = N.getValueType();
2551 unsigned Opc = N.getOpcode();
2552
2553 // index: add(x,c) -> index: x, disp + c
2554 if (CurDAG->isBaseWithConstantOffset(N)) {
2555 auto *AddVal = cast<ConstantSDNode>(N.getOperand(1));
2556 uint64_t Offset = (uint64_t)AddVal->getSExtValue() * AM.Scale;
2557 if (!foldOffsetIntoAddress(Offset, AM))
2558 return matchIndexRecursively(N.getOperand(0), AM, Depth + 1);
2559 }
2560
2561 // index: add(x,x) -> index: x, scale * 2
2562 if (Opc == ISD::ADD && N.getOperand(0) == N.getOperand(1)) {
2563 if (AM.Scale <= 4) {
2564 AM.Scale *= 2;
2565 return matchIndexRecursively(N.getOperand(0), AM, Depth + 1);
2566 }
2567 }
2568
2569 // index: shl(x,i) -> index: x, scale * (1 << i)
2570 if (Opc == X86ISD::VSHLI) {
2571 uint64_t ShiftAmt = N.getConstantOperandVal(1);
2572 uint64_t ScaleAmt = 1ULL << ShiftAmt;
2573 if ((AM.Scale * ScaleAmt) <= 8) {
2574 AM.Scale *= ScaleAmt;
2575 return matchIndexRecursively(N.getOperand(0), AM, Depth + 1);
2576 }
2577 }
2578
2579 // index: sext(add_nsw(x,c)) -> index: sext(x), disp + sext(c)
2580 // TODO: call matchIndexRecursively(AddSrc) if we won't corrupt sext?
2581 if (Opc == ISD::SIGN_EXTEND && !VT.isVector() && N.hasOneUse()) {
2582 SDValue Src = N.getOperand(0);
2583 if (Src.getOpcode() == ISD::ADD && Src->getFlags().hasNoSignedWrap() &&
2584 Src.hasOneUse()) {
2585 if (CurDAG->isBaseWithConstantOffset(Src)) {
2586 SDValue AddSrc = Src.getOperand(0);
2587 auto *AddVal = cast<ConstantSDNode>(Src.getOperand(1));
2588 int64_t Offset = AddVal->getSExtValue();
2589 if (!foldOffsetIntoAddress((uint64_t)Offset * AM.Scale, AM)) {
2590 SDLoc DL(N);
2591 SDValue ExtSrc = CurDAG->getNode(Opc, DL, VT, AddSrc);
2592 SDValue ExtVal = CurDAG->getSignedConstant(Offset, DL, VT);
2593 SDValue ExtAdd = CurDAG->getNode(ISD::ADD, DL, VT, ExtSrc, ExtVal);
2594 insertDAGNode(*CurDAG, N, ExtSrc);
2595 insertDAGNode(*CurDAG, N, ExtVal);
2596 insertDAGNode(*CurDAG, N, ExtAdd);
2597 CurDAG->ReplaceAllUsesWith(N, ExtAdd);
2598 CurDAG->RemoveDeadNode(N.getNode());
2599 return ExtSrc;
2600 }
2601 }
2602 }
2603 }
2604
2605 // index: zext(add_nuw(x,c)) -> index: zext(x), disp + zext(c)
2606 // index: zext(addlike(x,c)) -> index: zext(x), disp + zext(c)
2607 // TODO: call matchIndexRecursively(AddSrc) if we won't corrupt sext?
2608 if (Opc == ISD::ZERO_EXTEND && !VT.isVector() && N.hasOneUse()) {
2609 SDValue Src = N.getOperand(0);
2610 unsigned SrcOpc = Src.getOpcode();
2611 if (((SrcOpc == ISD::ADD && Src->getFlags().hasNoUnsignedWrap()) ||
2612 CurDAG->isADDLike(Src, /*NoWrap=*/true)) &&
2613 Src.hasOneUse()) {
2614 if (CurDAG->isBaseWithConstantOffset(Src)) {
2615 SDValue AddSrc = Src.getOperand(0);
2616 uint64_t Offset = Src.getConstantOperandVal(1);
2617 if (!foldOffsetIntoAddress(Offset * AM.Scale, AM)) {
2618 SDLoc DL(N);
2619 SDValue Res;
2620 // If we're also scaling, see if we can use that as well.
2621 if (AddSrc.getOpcode() == ISD::SHL &&
2622 isa<ConstantSDNode>(AddSrc.getOperand(1))) {
2623 SDValue ShVal = AddSrc.getOperand(0);
2624 uint64_t ShAmt = AddSrc.getConstantOperandVal(1);
2625 APInt HiBits =
2627 uint64_t ScaleAmt = 1ULL << ShAmt;
2628 if ((AM.Scale * ScaleAmt) <= 8 &&
2629 (AddSrc->getFlags().hasNoUnsignedWrap() ||
2630 CurDAG->MaskedValueIsZero(ShVal, HiBits))) {
2631 AM.Scale *= ScaleAmt;
2632 SDValue ExtShVal = CurDAG->getNode(Opc, DL, VT, ShVal);
2633 SDValue ExtShift = CurDAG->getNode(ISD::SHL, DL, VT, ExtShVal,
2634 AddSrc.getOperand(1));
2635 insertDAGNode(*CurDAG, N, ExtShVal);
2636 insertDAGNode(*CurDAG, N, ExtShift);
2637 AddSrc = ExtShift;
2638 Res = ExtShVal;
2639 }
2640 }
2641 SDValue ExtSrc = CurDAG->getNode(Opc, DL, VT, AddSrc);
2642 SDValue ExtVal = CurDAG->getConstant(Offset, DL, VT);
2643 SDValue ExtAdd = CurDAG->getNode(SrcOpc, DL, VT, ExtSrc, ExtVal);
2644 insertDAGNode(*CurDAG, N, ExtSrc);
2645 insertDAGNode(*CurDAG, N, ExtVal);
2646 insertDAGNode(*CurDAG, N, ExtAdd);
2647 CurDAG->ReplaceAllUsesWith(N, ExtAdd);
2648 CurDAG->RemoveDeadNode(N.getNode());
2649 return Res ? Res : ExtSrc;
2650 }
2651 }
2652 }
2653 }
2654
2655 // TODO: Handle extensions, shifted masks etc.
2656 return N;
2657}
2658
2659bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
2660 unsigned Depth) {
2661 LLVM_DEBUG({
2662 dbgs() << "MatchAddress: ";
2663 AM.dump(CurDAG);
2664 });
2665 // Limit recursion.
2667 return matchAddressBase(N, AM);
2668
2669 // If this is already a %rip relative address, we can only merge immediates
2670 // into it. Instead of handling this in every case, we handle it here.
2671 // RIP relative addressing: %rip + 32-bit displacement!
2672 if (AM.isRIPRelative()) {
2673 // FIXME: JumpTable and ExternalSymbol address currently don't like
2674 // displacements. It isn't very important, but this should be fixed for
2675 // consistency.
2676 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
2677 return true;
2678
2679 if (auto *Cst = dyn_cast<ConstantSDNode>(N))
2680 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
2681 return false;
2682 return true;
2683 }
2684
2685 switch (N.getOpcode()) {
2686 default: break;
2687 case ISD::LOCAL_RECOVER: {
2688 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
2689 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
2690 // Use the symbol and don't prefix it.
2691 AM.MCSym = ESNode->getMCSymbol();
2692 return false;
2693 }
2694 break;
2695 }
2696 case ISD::Constant: {
2697 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
2698 if (!foldOffsetIntoAddress(Val, AM))
2699 return false;
2700 break;
2701 }
2702
2703 case X86ISD::Wrapper:
2704 case X86ISD::WrapperRIP:
2705 if (!matchWrapper(N, AM))
2706 return false;
2707 break;
2708
2709 case ISD::LOAD:
2710 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
2711 return false;
2712 break;
2713
2714 case ISD::FrameIndex:
2715 if (AM.BaseType == X86ISelAddressMode::RegBase &&
2716 AM.Base_Reg.getNode() == nullptr &&
2717 (!Subtarget->is64Bit() || isDispSafeForFrameIndexOrRegBase(AM.Disp))) {
2718 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
2719 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
2720 return false;
2721 }
2722 break;
2723
2724 case ISD::SHL:
2725 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
2726 break;
2727
2728 if (auto *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
2729 unsigned Val = CN->getZExtValue();
2730 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
2731 // that the base operand remains free for further matching. If
2732 // the base doesn't end up getting used, a post-processing step
2733 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
2734 if (Val == 1 || Val == 2 || Val == 3) {
2735 SDValue ShVal = N.getOperand(0);
2736 AM.Scale = 1 << Val;
2737 AM.IndexReg = matchIndexRecursively(ShVal, AM, Depth + 1);
2738 return false;
2739 }
2740 }
2741 break;
2742
2743 case ISD::SRL: {
2744 // Scale must not be used already.
2745 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
2746
2747 // We only handle up to 64-bit values here as those are what matter for
2748 // addressing mode optimizations.
2749 assert(N.getSimpleValueType().getSizeInBits() <= 64 &&
2750 "Unexpected value size!");
2751
2752 SDValue And = N.getOperand(0);
2753 if (And.getOpcode() != ISD::AND) break;
2754 SDValue X = And.getOperand(0);
2755
2756 // The mask used for the transform is expected to be post-shift, but we
2757 // found the shift first so just apply the shift to the mask before passing
2758 // it down.
2759 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
2760 !isa<ConstantSDNode>(And.getOperand(1)))
2761 break;
2762 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
2763
2764 // Try to fold the mask and shift into the scale, and return false if we
2765 // succeed.
2766 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
2767 return false;
2768 break;
2769 }
2770
2771 case ISD::SMUL_LOHI:
2772 case ISD::UMUL_LOHI:
2773 // A mul_lohi where we need the low part can be folded as a plain multiply.
2774 if (N.getResNo() != 0) break;
2775 [[fallthrough]];
2776 case ISD::MUL:
2777 case X86ISD::MUL_IMM:
2778 // X*[3,5,9] -> X+X*[2,4,8]
2779 if (AM.BaseType == X86ISelAddressMode::RegBase &&
2780 AM.Base_Reg.getNode() == nullptr &&
2781 AM.IndexReg.getNode() == nullptr) {
2782 if (auto *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
2783 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
2784 CN->getZExtValue() == 9) {
2785 AM.Scale = unsigned(CN->getZExtValue())-1;
2786
2787 SDValue MulVal = N.getOperand(0);
2788 SDValue Reg;
2789
2790 // Okay, we know that we have a scale by now. However, if the scaled
2791 // value is an add of something and a constant, we can fold the
2792 // constant into the disp field here.
2793 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
2794 isa<ConstantSDNode>(MulVal.getOperand(1))) {
2795 Reg = MulVal.getOperand(0);
2796 auto *AddVal = cast<ConstantSDNode>(MulVal.getOperand(1));
2797 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
2798 if (foldOffsetIntoAddress(Disp, AM))
2799 Reg = N.getOperand(0);
2800 } else {
2801 Reg = N.getOperand(0);
2802 }
2803
2804 AM.IndexReg = AM.Base_Reg = Reg;
2805 return false;
2806 }
2807 }
2808 break;
2809
2810 case ISD::SUB: {
2811 // Given A-B, if A can be completely folded into the address leaving the
2812 // index field unused, use -B as the index. This is a win if A has multiple
2813 // parts that can be folded into the address. Also, this saves a mov if the
2814 // base register has other uses, since it avoids a two-address sub
2815 // instruction, however it costs an additional mov if the index register
2816 // has other uses.
2817 // B may itself be a constant shift, in which case the shift folds into
2818 // the scale - see below.
2819
2820 // Add an artificial use to this node so that we can keep track of
2821 // it if it gets CSE'd with a different node.
2822 HandleSDNode Handle(N);
2823
2824 // Test if the LHS of the sub can be folded.
2825 X86ISelAddressMode Backup = AM;
2826 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
2827 N = Handle.getValue();
2828 AM = Backup;
2829 break;
2830 }
2831 N = Handle.getValue();
2832 // Test if the index field is free for use.
2833 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
2834 AM = Backup;
2835 break;
2836 }
2837
2838 int Cost = 0;
2839 SDValue RHS = N.getOperand(1);
2840
2841 // A-(B<<C) can use -B as a scaled index for C in [1,3], which folds the
2842 // shift into the address as well as the subtract. When B is not a foldable
2843 // shift, NegScale stays empty and this is the plain A-B fold, which only
2844 // breaks even on instruction count - a-b is mov+sub either way. Absorbing
2845 // the shift saves one:
2846 //
2847 // a - (b << 2) movq %rdi, %rax -> negq %rsi
2848 // shlq $2, %rsi leaq (%rdi,%rsi,4), %rax
2849 // subq %rsi, %rax
2850 //
2851 // That pays for the negate, so drop the cost by one.
2852 std::optional<unsigned> NegScale;
2853 if (RHS.getOpcode() == ISD::SHL && RHS.hasOneUse()) {
2854 if (auto *ShAmt = dyn_cast<ConstantSDNode>(RHS.getOperand(1))) {
2855 uint64_t ShVal = ShAmt->getZExtValue();
2856 if (ShVal >= 1 && ShVal <= 3) {
2857 NegScale = 1u << ShVal;
2858 RHS = RHS.getOperand(0);
2859 --Cost;
2860 }
2861 }
2862 }
2863
2864 // If the RHS involves a register with multiple uses, this
2865 // transformation incurs an extra mov, due to the neg instruction
2866 // clobbering its operand. The CopyFromReg part of that is a guess -
2867 // SelectionDAG is per-block, so uses elsewhere are invisible - and it is
2868 // not applied to a folded shift, where it is wrong often enough to matter.
2869 // The multiple-use part still is; see @y_outlives_lea.
2870 if (!RHS.getNode()->hasOneUse() ||
2871 (!NegScale && RHS.getNode()->getOpcode() == ISD::CopyFromReg) ||
2872 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
2873 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
2874 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
2875 RHS.getOperand(0).getValueType() == MVT::i32))
2876 ++Cost;
2877 // A - (A << C), where the base is itself the value being negated.
2878 bool BaseIsNegatedValue = NegScale &&
2879 AM.BaseType == X86ISelAddressMode::RegBase &&
2880 AM.Base_Reg == RHS;
2881 // If the base is a register with multiple uses, this transformation may
2882 // save a mov - but not for BaseIsNegatedValue, where the baseline emits the
2883 // shift non-destructively into another register and the SUB writes A in
2884 // place, so there is no copy for the LEA to save. The copy the NEG needs
2885 // there is charged by the multiple-use test above.
2886 if (((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
2887 !AM.Base_Reg.getNode()->hasOneUse()) ||
2888 AM.BaseType == X86ISelAddressMode::FrameIndexBase) &&
2889 !BaseIsNegatedValue)
2890 --Cost;
2891 // If the folded LHS was interesting, this transformation saves
2892 // address arithmetic.
2893 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
2894 ((AM.Disp != 0) && (Backup.Disp == 0)) +
2895 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
2896 --Cost;
2897 // If it doesn't look like it may be an overall win, don't do it.
2898 if (Cost >= 0) {
2899 AM = Backup;
2900 break;
2901 }
2902
2903 // Ok, the transformation is legal and appears profitable. Go for it.
2904 // Negation will be emitted later to avoid creating dangling nodes if this
2905 // was an unprofitable LEA.
2906 AM.IndexReg = RHS;
2907 AM.NegateIndex = true;
2908 AM.Scale = NegScale.value_or(1);
2909 return false;
2910 }
2911
2912 case ISD::OR:
2913 case ISD::XOR:
2914 // See if we can treat the OR/XOR node as an ADD node.
2915 if (!CurDAG->isADDLike(N))
2916 break;
2917 [[fallthrough]];
2918 case ISD::ADD:
2919 if (!matchAdd(N, AM, Depth))
2920 return false;
2921 break;
2922
2923 case ISD::AND: {
2924 // Perform some heroic transforms on an and of a constant-count shift
2925 // with a constant to enable use of the scaled offset field.
2926
2927 // Scale must not be used already.
2928 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
2929
2930 // We only handle up to 64-bit values here as those are what matter for
2931 // addressing mode optimizations.
2932 assert(N.getSimpleValueType().getSizeInBits() <= 64 &&
2933 "Unexpected value size!");
2934
2935 if (!isa<ConstantSDNode>(N.getOperand(1)))
2936 break;
2937
2938 if (N.getOperand(0).getOpcode() == ISD::SRL) {
2939 SDValue Shift = N.getOperand(0);
2940 SDValue X = Shift.getOperand(0);
2941
2942 uint64_t Mask = N.getConstantOperandVal(1);
2943
2944 // Try to fold the mask and shift into an extract and scale.
2945 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
2946 return false;
2947
2948 // Try to fold the mask and shift directly into the scale.
2949 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
2950 return false;
2951
2952 // Try to fold the mask and shift into BEXTR and scale.
2953 if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget))
2954 return false;
2955 }
2956
2957 // Try to swap the mask and shift to place shifts which can be done as
2958 // a scale on the outside of the mask.
2959 if (!foldMaskedShiftToScaledMask(*CurDAG, N, AM))
2960 return false;
2961
2962 break;
2963 }
2964 case ISD::ZERO_EXTEND: {
2965 // Try to widen a zexted shift left to the same size as its use, so we can
2966 // match the shift as a scale factor.
2967 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
2968 break;
2969
2970 SDValue Src = N.getOperand(0);
2971
2972 // See if we can match a zext(addlike(x,c)).
2973 // TODO: Move more ZERO_EXTEND patterns into matchIndexRecursively.
2974 if (Src.getOpcode() == ISD::ADD || Src.getOpcode() == ISD::OR)
2975 if (SDValue Index = matchIndexRecursively(N, AM, Depth + 1))
2976 if (Index != N) {
2977 AM.IndexReg = Index;
2978 return false;
2979 }
2980
2981 // Peek through mask: zext(and(shl(x,c1),c2))
2982 APInt Mask = APInt::getAllOnes(Src.getScalarValueSizeInBits());
2983 if (Src.getOpcode() == ISD::AND && Src.hasOneUse())
2984 if (auto *MaskC = dyn_cast<ConstantSDNode>(Src.getOperand(1))) {
2985 Mask = MaskC->getAPIntValue();
2986 Src = Src.getOperand(0);
2987 }
2988
2989 if (Src.getOpcode() == ISD::SHL && Src.hasOneUse() && N->hasOneUse()) {
2990 // Give up if the shift is not a valid scale factor [1,2,3].
2991 SDValue ShlSrc = Src.getOperand(0);
2992 SDValue ShlAmt = Src.getOperand(1);
2993 auto *ShAmtC = dyn_cast<ConstantSDNode>(ShlAmt);
2994 if (!ShAmtC)
2995 break;
2996 unsigned ShAmtV = ShAmtC->getZExtValue();
2997 if (ShAmtV > 3)
2998 break;
2999
3000 // The narrow shift must only shift out zero bits (it must be 'nuw').
3001 // That makes it safe to widen to the destination type.
3002 APInt HighZeros =
3003 APInt::getHighBitsSet(ShlSrc.getValueSizeInBits(), ShAmtV);
3004 if (!Src->getFlags().hasNoUnsignedWrap() &&
3005 !CurDAG->MaskedValueIsZero(ShlSrc, HighZeros & Mask))
3006 break;
3007
3008 // zext (shl nuw i8 %x, C1) to i32
3009 // --> shl (zext i8 %x to i32), (zext C1)
3010 // zext (and (shl nuw i8 %x, C1), C2) to i32
3011 // --> shl (zext i8 (and %x, C2 >> C1) to i32), (zext C1)
3012 MVT SrcVT = ShlSrc.getSimpleValueType();
3013 MVT VT = N.getSimpleValueType();
3014 SDLoc DL(N);
3015
3016 SDValue Res = ShlSrc;
3017 if (!Mask.isAllOnes()) {
3018 Res = CurDAG->getConstant(Mask.lshr(ShAmtV), DL, SrcVT);
3019 insertDAGNode(*CurDAG, N, Res);
3020 Res = CurDAG->getNode(ISD::AND, DL, SrcVT, ShlSrc, Res);
3021 insertDAGNode(*CurDAG, N, Res);
3022 }
3023 SDValue Zext = CurDAG->getNode(ISD::ZERO_EXTEND, DL, VT, Res);
3024 insertDAGNode(*CurDAG, N, Zext);
3025 SDValue NewShl = CurDAG->getNode(ISD::SHL, DL, VT, Zext, ShlAmt);
3026 insertDAGNode(*CurDAG, N, NewShl);
3027 CurDAG->ReplaceAllUsesWith(N, NewShl);
3028 CurDAG->RemoveDeadNode(N.getNode());
3029
3030 // Convert the shift to scale factor.
3031 AM.Scale = 1 << ShAmtV;
3032 // If matchIndexRecursively is not called here,
3033 // Zext may be replaced by other nodes but later used to call a builder
3034 // method
3035 AM.IndexReg = matchIndexRecursively(Zext, AM, Depth + 1);
3036 return false;
3037 }
3038
3039 if (Src.getOpcode() == ISD::SRL && !Mask.isAllOnes()) {
3040 // Try to fold the mask and shift into an extract and scale.
3041 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask.getZExtValue(), Src,
3042 Src.getOperand(0), AM))
3043 return false;
3044
3045 // Try to fold the mask and shift directly into the scale.
3046 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask.getZExtValue(), Src,
3047 Src.getOperand(0), AM))
3048 return false;
3049
3050 // Try to fold the mask and shift into BEXTR and scale.
3051 if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask.getZExtValue(), Src,
3052 Src.getOperand(0), AM, *Subtarget))
3053 return false;
3054 }
3055
3056 break;
3057 }
3058 }
3059
3060 return matchAddressBase(N, AM);
3061}
3062
3063/// Helper for MatchAddress. Add the specified node to the
3064/// specified addressing mode without any further recursion.
3065bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
3066 // Is the base register already occupied?
3067 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
3068 // If so, check to see if the scale index register is set.
3069 if (!AM.IndexReg.getNode()) {
3070 AM.IndexReg = N;
3071 AM.Scale = 1;
3072 return false;
3073 }
3074
3075 // Otherwise, we cannot select it.
3076 return true;
3077 }
3078
3079 // Default, generate it as a register.
3080 AM.BaseType = X86ISelAddressMode::RegBase;
3081 AM.Base_Reg = N;
3082 return false;
3083}
3084
3085bool X86DAGToDAGISel::matchVectorAddressRecursively(SDValue N,
3086 X86ISelAddressMode &AM,
3087 unsigned Depth) {
3088 LLVM_DEBUG({
3089 dbgs() << "MatchVectorAddress: ";
3090 AM.dump(CurDAG);
3091 });
3092 // Limit recursion.
3094 return matchAddressBase(N, AM);
3095
3096 // TODO: Support other operations.
3097 switch (N.getOpcode()) {
3098 case ISD::Constant: {
3099 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
3100 if (!foldOffsetIntoAddress(Val, AM))
3101 return false;
3102 break;
3103 }
3104 case X86ISD::Wrapper:
3105 if (!matchWrapper(N, AM))
3106 return false;
3107 break;
3108 case ISD::ADD: {
3109 // Add an artificial use to this node so that we can keep track of
3110 // it if it gets CSE'd with a different node.
3111 HandleSDNode Handle(N);
3112
3113 X86ISelAddressMode Backup = AM;
3114 if (!matchVectorAddressRecursively(N.getOperand(0), AM, Depth + 1) &&
3115 !matchVectorAddressRecursively(Handle.getValue().getOperand(1), AM,
3116 Depth + 1))
3117 return false;
3118 AM = Backup;
3119
3120 // Try again after commuting the operands.
3121 if (!matchVectorAddressRecursively(Handle.getValue().getOperand(1), AM,
3122 Depth + 1) &&
3123 !matchVectorAddressRecursively(Handle.getValue().getOperand(0), AM,
3124 Depth + 1))
3125 return false;
3126 AM = Backup;
3127
3128 N = Handle.getValue();
3129 break;
3130 }
3131 }
3132
3133 return matchAddressBase(N, AM);
3134}
3135
3136/// Helper for selectVectorAddr. Handles things that can be folded into a
3137/// gather/scatter address. The index register and scale should have already
3138/// been handled.
3139bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
3140 return matchVectorAddressRecursively(N, AM, 0);
3141}
3142
3143bool X86DAGToDAGISel::selectVectorAddr(MemSDNode *Parent, SDValue BasePtr,
3144 SDValue IndexOp, SDValue ScaleOp,
3145 SDValue &Base, SDValue &Scale,
3146 SDValue &Index, SDValue &Disp,
3147 SDValue &Segment) {
3148 X86ISelAddressMode AM;
3149 AM.Scale = ScaleOp->getAsZExtVal();
3150
3151 // Attempt to match index patterns, as long as we're not relying on implicit
3152 // sign-extension, which is performed BEFORE scale.
3153 if (IndexOp.getScalarValueSizeInBits() == BasePtr.getScalarValueSizeInBits())
3154 AM.IndexReg = matchIndexRecursively(IndexOp, AM, 0);
3155 else
3156 AM.IndexReg = IndexOp;
3157
3158 unsigned AddrSpace = Parent->getPointerInfo().getAddrSpace();
3159 if (AddrSpace == X86AS::GS)
3160 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
3161 if (AddrSpace == X86AS::FS)
3162 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
3163 if (AddrSpace == X86AS::SS)
3164 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
3165
3166 SDLoc DL(BasePtr);
3167 MVT VT = BasePtr.getSimpleValueType();
3168
3169 // Try to match into the base and displacement fields.
3170 if (matchVectorAddress(BasePtr, AM))
3171 return false;
3172
3173 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
3174 return true;
3175}
3176
3177/// Returns true if it is able to pattern match an addressing mode.
3178/// It returns the operands which make up the maximal addressing mode it can
3179/// match by reference.
3180///
3181/// Parent is the parent node of the addr operand that is being matched. It
3182/// is always a load, store, atomic node, or null. It is only null when
3183/// checking memory operands for inline asm nodes.
3184bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
3185 SDValue &Scale, SDValue &Index, SDValue &Disp,
3186 SDValue &Segment, bool HasNDDM) {
3187 X86ISelAddressMode AM;
3188
3189 if (Parent &&
3190 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
3191 // that are not a MemSDNode, and thus don't have proper addrspace info.
3192 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
3193 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
3194 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
3195 Parent->getOpcode() != X86ISD::ENQCMD && // Fixme
3196 Parent->getOpcode() != X86ISD::ENQCMDS && // Fixme
3197 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
3198 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
3199 unsigned AddrSpace =
3200 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
3201 if (AddrSpace == X86AS::GS)
3202 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
3203 if (AddrSpace == X86AS::FS)
3204 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
3205 if (AddrSpace == X86AS::SS)
3206 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
3207 }
3208
3209 // Save the DL and VT before calling matchAddress, it can invalidate N.
3210 SDLoc DL(N);
3211 MVT VT = N.getSimpleValueType();
3212
3213 if (matchAddress(N, AM))
3214 return false;
3215
3216 if (!HasNDDM && !AM.isRIPRelative())
3217 return false;
3218
3219 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
3220 return true;
3221}
3222
3223bool X86DAGToDAGISel::selectNDDAddr(SDNode *Parent, SDValue N, SDValue &Base,
3224 SDValue &Scale, SDValue &Index,
3225 SDValue &Disp, SDValue &Segment) {
3226 return selectAddr(Parent, N, Base, Scale, Index, Disp, Segment,
3227 Subtarget->hasNDDM());
3228}
3229
3230bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
3231 // Cannot use 32 bit constants to reference objects in kernel/large code
3232 // model.
3233 if (TM.getCodeModel() == CodeModel::Kernel ||
3234 TM.getCodeModel() == CodeModel::Large)
3235 return false;
3236
3237 // In static codegen with small code model, we can get the address of a label
3238 // into a register with 'movl'
3239 if (N->getOpcode() != X86ISD::Wrapper)
3240 return false;
3241
3242 N = N.getOperand(0);
3243
3244 // At least GNU as does not accept 'movl' for TPOFF relocations.
3245 // FIXME: We could use 'movl' when we know we are targeting MC.
3246 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
3247 return false;
3248
3249 Imm = N;
3250 // Small/medium code model can reference non-TargetGlobalAddress objects with
3251 // 32 bit constants.
3252 if (N->getOpcode() != ISD::TargetGlobalAddress) {
3253 return TM.getCodeModel() == CodeModel::Small ||
3254 TM.getCodeModel() == CodeModel::Medium;
3255 }
3256
3257 const GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
3258 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
3259 return CR->getUnsignedMax().ult(1ull << 32);
3260
3261 return !TM.isLargeGlobalValue(GV);
3262}
3263
3264bool X86DAGToDAGISel::selectLEA64_Addr(SDValue N, SDValue &Base, SDValue &Scale,
3265 SDValue &Index, SDValue &Disp,
3266 SDValue &Segment) {
3267 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
3268 SDLoc DL(N);
3269
3270 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
3271 return false;
3272
3273 EVT BaseType = Base.getValueType();
3274 unsigned SubReg;
3275 if (BaseType == MVT::i8)
3276 SubReg = X86::sub_8bit;
3277 else if (BaseType == MVT::i16)
3278 SubReg = X86::sub_16bit;
3279 else
3280 SubReg = X86::sub_32bit;
3281
3283 if (RN && RN->getReg() == 0)
3284 Base = CurDAG->getRegister(0, MVT::i64);
3285 else if ((BaseType == MVT::i8 || BaseType == MVT::i16 ||
3286 BaseType == MVT::i32) &&
3288 // Base could already be %rip, particularly in the x32 ABI.
3289 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
3290 MVT::i64), 0);
3291 Base = CurDAG->getTargetInsertSubreg(SubReg, DL, MVT::i64, ImplDef, Base);
3292 }
3293
3294 [[maybe_unused]] EVT IndexType = Index.getValueType();
3296 if (RN && RN->getReg() == 0)
3297 Index = CurDAG->getRegister(0, MVT::i64);
3298 else {
3299 assert((IndexType == BaseType) &&
3300 "Expect to be extending 8/16/32-bit registers for use in LEA");
3301 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
3302 MVT::i64), 0);
3303 Index = CurDAG->getTargetInsertSubreg(SubReg, DL, MVT::i64, ImplDef, Index);
3304 }
3305
3306 return true;
3307}
3308
3309/// Calls SelectAddr and determines if the maximal addressing
3310/// mode it matches can be cost effectively emitted as an LEA instruction.
3311bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
3312 SDValue &Base, SDValue &Scale,
3313 SDValue &Index, SDValue &Disp,
3314 SDValue &Segment) {
3315 X86ISelAddressMode AM;
3316 AM.IsForLEA = true;
3317
3318 // Save the DL and VT before calling matchAddress, it can invalidate N.
3319 SDLoc DL(N);
3320 MVT VT = N.getSimpleValueType();
3321
3322 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
3323 // segments.
3324 SDValue Copy = AM.Segment;
3325 SDValue T = CurDAG->getRegister(0, MVT::i32);
3326 AM.Segment = T;
3327 if (matchAddress(N, AM))
3328 return false;
3329 assert (T == AM.Segment);
3330 AM.Segment = Copy;
3331
3332 unsigned Complexity = 0;
3333 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode())
3334 Complexity = 1;
3335 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
3336 Complexity = 4;
3337
3338 if (AM.IndexReg.getNode())
3339 Complexity++;
3340
3341 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
3342 // a simple shift.
3343 if (AM.Scale > 1)
3344 Complexity++;
3345
3346 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
3347 // to a LEA. This is determined with some experimentation but is by no means
3348 // optimal (especially for code size consideration). LEA is nice because of
3349 // its three-address nature. Tweak the cost function again when we can run
3350 // convertToThreeAddress() at register allocation time.
3351 if (AM.hasSymbolicDisplacement()) {
3352 // For X86-64, always use LEA to materialize RIP-relative addresses.
3353 if (Subtarget->is64Bit())
3354 Complexity = 4;
3355 else
3356 Complexity += 2;
3357 }
3358
3359 // Heuristic: try harder to form an LEA from ADD if the operands set flags.
3360 // Unlike ADD, LEA does not affect flags, so we will be less likely to require
3361 // duplicating flag-producing instructions later in the pipeline.
3362 if (N.getOpcode() == ISD::ADD) {
3363 auto isMathWithFlags = [](SDValue V) {
3364 switch (V.getOpcode()) {
3365 case X86ISD::ADD:
3366 case X86ISD::SUB:
3367 case X86ISD::ADC:
3368 case X86ISD::SBB:
3369 case X86ISD::SMUL:
3370 case X86ISD::UMUL:
3371 /* TODO: These opcodes can be added safely, but we may want to justify
3372 their inclusion for different reasons (better for reg-alloc).
3373 case X86ISD::OR:
3374 case X86ISD::XOR:
3375 case X86ISD::AND:
3376 */
3377 // Value 1 is the flag output of the node - verify it's not dead.
3378 return !SDValue(V.getNode(), 1).use_empty();
3379 default:
3380 return false;
3381 }
3382 };
3383 // TODO: We might want to factor in whether there's a load folding
3384 // opportunity for the math op that disappears with LEA.
3385 if (isMathWithFlags(N.getOperand(0)) || isMathWithFlags(N.getOperand(1)))
3386 Complexity++;
3387 }
3388
3389 if (AM.Disp)
3390 Complexity++;
3391
3392 // If it isn't worth using an LEA, reject it.
3393 if (Complexity <= 2)
3394 return false;
3395
3396 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
3397 return true;
3398}
3399
3400/// This is only run on TargetGlobalTLSAddress nodes.
3401bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
3402 SDValue &Scale, SDValue &Index,
3403 SDValue &Disp, SDValue &Segment) {
3404 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress ||
3405 N.getOpcode() == ISD::TargetExternalSymbol);
3406
3407 X86ISelAddressMode AM;
3408 if (auto *GA = dyn_cast<GlobalAddressSDNode>(N)) {
3409 AM.GV = GA->getGlobal();
3410 AM.Disp += GA->getOffset();
3411 AM.SymbolFlags = GA->getTargetFlags();
3412 } else {
3413 auto *SA = cast<ExternalSymbolSDNode>(N);
3414 AM.ES = SA->getSymbol();
3415 AM.SymbolFlags = SA->getTargetFlags();
3416 }
3417
3418 if (Subtarget->is32Bit()) {
3419 AM.Scale = 1;
3420 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
3421 }
3422
3423 MVT VT = N.getSimpleValueType();
3424 getAddressOperands(AM, SDLoc(N), VT, Base, Scale, Index, Disp, Segment);
3425 return true;
3426}
3427
3428bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
3429 // Keep track of the original value type and whether this value was
3430 // truncated. If we see a truncation from pointer type to VT that truncates
3431 // bits that are known to be zero, we can use a narrow reference.
3432 EVT VT = N.getValueType();
3433 bool WasTruncated = false;
3434 if (N.getOpcode() == ISD::TRUNCATE) {
3435 WasTruncated = true;
3436 N = N.getOperand(0);
3437 }
3438
3439 if (N.getOpcode() != X86ISD::Wrapper)
3440 return false;
3441
3442 // We can only use non-GlobalValues as immediates if they were not truncated,
3443 // as we do not have any range information. If we have a GlobalValue and the
3444 // address was not truncated, we can select it as an operand directly.
3445 unsigned Opc = N.getOperand(0)->getOpcode();
3446 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
3447 Op = N.getOperand(0);
3448 // We can only select the operand directly if we didn't have to look past a
3449 // truncate.
3450 return !WasTruncated;
3451 }
3452
3453 // Check that the global's range fits into VT.
3454 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
3455 std::optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
3456 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
3457 return false;
3458
3459 // Okay, we can use a narrow reference.
3460 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
3461 GA->getOffset(), GA->getTargetFlags());
3462 return true;
3463}
3464
3465bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
3466 SDValue &Base, SDValue &Scale,
3467 SDValue &Index, SDValue &Disp,
3468 SDValue &Segment) {
3469 assert(Root && P && "Unknown root/parent nodes");
3470 if (!ISD::isNON_EXTLoad(N.getNode()) ||
3471 !IsProfitableToFold(N, P, Root) ||
3472 !IsLegalToFold(N, P, Root, OptLevel))
3473 return false;
3474
3475 return selectAddr(N.getNode(),
3476 N.getOperand(1), Base, Scale, Index, Disp, Segment);
3477}
3478
3479bool X86DAGToDAGISel::tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,
3480 SDValue &Base, SDValue &Scale,
3481 SDValue &Index, SDValue &Disp,
3482 SDValue &Segment) {
3483 assert(Root && P && "Unknown root/parent nodes");
3484 if (N->getOpcode() != X86ISD::VBROADCAST_LOAD ||
3485 !IsProfitableToFold(N, P, Root) ||
3486 !IsLegalToFold(N, P, Root, OptLevel))
3487 return false;
3488
3489 return selectAddr(N.getNode(),
3490 N.getOperand(1), Base, Scale, Index, Disp, Segment);
3491}
3492
3493/// Return an SDNode that returns the value of the global base register.
3494/// Output instructions required to initialize the global base register,
3495/// if necessary.
3496SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
3497 Register GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
3498 auto &DL = MF->getDataLayout();
3499 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
3500}
3501
3502bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
3503 if (N->getOpcode() == ISD::TRUNCATE)
3504 N = N->getOperand(0).getNode();
3505 if (N->getOpcode() != X86ISD::Wrapper)
3506 return false;
3507
3508 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
3509 if (!GA)
3510 return false;
3511
3512 auto *GV = GA->getGlobal();
3513 std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange();
3514 if (CR)
3515 return CR->getSignedMin().sge(-1ull << Width) &&
3516 CR->getSignedMax().slt(1ull << Width);
3517 // In the kernel code model, globals are in the negative 2GB of the address
3518 // space, so globals can be a sign extended 32-bit immediate.
3519 // In other code models, small globals are in the low 2GB of the address
3520 // space, so sign extending them is equivalent to zero extending them.
3521 return TM.getCodeModel() != CodeModel::Large && Width == 32 &&
3522 !TM.isLargeGlobalValue(GV);
3523}
3524
3525X86::CondCode X86DAGToDAGISel::getCondFromNode(SDNode *N) const {
3526 assert(N->isMachineOpcode() && "Unexpected node");
3527 unsigned Opc = N->getMachineOpcode();
3528 const MCInstrDesc &MCID = getInstrInfo()->get(Opc);
3529 int CondNo = X86::getCondSrcNoFromDesc(MCID);
3530 if (CondNo < 0)
3531 return X86::COND_INVALID;
3532
3533 return static_cast<X86::CondCode>(N->getConstantOperandVal(CondNo));
3534}
3535
3536/// Test whether the given X86ISD::CMP node has any users that use a flag
3537/// other than ZF.
3538bool X86DAGToDAGISel::onlyUsesZeroFlag(SDValue Flags) const {
3539 // Examine each user of the node.
3540 for (SDUse &Use : Flags->uses()) {
3541 // Only check things that use the flags.
3542 if (Use.getResNo() != Flags.getResNo())
3543 continue;
3544 SDNode *User = Use.getUser();
3545 // Only examine CopyToReg uses that copy to EFLAGS.
3546 if (User->getOpcode() != ISD::CopyToReg ||
3547 cast<RegisterSDNode>(User->getOperand(1))->getReg() != X86::EFLAGS)
3548 return false;
3549 // Examine each user of the CopyToReg use.
3550 for (SDUse &FlagUse : User->uses()) {
3551 // Only examine the Flag result.
3552 if (FlagUse.getResNo() != 1)
3553 continue;
3554 // Anything unusual: assume conservatively.
3555 if (!FlagUse.getUser()->isMachineOpcode())
3556 return false;
3557 // Examine the condition code of the user.
3558 X86::CondCode CC = getCondFromNode(FlagUse.getUser());
3559
3560 switch (CC) {
3561 // Comparisons which only use the zero flag.
3562 case X86::COND_E: case X86::COND_NE:
3563 continue;
3564 // Anything else: assume conservatively.
3565 default:
3566 return false;
3567 }
3568 }
3569 }
3570 return true;
3571}
3572
3573/// Test whether the given X86ISD::CMP node has any uses which require the SF
3574/// flag to be accurate.
3575bool X86DAGToDAGISel::hasNoSignFlagUses(SDValue Flags) const {
3576 // Examine each user of the node.
3577 for (SDUse &Use : Flags->uses()) {
3578 // Only check things that use the flags.
3579 if (Use.getResNo() != Flags.getResNo())
3580 continue;
3581 SDNode *User = Use.getUser();
3582 // Only examine CopyToReg uses that copy to EFLAGS.
3583 if (User->getOpcode() != ISD::CopyToReg ||
3584 cast<RegisterSDNode>(User->getOperand(1))->getReg() != X86::EFLAGS)
3585 return false;
3586 // Examine each user of the CopyToReg use.
3587 for (SDUse &FlagUse : User->uses()) {
3588 // Only examine the Flag result.
3589 if (FlagUse.getResNo() != 1)
3590 continue;
3591 // Anything unusual: assume conservatively.
3592 if (!FlagUse.getUser()->isMachineOpcode())
3593 return false;
3594 // Examine the condition code of the user.
3595 X86::CondCode CC = getCondFromNode(FlagUse.getUser());
3596
3597 switch (CC) {
3598 // Comparisons which don't examine the SF flag.
3599 case X86::COND_A: case X86::COND_AE:
3600 case X86::COND_B: case X86::COND_BE:
3601 case X86::COND_E: case X86::COND_NE:
3602 case X86::COND_O: case X86::COND_NO:
3603 case X86::COND_P: case X86::COND_NP:
3604 continue;
3605 // Anything else: assume conservatively.
3606 default:
3607 return false;
3608 }
3609 }
3610 }
3611 return true;
3612}
3613
3615 switch (CC) {
3616 // Comparisons which don't examine the CF flag.
3617 case X86::COND_O: case X86::COND_NO:
3618 case X86::COND_E: case X86::COND_NE:
3619 case X86::COND_S: case X86::COND_NS:
3620 case X86::COND_P: case X86::COND_NP:
3621 case X86::COND_L: case X86::COND_GE:
3622 case X86::COND_G: case X86::COND_LE:
3623 return false;
3624 // Anything else: assume conservatively.
3625 default:
3626 return true;
3627 }
3628}
3629
3630/// Test whether the given node which sets flags has any uses which require the
3631/// CF flag to be accurate.
3632 bool X86DAGToDAGISel::hasNoCarryFlagUses(SDValue Flags) const {
3633 // Examine each user of the node.
3634 for (SDUse &Use : Flags->uses()) {
3635 // Only check things that use the flags.
3636 if (Use.getResNo() != Flags.getResNo())
3637 continue;
3638
3639 SDNode *User = Use.getUser();
3640 unsigned UserOpc = User->getOpcode();
3641
3642 if (UserOpc == ISD::CopyToReg) {
3643 // Only examine CopyToReg uses that copy to EFLAGS.
3644 if (cast<RegisterSDNode>(User->getOperand(1))->getReg() != X86::EFLAGS)
3645 return false;
3646 // Examine each user of the CopyToReg use.
3647 for (SDUse &FlagUse : User->uses()) {
3648 // Only examine the Flag result.
3649 if (FlagUse.getResNo() != 1)
3650 continue;
3651 // Anything unusual: assume conservatively.
3652 if (!FlagUse.getUser()->isMachineOpcode())
3653 return false;
3654 // Examine the condition code of the user.
3655 X86::CondCode CC = getCondFromNode(FlagUse.getUser());
3656
3657 if (mayUseCarryFlag(CC))
3658 return false;
3659 }
3660
3661 // This CopyToReg is ok. Move on to the next user.
3662 continue;
3663 }
3664
3665 // This might be an unselected node. So look for the pre-isel opcodes that
3666 // use flags.
3667 unsigned CCOpNo;
3668 switch (UserOpc) {
3669 default:
3670 // Something unusual. Be conservative.
3671 return false;
3672 case X86ISD::SETCC: CCOpNo = 0; break;
3673 case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
3674 case X86ISD::CMOV: CCOpNo = 2; break;
3675 case X86ISD::BRCOND: CCOpNo = 2; break;
3676 }
3677
3678 X86::CondCode CC = (X86::CondCode)User->getConstantOperandVal(CCOpNo);
3679 if (mayUseCarryFlag(CC))
3680 return false;
3681 }
3682 return true;
3683}
3684
3685bool X86DAGToDAGISel::checkTCRetEnoughRegs(SDNode *N) const {
3686 // Check that there is enough volatile registers to load the callee address.
3687
3688 const X86RegisterInfo *RI = Subtarget->getRegisterInfo();
3689 unsigned AvailGPRs;
3690 // The register classes below must stay in sync with what's used for
3691 // TCRETURNri, TCRETURN_HIPE32ri, TCRETURN_WIN64ri, etc).
3692 if (Subtarget->is64Bit()) {
3693 const TargetRegisterClass *TCGPRs =
3694 Subtarget->isCallingConvWin64(MF->getFunction().getCallingConv())
3695 ? &X86::GR64_TCW64RegClass
3696 : &X86::GR64_TCRegClass;
3697 // Can't use RSP or RIP for the load in general.
3698 assert(TCGPRs->contains(X86::RSP));
3699 assert(TCGPRs->contains(X86::RIP));
3700 AvailGPRs = TCGPRs->getNumRegs() - 2;
3701 } else {
3702 const TargetRegisterClass *TCGPRs =
3703 MF->getFunction().getCallingConv() == CallingConv::HiPE
3704 ? &X86::GR32RegClass
3705 : &X86::GR32_TCRegClass;
3706 // Can't use ESP for the address in general.
3707 assert(TCGPRs->contains(X86::ESP));
3708 AvailGPRs = TCGPRs->getNumRegs() - 1;
3709 }
3710
3711 // The load's base and index need up to two registers.
3712 unsigned LoadGPRs = 2;
3713
3714 assert(N->getOpcode() == X86ISD::TC_RETURN);
3715 // X86tcret args: (*chain, ptr, imm, regs..., glue)
3716
3717 if (Subtarget->is32Bit()) {
3718 // FIXME: This was carried from X86tcret_1reg which was used for 32-bit,
3719 // but it could apply to 64-bit too.
3720 const SDValue &BasePtr = cast<LoadSDNode>(N->getOperand(1))->getBasePtr();
3721 if (isa<FrameIndexSDNode>(BasePtr)) {
3722 LoadGPRs -= 2; // Base is fixed index off ESP; no regs needed.
3723 } else if (BasePtr.getOpcode() == X86ISD::Wrapper &&
3724 isa<GlobalAddressSDNode>(BasePtr->getOperand(0))) {
3725 if (getTargetMachine().isPositionIndependent())
3726 return false;
3727 LoadGPRs -= 1; // Base is a global (immediate since this is non-PIC), no
3728 // reg needed.
3729 }
3730 }
3731
3732 unsigned ArgGPRs = 0;
3733 for (unsigned I = 3, E = N->getNumOperands(); I != E; ++I) {
3734 if (const auto *RN = dyn_cast<RegisterSDNode>(N->getOperand(I))) {
3735 if (!RI->isGeneralPurposeRegister(*MF, RN->getReg()))
3736 continue;
3737 if (++ArgGPRs + LoadGPRs > AvailGPRs)
3738 return false;
3739 }
3740 }
3741
3742 return true;
3743}
3744
3745/// Check whether or not the chain ending in StoreNode is suitable for doing
3746/// the {load; op; store} to modify transformation.
3748 SDValue StoredVal, SelectionDAG *CurDAG,
3749 unsigned LoadOpNo,
3750 LoadSDNode *&LoadNode,
3751 SDValue &InputChain) {
3752 // Is the stored value result 0 of the operation?
3753 if (StoredVal.getResNo() != 0) return false;
3754
3755 // Are there other uses of the operation other than the store?
3756 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
3757
3758 // Is the store non-extending and non-indexed?
3759 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
3760 return false;
3761
3762 SDValue Load = StoredVal->getOperand(LoadOpNo);
3763 // Is the stored value a non-extending and non-indexed load?
3764 if (!ISD::isNormalLoad(Load.getNode())) return false;
3765
3766 // Return LoadNode by reference.
3767 LoadNode = cast<LoadSDNode>(Load);
3768
3769 // Is store the only read of the loaded value?
3770 if (!Load.hasOneUse())
3771 return false;
3772
3773 // Is the address of the store the same as the load?
3774 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
3775 LoadNode->getOffset() != StoreNode->getOffset())
3776 return false;
3777
3778 bool FoundLoad = false;
3779 SmallVector<SDValue, 4> ChainOps;
3780 SmallVector<const SDNode *, 4> LoopWorklist;
3782 const unsigned int Max = 1024;
3783
3784 // Visualization of Load-Op-Store fusion:
3785 // -------------------------
3786 // Legend:
3787 // *-lines = Chain operand dependencies.
3788 // |-lines = Normal operand dependencies.
3789 // Dependencies flow down and right. n-suffix references multiple nodes.
3790 //
3791 // C Xn C
3792 // * * *
3793 // * * *
3794 // Xn A-LD Yn TF Yn
3795 // * * \ | * |
3796 // * * \ | * |
3797 // * * \ | => A--LD_OP_ST
3798 // * * \| \
3799 // TF OP \
3800 // * | \ Zn
3801 // * | \
3802 // A-ST Zn
3803 //
3804
3805 // This merge induced dependences from: #1: Xn -> LD, OP, Zn
3806 // #2: Yn -> LD
3807 // #3: ST -> Zn
3808
3809 // Ensure the transform is safe by checking for the dual
3810 // dependencies to make sure we do not induce a loop.
3811
3812 // As LD is a predecessor to both OP and ST we can do this by checking:
3813 // a). if LD is a predecessor to a member of Xn or Yn.
3814 // b). if a Zn is a predecessor to ST.
3815
3816 // However, (b) can only occur through being a chain predecessor to
3817 // ST, which is the same as Zn being a member or predecessor of Xn,
3818 // which is a subset of LD being a predecessor of Xn. So it's
3819 // subsumed by check (a).
3820
3821 SDValue Chain = StoreNode->getChain();
3822
3823 // Gather X elements in ChainOps.
3824 if (Chain == Load.getValue(1)) {
3825 FoundLoad = true;
3826 ChainOps.push_back(Load.getOperand(0));
3827 } else if (Chain.getOpcode() == ISD::TokenFactor) {
3828 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
3829 SDValue Op = Chain.getOperand(i);
3830 if (Op == Load.getValue(1)) {
3831 FoundLoad = true;
3832 // Drop Load, but keep its chain. No cycle check necessary.
3833 ChainOps.push_back(Load.getOperand(0));
3834 continue;
3835 }
3836 LoopWorklist.push_back(Op.getNode());
3837 ChainOps.push_back(Op);
3838 }
3839 }
3840
3841 if (!FoundLoad)
3842 return false;
3843
3844 // Worklist is currently Xn. Add Yn to worklist.
3845 for (SDValue Op : StoredVal->ops())
3846 if (Op.getNode() != LoadNode)
3847 LoopWorklist.push_back(Op.getNode());
3848
3849 // Check (a) if Load is a predecessor to Xn + Yn
3850 if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
3851 true))
3852 return false;
3853
3854 InputChain =
3855 CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
3856 return true;
3857}
3858
3859// Change a chain of {load; op; store} of the same value into a simple op
3860// through memory of that value, if the uses of the modified value and its
3861// address are suitable.
3862//
3863// The tablegen pattern memory operand pattern is currently not able to match
3864// the case where the EFLAGS on the original operation are used.
3865//
3866// To move this to tablegen, we'll need to improve tablegen to allow flags to
3867// be transferred from a node in the pattern to the result node, probably with
3868// a new keyword. For example, we have this
3869// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
3870// [(store (add (loadi64 addr:$dst), -1), addr:$dst)]>;
3871// but maybe need something like this
3872// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
3873// [(store (X86add_flag (loadi64 addr:$dst), -1), addr:$dst),
3874// (transferrable EFLAGS)]>;
3875//
3876// Until then, we manually fold these and instruction select the operation
3877// here.
3878bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
3879 auto *StoreNode = cast<StoreSDNode>(Node);
3880 SDValue StoredVal = StoreNode->getOperand(1);
3881 unsigned Opc = StoredVal->getOpcode();
3882
3883 // Before we try to select anything, make sure this is memory operand size
3884 // and opcode we can handle. Note that this must match the code below that
3885 // actually lowers the opcodes.
3886 EVT MemVT = StoreNode->getMemoryVT();
3887 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
3888 MemVT != MVT::i8)
3889 return false;
3890
3891 bool IsCommutable = false;
3892 bool IsNegate = false;
3893 switch (Opc) {
3894 default:
3895 return false;
3896 case X86ISD::SUB:
3897 IsNegate = isNullConstant(StoredVal.getOperand(0));
3898 break;
3899 case X86ISD::SBB:
3900 break;
3901 case X86ISD::ADD:
3902 case X86ISD::ADC:
3903 case X86ISD::AND:
3904 case X86ISD::OR:
3905 case X86ISD::XOR:
3906 IsCommutable = true;
3907 break;
3908 }
3909
3910 unsigned LoadOpNo = IsNegate ? 1 : 0;
3911 LoadSDNode *LoadNode = nullptr;
3912 SDValue InputChain;
3913 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
3914 LoadNode, InputChain)) {
3915 if (!IsCommutable)
3916 return false;
3917
3918 // This operation is commutable, try the other operand.
3919 LoadOpNo = 1;
3920 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
3921 LoadNode, InputChain))
3922 return false;
3923 }
3924
3925 SDValue Base, Scale, Index, Disp, Segment;
3926 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
3927 Segment))
3928 return false;
3929
3930 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
3931 unsigned Opc8) {
3932 switch (MemVT.getSimpleVT().SimpleTy) {
3933 case MVT::i64:
3934 return Opc64;
3935 case MVT::i32:
3936 return Opc32;
3937 case MVT::i16:
3938 return Opc16;
3939 case MVT::i8:
3940 return Opc8;
3941 default:
3942 llvm_unreachable("Invalid size!");
3943 }
3944 };
3945
3946 MachineSDNode *Result;
3947 switch (Opc) {
3948 case X86ISD::SUB:
3949 // Handle negate.
3950 if (IsNegate) {
3951 unsigned NewOpc = SelectOpcode(X86::NEG64m, X86::NEG32m, X86::NEG16m,
3952 X86::NEG8m);
3953 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
3954 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
3955 MVT::Other, Ops);
3956 break;
3957 }
3958 [[fallthrough]];
3959 case X86ISD::ADD:
3960 // Try to match inc/dec.
3961 if (!Subtarget->slowIncDec() || CurDAG->shouldOptForSize()) {
3962 bool IsOne = isOneConstant(StoredVal.getOperand(1));
3963 bool IsNegOne = isAllOnesConstant(StoredVal.getOperand(1));
3964 // ADD/SUB with 1/-1 and carry flag isn't used can use inc/dec.
3965 if ((IsOne || IsNegOne) && hasNoCarryFlagUses(StoredVal.getValue(1))) {
3966 unsigned NewOpc =
3967 ((Opc == X86ISD::ADD) == IsOne)
3968 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
3969 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
3970 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
3971 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
3972 MVT::Other, Ops);
3973 break;
3974 }
3975 }
3976 [[fallthrough]];
3977 case X86ISD::ADC:
3978 case X86ISD::SBB:
3979 case X86ISD::AND:
3980 case X86ISD::OR:
3981 case X86ISD::XOR: {
3982 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
3983 switch (Opc) {
3984 case X86ISD::ADD:
3985 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
3986 X86::ADD8mr);
3987 case X86ISD::ADC:
3988 return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
3989 X86::ADC8mr);
3990 case X86ISD::SUB:
3991 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
3992 X86::SUB8mr);
3993 case X86ISD::SBB:
3994 return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
3995 X86::SBB8mr);
3996 case X86ISD::AND:
3997 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
3998 X86::AND8mr);
3999 case X86ISD::OR:
4000 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
4001 case X86ISD::XOR:
4002 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
4003 X86::XOR8mr);
4004 default:
4005 llvm_unreachable("Invalid opcode!");
4006 }
4007 };
4008 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
4009 switch (Opc) {
4010 case X86ISD::ADD:
4011 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
4012 X86::ADD8mi);
4013 case X86ISD::ADC:
4014 return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
4015 X86::ADC8mi);
4016 case X86ISD::SUB:
4017 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
4018 X86::SUB8mi);
4019 case X86ISD::SBB:
4020 return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
4021 X86::SBB8mi);
4022 case X86ISD::AND:
4023 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
4024 X86::AND8mi);
4025 case X86ISD::OR:
4026 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
4027 X86::OR8mi);
4028 case X86ISD::XOR:
4029 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
4030 X86::XOR8mi);
4031 default:
4032 llvm_unreachable("Invalid opcode!");
4033 }
4034 };
4035
4036 unsigned NewOpc = SelectRegOpcode(Opc);
4037 SDValue Operand = StoredVal->getOperand(1-LoadOpNo);
4038
4039 // See if the operand is a constant that we can fold into an immediate
4040 // operand.
4041 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
4042 int64_t OperandV = OperandC->getSExtValue();
4043
4044 // Check if we can shrink the operand enough to fit in an immediate (or
4045 // fit into a smaller immediate) by negating it and switching the
4046 // operation.
4047 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
4048 ((MemVT != MVT::i8 && !isInt<8>(OperandV) && isInt<8>(-OperandV)) ||
4049 (MemVT == MVT::i64 && !isInt<32>(OperandV) &&
4050 isInt<32>(-OperandV))) &&
4051 hasNoCarryFlagUses(StoredVal.getValue(1))) {
4052 OperandV = -OperandV;
4053 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
4054 }
4055
4056 if (MemVT != MVT::i64 || isInt<32>(OperandV)) {
4057 Operand = CurDAG->getSignedTargetConstant(OperandV, SDLoc(Node), MemVT);
4058 NewOpc = SelectImmOpcode(Opc);
4059 }
4060 }
4061
4062 if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
4063 SDValue CopyTo =
4064 CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
4065 StoredVal.getOperand(2), SDValue());
4066
4067 const SDValue Ops[] = {Base, Scale, Index, Disp,
4068 Segment, Operand, CopyTo, CopyTo.getValue(1)};
4069 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
4070 Ops);
4071 } else {
4072 const SDValue Ops[] = {Base, Scale, Index, Disp,
4073 Segment, Operand, InputChain};
4074 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
4075 Ops);
4076 }
4077 break;
4078 }
4079 default:
4080 llvm_unreachable("Invalid opcode!");
4081 }
4082
4083 MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(),
4084 LoadNode->getMemOperand()};
4085 CurDAG->setNodeMemRefs(Result, MemOps);
4086
4087 // Update Load Chain uses as well.
4088 ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
4089 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
4090 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
4091 CurDAG->RemoveDeadNode(Node);
4092 return true;
4093}
4094
4095// See if this is an X & Mask that we can match to BEXTR/BZHI.
4096// Where Mask is one of the following patterns:
4097// a) x & (1 << nbits) - 1
4098// b) x & ~(-1 << nbits)
4099// c) x & (-1 >> (32 - y))
4100// d) x << (32 - y) >> (32 - y)
4101// e) (1 << nbits) - 1
4102bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) {
4103 assert(
4104 (Node->getOpcode() == ISD::ADD || Node->getOpcode() == ISD::AND ||
4105 Node->getOpcode() == ISD::SRL) &&
4106 "Should be either an and-mask, or right-shift after clearing high bits.");
4107
4108 // BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one.
4109 if (!Subtarget->hasBMI() && !Subtarget->hasBMI2())
4110 return false;
4111
4112 MVT NVT = Node->getSimpleValueType(0);
4113
4114 // Only supported for 32 and 64 bits.
4115 if (NVT != MVT::i32 && NVT != MVT::i64)
4116 return false;
4117
4118 SDValue NBits;
4119 bool NegateNBits;
4120
4121 // If we have BMI2's BZHI, we are ok with muti-use patterns.
4122 // Else, if we only have BMI1's BEXTR, we require one-use.
4123 const bool AllowExtraUsesByDefault = Subtarget->hasBMI2();
4124 auto checkUses = [AllowExtraUsesByDefault](
4125 SDValue Op, unsigned NUses,
4126 std::optional<bool> AllowExtraUses) {
4127 return AllowExtraUses.value_or(AllowExtraUsesByDefault) ||
4128 Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo());
4129 };
4130 auto checkOneUse = [checkUses](SDValue Op,
4131 std::optional<bool> AllowExtraUses =
4132 std::nullopt) {
4133 return checkUses(Op, 1, AllowExtraUses);
4134 };
4135 auto checkTwoUse = [checkUses](SDValue Op,
4136 std::optional<bool> AllowExtraUses =
4137 std::nullopt) {
4138 return checkUses(Op, 2, AllowExtraUses);
4139 };
4140
4141 auto peekThroughOneUseTruncation = [checkOneUse](SDValue V) {
4142 if (V->getOpcode() == ISD::TRUNCATE && checkOneUse(V)) {
4143 assert(V.getSimpleValueType() == MVT::i32 &&
4144 V.getOperand(0).getSimpleValueType() == MVT::i64 &&
4145 "Expected i64 -> i32 truncation");
4146 V = V.getOperand(0);
4147 }
4148 return V;
4149 };
4150
4151 // a) x & ((1 << nbits) + (-1))
4152 auto matchPatternA = [checkOneUse, peekThroughOneUseTruncation, &NBits,
4153 &NegateNBits](SDValue Mask) -> bool {
4154 // Match `add`. Must only have one use!
4155 if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask))
4156 return false;
4157 // We should be adding all-ones constant (i.e. subtracting one.)
4158 if (!isAllOnesConstant(Mask->getOperand(1)))
4159 return false;
4160 // Match `1 << nbits`. Might be truncated. Must only have one use!
4161 SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));
4162 if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
4163 return false;
4164 if (!isOneConstant(M0->getOperand(0)))
4165 return false;
4166 NBits = M0->getOperand(1);
4167 NegateNBits = false;
4168 return true;
4169 };
4170
4171 auto isAllOnes = [this, peekThroughOneUseTruncation, NVT](SDValue V) {
4172 V = peekThroughOneUseTruncation(V);
4173 return CurDAG->MaskedValueIsAllOnes(
4174 V, APInt::getLowBitsSet(V.getSimpleValueType().getSizeInBits(),
4175 NVT.getSizeInBits()));
4176 };
4177
4178 // b) x & ~(-1 << nbits)
4179 auto matchPatternB = [checkOneUse, isAllOnes, peekThroughOneUseTruncation,
4180 &NBits, &NegateNBits](SDValue Mask) -> bool {
4181 // Match `~()`. Must only have one use!
4182 if (Mask.getOpcode() != ISD::XOR || !checkOneUse(Mask))
4183 return false;
4184 // The -1 only has to be all-ones for the final Node's NVT.
4185 if (!isAllOnes(Mask->getOperand(1)))
4186 return false;
4187 // Match `-1 << nbits`. Might be truncated. Must only have one use!
4188 SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));
4189 if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
4190 return false;
4191 // The -1 only has to be all-ones for the final Node's NVT.
4192 if (!isAllOnes(M0->getOperand(0)))
4193 return false;
4194 NBits = M0->getOperand(1);
4195 NegateNBits = false;
4196 return true;
4197 };
4198
4199 // Try to match potentially-truncated shift amount as `(bitwidth - y)`,
4200 // or leave the shift amount as-is, but then we'll have to negate it.
4201 auto canonicalizeShiftAmt = [&NBits, &NegateNBits](SDValue ShiftAmt,
4202 unsigned Bitwidth) {
4203 NBits = ShiftAmt;
4204 NegateNBits = true;
4205 // Skip over a truncate of the shift amount, if any.
4206 if (NBits.getOpcode() == ISD::TRUNCATE)
4207 NBits = NBits.getOperand(0);
4208 // Try to match the shift amount as (bitwidth - y). It should go away, too.
4209 // If it doesn't match, that's fine, we'll just negate it ourselves.
4210 if (NBits.getOpcode() != ISD::SUB)
4211 return;
4212 auto *V0 = dyn_cast<ConstantSDNode>(NBits.getOperand(0));
4213 if (!V0 || V0->getZExtValue() != Bitwidth)
4214 return;
4215 NBits = NBits.getOperand(1);
4216 NegateNBits = false;
4217 };
4218
4219 // c) x & (-1 >> z) but then we'll have to subtract z from bitwidth
4220 // or
4221 // c) x & (-1 >> (32 - y))
4222 auto matchPatternC = [checkOneUse, peekThroughOneUseTruncation, &NegateNBits,
4223 canonicalizeShiftAmt](SDValue Mask) -> bool {
4224 // The mask itself may be truncated.
4225 Mask = peekThroughOneUseTruncation(Mask);
4226 unsigned Bitwidth = Mask.getSimpleValueType().getSizeInBits();
4227 // Match `l>>`. Must only have one use!
4228 if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask))
4229 return false;
4230 // We should be shifting truly all-ones constant.
4231 if (!isAllOnesConstant(Mask.getOperand(0)))
4232 return false;
4233 SDValue M1 = Mask.getOperand(1);
4234 // The shift amount should not be used externally.
4235 if (!checkOneUse(M1))
4236 return false;
4237 canonicalizeShiftAmt(M1, Bitwidth);
4238 // Pattern c. is non-canonical, and is expanded into pattern d. iff there
4239 // is no extra use of the mask. Clearly, there was one since we are here.
4240 // But at the same time, if we need to negate the shift amount,
4241 // then we don't want the mask to stick around, else it's unprofitable.
4242 return !NegateNBits;
4243 };
4244
4245 SDValue X;
4246
4247 // d) x << z >> z but then we'll have to subtract z from bitwidth
4248 // or
4249 // d) x << (32 - y) >> (32 - y)
4250 auto matchPatternD = [checkOneUse, checkTwoUse, canonicalizeShiftAmt,
4251 AllowExtraUsesByDefault, &NegateNBits,
4252 &X](SDNode *Node) -> bool {
4253 if (Node->getOpcode() != ISD::SRL)
4254 return false;
4255 SDValue N0 = Node->getOperand(0);
4256 if (N0->getOpcode() != ISD::SHL)
4257 return false;
4258 unsigned Bitwidth = N0.getSimpleValueType().getSizeInBits();
4259 SDValue N1 = Node->getOperand(1);
4260 SDValue N01 = N0->getOperand(1);
4261 // Both of the shifts must be by the exact same value.
4262 if (N1 != N01)
4263 return false;
4264 canonicalizeShiftAmt(N1, Bitwidth);
4265 // There should not be any external uses of the inner shift / shift amount.
4266 // Note that while we are generally okay with external uses given BMI2,
4267 // iff we need to negate the shift amount, we are not okay with extra uses.
4268 const bool AllowExtraUses = AllowExtraUsesByDefault && !NegateNBits;
4269 if (!checkOneUse(N0, AllowExtraUses) || !checkTwoUse(N1, AllowExtraUses))
4270 return false;
4271 X = N0->getOperand(0);
4272 return true;
4273 };
4274
4275 auto matchLowBitMask = [matchPatternA, matchPatternB,
4276 matchPatternC](SDValue Mask) -> bool {
4277 return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask);
4278 };
4279
4280 if (Node->getOpcode() == ISD::AND) {
4281 X = Node->getOperand(0);
4282 SDValue Mask = Node->getOperand(1);
4283
4284 if (matchLowBitMask(Mask)) {
4285 // Great.
4286 } else {
4287 std::swap(X, Mask);
4288 if (!matchLowBitMask(Mask))
4289 return false;
4290 }
4291 } else if (matchLowBitMask(SDValue(Node, 0))) {
4292 X = CurDAG->getAllOnesConstant(SDLoc(Node), NVT);
4293 } else if (!matchPatternD(Node))
4294 return false;
4295
4296 // If we need to negate the shift amount, require BMI2 BZHI support.
4297 // It's just too unprofitable for BMI1 BEXTR.
4298 if (NegateNBits && !Subtarget->hasBMI2())
4299 return false;
4300
4301 SDLoc DL(Node);
4302
4303 if (NBits.getSimpleValueType() != MVT::i8) {
4304 // Truncate the shift amount.
4305 NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits);
4306 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
4307 }
4308
4309 // Turn (i32)(x & imm8) into (i32)x & imm32.
4310 ConstantSDNode *Imm = nullptr;
4311 if (NBits->getOpcode() == ISD::AND)
4312 if ((Imm = dyn_cast<ConstantSDNode>(NBits->getOperand(1))))
4313 NBits = NBits->getOperand(0);
4314
4315 // Insert 8-bit NBits into lowest 8 bits of 32-bit register.
4316 // All the other bits are undefined, we do not care about them.
4317 SDValue ImplDef = SDValue(
4318 CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i32), 0);
4319 insertDAGNode(*CurDAG, SDValue(Node, 0), ImplDef);
4320
4321 SDValue SRIdxVal = CurDAG->getTargetConstant(X86::sub_8bit, DL, MVT::i32);
4322 insertDAGNode(*CurDAG, SDValue(Node, 0), SRIdxVal);
4323 NBits = SDValue(CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
4324 MVT::i32, ImplDef, NBits, SRIdxVal),
4325 0);
4326 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
4327
4328 if (Imm) {
4329 NBits =
4330 CurDAG->getNode(ISD::AND, DL, MVT::i32, NBits,
4331 CurDAG->getConstant(Imm->getZExtValue(), DL, MVT::i32));
4332 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
4333 }
4334
4335 // We might have matched the amount of high bits to be cleared,
4336 // but we want the amount of low bits to be kept, so negate it then.
4337 if (NegateNBits) {
4338 SDValue BitWidthC = CurDAG->getConstant(NVT.getSizeInBits(), DL, MVT::i32);
4339 insertDAGNode(*CurDAG, SDValue(Node, 0), BitWidthC);
4340
4341 NBits = CurDAG->getNode(ISD::SUB, DL, MVT::i32, BitWidthC, NBits);
4342 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
4343 }
4344
4345 if (Subtarget->hasBMI2()) {
4346 // Great, just emit the BZHI..
4347 if (NVT != MVT::i32) {
4348 // But have to place the bit count into the wide-enough register first.
4349 NBits = CurDAG->getNode(ISD::ANY_EXTEND, DL, NVT, NBits);
4350 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
4351 }
4352
4353 SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, NVT, X, NBits);
4354 ReplaceNode(Node, Extract.getNode());
4355 SelectCode(Extract.getNode());
4356 return true;
4357 }
4358
4359 // Else, if we do *NOT* have BMI2, let's find out if the if the 'X' is
4360 // *logically* shifted (potentially with one-use trunc inbetween),
4361 // and the truncation was the only use of the shift,
4362 // and if so look past one-use truncation.
4363 {
4364 SDValue RealX = peekThroughOneUseTruncation(X);
4365 // FIXME: only if the shift is one-use?
4366 if (RealX != X && RealX.getOpcode() == ISD::SRL)
4367 X = RealX;
4368 }
4369
4370 MVT XVT = X.getSimpleValueType();
4371
4372 // Else, emitting BEXTR requires one more step.
4373 // The 'control' of BEXTR has the pattern of:
4374 // [15...8 bit][ 7...0 bit] location
4375 // [ bit count][ shift] name
4376 // I.e. 0b000000011'00000001 means (x >> 0b1) & 0b11
4377
4378 // Shift NBits left by 8 bits, thus producing 'control'.
4379 // This makes the low 8 bits to be zero.
4380 SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8);
4381 insertDAGNode(*CurDAG, SDValue(Node, 0), C8);
4382 SDValue Control = CurDAG->getNode(ISD::SHL, DL, MVT::i32, NBits, C8);
4383 insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
4384
4385 // If the 'X' is *logically* shifted, we can fold that shift into 'control'.
4386 // FIXME: only if the shift is one-use?
4387 if (X.getOpcode() == ISD::SRL) {
4388 SDValue ShiftAmt = X.getOperand(1);
4389 X = X.getOperand(0);
4390
4391 assert(ShiftAmt.getValueType() == MVT::i8 &&
4392 "Expected shift amount to be i8");
4393
4394 // Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero!
4395 // We could zext to i16 in some form, but we intentionally don't do that.
4396 SDValue OrigShiftAmt = ShiftAmt;
4397 ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShiftAmt);
4398 insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt);
4399
4400 // And now 'or' these low 8 bits of shift amount into the 'control'.
4401 Control = CurDAG->getNode(ISD::OR, DL, MVT::i32, Control, ShiftAmt);
4402 insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
4403 }
4404
4405 // But have to place the 'control' into the wide-enough register first.
4406 if (XVT != MVT::i32) {
4407 Control = CurDAG->getNode(ISD::ANY_EXTEND, DL, XVT, Control);
4408 insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
4409 }
4410
4411 // And finally, form the BEXTR itself.
4412 SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, XVT, X, Control);
4413
4414 // The 'X' was originally truncated. Do that now.
4415 if (XVT != NVT) {
4416 insertDAGNode(*CurDAG, SDValue(Node, 0), Extract);
4417 Extract = CurDAG->getNode(ISD::TRUNCATE, DL, NVT, Extract);
4418 }
4419
4420 ReplaceNode(Node, Extract.getNode());
4421 SelectCode(Extract.getNode());
4422
4423 return true;
4424}
4425
4426// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
4427MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) {
4428 MVT NVT = Node->getSimpleValueType(0);
4429 SDLoc dl(Node);
4430
4431 SDValue N0 = Node->getOperand(0);
4432 SDValue N1 = Node->getOperand(1);
4433
4434 // If we have TBM we can use an immediate for the control. If we have BMI
4435 // we should only do this if the BEXTR instruction is implemented well.
4436 // Otherwise moving the control into a register makes this more costly.
4437 // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM
4438 // hoisting the move immediate would make it worthwhile with a less optimal
4439 // BEXTR?
4440 bool PreferBEXTR =
4441 Subtarget->hasTBM() || (Subtarget->hasBMI() && Subtarget->hasFastBEXTR());
4442 if (!PreferBEXTR && !Subtarget->hasBMI2())
4443 return nullptr;
4444
4445 // Must have a shift right.
4446 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
4447 return nullptr;
4448
4449 // Shift can't have additional users.
4450 if (!N0->hasOneUse())
4451 return nullptr;
4452
4453 // Only supported for 32 and 64 bits.
4454 if (NVT != MVT::i32 && NVT != MVT::i64)
4455 return nullptr;
4456
4457 // Shift amount and RHS of and must be constant.
4458 auto *MaskCst = dyn_cast<ConstantSDNode>(N1);
4459 auto *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
4460 if (!MaskCst || !ShiftCst)
4461 return nullptr;
4462
4463 // And RHS must be a mask.
4464 uint64_t Mask = MaskCst->getZExtValue();
4465 if (!isMask_64(Mask))
4466 return nullptr;
4467
4468 uint64_t Shift = ShiftCst->getZExtValue();
4469 uint64_t MaskSize = llvm::popcount(Mask);
4470
4471 // Don't interfere with something that can be handled by extracting AH.
4472 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
4473 if (Shift == 8 && MaskSize == 8)
4474 return nullptr;
4475
4476 // Make sure we are only using bits that were in the original value, not
4477 // shifted in.
4478 if (Shift + MaskSize > NVT.getSizeInBits())
4479 return nullptr;
4480
4481 // BZHI, if available, is always fast, unlike BEXTR. But even if we decide
4482 // that we can't use BEXTR, it is only worthwhile using BZHI if the mask
4483 // does not fit into 32 bits. Load folding is not a sufficient reason.
4484 if (!PreferBEXTR && MaskSize <= 32)
4485 return nullptr;
4486
4487 SDValue Control;
4488 unsigned ROpc, MOpc;
4489
4490#define GET_EGPR_IF_ENABLED(OPC) (Subtarget->hasEGPR() ? OPC##_EVEX : OPC)
4491 if (!PreferBEXTR) {
4492 assert(Subtarget->hasBMI2() && "We must have BMI2's BZHI then.");
4493 // If we can't make use of BEXTR then we can't fuse shift+mask stages.
4494 // Let's perform the mask first, and apply shift later. Note that we need to
4495 // widen the mask to account for the fact that we'll apply shift afterwards!
4496 Control = CurDAG->getTargetConstant(Shift + MaskSize, dl, NVT);
4497 ROpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BZHI64rr)
4498 : GET_EGPR_IF_ENABLED(X86::BZHI32rr);
4499 MOpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BZHI64rm)
4500 : GET_EGPR_IF_ENABLED(X86::BZHI32rm);
4501 unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
4502 Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);
4503 } else {
4504 // The 'control' of BEXTR has the pattern of:
4505 // [15...8 bit][ 7...0 bit] location
4506 // [ bit count][ shift] name
4507 // I.e. 0b000000011'00000001 means (x >> 0b1) & 0b11
4508 Control = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
4509 if (Subtarget->hasTBM()) {
4510 ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
4511 MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
4512 } else {
4513 assert(Subtarget->hasBMI() && "We must have BMI1's BEXTR then.");
4514 // BMI requires the immediate to placed in a register.
4515 ROpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BEXTR64rr)
4516 : GET_EGPR_IF_ENABLED(X86::BEXTR32rr);
4517 MOpc = NVT == MVT::i64 ? GET_EGPR_IF_ENABLED(X86::BEXTR64rm)
4518 : GET_EGPR_IF_ENABLED(X86::BEXTR32rm);
4519 unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
4520 Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);
4521 }
4522 }
4523
4524 MachineSDNode *NewNode;
4525 SDValue Input = N0->getOperand(0);
4526 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4527 if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4528 SDValue Ops[] = {
4529 Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Control, Input.getOperand(0)};
4530 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
4531 NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4532 // Update the chain.
4533 ReplaceUses(Input.getValue(1), SDValue(NewNode, 2));
4534 // Record the mem-refs
4535 CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()});
4536 } else {
4537 NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, MVT::i32, Input, Control);
4538 }
4539
4540 if (!PreferBEXTR) {
4541 // We still need to apply the shift.
4542 SDValue ShAmt = CurDAG->getTargetConstant(Shift, dl, NVT);
4543 unsigned NewOpc = NVT == MVT::i64 ? GET_ND_IF_ENABLED(X86::SHR64ri)
4544 : GET_ND_IF_ENABLED(X86::SHR32ri);
4545 NewNode =
4546 CurDAG->getMachineNode(NewOpc, dl, NVT, SDValue(NewNode, 0), ShAmt);
4547 }
4548
4549 return NewNode;
4550}
4551
4552// Emit a PCMISTR(I/M) instruction.
4553MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
4554 bool MayFoldLoad, const SDLoc &dl,
4555 MVT VT, SDNode *Node) {
4556 SDValue N0 = Node->getOperand(0);
4557 SDValue N1 = Node->getOperand(1);
4558 SDValue Imm = Node->getOperand(2);
4559 auto *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
4560 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
4561
4562 // Try to fold a load. No need to check alignment.
4563 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4564 if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4565 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
4566 N1.getOperand(0) };
4567 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
4568 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4569 // Update the chain.
4570 ReplaceUses(N1.getValue(1), SDValue(CNode, 2));
4571 // Record the mem-refs
4572 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
4573 return CNode;
4574 }
4575
4576 SDValue Ops[] = { N0, N1, Imm };
4577 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
4578 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
4579 return CNode;
4580}
4581
4582// Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
4583// to emit a second instruction after this one. This is needed since we have two
4584// copyToReg nodes glued before this and we need to continue that glue through.
4585MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
4586 bool MayFoldLoad, const SDLoc &dl,
4587 MVT VT, SDNode *Node,
4588 SDValue &InGlue) {
4589 SDValue N0 = Node->getOperand(0);
4590 SDValue N2 = Node->getOperand(2);
4591 SDValue Imm = Node->getOperand(4);
4592 auto *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
4593 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
4594
4595 // Try to fold a load. No need to check alignment.
4596 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4597 if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4598 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
4599 N2.getOperand(0), InGlue };
4600 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
4601 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4602 InGlue = SDValue(CNode, 3);
4603 // Update the chain.
4604 ReplaceUses(N2.getValue(1), SDValue(CNode, 2));
4605 // Record the mem-refs
4606 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()});
4607 return CNode;
4608 }
4609
4610 SDValue Ops[] = { N0, N2, Imm, InGlue };
4611 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
4612 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
4613 InGlue = SDValue(CNode, 2);
4614 return CNode;
4615}
4616
4617bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
4618 EVT VT = N->getValueType(0);
4619
4620 // Only handle scalar shifts.
4621 if (VT.isVector())
4622 return false;
4623
4624 // Narrower shifts only mask to 5 bits in hardware.
4625 unsigned Size = VT == MVT::i64 ? 64 : 32;
4626
4627 SDValue OrigShiftAmt = N->getOperand(1);
4628 SDValue ShiftAmt = OrigShiftAmt;
4629 SDLoc DL(N);
4630
4631 // Skip over a truncate of the shift amount.
4632 if (ShiftAmt->getOpcode() == ISD::TRUNCATE)
4633 ShiftAmt = ShiftAmt->getOperand(0);
4634
4635 // This function is called after X86DAGToDAGISel::matchBitExtract(),
4636 // so we are not afraid that we might mess up BZHI/BEXTR pattern.
4637
4638 SDValue NewShiftAmt;
4639 if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB ||
4640 ShiftAmt->getOpcode() == ISD::XOR) {
4641 SDValue Add0 = ShiftAmt->getOperand(0);
4642 SDValue Add1 = ShiftAmt->getOperand(1);
4643 auto *Add0C = dyn_cast<ConstantSDNode>(Add0);
4644 auto *Add1C = dyn_cast<ConstantSDNode>(Add1);
4645 // If we are shifting by X+/-/^N where N == 0 mod Size, then just shift by X
4646 // to avoid the ADD/SUB/XOR.
4647 if (Add1C && Add1C->getAPIntValue().urem(Size) == 0) {
4648 NewShiftAmt = Add0;
4649
4650 } else if (ShiftAmt->getOpcode() != ISD::ADD && ShiftAmt.hasOneUse() &&
4651 ((Add0C && Add0C->getAPIntValue().urem(Size) == Size - 1) ||
4652 (Add1C && Add1C->getAPIntValue().urem(Size) == Size - 1))) {
4653 // If we are doing a NOT on just the lower bits with (Size*N-1) -/^ X
4654 // we can replace it with a NOT. In the XOR case it may save some code
4655 // size, in the SUB case it also may save a move.
4656 assert(Add0C == nullptr || Add1C == nullptr);
4657
4658 // We can only do N-X, not X-N
4659 if (ShiftAmt->getOpcode() == ISD::SUB && Add0C == nullptr)
4660 return false;
4661
4662 EVT OpVT = ShiftAmt.getValueType();
4663
4664 SDValue AllOnes = CurDAG->getAllOnesConstant(DL, OpVT);
4665 NewShiftAmt = CurDAG->getNode(ISD::XOR, DL, OpVT,
4666 Add0C == nullptr ? Add0 : Add1, AllOnes);
4667 insertDAGNode(*CurDAG, OrigShiftAmt, AllOnes);
4668 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
4669 // If we are shifting by N-X where N == 0 mod Size, then just shift by
4670 // -X to generate a NEG instead of a SUB of a constant.
4671 } else if (ShiftAmt->getOpcode() == ISD::SUB && Add0C &&
4672 Add0C->getZExtValue() != 0) {
4673 EVT SubVT = ShiftAmt.getValueType();
4674 SDValue X;
4675 if (Add0C->getZExtValue() % Size == 0)
4676 X = Add1;
4677 else if (ShiftAmt.hasOneUse() && Size == 64 &&
4678 Add0C->getZExtValue() % 32 == 0) {
4679 // We have a 64-bit shift by (n*32-x), turn it into -(x+n*32).
4680 // This is mainly beneficial if we already compute (x+n*32).
4681 if (Add1.getOpcode() == ISD::TRUNCATE) {
4682 Add1 = Add1.getOperand(0);
4683 SubVT = Add1.getValueType();
4684 }
4685 if (Add0.getValueType() != SubVT) {
4686 Add0 = CurDAG->getZExtOrTrunc(Add0, DL, SubVT);
4687 insertDAGNode(*CurDAG, OrigShiftAmt, Add0);
4688 }
4689
4690 X = CurDAG->getNode(ISD::ADD, DL, SubVT, Add1, Add0);
4691 insertDAGNode(*CurDAG, OrigShiftAmt, X);
4692 } else
4693 return false;
4694 // Insert a negate op.
4695 // TODO: This isn't guaranteed to replace the sub if there is a logic cone
4696 // that uses it that's not a shift.
4697 SDValue Zero = CurDAG->getConstant(0, DL, SubVT);
4698 SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, X);
4699 NewShiftAmt = Neg;
4700
4701 // Insert these operands into a valid topological order so they can
4702 // get selected independently.
4703 insertDAGNode(*CurDAG, OrigShiftAmt, Zero);
4704 insertDAGNode(*CurDAG, OrigShiftAmt, Neg);
4705 } else
4706 return false;
4707 } else
4708 return false;
4709
4710 if (NewShiftAmt.getValueType() != MVT::i8) {
4711 // Need to truncate the shift amount.
4712 NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt);
4713 // Add to a correct topological ordering.
4714 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
4715 }
4716
4717 // Insert a new mask to keep the shift amount legal. This should be removed
4718 // by isel patterns.
4719 NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt,
4720 CurDAG->getConstant(Size - 1, DL, MVT::i8));
4721 // Place in a correct topological ordering.
4722 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
4723
4724 SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
4725 NewShiftAmt);
4726 if (UpdatedNode != N) {
4727 // If we found an existing node, we should replace ourselves with that node
4728 // and wait for it to be selected after its other users.
4729 ReplaceNode(N, UpdatedNode);
4730 return true;
4731 }
4732
4733 // If the original shift amount is now dead, delete it so that we don't run
4734 // it through isel.
4735 if (OrigShiftAmt.getNode()->use_empty())
4736 CurDAG->RemoveDeadNode(OrigShiftAmt.getNode());
4737
4738 // Now that we've optimized the shift amount, defer to normal isel to get
4739 // load folding and legacy vs BMI2 selection without repeating it here.
4740 SelectCode(N);
4741 return true;
4742}
4743
4744bool X86DAGToDAGISel::tryShrinkShlLogicImm(SDNode *N) {
4745 MVT NVT = N->getSimpleValueType(0);
4746 unsigned Opcode = N->getOpcode();
4747 SDLoc dl(N);
4748
4749 // For operations of the form (x << C1) op C2, check if we can use a smaller
4750 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
4751 SDValue Shift = N->getOperand(0);
4752 SDValue N1 = N->getOperand(1);
4753
4754 auto *Cst = dyn_cast<ConstantSDNode>(N1);
4755 if (!Cst)
4756 return false;
4757
4758 int64_t Val = Cst->getSExtValue();
4759
4760 // If we have an any_extend feeding the AND, look through it to see if there
4761 // is a shift behind it. But only if the AND doesn't use the extended bits.
4762 // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
4763 bool FoundAnyExtend = false;
4764 if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
4765 Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
4766 isUInt<32>(Val)) {
4767 FoundAnyExtend = true;
4768 Shift = Shift.getOperand(0);
4769 }
4770
4771 if (Shift.getOpcode() != ISD::SHL || !Shift.hasOneUse())
4772 return false;
4773
4774 // i8 is unshrinkable, i16 should be promoted to i32.
4775 if (NVT != MVT::i32 && NVT != MVT::i64)
4776 return false;
4777
4778 auto *ShlCst = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4779 if (!ShlCst)
4780 return false;
4781
4782 uint64_t ShAmt = ShlCst->getZExtValue();
4783
4784 // Make sure that we don't change the operation by removing bits.
4785 // This only matters for OR and XOR, AND is unaffected.
4786 uint64_t RemovedBitsMask = (1ULL << ShAmt) - 1;
4787 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
4788 return false;
4789
4790 // Check the minimum bitwidth for the new constant.
4791 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
4792 auto CanShrinkImmediate = [&](int64_t &ShiftedVal) {
4793 if (Opcode == ISD::AND) {
4794 // AND32ri is the same as AND64ri32 with zext imm.
4795 // Try this before sign extended immediates below.
4796 ShiftedVal = (uint64_t)Val >> ShAmt;
4797 if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
4798 return true;
4799 // Also swap order when the AND can become MOVZX.
4800 if (ShiftedVal == UINT8_MAX || ShiftedVal == UINT16_MAX)
4801 return true;
4802 }
4803 ShiftedVal = Val >> ShAmt;
4804 if ((!isInt<8>(Val) && isInt<8>(ShiftedVal)) ||
4805 (!isInt<32>(Val) && isInt<32>(ShiftedVal)))
4806 return true;
4807 if (Opcode != ISD::AND) {
4808 // MOV32ri+OR64r/XOR64r is cheaper than MOV64ri64+OR64rr/XOR64rr
4809 ShiftedVal = (uint64_t)Val >> ShAmt;
4810 if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
4811 return true;
4812 }
4813 return false;
4814 };
4815
4816 int64_t ShiftedVal;
4817 if (!CanShrinkImmediate(ShiftedVal))
4818 return false;
4819
4820 // Ok, we can reorder to get a smaller immediate.
4821
4822 // But, its possible the original immediate allowed an AND to become MOVZX.
4823 // Doing this late due to avoid the MakedValueIsZero call as late as
4824 // possible.
4825 if (Opcode == ISD::AND) {
4826 // Find the smallest zext this could possibly be.
4827 unsigned ZExtWidth = Cst->getAPIntValue().getActiveBits();
4828 ZExtWidth = llvm::bit_ceil(std::max(ZExtWidth, 8U));
4829
4830 // Figure out which bits need to be zero to achieve that mask.
4831 APInt NeededMask = APInt::getLowBitsSet(NVT.getSizeInBits(),
4832 ZExtWidth);
4833 NeededMask &= ~Cst->getAPIntValue();
4834
4835 if (CurDAG->MaskedValueIsZero(N->getOperand(0), NeededMask))
4836 return false;
4837 }
4838
4839 SDValue X = Shift.getOperand(0);
4840 if (FoundAnyExtend) {
4841 SDValue NewX = CurDAG->getNode(ISD::ANY_EXTEND, dl, NVT, X);
4842 insertDAGNode(*CurDAG, SDValue(N, 0), NewX);
4843 X = NewX;
4844 }
4845
4846 SDValue NewCst = CurDAG->getSignedConstant(ShiftedVal, dl, NVT);
4847 insertDAGNode(*CurDAG, SDValue(N, 0), NewCst);
4848 SDValue NewBinOp = CurDAG->getNode(Opcode, dl, NVT, X, NewCst);
4849 insertDAGNode(*CurDAG, SDValue(N, 0), NewBinOp);
4850 SDValue NewSHL = CurDAG->getNode(ISD::SHL, dl, NVT, NewBinOp,
4851 Shift.getOperand(1));
4852 ReplaceNode(N, NewSHL.getNode());
4853 SelectCode(NewSHL.getNode());
4854 return true;
4855}
4856
4857bool X86DAGToDAGISel::matchVPTERNLOG(SDNode *Root, SDNode *ParentA,
4858 SDNode *ParentB, SDNode *ParentC,
4860 uint8_t Imm) {
4861 assert(A.isOperandOf(ParentA) && B.isOperandOf(ParentB) &&
4862 C.isOperandOf(ParentC) && "Incorrect parent node");
4863
4864 auto tryFoldLoadOrBCast =
4865 [this](SDNode *Root, SDNode *P, SDValue &L, SDValue &Base, SDValue &Scale,
4866 SDValue &Index, SDValue &Disp, SDValue &Segment) {
4867 if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment))
4868 return true;
4869
4870 // Not a load, check for broadcast which may be behind a bitcast.
4871 if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) {
4872 P = L.getNode();
4873 L = L.getOperand(0);
4874 }
4875
4876 if (L.getOpcode() != X86ISD::VBROADCAST_LOAD)
4877 return false;
4878
4879 // Only 32 and 64 bit broadcasts are supported.
4880 auto *MemIntr = cast<MemIntrinsicSDNode>(L);
4881 unsigned Size = MemIntr->getMemoryVT().getSizeInBits();
4882 if (Size != 32 && Size != 64)
4883 return false;
4884
4885 return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment);
4886 };
4887
4888 bool FoldedLoad = false;
4889 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4890 if (tryFoldLoadOrBCast(Root, ParentC, C, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4891 FoldedLoad = true;
4892 } else if (tryFoldLoadOrBCast(Root, ParentA, A, Tmp0, Tmp1, Tmp2, Tmp3,
4893 Tmp4)) {
4894 FoldedLoad = true;
4895 std::swap(A, C);
4896 // Swap bits 1/4 and 3/6.
4897 uint8_t OldImm = Imm;
4898 Imm = OldImm & 0xa5;
4899 if (OldImm & 0x02) Imm |= 0x10;
4900 if (OldImm & 0x10) Imm |= 0x02;
4901 if (OldImm & 0x08) Imm |= 0x40;
4902 if (OldImm & 0x40) Imm |= 0x08;
4903 } else if (tryFoldLoadOrBCast(Root, ParentB, B, Tmp0, Tmp1, Tmp2, Tmp3,
4904 Tmp4)) {
4905 FoldedLoad = true;
4906 std::swap(B, C);
4907 // Swap bits 1/2 and 5/6.
4908 uint8_t OldImm = Imm;
4909 Imm = OldImm & 0x99;
4910 if (OldImm & 0x02) Imm |= 0x04;
4911 if (OldImm & 0x04) Imm |= 0x02;
4912 if (OldImm & 0x20) Imm |= 0x40;
4913 if (OldImm & 0x40) Imm |= 0x20;
4914 }
4915
4916 SDLoc DL(Root);
4917
4918 SDValue TImm = CurDAG->getTargetConstant(Imm, DL, MVT::i8);
4919
4920 MVT NVT = Root->getSimpleValueType(0);
4921
4922 MachineSDNode *MNode;
4923 if (FoldedLoad) {
4924 SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
4925
4926 unsigned Opc;
4927 if (C.getOpcode() == X86ISD::VBROADCAST_LOAD) {
4928 auto *MemIntr = cast<MemIntrinsicSDNode>(C);
4929 unsigned EltSize = MemIntr->getMemoryVT().getSizeInBits();
4930 assert((EltSize == 32 || EltSize == 64) && "Unexpected broadcast size!");
4931
4932 bool UseD = EltSize == 32;
4933 if (NVT.is128BitVector())
4934 Opc = UseD ? X86::VPTERNLOGDZ128rmbi : X86::VPTERNLOGQZ128rmbi;
4935 else if (NVT.is256BitVector())
4936 Opc = UseD ? X86::VPTERNLOGDZ256rmbi : X86::VPTERNLOGQZ256rmbi;
4937 else if (NVT.is512BitVector())
4938 Opc = UseD ? X86::VPTERNLOGDZrmbi : X86::VPTERNLOGQZrmbi;
4939 else
4940 llvm_unreachable("Unexpected vector size!");
4941 } else {
4942 bool UseD = NVT.getVectorElementType() == MVT::i32;
4943 if (NVT.is128BitVector())
4944 Opc = UseD ? X86::VPTERNLOGDZ128rmi : X86::VPTERNLOGQZ128rmi;
4945 else if (NVT.is256BitVector())
4946 Opc = UseD ? X86::VPTERNLOGDZ256rmi : X86::VPTERNLOGQZ256rmi;
4947 else if (NVT.is512BitVector())
4948 Opc = UseD ? X86::VPTERNLOGDZrmi : X86::VPTERNLOGQZrmi;
4949 else
4950 llvm_unreachable("Unexpected vector size!");
4951 }
4952
4953 SDValue Ops[] = {A, B, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, TImm, C.getOperand(0)};
4954 MNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops);
4955
4956 // Update the chain.
4957 ReplaceUses(C.getValue(1), SDValue(MNode, 1));
4958 // Record the mem-refs
4959 CurDAG->setNodeMemRefs(MNode, {cast<MemSDNode>(C)->getMemOperand()});
4960 } else {
4961 bool UseD = NVT.getVectorElementType() == MVT::i32;
4962 unsigned Opc;
4963 if (NVT.is128BitVector())
4964 Opc = UseD ? X86::VPTERNLOGDZ128rri : X86::VPTERNLOGQZ128rri;
4965 else if (NVT.is256BitVector())
4966 Opc = UseD ? X86::VPTERNLOGDZ256rri : X86::VPTERNLOGQZ256rri;
4967 else if (NVT.is512BitVector())
4968 Opc = UseD ? X86::VPTERNLOGDZrri : X86::VPTERNLOGQZrri;
4969 else
4970 llvm_unreachable("Unexpected vector size!");
4971
4972 MNode = CurDAG->getMachineNode(Opc, DL, NVT, {A, B, C, TImm});
4973 }
4974
4975 ReplaceUses(SDValue(Root, 0), SDValue(MNode, 0));
4976 CurDAG->RemoveDeadNode(Root);
4977 return true;
4978}
4979
4980// Try to match two logic ops to a VPTERNLOG.
4981// FIXME: Handle more complex patterns that use an operand more than once?
4982bool X86DAGToDAGISel::tryVPTERNLOG(SDNode *N) {
4983 MVT NVT = N->getSimpleValueType(0);
4984
4985 // Make sure we support VPTERNLOG.
4986 if (!NVT.isVector() || !Subtarget->hasAVX512() ||
4987 NVT.getVectorElementType() == MVT::i1)
4988 return false;
4989
4990 // We need VLX for 128/256-bit.
4991 if (!(Subtarget->hasVLX() || NVT.is512BitVector()))
4992 return false;
4993
4994 auto getFoldableLogicOp = [](SDValue Op) {
4995 // Peek through single use bitcast.
4996 if (Op.getOpcode() == ISD::BITCAST && Op.hasOneUse())
4997 Op = Op.getOperand(0);
4998
4999 if (!Op.hasOneUse())
5000 return SDValue();
5001
5002 unsigned Opc = Op.getOpcode();
5003 if (Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR ||
5004 Opc == X86ISD::ANDNP)
5005 return Op;
5006
5007 return SDValue();
5008 };
5009
5010 SDValue N0, N1, A, FoldableOp;
5011
5012 // Identify and (optionally) peel an outer NOT that wraps a pure logic tree
5013 auto tryPeelOuterNotWrappingLogic = [&](SDNode *Op) {
5014 if (Op->getOpcode() == ISD::XOR && Op->hasOneUse() &&
5015 ISD::isBuildVectorAllOnes(Op->getOperand(1).getNode())) {
5016 SDValue InnerOp = getFoldableLogicOp(Op->getOperand(0));
5017
5018 if (!InnerOp)
5019 return SDValue();
5020
5021 N0 = InnerOp.getOperand(0);
5022 N1 = InnerOp.getOperand(1);
5023 if ((FoldableOp = getFoldableLogicOp(N1))) {
5024 A = N0;
5025 return InnerOp;
5026 }
5027 if ((FoldableOp = getFoldableLogicOp(N0))) {
5028 A = N1;
5029 return InnerOp;
5030 }
5031 }
5032 return SDValue();
5033 };
5034
5035 bool PeeledOuterNot = false;
5036 SDNode *OriN = N;
5037 if (SDValue InnerOp = tryPeelOuterNotWrappingLogic(N)) {
5038 PeeledOuterNot = true;
5039 N = InnerOp.getNode();
5040 } else {
5041 N0 = N->getOperand(0);
5042 N1 = N->getOperand(1);
5043
5044 if ((FoldableOp = getFoldableLogicOp(N1)))
5045 A = N0;
5046 else if ((FoldableOp = getFoldableLogicOp(N0)))
5047 A = N1;
5048 else
5049 return false;
5050 }
5051
5052 SDValue B = FoldableOp.getOperand(0);
5053 SDValue C = FoldableOp.getOperand(1);
5054 SDNode *ParentA = N;
5055 SDNode *ParentB = FoldableOp.getNode();
5056 SDNode *ParentC = FoldableOp.getNode();
5057
5058 // We can build the appropriate control immediate by performing the logic
5059 // operation we're matching using these constants for A, B, and C.
5060 uint8_t TernlogMagicA = 0xf0;
5061 uint8_t TernlogMagicB = 0xcc;
5062 uint8_t TernlogMagicC = 0xaa;
5063
5064 // Some of the inputs may be inverted, peek through them and invert the
5065 // magic values accordingly.
5066 // TODO: There may be a bitcast before the xor that we should peek through.
5067 auto PeekThroughNot = [](SDValue &Op, SDNode *&Parent, uint8_t &Magic) {
5068 if (Op.getOpcode() == ISD::XOR && Op.hasOneUse() &&
5069 ISD::isBuildVectorAllOnes(Op.getOperand(1).getNode())) {
5070 Magic = ~Magic;
5071 Parent = Op.getNode();
5072 Op = Op.getOperand(0);
5073 }
5074 };
5075
5076 PeekThroughNot(A, ParentA, TernlogMagicA);
5077 PeekThroughNot(B, ParentB, TernlogMagicB);
5078 PeekThroughNot(C, ParentC, TernlogMagicC);
5079
5080 uint8_t Imm;
5081 switch (FoldableOp.getOpcode()) {
5082 default: llvm_unreachable("Unexpected opcode!");
5083 case ISD::AND: Imm = TernlogMagicB & TernlogMagicC; break;
5084 case ISD::OR: Imm = TernlogMagicB | TernlogMagicC; break;
5085 case ISD::XOR: Imm = TernlogMagicB ^ TernlogMagicC; break;
5086 case X86ISD::ANDNP: Imm = ~(TernlogMagicB) & TernlogMagicC; break;
5087 }
5088
5089 switch (N->getOpcode()) {
5090 default: llvm_unreachable("Unexpected opcode!");
5091 case X86ISD::ANDNP:
5092 if (A == N0)
5093 Imm &= ~TernlogMagicA;
5094 else
5095 Imm = ~(Imm) & TernlogMagicA;
5096 break;
5097 case ISD::AND: Imm &= TernlogMagicA; break;
5098 case ISD::OR: Imm |= TernlogMagicA; break;
5099 case ISD::XOR: Imm ^= TernlogMagicA; break;
5100 }
5101
5102 if (PeeledOuterNot)
5103 Imm = ~Imm;
5104
5105 return matchVPTERNLOG(OriN, ParentA, ParentB, ParentC, A, B, C, Imm);
5106}
5107
5108/// If the high bits of an 'and' operand are known zero, try setting the
5109/// high bits of an 'and' constant operand to produce a smaller encoding by
5110/// creating a small, sign-extended negative immediate rather than a large
5111/// positive one. This reverses a transform in SimplifyDemandedBits that
5112/// shrinks mask constants by clearing bits. There is also a possibility that
5113/// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
5114/// case, just replace the 'and'. Return 'true' if the node is replaced.
5115bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
5116 // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
5117 // have immediate operands.
5118 MVT VT = And->getSimpleValueType(0);
5119 if (VT != MVT::i32 && VT != MVT::i64)
5120 return false;
5121
5122 auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
5123 if (!And1C)
5124 return false;
5125
5126 // Bail out if the mask constant is already negative. It's can't shrink more.
5127 // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
5128 // patterns to use a 32-bit and instead of a 64-bit and by relying on the
5129 // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
5130 // are negative too.
5131 APInt MaskVal = And1C->getAPIntValue();
5132 unsigned MaskLZ = MaskVal.countl_zero();
5133 if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
5134 return false;
5135
5136 // Don't extend into the upper 32 bits of a 64 bit mask.
5137 if (VT == MVT::i64 && MaskLZ >= 32) {
5138 MaskLZ -= 32;
5139 MaskVal = MaskVal.trunc(32);
5140 }
5141
5142 SDValue And0 = And->getOperand(0);
5143 APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
5144 APInt NegMaskVal = MaskVal | HighZeros;
5145
5146 // If a negative constant would not allow a smaller encoding, there's no need
5147 // to continue. Only change the constant when we know it's a win.
5148 unsigned MinWidth = NegMaskVal.getSignificantBits();
5149 if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getSignificantBits() <= 32))
5150 return false;
5151
5152 // Extend masks if we truncated above.
5153 if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
5154 NegMaskVal = NegMaskVal.zext(64);
5155 HighZeros = HighZeros.zext(64);
5156 }
5157
5158 // The variable operand must be all zeros in the top bits to allow using the
5159 // new, negative constant as the mask.
5160 // TODO: Handle constant folding?
5161 KnownBits Known0 = CurDAG->computeKnownBits(And0);
5162 if (Known0.isConstant() || !HighZeros.isSubsetOf(Known0.Zero))
5163 return false;
5164
5165 // Check if the mask is -1. In that case, this is an unnecessary instruction
5166 // that escaped earlier analysis.
5167 if (NegMaskVal.isAllOnes()) {
5168 ReplaceNode(And, And0.getNode());
5169 return true;
5170 }
5171
5172 // A negative mask allows a smaller encoding. Create a new 'and' node.
5173 SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
5174 insertDAGNode(*CurDAG, SDValue(And, 0), NewMask);
5175 SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
5176 ReplaceNode(And, NewAnd.getNode());
5177 SelectCode(NewAnd.getNode());
5178 return true;
5179}
5180
5181static unsigned getVPTESTMOpc(MVT TestVT, bool IsTestN, bool FoldedLoad,
5182 bool FoldedBCast, bool Masked) {
5183#define VPTESTM_CASE(VT, SUFFIX) \
5184case MVT::VT: \
5185 if (Masked) \
5186 return IsTestN ? X86::VPTESTNM##SUFFIX##k: X86::VPTESTM##SUFFIX##k; \
5187 return IsTestN ? X86::VPTESTNM##SUFFIX : X86::VPTESTM##SUFFIX;
5188
5189
5190#define VPTESTM_BROADCAST_CASES(SUFFIX) \
5191default: llvm_unreachable("Unexpected VT!"); \
5192VPTESTM_CASE(v4i32, DZ128##SUFFIX) \
5193VPTESTM_CASE(v2i64, QZ128##SUFFIX) \
5194VPTESTM_CASE(v8i32, DZ256##SUFFIX) \
5195VPTESTM_CASE(v4i64, QZ256##SUFFIX) \
5196VPTESTM_CASE(v16i32, DZ##SUFFIX) \
5197VPTESTM_CASE(v8i64, QZ##SUFFIX)
5198
5199#define VPTESTM_FULL_CASES(SUFFIX) \
5200VPTESTM_BROADCAST_CASES(SUFFIX) \
5201VPTESTM_CASE(v16i8, BZ128##SUFFIX) \
5202VPTESTM_CASE(v8i16, WZ128##SUFFIX) \
5203VPTESTM_CASE(v32i8, BZ256##SUFFIX) \
5204VPTESTM_CASE(v16i16, WZ256##SUFFIX) \
5205VPTESTM_CASE(v64i8, BZ##SUFFIX) \
5206VPTESTM_CASE(v32i16, WZ##SUFFIX)
5207
5208 if (FoldedBCast) {
5209 switch (TestVT.SimpleTy) {
5211 }
5212 }
5213
5214 if (FoldedLoad) {
5215 switch (TestVT.SimpleTy) {
5217 }
5218 }
5219
5220 switch (TestVT.SimpleTy) {
5222 }
5223
5224#undef VPTESTM_FULL_CASES
5225#undef VPTESTM_BROADCAST_CASES
5226#undef VPTESTM_CASE
5227}
5228
5229static void orderRegForMul(SDValue &N0, SDValue &N1, const unsigned LoReg,
5230 const MachineRegisterInfo &MRI) {
5231 auto GetPhysReg = [&](SDValue V) -> Register {
5232 if (V.getOpcode() != ISD::CopyFromReg)
5233 return Register();
5234 Register Reg = cast<RegisterSDNode>(V.getOperand(1))->getReg();
5235 if (Reg.isVirtual())
5236 return MRI.getLiveInPhysReg(Reg);
5237 return Reg;
5238 };
5239
5240 if (GetPhysReg(N1) == LoReg && GetPhysReg(N0) != LoReg)
5241 std::swap(N0, N1);
5242}
5243
5244// Try to create VPTESTM instruction. If InMask is not null, it will be used
5245// to form a masked operation.
5246bool X86DAGToDAGISel::tryVPTESTM(SDNode *Root, SDValue Setcc,
5247 SDValue InMask) {
5248 assert(Subtarget->hasAVX512() && "Expected AVX512!");
5249 assert(Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 &&
5250 "Unexpected VT!");
5251
5252 // Look for equal and not equal compares.
5253 ISD::CondCode CC = cast<CondCodeSDNode>(Setcc.getOperand(2))->get();
5254 if (CC != ISD::SETEQ && CC != ISD::SETNE)
5255 return false;
5256
5257 SDValue SetccOp0 = Setcc.getOperand(0);
5258 SDValue SetccOp1 = Setcc.getOperand(1);
5259
5260 // Canonicalize the all zero vector to the RHS.
5261 if (ISD::isBuildVectorAllZeros(SetccOp0.getNode()))
5262 std::swap(SetccOp0, SetccOp1);
5263
5264 // See if we're comparing against zero.
5265 if (!ISD::isBuildVectorAllZeros(SetccOp1.getNode()))
5266 return false;
5267
5268 SDValue N0 = SetccOp0;
5269
5270 MVT CmpVT = N0.getSimpleValueType();
5271 MVT CmpSVT = CmpVT.getVectorElementType();
5272
5273 // Start with both operands the same. We'll try to refine this.
5274 SDValue Src0 = N0;
5275 SDValue Src1 = N0;
5276
5277 {
5278 // Look through single use bitcasts.
5279 SDValue N0Temp = N0;
5280 if (N0Temp.getOpcode() == ISD::BITCAST && N0Temp.hasOneUse())
5281 N0Temp = N0.getOperand(0);
5282
5283 // Look for single use AND.
5284 if (N0Temp.getOpcode() == ISD::AND && N0Temp.hasOneUse()) {
5285 Src0 = N0Temp.getOperand(0);
5286 Src1 = N0Temp.getOperand(1);
5287 }
5288 }
5289
5290 // Without VLX we need to widen the operation.
5291 bool Widen = !Subtarget->hasVLX() && !CmpVT.is512BitVector();
5292
5293 auto tryFoldLoadOrBCast = [&](SDNode *Root, SDNode *P, SDValue &L,
5294 SDValue &Base, SDValue &Scale, SDValue &Index,
5295 SDValue &Disp, SDValue &Segment) {
5296 // If we need to widen, we can't fold the load.
5297 if (!Widen)
5298 if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment))
5299 return true;
5300
5301 // If we didn't fold a load, try to match broadcast. No widening limitation
5302 // for this. But only 32 and 64 bit types are supported.
5303 if (CmpSVT != MVT::i32 && CmpSVT != MVT::i64)
5304 return false;
5305
5306 // Look through single use bitcasts.
5307 if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) {
5308 P = L.getNode();
5309 L = L.getOperand(0);
5310 }
5311
5312 if (L.getOpcode() != X86ISD::VBROADCAST_LOAD)
5313 return false;
5314
5315 auto *MemIntr = cast<MemIntrinsicSDNode>(L);
5316 if (MemIntr->getMemoryVT().getSizeInBits() != CmpSVT.getSizeInBits())
5317 return false;
5318
5319 return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment);
5320 };
5321
5322 // We can only fold loads if the sources are unique.
5323 bool CanFoldLoads = Src0 != Src1;
5324
5325 bool FoldedLoad = false;
5326 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
5327 if (CanFoldLoads) {
5328 FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src1, Tmp0, Tmp1, Tmp2,
5329 Tmp3, Tmp4);
5330 if (!FoldedLoad) {
5331 // And is commutative.
5332 FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src0, Tmp0, Tmp1,
5333 Tmp2, Tmp3, Tmp4);
5334 if (FoldedLoad)
5335 std::swap(Src0, Src1);
5336 }
5337 }
5338
5339 bool FoldedBCast = FoldedLoad && Src1.getOpcode() == X86ISD::VBROADCAST_LOAD;
5340
5341 bool IsMasked = InMask.getNode() != nullptr;
5342
5343 SDLoc dl(Root);
5344
5345 MVT ResVT = Setcc.getSimpleValueType();
5346 MVT MaskVT = ResVT;
5347 if (Widen) {
5348 // Widen the inputs using insert_subreg or copy_to_regclass.
5349 unsigned Scale = CmpVT.is128BitVector() ? 4 : 2;
5350 unsigned SubReg = CmpVT.is128BitVector() ? X86::sub_xmm : X86::sub_ymm;
5351 unsigned NumElts = CmpVT.getVectorNumElements() * Scale;
5352 CmpVT = MVT::getVectorVT(CmpSVT, NumElts);
5353 MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
5354 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, dl,
5355 CmpVT), 0);
5356 Src0 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src0);
5357
5358 if (!FoldedBCast)
5359 Src1 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src1);
5360
5361 if (IsMasked) {
5362 // Widen the mask.
5363 unsigned RegClass = TLI->getRegClassFor(MaskVT)->getID();
5364 SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
5365 InMask = SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
5366 dl, MaskVT, InMask, RC), 0);
5367 }
5368 }
5369
5370 bool IsTestN = CC == ISD::SETEQ;
5371 unsigned Opc = getVPTESTMOpc(CmpVT, IsTestN, FoldedLoad, FoldedBCast,
5372 IsMasked);
5373
5374 MachineSDNode *CNode;
5375 if (FoldedLoad) {
5376 SDVTList VTs = CurDAG->getVTList(MaskVT, MVT::Other);
5377
5378 if (IsMasked) {
5379 SDValue Ops[] = { InMask, Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
5380 Src1.getOperand(0) };
5381 CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
5382 } else {
5383 SDValue Ops[] = { Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
5384 Src1.getOperand(0) };
5385 CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
5386 }
5387
5388 // Update the chain.
5389 ReplaceUses(Src1.getValue(1), SDValue(CNode, 1));
5390 // Record the mem-refs
5391 CurDAG->setNodeMemRefs(CNode, {cast<MemSDNode>(Src1)->getMemOperand()});
5392 } else {
5393 if (IsMasked)
5394 CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, InMask, Src0, Src1);
5395 else
5396 CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, Src0, Src1);
5397 }
5398
5399 // If we widened, we need to shrink the mask VT.
5400 if (Widen) {
5401 unsigned RegClass = TLI->getRegClassFor(ResVT)->getID();
5402 SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
5403 CNode = CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
5404 dl, ResVT, SDValue(CNode, 0), RC);
5405 }
5406
5407 ReplaceUses(SDValue(Root, 0), SDValue(CNode, 0));
5408 CurDAG->RemoveDeadNode(Root);
5409 return true;
5410}
5411
5412// Try to match the bitselect pattern (or (and A, B), (andn A, C)). Turn it
5413// into vpternlog.
5414bool X86DAGToDAGISel::tryMatchBitSelect(SDNode *N) {
5415 assert(N->getOpcode() == ISD::OR && "Unexpected opcode!");
5416
5417 MVT NVT = N->getSimpleValueType(0);
5418
5419 // Make sure we support VPTERNLOG.
5420 if (!NVT.isVector() || !Subtarget->hasAVX512())
5421 return false;
5422
5423 // We need VLX for 128/256-bit.
5424 if (!(Subtarget->hasVLX() || NVT.is512BitVector()))
5425 return false;
5426
5427 SDValue N0 = N->getOperand(0);
5428 SDValue N1 = N->getOperand(1);
5429
5430 // Canonicalize AND to LHS.
5431 if (N1.getOpcode() == ISD::AND)
5432 std::swap(N0, N1);
5433
5434 if (N0.getOpcode() != ISD::AND ||
5435 N1.getOpcode() != X86ISD::ANDNP ||
5436 !N0.hasOneUse() || !N1.hasOneUse())
5437 return false;
5438
5439 // ANDN is not commutable, use it to pick down A and C.
5440 SDValue A = N1.getOperand(0);
5441 SDValue C = N1.getOperand(1);
5442
5443 // AND is commutable, if one operand matches A, the other operand is B.
5444 // Otherwise this isn't a match.
5445 SDValue B;
5446 if (N0.getOperand(0) == A)
5447 B = N0.getOperand(1);
5448 else if (N0.getOperand(1) == A)
5449 B = N0.getOperand(0);
5450 else
5451 return false;
5452
5453 SDLoc dl(N);
5454 SDValue Imm = CurDAG->getTargetConstant(0xCA, dl, MVT::i8);
5455 SDValue Ternlog = CurDAG->getNode(X86ISD::VPTERNLOG, dl, NVT, A, B, C, Imm);
5456 ReplaceNode(N, Ternlog.getNode());
5457
5458 return matchVPTERNLOG(Ternlog.getNode(), Ternlog.getNode(), Ternlog.getNode(),
5459 Ternlog.getNode(), A, B, C, 0xCA);
5460}
5461
5462void X86DAGToDAGISel::Select(SDNode *Node) {
5463 MVT NVT = Node->getSimpleValueType(0);
5464 unsigned Opcode = Node->getOpcode();
5465 SDLoc dl(Node);
5466
5467 if (Node->isMachineOpcode()) {
5468 LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
5469 Node->setNodeId(-1);
5470 return; // Already selected.
5471 }
5472
5473 switch (Opcode) {
5474 default: break;
5476 unsigned IntNo = Node->getConstantOperandVal(1);
5477 switch (IntNo) {
5478 default: break;
5479 case Intrinsic::x86_encodekey128:
5480 case Intrinsic::x86_encodekey256: {
5481 if (!Subtarget->hasKL())
5482 break;
5483
5484 unsigned Opcode;
5485 switch (IntNo) {
5486 default: llvm_unreachable("Impossible intrinsic");
5487 case Intrinsic::x86_encodekey128:
5488 Opcode = X86::ENCODEKEY128;
5489 break;
5490 case Intrinsic::x86_encodekey256:
5491 Opcode = X86::ENCODEKEY256;
5492 break;
5493 }
5494
5495 SDValue Chain = Node->getOperand(0);
5496 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM0, Node->getOperand(3),
5497 SDValue());
5498 if (Opcode == X86::ENCODEKEY256)
5499 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM1, Node->getOperand(4),
5500 Chain.getValue(1));
5501
5502 MachineSDNode *Res = CurDAG->getMachineNode(
5503 Opcode, dl, Node->getVTList(),
5504 {Node->getOperand(2), Chain, Chain.getValue(1)});
5505 ReplaceNode(Node, Res);
5506 return;
5507 }
5508 case Intrinsic::x86_tileloaddrs64_internal:
5509 case Intrinsic::x86_tileloaddrst164_internal:
5510 if (!Subtarget->hasAMXMOVRS())
5511 break;
5512 [[fallthrough]];
5513 case Intrinsic::x86_tileloadd64_internal:
5514 case Intrinsic::x86_tileloaddt164_internal: {
5515 if (!Subtarget->hasAMXTILE())
5516 break;
5517 auto *MFI =
5518 CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
5519 MFI->setAMXProgModel(AMXProgModelEnum::ManagedRA);
5520 unsigned Opc;
5521 switch (IntNo) {
5522 default:
5523 llvm_unreachable("Unexpected intrinsic!");
5524 case Intrinsic::x86_tileloaddrs64_internal:
5525 Opc = X86::PTILELOADDRSV;
5526 break;
5527 case Intrinsic::x86_tileloaddrst164_internal:
5528 Opc = X86::PTILELOADDRST1V;
5529 break;
5530 case Intrinsic::x86_tileloadd64_internal:
5531 Opc = X86::PTILELOADDV;
5532 break;
5533 case Intrinsic::x86_tileloaddt164_internal:
5534 Opc = X86::PTILELOADDT1V;
5535 break;
5536 }
5537 // _tile_loadd_internal(row, col, buf, STRIDE)
5538 SDValue Base = Node->getOperand(4);
5539 SDValue Scale = getI8Imm(1, dl);
5540 SDValue Index = Node->getOperand(5);
5541 SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);
5542 SDValue Segment = CurDAG->getRegister(0, MVT::i16);
5543 SDValue Chain = Node->getOperand(0);
5544 MachineSDNode *CNode;
5545 SDValue Ops[] = {Node->getOperand(2),
5546 Node->getOperand(3),
5547 Base,
5548 Scale,
5549 Index,
5550 Disp,
5551 Segment,
5552 Chain};
5553 CNode = CurDAG->getMachineNode(Opc, dl, {MVT::x86amx, MVT::Other}, Ops);
5554 ReplaceNode(Node, CNode);
5555 return;
5556 }
5557 }
5558 break;
5559 }
5560 case ISD::INTRINSIC_VOID: {
5561 unsigned IntNo = Node->getConstantOperandVal(1);
5562 switch (IntNo) {
5563 default: break;
5564 case Intrinsic::x86_sse3_monitor:
5565 case Intrinsic::x86_monitorx:
5566 case Intrinsic::x86_clzero: {
5567 bool Use64BitPtr = Node->getOperand(2).getValueType() == MVT::i64;
5568
5569 unsigned Opc = 0;
5570 switch (IntNo) {
5571 default: llvm_unreachable("Unexpected intrinsic!");
5572 case Intrinsic::x86_sse3_monitor:
5573 if (!Subtarget->hasSSE3())
5574 break;
5575 Opc = Use64BitPtr ? X86::MONITOR64rrr : X86::MONITOR32rrr;
5576 break;
5577 case Intrinsic::x86_monitorx:
5578 if (!Subtarget->hasMWAITX())
5579 break;
5580 Opc = Use64BitPtr ? X86::MONITORX64rrr : X86::MONITORX32rrr;
5581 break;
5582 case Intrinsic::x86_clzero:
5583 if (!Subtarget->hasCLZERO())
5584 break;
5585 Opc = Use64BitPtr ? X86::CLZERO64r : X86::CLZERO32r;
5586 break;
5587 }
5588
5589 if (Opc) {
5590 unsigned PtrReg = Use64BitPtr ? X86::RAX : X86::EAX;
5591 SDValue Chain = CurDAG->getCopyToReg(Node->getOperand(0), dl, PtrReg,
5592 Node->getOperand(2), SDValue());
5593 SDValue InGlue = Chain.getValue(1);
5594
5595 if (IntNo == Intrinsic::x86_sse3_monitor ||
5596 IntNo == Intrinsic::x86_monitorx) {
5597 // Copy the other two operands to ECX and EDX.
5598 Chain = CurDAG->getCopyToReg(Chain, dl, X86::ECX, Node->getOperand(3),
5599 InGlue);
5600 InGlue = Chain.getValue(1);
5601 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EDX, Node->getOperand(4),
5602 InGlue);
5603 InGlue = Chain.getValue(1);
5604 }
5605
5606 MachineSDNode *CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,
5607 { Chain, InGlue});
5608 ReplaceNode(Node, CNode);
5609 return;
5610 }
5611
5612 break;
5613 }
5614 case Intrinsic::x86_tilestored64_internal: {
5615 auto *MFI =
5616 CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
5617 MFI->setAMXProgModel(AMXProgModelEnum::ManagedRA);
5618 unsigned Opc = X86::PTILESTOREDV;
5619 // _tile_stored_internal(row, col, buf, STRIDE, c)
5620 SDValue Base = Node->getOperand(4);
5621 SDValue Scale = getI8Imm(1, dl);
5622 SDValue Index = Node->getOperand(5);
5623 SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);
5624 SDValue Segment = CurDAG->getRegister(0, MVT::i16);
5625 SDValue Chain = Node->getOperand(0);
5626 MachineSDNode *CNode;
5627 SDValue Ops[] = {Node->getOperand(2),
5628 Node->getOperand(3),
5629 Base,
5630 Scale,
5631 Index,
5632 Disp,
5633 Segment,
5634 Node->getOperand(6),
5635 Chain};
5636 CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
5637 ReplaceNode(Node, CNode);
5638 return;
5639 }
5640 case Intrinsic::x86_tileloaddrs64:
5641 case Intrinsic::x86_tileloaddrst164:
5642 if (!Subtarget->hasAMXMOVRS())
5643 break;
5644 [[fallthrough]];
5645 case Intrinsic::x86_tileloadd64:
5646 case Intrinsic::x86_tileloaddt164:
5647 case Intrinsic::x86_tilestored64: {
5648 if (!Subtarget->hasAMXTILE())
5649 break;
5650 auto *MFI =
5651 CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
5652 MFI->setAMXProgModel(AMXProgModelEnum::DirectReg);
5653 unsigned Opc;
5654 switch (IntNo) {
5655 default: llvm_unreachable("Unexpected intrinsic!");
5656 case Intrinsic::x86_tileloadd64: Opc = X86::PTILELOADD; break;
5657 case Intrinsic::x86_tileloaddrs64:
5658 Opc = X86::PTILELOADDRS;
5659 break;
5660 case Intrinsic::x86_tileloaddt164: Opc = X86::PTILELOADDT1; break;
5661 case Intrinsic::x86_tileloaddrst164:
5662 Opc = X86::PTILELOADDRST1;
5663 break;
5664 case Intrinsic::x86_tilestored64: Opc = X86::PTILESTORED; break;
5665 }
5666 // FIXME: Match displacement and scale.
5667 unsigned TIndex = Node->getConstantOperandVal(2);
5668 SDValue TReg = getI8Imm(TIndex, dl);
5669 SDValue Base = Node->getOperand(3);
5670 SDValue Scale = getI8Imm(1, dl);
5671 SDValue Index = Node->getOperand(4);
5672 SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);
5673 SDValue Segment = CurDAG->getRegister(0, MVT::i16);
5674 SDValue Chain = Node->getOperand(0);
5675 MachineSDNode *CNode;
5676 if (Opc == X86::PTILESTORED) {
5677 SDValue Ops[] = { Base, Scale, Index, Disp, Segment, TReg, Chain };
5678 CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
5679 } else {
5680 SDValue Ops[] = { TReg, Base, Scale, Index, Disp, Segment, Chain };
5681 CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
5682 }
5683 ReplaceNode(Node, CNode);
5684 return;
5685 }
5686 }
5687 break;
5688 }
5689 case ISD::BRIND:
5690 case X86ISD::NT_BRIND: {
5691 if (Subtarget->isTarget64BitILP32()) {
5692 // Converts a 32-bit register to a 64-bit, zero-extended version of
5693 // it. This is needed because x86-64 can do many things, but jmp %r32
5694 // ain't one of them.
5695 SDValue Target = Node->getOperand(1);
5696 assert(Target.getValueType() == MVT::i32 && "Unexpected VT!");
5697 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, MVT::i64);
5698 SDValue Brind = CurDAG->getNode(Opcode, dl, MVT::Other,
5699 Node->getOperand(0), ZextTarget);
5700 ReplaceNode(Node, Brind.getNode());
5701 SelectCode(ZextTarget.getNode());
5702 SelectCode(Brind.getNode());
5703 return;
5704 }
5705 break;
5706 }
5708 ReplaceNode(Node, getGlobalBaseReg());
5709 return;
5710
5711 case ISD::BITCAST:
5712 // Just drop all 128/256/512-bit bitcasts.
5713 if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() ||
5714 NVT == MVT::f128) {
5715 ReplaceUses(SDValue(Node, 0), Node->getOperand(0));
5716 CurDAG->RemoveDeadNode(Node);
5717 return;
5718 }
5719 break;
5720
5721 case ISD::SRL:
5722 if (matchBitExtract(Node))
5723 return;
5724 [[fallthrough]];
5725 case ISD::SRA:
5726 case ISD::SHL:
5727 if (tryShiftAmountMod(Node))
5728 return;
5729 break;
5730
5731 case X86ISD::VPTERNLOG: {
5732 uint8_t Imm = Node->getConstantOperandVal(3);
5733 if (matchVPTERNLOG(Node, Node, Node, Node, Node->getOperand(0),
5734 Node->getOperand(1), Node->getOperand(2), Imm))
5735 return;
5736 break;
5737 }
5738
5739 case X86ISD::ANDNP:
5740 if (tryVPTERNLOG(Node))
5741 return;
5742 break;
5743
5744 case ISD::AND:
5745 if (NVT.isVectorOf(MVT::i1)) {
5746 // Try to form a masked VPTESTM. Operands can be in either order.
5747 SDValue N0 = Node->getOperand(0);
5748 SDValue N1 = Node->getOperand(1);
5749 if (N0.getOpcode() == ISD::SETCC && N0.hasOneUse() &&
5750 tryVPTESTM(Node, N0, N1))
5751 return;
5752 if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse() &&
5753 tryVPTESTM(Node, N1, N0))
5754 return;
5755 }
5756
5757 if (MachineSDNode *NewNode = matchBEXTRFromAndImm(Node)) {
5758 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
5759 CurDAG->RemoveDeadNode(Node);
5760 return;
5761 }
5762 if (matchBitExtract(Node))
5763 return;
5764 if (AndImmShrink && shrinkAndImmediate(Node))
5765 return;
5766
5767 [[fallthrough]];
5768 case ISD::OR:
5769 case ISD::XOR:
5770 if (tryShrinkShlLogicImm(Node))
5771 return;
5772 if (Opcode == ISD::OR && tryMatchBitSelect(Node))
5773 return;
5774 if (tryVPTERNLOG(Node))
5775 return;
5776
5777 [[fallthrough]];
5778 case ISD::ADD:
5779 if (Opcode == ISD::ADD && matchBitExtract(Node))
5780 return;
5781 [[fallthrough]];
5782 case ISD::SUB: {
5783 // Try to avoid folding immediates with multiple uses for optsize.
5784 // This code tries to select to register form directly to avoid going
5785 // through the isel table which might fold the immediate. We can't change
5786 // the patterns on the add/sub/and/or/xor with immediate paterns in the
5787 // tablegen files to check immediate use count without making the patterns
5788 // unavailable to the fast-isel table.
5789 if (!CurDAG->shouldOptForSize())
5790 break;
5791
5792 // Only handle i8/i16/i32/i64.
5793 if (NVT != MVT::i8 && NVT != MVT::i16 && NVT != MVT::i32 && NVT != MVT::i64)
5794 break;
5795
5796 SDValue N0 = Node->getOperand(0);
5797 SDValue N1 = Node->getOperand(1);
5798
5799 auto *Cst = dyn_cast<ConstantSDNode>(N1);
5800 if (!Cst)
5801 break;
5802
5803 int64_t Val = Cst->getSExtValue();
5804
5805 // Make sure its an immediate that is considered foldable.
5806 // FIXME: Handle unsigned 32 bit immediates for 64-bit AND.
5807 if (!isInt<8>(Val) && !isInt<32>(Val))
5808 break;
5809
5810 // If this can match to INC/DEC, let it go.
5811 if (Opcode == ISD::ADD && (Val == 1 || Val == -1))
5812 break;
5813
5814 // Check if we should avoid folding this immediate.
5815 if (!shouldAvoidImmediateInstFormsForSize(N1.getNode()))
5816 break;
5817
5818 // We should not fold the immediate. So we need a register form instead.
5819 unsigned ROpc, MOpc;
5820 switch (NVT.SimpleTy) {
5821 default: llvm_unreachable("Unexpected VT!");
5822 case MVT::i8:
5823 switch (Opcode) {
5824 default: llvm_unreachable("Unexpected opcode!");
5825 case ISD::ADD:
5826 ROpc = GET_ND_IF_ENABLED(X86::ADD8rr);
5827 MOpc = GET_NDM_IF_ENABLED(X86::ADD8rm);
5828 break;
5829 case ISD::SUB:
5830 ROpc = GET_ND_IF_ENABLED(X86::SUB8rr);
5831 MOpc = GET_NDM_IF_ENABLED(X86::SUB8rm);
5832 break;
5833 case ISD::AND:
5834 ROpc = GET_ND_IF_ENABLED(X86::AND8rr);
5835 MOpc = GET_NDM_IF_ENABLED(X86::AND8rm);
5836 break;
5837 case ISD::OR:
5838 ROpc = GET_ND_IF_ENABLED(X86::OR8rr);
5839 MOpc = GET_NDM_IF_ENABLED(X86::OR8rm);
5840 break;
5841 case ISD::XOR:
5842 ROpc = GET_ND_IF_ENABLED(X86::XOR8rr);
5843 MOpc = GET_NDM_IF_ENABLED(X86::XOR8rm);
5844 break;
5845 }
5846 break;
5847 case MVT::i16:
5848 switch (Opcode) {
5849 default: llvm_unreachable("Unexpected opcode!");
5850 case ISD::ADD:
5851 ROpc = GET_ND_IF_ENABLED(X86::ADD16rr);
5852 MOpc = GET_NDM_IF_ENABLED(X86::ADD16rm);
5853 break;
5854 case ISD::SUB:
5855 ROpc = GET_ND_IF_ENABLED(X86::SUB16rr);
5856 MOpc = GET_NDM_IF_ENABLED(X86::SUB16rm);
5857 break;
5858 case ISD::AND:
5859 ROpc = GET_ND_IF_ENABLED(X86::AND16rr);
5860 MOpc = GET_NDM_IF_ENABLED(X86::AND16rm);
5861 break;
5862 case ISD::OR:
5863 ROpc = GET_ND_IF_ENABLED(X86::OR16rr);
5864 MOpc = GET_NDM_IF_ENABLED(X86::OR16rm);
5865 break;
5866 case ISD::XOR:
5867 ROpc = GET_ND_IF_ENABLED(X86::XOR16rr);
5868 MOpc = GET_NDM_IF_ENABLED(X86::XOR16rm);
5869 break;
5870 }
5871 break;
5872 case MVT::i32:
5873 switch (Opcode) {
5874 default: llvm_unreachable("Unexpected opcode!");
5875 case ISD::ADD:
5876 ROpc = GET_ND_IF_ENABLED(X86::ADD32rr);
5877 MOpc = GET_NDM_IF_ENABLED(X86::ADD32rm);
5878 break;
5879 case ISD::SUB:
5880 ROpc = GET_ND_IF_ENABLED(X86::SUB32rr);
5881 MOpc = GET_NDM_IF_ENABLED(X86::SUB32rm);
5882 break;
5883 case ISD::AND:
5884 ROpc = GET_ND_IF_ENABLED(X86::AND32rr);
5885 MOpc = GET_NDM_IF_ENABLED(X86::AND32rm);
5886 break;
5887 case ISD::OR:
5888 ROpc = GET_ND_IF_ENABLED(X86::OR32rr);
5889 MOpc = GET_NDM_IF_ENABLED(X86::OR32rm);
5890 break;
5891 case ISD::XOR:
5892 ROpc = GET_ND_IF_ENABLED(X86::XOR32rr);
5893 MOpc = GET_NDM_IF_ENABLED(X86::XOR32rm);
5894 break;
5895 }
5896 break;
5897 case MVT::i64:
5898 switch (Opcode) {
5899 default: llvm_unreachable("Unexpected opcode!");
5900 case ISD::ADD:
5901 ROpc = GET_ND_IF_ENABLED(X86::ADD64rr);
5902 MOpc = GET_NDM_IF_ENABLED(X86::ADD64rm);
5903 break;
5904 case ISD::SUB:
5905 ROpc = GET_ND_IF_ENABLED(X86::SUB64rr);
5906 MOpc = GET_NDM_IF_ENABLED(X86::SUB64rm);
5907 break;
5908 case ISD::AND:
5909 ROpc = GET_ND_IF_ENABLED(X86::AND64rr);
5910 MOpc = GET_NDM_IF_ENABLED(X86::AND64rm);
5911 break;
5912 case ISD::OR:
5913 ROpc = GET_ND_IF_ENABLED(X86::OR64rr);
5914 MOpc = GET_NDM_IF_ENABLED(X86::OR64rm);
5915 break;
5916 case ISD::XOR:
5917 ROpc = GET_ND_IF_ENABLED(X86::XOR64rr);
5918 MOpc = GET_NDM_IF_ENABLED(X86::XOR64rm);
5919 break;
5920 }
5921 break;
5922 }
5923
5924 // Ok this is a AND/OR/XOR/ADD/SUB with constant.
5925
5926 // If this is a not a subtract, we can still try to fold a load.
5927 if (Opcode != ISD::SUB) {
5928 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
5929 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
5930 SDValue Ops[] = { N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
5931 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
5932 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
5933 // Update the chain.
5934 ReplaceUses(N0.getValue(1), SDValue(CNode, 2));
5935 // Record the mem-refs
5936 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N0)->getMemOperand()});
5937 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
5938 CurDAG->RemoveDeadNode(Node);
5939 return;
5940 }
5941 }
5942
5943 CurDAG->SelectNodeTo(Node, ROpc, NVT, MVT::i32, N0, N1);
5944 return;
5945 }
5946
5947 case X86ISD::SMUL:
5948 // i16/i32/i64 are handled with isel patterns.
5949 if (NVT != MVT::i8)
5950 break;
5951 [[fallthrough]];
5952 case X86ISD::UMUL: {
5953 SDValue N0 = Node->getOperand(0);
5954 SDValue N1 = Node->getOperand(1);
5955
5956 unsigned LoReg, ROpc, MOpc;
5957 switch (NVT.SimpleTy) {
5958 default: llvm_unreachable("Unsupported VT!");
5959 case MVT::i8:
5960 LoReg = X86::AL;
5961 ROpc = Opcode == X86ISD::SMUL ? X86::IMUL8r : X86::MUL8r;
5962 MOpc = Opcode == X86ISD::SMUL ? X86::IMUL8m : X86::MUL8m;
5963 break;
5964 case MVT::i16:
5965 LoReg = X86::AX;
5966 ROpc = X86::MUL16r;
5967 MOpc = X86::MUL16m;
5968 break;
5969 case MVT::i32:
5970 LoReg = X86::EAX;
5971 ROpc = X86::MUL32r;
5972 MOpc = X86::MUL32m;
5973 break;
5974 case MVT::i64:
5975 LoReg = X86::RAX;
5976 ROpc = X86::MUL64r;
5977 MOpc = X86::MUL64m;
5978 break;
5979 }
5980
5981 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
5982 bool FoldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
5983 // Multiply is commutative.
5984 if (!FoldedLoad) {
5985 FoldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
5986 if (FoldedLoad)
5987 std::swap(N0, N1);
5988 }
5989
5990 // UMUL/SMUL have an implicit source in LoReg (AL/AX/EAX/RAX). Prefer the
5991 // operand that's already there to avoid an extra register-to-register move.
5992 if (!FoldedLoad)
5993 orderRegForMul(N0, N1, LoReg, CurDAG->getMachineFunction().getRegInfo());
5994
5995 SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
5996 N0, SDValue()).getValue(1);
5997
5998 MachineSDNode *CNode;
5999 if (FoldedLoad) {
6000 // i16/i32/i64 use an instruction that produces a low and high result even
6001 // though only the low result is used.
6002 SDVTList VTs;
6003 if (NVT == MVT::i8)
6004 VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
6005 else
6006 VTs = CurDAG->getVTList(NVT, NVT, MVT::i32, MVT::Other);
6007
6008 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
6009 InGlue };
6010 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
6011
6012 // Update the chain.
6013 ReplaceUses(N1.getValue(1), SDValue(CNode, NVT == MVT::i8 ? 2 : 3));
6014 // Record the mem-refs
6015 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
6016 } else {
6017 // i16/i32/i64 use an instruction that produces a low and high result even
6018 // though only the low result is used.
6019 SDVTList VTs;
6020 if (NVT == MVT::i8)
6021 VTs = CurDAG->getVTList(NVT, MVT::i32);
6022 else
6023 VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
6024
6025 CNode = CurDAG->getMachineNode(ROpc, dl, VTs, {N1, InGlue});
6026 }
6027
6028 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
6029 ReplaceUses(SDValue(Node, 1), SDValue(CNode, NVT == MVT::i8 ? 1 : 2));
6030 CurDAG->RemoveDeadNode(Node);
6031 return;
6032 }
6033
6034 case ISD::SMUL_LOHI:
6035 case ISD::UMUL_LOHI: {
6036 SDValue N0 = Node->getOperand(0);
6037 SDValue N1 = Node->getOperand(1);
6038
6039 unsigned Opc, MOpc;
6040 unsigned LoReg, HiReg;
6041 bool IsSigned = Opcode == ISD::SMUL_LOHI;
6042 bool UseMULX = !IsSigned && Subtarget->hasBMI2();
6043 bool UseMULXHi = UseMULX && SDValue(Node, 0).use_empty();
6044 switch (NVT.SimpleTy) {
6045 default: llvm_unreachable("Unsupported VT!");
6046 case MVT::i32:
6047 Opc = UseMULXHi ? X86::MULX32Hrr
6048 : UseMULX ? GET_EGPR_IF_ENABLED(X86::MULX32rr)
6049 : IsSigned ? X86::IMUL32r
6050 : X86::MUL32r;
6051 MOpc = UseMULXHi ? X86::MULX32Hrm
6052 : UseMULX ? GET_EGPR_IF_ENABLED(X86::MULX32rm)
6053 : IsSigned ? X86::IMUL32m
6054 : X86::MUL32m;
6055 LoReg = UseMULX ? X86::EDX : X86::EAX;
6056 HiReg = X86::EDX;
6057 break;
6058 case MVT::i64:
6059 Opc = UseMULXHi ? X86::MULX64Hrr
6060 : UseMULX ? GET_EGPR_IF_ENABLED(X86::MULX64rr)
6061 : IsSigned ? X86::IMUL64r
6062 : X86::MUL64r;
6063 MOpc = UseMULXHi ? X86::MULX64Hrm
6064 : UseMULX ? GET_EGPR_IF_ENABLED(X86::MULX64rm)
6065 : IsSigned ? X86::IMUL64m
6066 : X86::MUL64m;
6067 LoReg = UseMULX ? X86::RDX : X86::RAX;
6068 HiReg = X86::RDX;
6069 break;
6070 }
6071
6072 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
6073 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
6074 // Multiply is commutative.
6075 if (!foldedLoad) {
6076 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
6077 if (foldedLoad)
6078 std::swap(N0, N1);
6079 }
6080
6081 // UMUL/SMUL_LOHI has an implicit source in LoReg (RDX for MULX, RAX for
6082 // MUL/IMUL). Prefer the operand that's already there.
6083 if (!foldedLoad)
6084 orderRegForMul(N0, N1, LoReg, CurDAG->getMachineFunction().getRegInfo());
6085
6086 SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
6087 N0, SDValue()).getValue(1);
6088 SDValue ResHi, ResLo;
6089 if (foldedLoad) {
6090 SDValue Chain;
6091 MachineSDNode *CNode = nullptr;
6092 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
6093 InGlue };
6094 if (UseMULXHi) {
6095 SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
6096 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
6097 ResHi = SDValue(CNode, 0);
6098 Chain = SDValue(CNode, 1);
6099 } else if (UseMULX) {
6100 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other);
6101 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
6102 ResHi = SDValue(CNode, 0);
6103 ResLo = SDValue(CNode, 1);
6104 Chain = SDValue(CNode, 2);
6105 } else {
6106 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
6107 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
6108 Chain = SDValue(CNode, 0);
6109 InGlue = SDValue(CNode, 1);
6110 }
6111
6112 // Update the chain.
6113 ReplaceUses(N1.getValue(1), Chain);
6114 // Record the mem-refs
6115 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
6116 } else {
6117 SDValue Ops[] = { N1, InGlue };
6118 if (UseMULXHi) {
6119 SDVTList VTs = CurDAG->getVTList(NVT);
6120 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
6121 ResHi = SDValue(CNode, 0);
6122 } else if (UseMULX) {
6123 SDVTList VTs = CurDAG->getVTList(NVT, NVT);
6124 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
6125 ResHi = SDValue(CNode, 0);
6126 ResLo = SDValue(CNode, 1);
6127 } else {
6128 SDVTList VTs = CurDAG->getVTList(MVT::Glue);
6129 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
6130 InGlue = SDValue(CNode, 0);
6131 }
6132 }
6133
6134 // Copy the low half of the result, if it is needed.
6135 if (!SDValue(Node, 0).use_empty()) {
6136 if (!ResLo) {
6137 assert(LoReg && "Register for low half is not defined!");
6138 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg,
6139 NVT, InGlue);
6140 InGlue = ResLo.getValue(2);
6141 }
6142 ReplaceUses(SDValue(Node, 0), ResLo);
6143 LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG);
6144 dbgs() << '\n');
6145 }
6146 // Copy the high half of the result, if it is needed.
6147 if (!SDValue(Node, 1).use_empty()) {
6148 if (!ResHi) {
6149 assert(HiReg && "Register for high half is not defined!");
6150 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg,
6151 NVT, InGlue);
6152 InGlue = ResHi.getValue(2);
6153 }
6154 ReplaceUses(SDValue(Node, 1), ResHi);
6155 LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG);
6156 dbgs() << '\n');
6157 }
6158
6159 CurDAG->RemoveDeadNode(Node);
6160 return;
6161 }
6162
6163 case ISD::SDIVREM:
6164 case ISD::UDIVREM: {
6165 SDValue N0 = Node->getOperand(0);
6166 SDValue N1 = Node->getOperand(1);
6167
6168 unsigned ROpc, MOpc;
6169 bool isSigned = Opcode == ISD::SDIVREM;
6170 if (!isSigned) {
6171 switch (NVT.SimpleTy) {
6172 default: llvm_unreachable("Unsupported VT!");
6173 case MVT::i8: ROpc = X86::DIV8r; MOpc = X86::DIV8m; break;
6174 case MVT::i16: ROpc = X86::DIV16r; MOpc = X86::DIV16m; break;
6175 case MVT::i32: ROpc = X86::DIV32r; MOpc = X86::DIV32m; break;
6176 case MVT::i64: ROpc = X86::DIV64r; MOpc = X86::DIV64m; break;
6177 }
6178 } else {
6179 switch (NVT.SimpleTy) {
6180 default: llvm_unreachable("Unsupported VT!");
6181 case MVT::i8: ROpc = X86::IDIV8r; MOpc = X86::IDIV8m; break;
6182 case MVT::i16: ROpc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
6183 case MVT::i32: ROpc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
6184 case MVT::i64: ROpc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
6185 }
6186 }
6187
6188 unsigned LoReg, HiReg, ClrReg;
6189 unsigned SExtOpcode;
6190 switch (NVT.SimpleTy) {
6191 default: llvm_unreachable("Unsupported VT!");
6192 case MVT::i8:
6193 LoReg = X86::AL; ClrReg = HiReg = X86::AH;
6194 SExtOpcode = 0; // Not used.
6195 break;
6196 case MVT::i16:
6197 LoReg = X86::AX; HiReg = X86::DX;
6198 ClrReg = X86::DX;
6199 SExtOpcode = X86::CWD;
6200 break;
6201 case MVT::i32:
6202 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
6203 SExtOpcode = X86::CDQ;
6204 break;
6205 case MVT::i64:
6206 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
6207 SExtOpcode = X86::CQO;
6208 break;
6209 }
6210
6211 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
6212 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
6213 bool signBitIsZero = CurDAG->SignBitIsZero(N0);
6214
6215 SDValue InGlue;
6216 if (NVT == MVT::i8) {
6217 // Special case for div8, just use a move with zero extension to AX to
6218 // clear the upper 8 bits (AH).
6219 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain;
6220 MachineSDNode *Move;
6221 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
6222 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
6223 unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rm8
6224 : X86::MOVZX16rm8;
6225 Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, MVT::Other, Ops);
6226 Chain = SDValue(Move, 1);
6227 ReplaceUses(N0.getValue(1), Chain);
6228 // Record the mem-refs
6229 CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()});
6230 } else {
6231 unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rr8
6232 : X86::MOVZX16rr8;
6233 Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, N0);
6234 Chain = CurDAG->getEntryNode();
6235 }
6236 Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, SDValue(Move, 0),
6237 SDValue());
6238 InGlue = Chain.getValue(1);
6239 } else {
6240 InGlue =
6241 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
6242 LoReg, N0, SDValue()).getValue(1);
6243 if (isSigned && !signBitIsZero) {
6244 // Sign extend the low part into the high part.
6245 InGlue =
6246 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InGlue),0);
6247 } else {
6248 // Zero out the high part, effectively zero extending the input.
6249 SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);
6250 SDValue ClrNode =
6251 SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, {}), 0);
6252 switch (NVT.SimpleTy) {
6253 case MVT::i16:
6254 ClrNode =
6255 SDValue(CurDAG->getMachineNode(
6256 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
6257 CurDAG->getTargetConstant(X86::sub_16bit, dl,
6258 MVT::i32)),
6259 0);
6260 break;
6261 case MVT::i32:
6262 break;
6263 case MVT::i64:
6264 ClrNode = SDValue(
6265 CurDAG->getMachineNode(
6266 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64, ClrNode,
6267 CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
6268 0);
6269 break;
6270 default:
6271 llvm_unreachable("Unexpected division source");
6272 }
6273
6274 InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
6275 ClrNode, InGlue).getValue(1);
6276 }
6277 }
6278
6279 if (foldedLoad) {
6280 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
6281 InGlue };
6282 MachineSDNode *CNode =
6283 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
6284 InGlue = SDValue(CNode, 1);
6285 // Update the chain.
6286 ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
6287 // Record the mem-refs
6288 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
6289 } else {
6290 InGlue =
6291 SDValue(CurDAG->getMachineNode(ROpc, dl, MVT::Glue, N1, InGlue), 0);
6292 }
6293
6294 // Prevent use of AH in a REX instruction by explicitly copying it to
6295 // an ABCD_L register.
6296 //
6297 // The current assumption of the register allocator is that isel
6298 // won't generate explicit references to the GR8_ABCD_H registers. If
6299 // the allocator and/or the backend get enhanced to be more robust in
6300 // that regard, this can be, and should be, removed.
6301 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
6302 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
6303 unsigned AHExtOpcode =
6304 isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;
6305
6306 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
6307 MVT::Glue, AHCopy, InGlue);
6308 SDValue Result(RNode, 0);
6309 InGlue = SDValue(RNode, 1);
6310
6311 Result =
6312 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
6313
6314 ReplaceUses(SDValue(Node, 1), Result);
6315 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
6316 dbgs() << '\n');
6317 }
6318 // Copy the division (low) result, if it is needed.
6319 if (!SDValue(Node, 0).use_empty()) {
6320 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
6321 LoReg, NVT, InGlue);
6322 InGlue = Result.getValue(2);
6323 ReplaceUses(SDValue(Node, 0), Result);
6324 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
6325 dbgs() << '\n');
6326 }
6327 // Copy the remainder (high) result, if it is needed.
6328 if (!SDValue(Node, 1).use_empty()) {
6329 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
6330 HiReg, NVT, InGlue);
6331 InGlue = Result.getValue(2);
6332 ReplaceUses(SDValue(Node, 1), Result);
6333 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
6334 dbgs() << '\n');
6335 }
6336 CurDAG->RemoveDeadNode(Node);
6337 return;
6338 }
6339
6340 case X86ISD::FCMP:
6341 case X86ISD::STRICT_FCMP:
6342 case X86ISD::STRICT_FCMPS: {
6343 bool IsStrictCmp = Node->getOpcode() == X86ISD::STRICT_FCMP ||
6344 Node->getOpcode() == X86ISD::STRICT_FCMPS;
6345 SDValue N0 = Node->getOperand(IsStrictCmp ? 1 : 0);
6346 SDValue N1 = Node->getOperand(IsStrictCmp ? 2 : 1);
6347
6348 // Save the original VT of the compare.
6349 MVT CmpVT = N0.getSimpleValueType();
6350
6351 // Floating point needs special handling if we don't have FCOMI.
6352 if (Subtarget->canUseCMOV())
6353 break;
6354
6355 bool IsSignaling = Node->getOpcode() == X86ISD::STRICT_FCMPS;
6356
6357 unsigned Opc;
6358 switch (CmpVT.SimpleTy) {
6359 default: llvm_unreachable("Unexpected type!");
6360 case MVT::f32:
6361 Opc = IsSignaling ? X86::COM_Fpr32 : X86::UCOM_Fpr32;
6362 break;
6363 case MVT::f64:
6364 Opc = IsSignaling ? X86::COM_Fpr64 : X86::UCOM_Fpr64;
6365 break;
6366 case MVT::f80:
6367 Opc = IsSignaling ? X86::COM_Fpr80 : X86::UCOM_Fpr80;
6368 break;
6369 }
6370
6371 SDValue Chain =
6372 IsStrictCmp ? Node->getOperand(0) : CurDAG->getEntryNode();
6373 SDValue Glue;
6374 if (IsStrictCmp) {
6375 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
6376 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, VTs, {N0, N1, Chain}), 0);
6377 Glue = Chain.getValue(1);
6378 } else {
6379 Glue = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N0, N1), 0);
6380 }
6381
6382 // Move FPSW to AX.
6383 SDValue FNSTSW =
6384 SDValue(CurDAG->getMachineNode(X86::FNSTSW16r, dl, MVT::i16, Glue), 0);
6385
6386 // Extract upper 8-bits of AX.
6387 SDValue Extract =
6388 CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl, MVT::i8, FNSTSW);
6389
6390 // Move AH into flags.
6391 // Some 64-bit targets lack SAHF support, but they do support FCOMI.
6392 assert(Subtarget->canUseLAHFSAHF() &&
6393 "Target doesn't support SAHF or FCOMI?");
6394 SDValue AH = CurDAG->getCopyToReg(Chain, dl, X86::AH, Extract, SDValue());
6395 Chain = AH;
6396 SDValue SAHF = SDValue(
6397 CurDAG->getMachineNode(X86::SAHF, dl, MVT::i32, AH.getValue(1)), 0);
6398
6399 if (IsStrictCmp)
6400 ReplaceUses(SDValue(Node, 1), Chain);
6401
6402 ReplaceUses(SDValue(Node, 0), SAHF);
6403 CurDAG->RemoveDeadNode(Node);
6404 return;
6405 }
6406
6407 case X86ISD::CMP: {
6408 SDValue N0 = Node->getOperand(0);
6409 SDValue N1 = Node->getOperand(1);
6410
6411 // Optimizations for TEST compares.
6412 if (!isNullConstant(N1))
6413 break;
6414
6415 // Save the original VT of the compare.
6416 MVT CmpVT = N0.getSimpleValueType();
6417
6418 // If we are comparing (and (shr X, C, Mask) with 0, emit a BEXTR followed
6419 // by a test instruction. The test should be removed later by
6420 // analyzeCompare if we are using only the zero flag.
6421 // TODO: Should we check the users and use the BEXTR flags directly?
6422 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
6423 if (MachineSDNode *NewNode = matchBEXTRFromAndImm(N0.getNode())) {
6424 unsigned TestOpc = CmpVT == MVT::i64 ? X86::TEST64rr
6425 : X86::TEST32rr;
6426 SDValue BEXTR = SDValue(NewNode, 0);
6427 NewNode = CurDAG->getMachineNode(TestOpc, dl, MVT::i32, BEXTR, BEXTR);
6428 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
6429 CurDAG->RemoveDeadNode(Node);
6430 return;
6431 }
6432 }
6433
6434 // We can peek through truncates, but we need to be careful below.
6435 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
6436 N0 = N0.getOperand(0);
6437
6438 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
6439 // use a smaller encoding.
6440 // Look past the truncate if CMP is the only use of it.
6441 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
6442 N0.getValueType() != MVT::i8) {
6443 auto *MaskC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6444 if (!MaskC)
6445 break;
6446
6447 // We may have looked through a truncate so mask off any bits that
6448 // shouldn't be part of the compare.
6449 uint64_t Mask = MaskC->getZExtValue();
6451
6452 // Check if we can replace AND+IMM{32,64} with a shift. This is possible
6453 // for masks like 0xFF000000 or 0x00FFFFFF and if we care only about the
6454 // zero flag.
6455 if (CmpVT == MVT::i64 && !isInt<8>(Mask) && isShiftedMask_64(Mask) &&
6456 onlyUsesZeroFlag(SDValue(Node, 0))) {
6457 unsigned ShiftOpcode = ISD::DELETED_NODE;
6458 unsigned ShiftAmt;
6459 unsigned SubRegIdx;
6460 MVT SubRegVT;
6461 unsigned TestOpcode;
6462 unsigned LeadingZeros = llvm::countl_zero(Mask);
6463 unsigned TrailingZeros = llvm::countr_zero(Mask);
6464
6465 // With leading/trailing zeros, the transform is profitable if we can
6466 // eliminate a movabsq or shrink a 32-bit immediate to 8-bit without
6467 // incurring any extra register moves.
6468 bool SavesBytes = !isInt<32>(Mask) || N0.getOperand(0).hasOneUse();
6469 if (LeadingZeros == 0 && SavesBytes) {
6470 // If the mask covers the most significant bit, then we can replace
6471 // TEST+AND with a SHR and check eflags.
6472 // This emits a redundant TEST which is subsequently eliminated.
6473 ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);
6474 ShiftAmt = TrailingZeros;
6475 SubRegIdx = 0;
6476 TestOpcode = X86::TEST64rr;
6477 } else if (TrailingZeros == 0 && SavesBytes) {
6478 // If the mask covers the least significant bit, then we can replace
6479 // TEST+AND with a SHL and check eflags.
6480 // This emits a redundant TEST which is subsequently eliminated,
6481 // except for shift amounts 1 to 3: isDefConvertible() rejects those
6482 // SHLs to keep them convertible to LEA, so the TEST would survive.
6483 if (LeadingZeros == 1) {
6484 // Shift out the top bit by doubling with ADD reg,reg instead: it
6485 // is the same length and sets ZF identically, but the peephole
6486 // does fold the TEST into it, and it runs on more ports.
6487 MachineSDNode *Add = CurDAG->getMachineNode(
6488 GET_ND_IF_ENABLED(X86::ADD64rr), dl, MVT::i64, MVT::i32,
6489 N0.getOperand(0), N0.getOperand(0));
6490 MachineSDNode *Test = CurDAG->getMachineNode(
6491 X86::TEST64rr, dl, MVT::i32, SDValue(Add, 0), SDValue(Add, 0));
6492 ReplaceNode(Node, Test);
6493 return;
6494 }
6495 ShiftOpcode = GET_ND_IF_ENABLED(X86::SHL64ri);
6496 ShiftAmt = LeadingZeros;
6497 SubRegIdx = 0;
6498 TestOpcode = X86::TEST64rr;
6499 } else if (MaskC->hasOneUse() && !isInt<32>(Mask)) {
6500 // If the shifted mask extends into the high half and is 8/16/32 bits
6501 // wide, then replace it with a SHR and a TEST8rr/TEST16rr/TEST32rr.
6502 unsigned PopCount = 64 - LeadingZeros - TrailingZeros;
6503 if (PopCount == 8) {
6504 ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);
6505 ShiftAmt = TrailingZeros;
6506 SubRegIdx = X86::sub_8bit;
6507 SubRegVT = MVT::i8;
6508 TestOpcode = X86::TEST8rr;
6509 } else if (PopCount == 16) {
6510 ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);
6511 ShiftAmt = TrailingZeros;
6512 SubRegIdx = X86::sub_16bit;
6513 SubRegVT = MVT::i16;
6514 TestOpcode = X86::TEST16rr;
6515 } else if (PopCount == 32) {
6516 ShiftOpcode = GET_ND_IF_ENABLED(X86::SHR64ri);
6517 ShiftAmt = TrailingZeros;
6518 SubRegIdx = X86::sub_32bit;
6519 SubRegVT = MVT::i32;
6520 TestOpcode = X86::TEST32rr;
6521 }
6522 }
6523 if (ShiftOpcode != ISD::DELETED_NODE) {
6524 SDValue ShiftC = CurDAG->getTargetConstant(ShiftAmt, dl, MVT::i64);
6525 SDValue Shift = SDValue(
6526 CurDAG->getMachineNode(ShiftOpcode, dl, MVT::i64, MVT::i32,
6527 N0.getOperand(0), ShiftC),
6528 0);
6529 if (SubRegIdx != 0) {
6530 Shift =
6531 CurDAG->getTargetExtractSubreg(SubRegIdx, dl, SubRegVT, Shift);
6532 }
6533 MachineSDNode *Test =
6534 CurDAG->getMachineNode(TestOpcode, dl, MVT::i32, Shift, Shift);
6535 ReplaceNode(Node, Test);
6536 return;
6537 }
6538 }
6539
6540 MVT VT;
6541 int SubRegOp;
6542 unsigned ROpc, MOpc;
6543
6544 // For each of these checks we need to be careful if the sign flag is
6545 // being used. It is only safe to use the sign flag in two conditions,
6546 // either the sign bit in the shrunken mask is zero or the final test
6547 // size is equal to the original compare size.
6548
6549 if (isUInt<8>(Mask) &&
6550 (!(Mask & 0x80) || CmpVT == MVT::i8 ||
6551 hasNoSignFlagUses(SDValue(Node, 0)))) {
6552 // For example, convert "testl %eax, $8" to "testb %al, $8"
6553 VT = MVT::i8;
6554 SubRegOp = X86::sub_8bit;
6555 ROpc = X86::TEST8ri;
6556 MOpc = X86::TEST8mi;
6557 } else if (OptForMinSize && isUInt<16>(Mask) &&
6558 (!(Mask & 0x8000) || CmpVT == MVT::i16 ||
6559 hasNoSignFlagUses(SDValue(Node, 0)))) {
6560 // For example, "testl %eax, $32776" to "testw %ax, $32776".
6561 // NOTE: We only want to form TESTW instructions if optimizing for
6562 // min size. Otherwise we only save one byte and possibly get a length
6563 // changing prefix penalty in the decoders.
6564 VT = MVT::i16;
6565 SubRegOp = X86::sub_16bit;
6566 ROpc = X86::TEST16ri;
6567 MOpc = X86::TEST16mi;
6568 } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
6569 ((!(Mask & 0x80000000) &&
6570 // Without minsize 16-bit Cmps can get here so we need to
6571 // be sure we calculate the correct sign flag if needed.
6572 (CmpVT != MVT::i16 || !(Mask & 0x8000))) ||
6573 CmpVT == MVT::i32 ||
6574 hasNoSignFlagUses(SDValue(Node, 0)))) {
6575 // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
6576 // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
6577 // Otherwize, we find ourselves in a position where we have to do
6578 // promotion. If previous passes did not promote the and, we assume
6579 // they had a good reason not to and do not promote here.
6580 VT = MVT::i32;
6581 SubRegOp = X86::sub_32bit;
6582 ROpc = X86::TEST32ri;
6583 MOpc = X86::TEST32mi;
6584 } else {
6585 // No eligible transformation was found.
6586 break;
6587 }
6588
6589 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
6590 SDValue Reg = N0.getOperand(0);
6591
6592 // Emit a testl or testw.
6593 MachineSDNode *NewNode;
6594 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
6595 if (tryFoldLoad(Node, N0.getNode(), Reg, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
6596 if (auto *LoadN = dyn_cast<LoadSDNode>(N0.getOperand(0).getNode())) {
6597 if (!LoadN->isSimple()) {
6598 unsigned NumVolBits = LoadN->getValueType(0).getSizeInBits();
6599 if ((MOpc == X86::TEST8mi && NumVolBits != 8) ||
6600 (MOpc == X86::TEST16mi && NumVolBits != 16) ||
6601 (MOpc == X86::TEST32mi && NumVolBits != 32))
6602 break;
6603 }
6604 }
6605 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
6606 Reg.getOperand(0) };
6607 NewNode = CurDAG->getMachineNode(MOpc, dl, MVT::i32, MVT::Other, Ops);
6608 // Update the chain.
6609 ReplaceUses(Reg.getValue(1), SDValue(NewNode, 1));
6610 // Record the mem-refs
6611 CurDAG->setNodeMemRefs(NewNode,
6612 {cast<LoadSDNode>(Reg)->getMemOperand()});
6613 } else {
6614 // Extract the subregister if necessary.
6615 if (N0.getValueType() != VT)
6616 Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
6617
6618 NewNode = CurDAG->getMachineNode(ROpc, dl, MVT::i32, Reg, Imm);
6619 }
6620 // Replace CMP with TEST.
6621 ReplaceNode(Node, NewNode);
6622 return;
6623 }
6624 break;
6625 }
6626 case X86ISD::PCMPISTR: {
6627 if (!Subtarget->hasSSE42())
6628 break;
6629
6630 bool NeedIndex = !SDValue(Node, 0).use_empty();
6631 bool NeedMask = !SDValue(Node, 1).use_empty();
6632 // We can't fold a load if we are going to make two instructions.
6633 bool MayFoldLoad = !NeedIndex || !NeedMask;
6634
6635 MachineSDNode *CNode;
6636 if (NeedMask) {
6637 unsigned ROpc =
6638 Subtarget->hasAVX() ? X86::VPCMPISTRMrri : X86::PCMPISTRMrri;
6639 unsigned MOpc =
6640 Subtarget->hasAVX() ? X86::VPCMPISTRMrmi : X86::PCMPISTRMrmi;
6641 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);
6642 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
6643 }
6644 if (NeedIndex || !NeedMask) {
6645 unsigned ROpc =
6646 Subtarget->hasAVX() ? X86::VPCMPISTRIrri : X86::PCMPISTRIrri;
6647 unsigned MOpc =
6648 Subtarget->hasAVX() ? X86::VPCMPISTRIrmi : X86::PCMPISTRIrmi;
6649 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);
6650 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
6651 }
6652
6653 // Connect the flag usage to the last instruction created.
6654 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
6655 CurDAG->RemoveDeadNode(Node);
6656 return;
6657 }
6658 case X86ISD::PCMPESTR: {
6659 if (!Subtarget->hasSSE42())
6660 break;
6661
6662 // Copy the two implicit register inputs.
6663 SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,
6664 Node->getOperand(1),
6665 SDValue()).getValue(1);
6666 InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,
6667 Node->getOperand(3), InGlue).getValue(1);
6668
6669 bool NeedIndex = !SDValue(Node, 0).use_empty();
6670 bool NeedMask = !SDValue(Node, 1).use_empty();
6671 // We can't fold a load if we are going to make two instructions.
6672 bool MayFoldLoad = !NeedIndex || !NeedMask;
6673
6674 MachineSDNode *CNode;
6675 if (NeedMask) {
6676 unsigned ROpc =
6677 Subtarget->hasAVX() ? X86::VPCMPESTRMrri : X86::PCMPESTRMrri;
6678 unsigned MOpc =
6679 Subtarget->hasAVX() ? X86::VPCMPESTRMrmi : X86::PCMPESTRMrmi;
6680 CNode =
6681 emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node, InGlue);
6682 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
6683 }
6684 if (NeedIndex || !NeedMask) {
6685 unsigned ROpc =
6686 Subtarget->hasAVX() ? X86::VPCMPESTRIrri : X86::PCMPESTRIrri;
6687 unsigned MOpc =
6688 Subtarget->hasAVX() ? X86::VPCMPESTRIrmi : X86::PCMPESTRIrmi;
6689 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InGlue);
6690 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
6691 }
6692 // Connect the flag usage to the last instruction created.
6693 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
6694 CurDAG->RemoveDeadNode(Node);
6695 return;
6696 }
6697
6698 case ISD::SETCC: {
6699 if (NVT.isVector() && tryVPTESTM(Node, SDValue(Node, 0), SDValue()))
6700 return;
6701
6702 break;
6703 }
6704
6705 case ISD::STORE:
6706 if (foldLoadStoreIntoMemOperand(Node))
6707 return;
6708 break;
6709
6710 case X86ISD::SETCC_CARRY: {
6711 MVT VT = Node->getSimpleValueType(0);
6713 if (Subtarget->hasSBBDepBreaking()) {
6714 // We have to do this manually because tblgen will put the eflags copy in
6715 // the wrong place if we use an extract_subreg in the pattern.
6716 // Copy flags to the EFLAGS register and glue it to next node.
6717 SDValue EFLAGS =
6718 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,
6719 Node->getOperand(1), SDValue());
6720
6721 // Create a 64-bit instruction if the result is 64-bits otherwise use the
6722 // 32-bit version.
6723 unsigned Opc = VT == MVT::i64 ? X86::SETB_C64r : X86::SETB_C32r;
6724 MVT SetVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;
6725 Result = SDValue(
6726 CurDAG->getMachineNode(Opc, dl, SetVT, EFLAGS, EFLAGS.getValue(1)),
6727 0);
6728 } else {
6729 // The target does not recognize sbb with the same reg operand as a
6730 // no-source idiom, so we explicitly zero the input values.
6731 Result = getSBBZero(Node);
6732 }
6733
6734 // For less than 32-bits we need to extract from the 32-bit node.
6735 if (VT == MVT::i8 || VT == MVT::i16) {
6736 int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit;
6737 Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result);
6738 }
6739
6740 ReplaceUses(SDValue(Node, 0), Result);
6741 CurDAG->RemoveDeadNode(Node);
6742 return;
6743 }
6744 case X86ISD::SBB: {
6745 if (isNullConstant(Node->getOperand(0)) &&
6746 isNullConstant(Node->getOperand(1))) {
6747 SDValue Result = getSBBZero(Node);
6748
6749 // Replace the flag use.
6750 ReplaceUses(SDValue(Node, 1), Result.getValue(1));
6751
6752 // Replace the result use.
6753 if (!SDValue(Node, 0).use_empty()) {
6754 // For less than 32-bits we need to extract from the 32-bit node.
6755 MVT VT = Node->getSimpleValueType(0);
6756 if (VT == MVT::i8 || VT == MVT::i16) {
6757 int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit;
6758 Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result);
6759 }
6760 ReplaceUses(SDValue(Node, 0), Result);
6761 }
6762
6763 CurDAG->RemoveDeadNode(Node);
6764 return;
6765 }
6766 break;
6767 }
6768 case X86ISD::MGATHER: {
6769 auto *Mgt = cast<X86MaskedGatherSDNode>(Node);
6770 SDValue IndexOp = Mgt->getIndex();
6771 SDValue Mask = Mgt->getMask();
6772 MVT IndexVT = IndexOp.getSimpleValueType();
6773 MVT ValueVT = Node->getSimpleValueType(0);
6774 MVT MaskVT = Mask.getSimpleValueType();
6775
6776 // This is just to prevent crashes if the nodes are malformed somehow. We're
6777 // otherwise only doing loose type checking in here based on type what
6778 // a type constraint would say just like table based isel.
6779 if (!ValueVT.isVector() || !MaskVT.isVector())
6780 break;
6781
6782 unsigned NumElts = ValueVT.getVectorNumElements();
6783 MVT ValueSVT = ValueVT.getVectorElementType();
6784
6785 bool IsFP = ValueSVT.isFloatingPoint();
6786 unsigned EltSize = ValueSVT.getSizeInBits();
6787
6788 unsigned Opc = 0;
6789 bool AVX512Gather = MaskVT.getVectorElementType() == MVT::i1;
6790 if (AVX512Gather) {
6791 if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
6792 Opc = IsFP ? X86::VGATHERDPSZ128rm : X86::VPGATHERDDZ128rm;
6793 else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
6794 Opc = IsFP ? X86::VGATHERDPSZ256rm : X86::VPGATHERDDZ256rm;
6795 else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32)
6796 Opc = IsFP ? X86::VGATHERDPSZrm : X86::VPGATHERDDZrm;
6797 else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
6798 Opc = IsFP ? X86::VGATHERDPDZ128rm : X86::VPGATHERDQZ128rm;
6799 else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
6800 Opc = IsFP ? X86::VGATHERDPDZ256rm : X86::VPGATHERDQZ256rm;
6801 else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64)
6802 Opc = IsFP ? X86::VGATHERDPDZrm : X86::VPGATHERDQZrm;
6803 else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
6804 Opc = IsFP ? X86::VGATHERQPSZ128rm : X86::VPGATHERQDZ128rm;
6805 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
6806 Opc = IsFP ? X86::VGATHERQPSZ256rm : X86::VPGATHERQDZ256rm;
6807 else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32)
6808 Opc = IsFP ? X86::VGATHERQPSZrm : X86::VPGATHERQDZrm;
6809 else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
6810 Opc = IsFP ? X86::VGATHERQPDZ128rm : X86::VPGATHERQQZ128rm;
6811 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
6812 Opc = IsFP ? X86::VGATHERQPDZ256rm : X86::VPGATHERQQZ256rm;
6813 else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64)
6814 Opc = IsFP ? X86::VGATHERQPDZrm : X86::VPGATHERQQZrm;
6815 } else {
6816 assert(EVT(MaskVT) == EVT(ValueVT).changeVectorElementTypeToInteger() &&
6817 "Unexpected mask VT!");
6818 if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
6819 Opc = IsFP ? X86::VGATHERDPSrm : X86::VPGATHERDDrm;
6820 else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
6821 Opc = IsFP ? X86::VGATHERDPSYrm : X86::VPGATHERDDYrm;
6822 else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
6823 Opc = IsFP ? X86::VGATHERDPDrm : X86::VPGATHERDQrm;
6824 else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
6825 Opc = IsFP ? X86::VGATHERDPDYrm : X86::VPGATHERDQYrm;
6826 else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
6827 Opc = IsFP ? X86::VGATHERQPSrm : X86::VPGATHERQDrm;
6828 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
6829 Opc = IsFP ? X86::VGATHERQPSYrm : X86::VPGATHERQDYrm;
6830 else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
6831 Opc = IsFP ? X86::VGATHERQPDrm : X86::VPGATHERQQrm;
6832 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
6833 Opc = IsFP ? X86::VGATHERQPDYrm : X86::VPGATHERQQYrm;
6834 }
6835
6836 if (!Opc)
6837 break;
6838
6839 SDValue Base, Scale, Index, Disp, Segment;
6840 if (!selectVectorAddr(Mgt, Mgt->getBasePtr(), IndexOp, Mgt->getScale(),
6841 Base, Scale, Index, Disp, Segment))
6842 break;
6843
6844 SDValue PassThru = Mgt->getPassThru();
6845 SDValue Chain = Mgt->getChain();
6846 // Gather instructions have a mask output not in the ISD node.
6847 SDVTList VTs = CurDAG->getVTList(ValueVT, MaskVT, MVT::Other);
6848
6849 MachineSDNode *NewNode;
6850 if (AVX512Gather) {
6851 SDValue Ops[] = {PassThru, Mask, Base, Scale,
6852 Index, Disp, Segment, Chain};
6853 NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
6854 } else {
6855 SDValue Ops[] = {PassThru, Base, Scale, Index,
6856 Disp, Segment, Mask, Chain};
6857 NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
6858 }
6859 CurDAG->setNodeMemRefs(NewNode, {Mgt->getMemOperand()});
6860 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
6861 ReplaceUses(SDValue(Node, 1), SDValue(NewNode, 2));
6862 CurDAG->RemoveDeadNode(Node);
6863 return;
6864 }
6865 case X86ISD::MSCATTER: {
6866 auto *Sc = cast<X86MaskedScatterSDNode>(Node);
6867 SDValue Value = Sc->getValue();
6868 SDValue IndexOp = Sc->getIndex();
6869 MVT IndexVT = IndexOp.getSimpleValueType();
6870 MVT ValueVT = Value.getSimpleValueType();
6871
6872 // This is just to prevent crashes if the nodes are malformed somehow. We're
6873 // otherwise only doing loose type checking in here based on type what
6874 // a type constraint would say just like table based isel.
6875 if (!ValueVT.isVector())
6876 break;
6877
6878 unsigned NumElts = ValueVT.getVectorNumElements();
6879 MVT ValueSVT = ValueVT.getVectorElementType();
6880
6881 bool IsFP = ValueSVT.isFloatingPoint();
6882 unsigned EltSize = ValueSVT.getSizeInBits();
6883
6884 unsigned Opc;
6885 if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
6886 Opc = IsFP ? X86::VSCATTERDPSZ128mr : X86::VPSCATTERDDZ128mr;
6887 else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
6888 Opc = IsFP ? X86::VSCATTERDPSZ256mr : X86::VPSCATTERDDZ256mr;
6889 else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32)
6890 Opc = IsFP ? X86::VSCATTERDPSZmr : X86::VPSCATTERDDZmr;
6891 else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
6892 Opc = IsFP ? X86::VSCATTERDPDZ128mr : X86::VPSCATTERDQZ128mr;
6893 else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
6894 Opc = IsFP ? X86::VSCATTERDPDZ256mr : X86::VPSCATTERDQZ256mr;
6895 else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64)
6896 Opc = IsFP ? X86::VSCATTERDPDZmr : X86::VPSCATTERDQZmr;
6897 else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
6898 Opc = IsFP ? X86::VSCATTERQPSZ128mr : X86::VPSCATTERQDZ128mr;
6899 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
6900 Opc = IsFP ? X86::VSCATTERQPSZ256mr : X86::VPSCATTERQDZ256mr;
6901 else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32)
6902 Opc = IsFP ? X86::VSCATTERQPSZmr : X86::VPSCATTERQDZmr;
6903 else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
6904 Opc = IsFP ? X86::VSCATTERQPDZ128mr : X86::VPSCATTERQQZ128mr;
6905 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
6906 Opc = IsFP ? X86::VSCATTERQPDZ256mr : X86::VPSCATTERQQZ256mr;
6907 else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64)
6908 Opc = IsFP ? X86::VSCATTERQPDZmr : X86::VPSCATTERQQZmr;
6909 else
6910 break;
6911
6912 SDValue Base, Scale, Index, Disp, Segment;
6913 if (!selectVectorAddr(Sc, Sc->getBasePtr(), IndexOp, Sc->getScale(),
6914 Base, Scale, Index, Disp, Segment))
6915 break;
6916
6917 SDValue Mask = Sc->getMask();
6918 SDValue Chain = Sc->getChain();
6919 // Scatter instructions have a mask output not in the ISD node.
6920 SDVTList VTs = CurDAG->getVTList(Mask.getValueType(), MVT::Other);
6921 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, Mask, Value, Chain};
6922
6923 MachineSDNode *NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
6924 CurDAG->setNodeMemRefs(NewNode, {Sc->getMemOperand()});
6925 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 1));
6926 CurDAG->RemoveDeadNode(Node);
6927 return;
6928 }
6930 auto *MFI = CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
6931 auto CallId = MFI->getPreallocatedIdForCallSite(
6932 cast<SrcValueSDNode>(Node->getOperand(1))->getValue());
6933 SDValue Chain = Node->getOperand(0);
6934 SDValue CallIdValue = CurDAG->getTargetConstant(CallId, dl, MVT::i32);
6935 MachineSDNode *New = CurDAG->getMachineNode(
6936 TargetOpcode::PREALLOCATED_SETUP, dl, MVT::Other, CallIdValue, Chain);
6937 ReplaceUses(SDValue(Node, 0), SDValue(New, 0)); // Chain
6938 CurDAG->RemoveDeadNode(Node);
6939 return;
6940 }
6941 case ISD::PREALLOCATED_ARG: {
6942 auto *MFI = CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>();
6943 auto CallId = MFI->getPreallocatedIdForCallSite(
6944 cast<SrcValueSDNode>(Node->getOperand(1))->getValue());
6945 SDValue Chain = Node->getOperand(0);
6946 SDValue CallIdValue = CurDAG->getTargetConstant(CallId, dl, MVT::i32);
6947 SDValue ArgIndex = Node->getOperand(2);
6948 SDValue Ops[3];
6949 Ops[0] = CallIdValue;
6950 Ops[1] = ArgIndex;
6951 Ops[2] = Chain;
6952 MachineSDNode *New = CurDAG->getMachineNode(
6953 TargetOpcode::PREALLOCATED_ARG, dl,
6954 CurDAG->getVTList(TLI->getPointerTy(CurDAG->getDataLayout()),
6955 MVT::Other),
6956 Ops);
6957 ReplaceUses(SDValue(Node, 0), SDValue(New, 0)); // Arg pointer
6958 ReplaceUses(SDValue(Node, 1), SDValue(New, 1)); // Chain
6959 CurDAG->RemoveDeadNode(Node);
6960 return;
6961 }
6966 if (!Subtarget->hasWIDEKL())
6967 break;
6968
6969 unsigned Opcode;
6970 switch (Node->getOpcode()) {
6971 default:
6972 llvm_unreachable("Unexpected opcode!");
6974 Opcode = X86::AESENCWIDE128KL;
6975 break;
6977 Opcode = X86::AESDECWIDE128KL;
6978 break;
6980 Opcode = X86::AESENCWIDE256KL;
6981 break;
6983 Opcode = X86::AESDECWIDE256KL;
6984 break;
6985 }
6986
6987 SDValue Chain = Node->getOperand(0);
6988 SDValue Addr = Node->getOperand(1);
6989
6990 SDValue Base, Scale, Index, Disp, Segment;
6991 if (!selectAddr(Node, Addr, Base, Scale, Index, Disp, Segment))
6992 break;
6993
6994 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM0, Node->getOperand(2),
6995 SDValue());
6996 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM1, Node->getOperand(3),
6997 Chain.getValue(1));
6998 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM2, Node->getOperand(4),
6999 Chain.getValue(1));
7000 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM3, Node->getOperand(5),
7001 Chain.getValue(1));
7002 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM4, Node->getOperand(6),
7003 Chain.getValue(1));
7004 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM5, Node->getOperand(7),
7005 Chain.getValue(1));
7006 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM6, Node->getOperand(8),
7007 Chain.getValue(1));
7008 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM7, Node->getOperand(9),
7009 Chain.getValue(1));
7010
7011 MachineSDNode *Res = CurDAG->getMachineNode(
7012 Opcode, dl, Node->getVTList(),
7013 {Base, Scale, Index, Disp, Segment, Chain, Chain.getValue(1)});
7014 CurDAG->setNodeMemRefs(Res, cast<MemSDNode>(Node)->getMemOperand());
7015 ReplaceNode(Node, Res);
7016 return;
7017 }
7019 SDValue Chain = Node->getOperand(0);
7020 Register Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
7021 SDValue Glue;
7022 if (Node->getNumValues() == 3)
7023 Glue = Node->getOperand(2);
7024 SDValue Copy =
7025 CurDAG->getCopyFromReg(Chain, dl, Reg, Node->getValueType(0), Glue);
7026 ReplaceNode(Node, Copy.getNode());
7027 return;
7028 }
7029 }
7030
7031 SelectCode(Node);
7032}
7033
7034bool X86DAGToDAGISel::SelectInlineAsmMemoryOperand(
7035 const SDValue &Op, InlineAsm::ConstraintCode ConstraintID,
7036 std::vector<SDValue> &OutOps) {
7037 SDValue Op0, Op1, Op2, Op3, Op4;
7038 switch (ConstraintID) {
7039 default:
7040 llvm_unreachable("Unexpected asm memory constraint");
7041 case InlineAsm::ConstraintCode::o: // offsetable ??
7042 case InlineAsm::ConstraintCode::v: // not offsetable ??
7043 case InlineAsm::ConstraintCode::m: // memory
7044 case InlineAsm::ConstraintCode::X:
7045 case InlineAsm::ConstraintCode::p: // address
7046 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
7047 return true;
7048 break;
7049 }
7050
7051 OutOps.push_back(Op0);
7052 OutOps.push_back(Op1);
7053 OutOps.push_back(Op2);
7054 OutOps.push_back(Op3);
7055 OutOps.push_back(Op4);
7056 return false;
7057}
7058
7061 std::make_unique<X86DAGToDAGISel>(TM, TM.getOptLevel())) {}
7062
7063/// This pass converts a legalized DAG into a X86-specific DAG,
7064/// ready for instruction scheduling.
7066 CodeGenOptLevel OptLevel) {
7067 return new X86DAGToDAGISelLegacy(TM, OptLevel);
7068}
static SDValue Widen(SelectionDAG *CurDAG, SDValue N)
return SDValue()
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
unsigned Imm
unsigned uint64_t
AMDGPU Register Bank Select
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis false
#define CASE(ATTRNAME, AANAME,...)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
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")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
dxil translate DXIL Translate Metadata
static bool isSigned(unsigned Opcode)
#define DEBUG_TYPE
const HexagonInstrInfo * TII
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
const MCPhysReg ArgGPRs[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode, SDValue StoredVal, SelectionDAG *CurDAG, LoadSDNode *&LoadNode, SDValue &InputChain)
static void insertDAGNode(SelectionDAG *DAG, SDNode *Pos, SDValue N)
#define PASS_NAME
static bool isRIPRelative(const MCInst &MI, const MCInstrInfo &MCII)
Check if the instruction uses RIP relative addressing.
#define FROM_TO(FROM, TO)
#define GET_EGPR_IF_ENABLED(OPC)
static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget)
static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N, uint64_t Mask, SDValue Shift, SDValue X, X86ISelAddressMode &AM)
static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N, uint64_t Mask, SDValue Shift, SDValue X, X86ISelAddressMode &AM)
static bool needBWI(MVT VT)
static unsigned getVPTESTMOpc(MVT TestVT, bool IsTestN, bool FoldedLoad, bool FoldedBCast, bool Masked)
#define GET_NDM_IF_ENABLED(OPC)
static bool foldMaskedShiftToBEXTR(SelectionDAG &DAG, SDValue N, uint64_t Mask, SDValue Shift, SDValue X, X86ISelAddressMode &AM, const X86Subtarget &Subtarget)
static bool mayUseCarryFlag(X86::CondCode CC)
static cl::opt< bool > EnablePromoteAnyextLoad("x86-promote-anyext-load", cl::init(true), cl::desc("Enable promoting aligned anyext load to wider load"), cl::Hidden)
static bool isEndbrImm(uint64_t Imm, unsigned BitWidth)
static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load, SDValue Call, SDValue OrigChain)
Replace the original chain operand of the call with load's chain operand and move load below the call...
#define GET_ND_IF_ENABLED(OPC)
#define VPTESTM_BROADCAST_CASES(SUFFIX)
static cl::opt< bool > AndImmShrink("x86-and-imm-shrink", cl::init(true), cl::desc("Enable setting constant bits to reduce size of mask immediates"), cl::Hidden)
static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N, X86ISelAddressMode &AM)
#define VPTESTM_FULL_CASES(SUFFIX)
static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq)
Return true if call address is a load and it can be moved below CALLSEQ_START and the chains leading ...
static bool isDispSafeForFrameIndexOrRegBase(int64_t Val)
static void orderRegForMul(SDValue &N0, SDValue &N1, const unsigned LoReg, const MachineRegisterInfo &MRI)
cl::opt< bool > IndirectBranchTracking("x86-indirect-branch-tracking", cl::init(false), cl::Hidden, cl::desc("Enable X86 indirect branch tracking pass."))
#define GET_ND_IF_ENABLED(OPC)
#define CASE_ND(OP)
Value * RHS
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1056
LLVM_ABI APInt trunc(unsigned width) const
Truncate to new width.
Definition APInt.cpp:969
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1552
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1262
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:303
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:293
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:386
unsigned countr_one() const
Count the number of trailing one bits.
Definition APInt.h:1677
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:695
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:727
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI std::optional< ConstantRange > getAbsoluteSymbolRange() const
If this is an absolute symbol reference, returns the range of the symbol, otherwise returns std::null...
Definition Globals.cpp:534
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
const SDValue & getOffset() const
unsigned getID() const
getID() - Return the register class ID number.
unsigned getNumRegs() const
getNumRegs - Return the number of registers in this class.
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.
bool is128BitVector() const
Return true if this is a 128-bit vector type.
unsigned getVectorMinNumElements() const
Given a vector type, return the minimum number of elements it contains.
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool is512BitVector() const
Return true if this is a 512-bit vector type.
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
bool is256BitVector() const
Return true if this is a 256-bit vector type.
bool isScalarInteger() const
Return true if this is an integer, not including vectors.
static MVT getVectorVT(MVT VT, unsigned NumElements)
MVT getVectorElementType() const
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
MVT getHalfNumVectorElementsVT() const
Return a VT for a vector type with the same element type but half the number of elements.
MVT getScalarType() const
If this is a vector, return the element type, otherwise return this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI MCRegister getLiveInPhysReg(Register VReg) const
getLiveInPhysReg - If VReg is a live-in virtual register, return the corresponding live-in physical r...
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
bool isNonTemporal() 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
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Represents one node in the SelectionDAG.
ArrayRef< SDUse > ops() const
int getNodeId() const
Return the unique node id.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
SDNodeFlags getFlags() const
MVT getSimpleValueType(unsigned ResNo) const
Return the type of a specified result as a simple type.
static bool hasPredecessorHelper(const SDNode *N, SmallPtrSetImpl< const SDNode * > &Visited, SmallVectorImpl< const SDNode * > &Worklist, unsigned int MaxSteps=0, bool TopologicalPrune=false)
Returns true if N is a predecessor of any node in Worklist.
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
bool use_empty() const
Return true if there are no uses of this node.
const SDValue & getOperand(unsigned Num) const
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
iterator_range< user_iterator > users()
op_iterator op_end() const
op_iterator op_begin() const
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isMachineOpcode() const
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
uint64_t getScalarValueSizeInBits() const
unsigned getResNo() const
get the index which selects a specific result in the SDNode
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getMachineOpcode() const
unsigned getOpcode() const
unsigned getNumOperands() const
SelectionDAGISelPass(std::unique_ptr< SelectionDAGISel > Selector)
SelectionDAGISel - This is the common base class used for SelectionDAG-based pattern-matching instruc...
static int getUninvalidatedNodeId(SDNode *N)
virtual bool runOnMachineFunction(MachineFunction &mf)
static void InvalidateNodeId(SDNode *N)
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
static constexpr unsigned MaxRecursionDepth
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
LLVM_ABI void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
LLVM_ABI SDNode * UpdateNodeOperands(SDNode *N, SDValue Op)
Mutate the specified node in-place to have the specified operands.
void RepositionNode(allnodes_iterator Position, SDNode *N)
Move node N in the AllNodes list to be immediately before the given iterator Position.
ilist< SDNode >::iterator allnodes_iterator
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
const SDValue & getBasePtr() const
const SDValue & getOffset() const
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
X86ISelDAGToDAGPass(X86TargetMachine &TM)
size_t getPreallocatedIdForCallSite(const Value *CS)
bool isScalarFPTypeInSSEReg(EVT VT) const
Return true if the specified scalar FP type is computed in an SSE register, not on the X87 floating p...
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:829
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:45
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:275
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:602
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:264
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:863
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:220
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:280
@ 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
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:667
@ PREALLOCATED_SETUP
PREALLOCATED_SETUP - This has 2 operands: an input chain and a SRCVALUE with the preallocated call Va...
@ TargetExternalSymbol
Definition ISDOpcodes.h:190
@ PREALLOCATED_ARG
PREALLOCATED_ARG - This has 3 operands: an input chain, a SRCVALUE with the preallocated call Value,...
@ BRIND
BRIND - Indirect branch.
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition ISDOpcodes.h:230
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:185
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:771
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:616
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:578
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:224
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:860
@ LOCAL_RECOVER
LOCAL_RECOVER - Represents the llvm.localrecover intrinsic.
Definition ISDOpcodes.h:135
@ ANY_EXTEND_VECTOR_INREG
ANY_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register any-extension of the low la...
Definition ISDOpcodes.h:909
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:988
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:815
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:328
@ STRICT_FROUNDEVEN
Definition ISDOpcodes.h:466
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:480
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:502
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:479
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:936
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:507
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:741
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:53
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:969
@ ZERO_EXTEND_VECTOR_INREG
ZERO_EXTEND_VECTOR_INREG(Vector) - This operator represents an in-register zero-extension of the low ...
Definition ISDOpcodes.h:931
@ STRICT_FNEARBYINT
Definition ISDOpcodes.h:458
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:866
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:213
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:186
LLVM_ABI bool isBuildVectorOfConstantSDNodes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR node of all ConstantSDNode or undef.
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LLVM_ABI bool isBuildVectorAllOnes(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are ~0 or undef.
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
@ GlobalBaseReg
The result of the mflr at function entry, used for PIC code.
@ X86
Windows x64, Windows Itanium (IA-64)
Definition MCAsmInfo.h:53
@ MO_NO_FLAG
MO_NO_FLAG - No flag for the operand.
@ EVEX
EVEX - Specifies that this instruction use EVEX form which provides syntax support up to 32 512-bit r...
@ VEX
VEX - encoding using 0xC4/0xC5.
@ XOP
XOP - Opcode prefix used by XOP instructions.
int getMemoryOperandNo(uint64_t TSFlags)
@ GlobalBaseReg
On Darwin, this node represents the result of the popl at function entry, used for PIC code.
@ POP_FROM_X87_REG
The same as ISD::CopyFromReg except that this node makes it explicit that it may lower to an x87 FPU ...
@ AddrNumOperands
Definition X86BaseInfo.h:36
int getCondSrcNoFromDesc(const MCInstrDesc &MCID)
Return the source operand # for condition code by MCID.
bool mayFoldLoad(SDValue Op, const X86Subtarget &Subtarget, bool AssumeSingleUse=false, bool IgnoreAlignment=false)
Check if Op is a load operation that could be folded into some other x86 instruction as a memory oper...
bool isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M, bool hasSymbolicDisplacement)
Returns true of the given offset can be fit into displacement field of the instruction.
bool isConstantSplat(SDValue Op, APInt &SplatVal, bool AllowPartialUndefs)
If Op is a constant whose elements are all the same constant or undefined, return true and return the...
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
constexpr uint16_t Magic
Definition SFrame.h:32
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:578
InstructionCost Cost
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
Op::Description Desc
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition MathExtras.h:274
unsigned M1(unsigned Val)
Definition VE.h:377
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition MathExtras.h:262
FunctionPass * createX86ISelDag(X86TargetMachine &TM, CodeGenOptLevel OptLevel)
This pass converts a legalized DAG into a X86-specific DAG, ready for instruction scheduling.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:149
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
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
unsigned M0(unsigned Val)
Definition VE.h:376
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isOneConstant(SDValue V)
Returns true if V is a constant integer one.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
Extended Value Type.
Definition ValueTypes.h:35
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
bool is128BitVector() const
Return true if this is a 128-bit vector type.
Definition ValueTypes.h:230
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
bool is256BitVector() const
Return true if this is a 256-bit vector type.
Definition ValueTypes.h:235
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
Matching combinators.
LLVM_ABI unsigned getAddrSpace() const
Return the LLVM IR address space number that this pointer points into.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
bool hasNoUnsignedWrap() const