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