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