1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This implements the TargetLowering class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/TargetLowering.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/CodeGen/CallingConvLower.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineJumpTableInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/TargetRegisterInfo.h"
22 #include "llvm/CodeGen/TargetSubtargetInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
37 /// NOTE: The TargetMachine owns TLOF.
38 TargetLowering::TargetLowering(const TargetMachine
&tm
)
39 : TargetLoweringBase(tm
) {}
41 const char *TargetLowering::getTargetNodeName(unsigned Opcode
) const {
45 bool TargetLowering::isPositionIndependent() const {
46 return getTargetMachine().isPositionIndependent();
49 /// Check whether a given call node is in tail position within its function. If
50 /// so, it sets Chain to the input chain of the tail call.
51 bool TargetLowering::isInTailCallPosition(SelectionDAG
&DAG
, SDNode
*Node
,
52 SDValue
&Chain
) const {
53 const Function
&F
= DAG
.getMachineFunction().getFunction();
55 // Conservatively require the attributes of the call to match those of
56 // the return. Ignore NoAlias and NonNull because they don't affect the
58 AttributeList CallerAttrs
= F
.getAttributes();
59 if (AttrBuilder(CallerAttrs
, AttributeList::ReturnIndex
)
60 .removeAttribute(Attribute::NoAlias
)
61 .removeAttribute(Attribute::NonNull
)
65 // It's not safe to eliminate the sign / zero extension of the return value.
66 if (CallerAttrs
.hasAttribute(AttributeList::ReturnIndex
, Attribute::ZExt
) ||
67 CallerAttrs
.hasAttribute(AttributeList::ReturnIndex
, Attribute::SExt
))
70 // Check if the only use is a function return node.
71 return isUsedByReturnOnly(Node
, Chain
);
74 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo
&MRI
,
75 const uint32_t *CallerPreservedMask
,
76 const SmallVectorImpl
<CCValAssign
> &ArgLocs
,
77 const SmallVectorImpl
<SDValue
> &OutVals
) const {
78 for (unsigned I
= 0, E
= ArgLocs
.size(); I
!= E
; ++I
) {
79 const CCValAssign
&ArgLoc
= ArgLocs
[I
];
80 if (!ArgLoc
.isRegLoc())
82 Register Reg
= ArgLoc
.getLocReg();
83 // Only look at callee saved registers.
84 if (MachineOperand::clobbersPhysReg(CallerPreservedMask
, Reg
))
86 // Check that we pass the value used for the caller.
87 // (We look for a CopyFromReg reading a virtual register that is used
88 // for the function live-in value of register Reg)
89 SDValue Value
= OutVals
[I
];
90 if (Value
->getOpcode() != ISD::CopyFromReg
)
92 unsigned ArgReg
= cast
<RegisterSDNode
>(Value
->getOperand(1))->getReg();
93 if (MRI
.getLiveInPhysReg(ArgReg
) != Reg
)
99 /// Set CallLoweringInfo attribute flags based on a call instruction
100 /// and called function attributes.
101 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase
*Call
,
103 IsSExt
= Call
->paramHasAttr(ArgIdx
, Attribute::SExt
);
104 IsZExt
= Call
->paramHasAttr(ArgIdx
, Attribute::ZExt
);
105 IsInReg
= Call
->paramHasAttr(ArgIdx
, Attribute::InReg
);
106 IsSRet
= Call
->paramHasAttr(ArgIdx
, Attribute::StructRet
);
107 IsNest
= Call
->paramHasAttr(ArgIdx
, Attribute::Nest
);
108 IsByVal
= Call
->paramHasAttr(ArgIdx
, Attribute::ByVal
);
109 IsInAlloca
= Call
->paramHasAttr(ArgIdx
, Attribute::InAlloca
);
110 IsReturned
= Call
->paramHasAttr(ArgIdx
, Attribute::Returned
);
111 IsSwiftSelf
= Call
->paramHasAttr(ArgIdx
, Attribute::SwiftSelf
);
112 IsSwiftError
= Call
->paramHasAttr(ArgIdx
, Attribute::SwiftError
);
113 Alignment
= Call
->getParamAlignment(ArgIdx
);
115 if (Call
->paramHasAttr(ArgIdx
, Attribute::ByVal
))
116 ByValType
= Call
->getParamByValType(ArgIdx
);
119 /// Generate a libcall taking the given operands as arguments and returning a
120 /// result of type RetVT.
121 std::pair
<SDValue
, SDValue
>
122 TargetLowering::makeLibCall(SelectionDAG
&DAG
, RTLIB::Libcall LC
, EVT RetVT
,
123 ArrayRef
<SDValue
> Ops
,
124 MakeLibCallOptions CallOptions
,
125 const SDLoc
&dl
) const {
126 TargetLowering::ArgListTy Args
;
127 Args
.reserve(Ops
.size());
129 TargetLowering::ArgListEntry Entry
;
130 for (SDValue Op
: Ops
) {
132 Entry
.Ty
= Entry
.Node
.getValueType().getTypeForEVT(*DAG
.getContext());
133 Entry
.IsSExt
= shouldSignExtendTypeInLibCall(Op
.getValueType(),
135 Entry
.IsZExt
= !Entry
.IsSExt
;
136 Args
.push_back(Entry
);
139 if (LC
== RTLIB::UNKNOWN_LIBCALL
)
140 report_fatal_error("Unsupported library call operation!");
141 SDValue Callee
= DAG
.getExternalSymbol(getLibcallName(LC
),
142 getPointerTy(DAG
.getDataLayout()));
144 Type
*RetTy
= RetVT
.getTypeForEVT(*DAG
.getContext());
145 TargetLowering::CallLoweringInfo
CLI(DAG
);
146 bool signExtend
= shouldSignExtendTypeInLibCall(RetVT
, CallOptions
.IsSExt
);
148 .setChain(DAG
.getEntryNode())
149 .setLibCallee(getLibcallCallingConv(LC
), RetTy
, Callee
, std::move(Args
))
150 .setNoReturn(CallOptions
.DoesNotReturn
)
151 .setDiscardResult(!CallOptions
.IsReturnValueUsed
)
152 .setIsPostTypeLegalization(CallOptions
.IsPostTypeLegalization
)
153 .setSExtResult(signExtend
)
154 .setZExtResult(!signExtend
);
155 return LowerCallTo(CLI
);
159 TargetLowering::findOptimalMemOpLowering(std::vector
<EVT
> &MemOps
,
160 unsigned Limit
, uint64_t Size
,
161 unsigned DstAlign
, unsigned SrcAlign
,
166 unsigned DstAS
, unsigned SrcAS
,
167 const AttributeList
&FuncAttributes
) const {
168 // If 'SrcAlign' is zero, that means the memory operation does not need to
169 // load the value, i.e. memset or memcpy from constant string. Otherwise,
170 // it's the inferred alignment of the source. 'DstAlign', on the other hand,
171 // is the specified alignment of the memory operation. If it is zero, that
172 // means it's possible to change the alignment of the destination.
173 // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
174 // not need to be loaded.
175 if (!(SrcAlign
== 0 || SrcAlign
>= DstAlign
))
178 EVT VT
= getOptimalMemOpType(Size
, DstAlign
, SrcAlign
,
179 IsMemset
, ZeroMemset
, MemcpyStrSrc
,
182 if (VT
== MVT::Other
) {
183 // Use the largest integer type whose alignment constraints are satisfied.
184 // We only need to check DstAlign here as SrcAlign is always greater or
185 // equal to DstAlign (or zero).
187 while (DstAlign
&& DstAlign
< VT
.getSizeInBits() / 8 &&
188 !allowsMisalignedMemoryAccesses(VT
, DstAS
, DstAlign
))
189 VT
= (MVT::SimpleValueType
)(VT
.getSimpleVT().SimpleTy
- 1);
190 assert(VT
.isInteger());
192 // Find the largest legal integer type.
194 while (!isTypeLegal(LVT
))
195 LVT
= (MVT::SimpleValueType
)(LVT
.SimpleTy
- 1);
196 assert(LVT
.isInteger());
198 // If the type we've chosen is larger than the largest legal integer type
199 // then use that instead.
204 unsigned NumMemOps
= 0;
206 unsigned VTSize
= VT
.getSizeInBits() / 8;
207 while (VTSize
> Size
) {
208 // For now, only use non-vector load / store's for the left-over pieces.
213 if (VT
.isVector() || VT
.isFloatingPoint()) {
214 NewVT
= (VT
.getSizeInBits() > 64) ? MVT::i64
: MVT::i32
;
215 if (isOperationLegalOrCustom(ISD::STORE
, NewVT
) &&
216 isSafeMemOpType(NewVT
.getSimpleVT()))
218 else if (NewVT
== MVT::i64
&&
219 isOperationLegalOrCustom(ISD::STORE
, MVT::f64
) &&
220 isSafeMemOpType(MVT::f64
)) {
221 // i64 is usually not legal on 32-bit targets, but f64 may be.
229 NewVT
= (MVT::SimpleValueType
)(NewVT
.getSimpleVT().SimpleTy
- 1);
230 if (NewVT
== MVT::i8
)
232 } while (!isSafeMemOpType(NewVT
.getSimpleVT()));
234 NewVTSize
= NewVT
.getSizeInBits() / 8;
236 // If the new VT cannot cover all of the remaining bits, then consider
237 // issuing a (or a pair of) unaligned and overlapping load / store.
239 if (NumMemOps
&& AllowOverlap
&& NewVTSize
< Size
&&
240 allowsMisalignedMemoryAccesses(VT
, DstAS
, DstAlign
,
241 MachineMemOperand::MONone
, &Fast
) &&
250 if (++NumMemOps
> Limit
)
253 MemOps
.push_back(VT
);
260 /// Soften the operands of a comparison. This code is shared among BR_CC,
261 /// SELECT_CC, and SETCC handlers.
262 void TargetLowering::softenSetCCOperands(SelectionDAG
&DAG
, EVT VT
,
263 SDValue
&NewLHS
, SDValue
&NewRHS
,
264 ISD::CondCode
&CCCode
,
265 const SDLoc
&dl
) const {
266 assert((VT
== MVT::f32
|| VT
== MVT::f64
|| VT
== MVT::f128
|| VT
== MVT::ppcf128
)
267 && "Unsupported setcc type!");
269 // Expand into one or more soft-fp libcall(s).
270 RTLIB::Libcall LC1
= RTLIB::UNKNOWN_LIBCALL
, LC2
= RTLIB::UNKNOWN_LIBCALL
;
271 bool ShouldInvertCC
= false;
275 LC1
= (VT
== MVT::f32
) ? RTLIB::OEQ_F32
:
276 (VT
== MVT::f64
) ? RTLIB::OEQ_F64
:
277 (VT
== MVT::f128
) ? RTLIB::OEQ_F128
: RTLIB::OEQ_PPCF128
;
281 LC1
= (VT
== MVT::f32
) ? RTLIB::UNE_F32
:
282 (VT
== MVT::f64
) ? RTLIB::UNE_F64
:
283 (VT
== MVT::f128
) ? RTLIB::UNE_F128
: RTLIB::UNE_PPCF128
;
287 LC1
= (VT
== MVT::f32
) ? RTLIB::OGE_F32
:
288 (VT
== MVT::f64
) ? RTLIB::OGE_F64
:
289 (VT
== MVT::f128
) ? RTLIB::OGE_F128
: RTLIB::OGE_PPCF128
;
293 LC1
= (VT
== MVT::f32
) ? RTLIB::OLT_F32
:
294 (VT
== MVT::f64
) ? RTLIB::OLT_F64
:
295 (VT
== MVT::f128
) ? RTLIB::OLT_F128
: RTLIB::OLT_PPCF128
;
299 LC1
= (VT
== MVT::f32
) ? RTLIB::OLE_F32
:
300 (VT
== MVT::f64
) ? RTLIB::OLE_F64
:
301 (VT
== MVT::f128
) ? RTLIB::OLE_F128
: RTLIB::OLE_PPCF128
;
305 LC1
= (VT
== MVT::f32
) ? RTLIB::OGT_F32
:
306 (VT
== MVT::f64
) ? RTLIB::OGT_F64
:
307 (VT
== MVT::f128
) ? RTLIB::OGT_F128
: RTLIB::OGT_PPCF128
;
310 LC1
= (VT
== MVT::f32
) ? RTLIB::UO_F32
:
311 (VT
== MVT::f64
) ? RTLIB::UO_F64
:
312 (VT
== MVT::f128
) ? RTLIB::UO_F128
: RTLIB::UO_PPCF128
;
315 LC1
= (VT
== MVT::f32
) ? RTLIB::O_F32
:
316 (VT
== MVT::f64
) ? RTLIB::O_F64
:
317 (VT
== MVT::f128
) ? RTLIB::O_F128
: RTLIB::O_PPCF128
;
320 // SETONE = SETOLT | SETOGT
321 LC1
= (VT
== MVT::f32
) ? RTLIB::OLT_F32
:
322 (VT
== MVT::f64
) ? RTLIB::OLT_F64
:
323 (VT
== MVT::f128
) ? RTLIB::OLT_F128
: RTLIB::OLT_PPCF128
;
324 LC2
= (VT
== MVT::f32
) ? RTLIB::OGT_F32
:
325 (VT
== MVT::f64
) ? RTLIB::OGT_F64
:
326 (VT
== MVT::f128
) ? RTLIB::OGT_F128
: RTLIB::OGT_PPCF128
;
329 LC1
= (VT
== MVT::f32
) ? RTLIB::UO_F32
:
330 (VT
== MVT::f64
) ? RTLIB::UO_F64
:
331 (VT
== MVT::f128
) ? RTLIB::UO_F128
: RTLIB::UO_PPCF128
;
332 LC2
= (VT
== MVT::f32
) ? RTLIB::OEQ_F32
:
333 (VT
== MVT::f64
) ? RTLIB::OEQ_F64
:
334 (VT
== MVT::f128
) ? RTLIB::OEQ_F128
: RTLIB::OEQ_PPCF128
;
337 // Invert CC for unordered comparisons
338 ShouldInvertCC
= true;
341 LC1
= (VT
== MVT::f32
) ? RTLIB::OGE_F32
:
342 (VT
== MVT::f64
) ? RTLIB::OGE_F64
:
343 (VT
== MVT::f128
) ? RTLIB::OGE_F128
: RTLIB::OGE_PPCF128
;
346 LC1
= (VT
== MVT::f32
) ? RTLIB::OGT_F32
:
347 (VT
== MVT::f64
) ? RTLIB::OGT_F64
:
348 (VT
== MVT::f128
) ? RTLIB::OGT_F128
: RTLIB::OGT_PPCF128
;
351 LC1
= (VT
== MVT::f32
) ? RTLIB::OLE_F32
:
352 (VT
== MVT::f64
) ? RTLIB::OLE_F64
:
353 (VT
== MVT::f128
) ? RTLIB::OLE_F128
: RTLIB::OLE_PPCF128
;
356 LC1
= (VT
== MVT::f32
) ? RTLIB::OLT_F32
:
357 (VT
== MVT::f64
) ? RTLIB::OLT_F64
:
358 (VT
== MVT::f128
) ? RTLIB::OLT_F128
: RTLIB::OLT_PPCF128
;
360 default: llvm_unreachable("Do not know how to soften this setcc!");
364 // Use the target specific return value for comparions lib calls.
365 EVT RetVT
= getCmpLibcallReturnType();
366 SDValue Ops
[2] = {NewLHS
, NewRHS
};
367 TargetLowering::MakeLibCallOptions CallOptions
;
368 NewLHS
= makeLibCall(DAG
, LC1
, RetVT
, Ops
, CallOptions
, dl
).first
;
369 NewRHS
= DAG
.getConstant(0, dl
, RetVT
);
371 CCCode
= getCmpLibcallCC(LC1
);
373 CCCode
= getSetCCInverse(CCCode
, /*isInteger=*/true);
375 if (LC2
!= RTLIB::UNKNOWN_LIBCALL
) {
376 SDValue Tmp
= DAG
.getNode(
378 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), RetVT
),
379 NewLHS
, NewRHS
, DAG
.getCondCode(CCCode
));
380 NewLHS
= makeLibCall(DAG
, LC2
, RetVT
, Ops
, CallOptions
, dl
).first
;
381 NewLHS
= DAG
.getNode(
383 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), RetVT
),
384 NewLHS
, NewRHS
, DAG
.getCondCode(getCmpLibcallCC(LC2
)));
385 NewLHS
= DAG
.getNode(ISD::OR
, dl
, Tmp
.getValueType(), Tmp
, NewLHS
);
390 /// Return the entry encoding for a jump table in the current function. The
391 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
392 unsigned TargetLowering::getJumpTableEncoding() const {
393 // In non-pic modes, just use the address of a block.
394 if (!isPositionIndependent())
395 return MachineJumpTableInfo::EK_BlockAddress
;
397 // In PIC mode, if the target supports a GPRel32 directive, use it.
398 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
399 return MachineJumpTableInfo::EK_GPRel32BlockAddress
;
401 // Otherwise, use a label difference.
402 return MachineJumpTableInfo::EK_LabelDifference32
;
405 SDValue
TargetLowering::getPICJumpTableRelocBase(SDValue Table
,
406 SelectionDAG
&DAG
) const {
407 // If our PIC model is GP relative, use the global offset table as the base.
408 unsigned JTEncoding
= getJumpTableEncoding();
410 if ((JTEncoding
== MachineJumpTableInfo::EK_GPRel64BlockAddress
) ||
411 (JTEncoding
== MachineJumpTableInfo::EK_GPRel32BlockAddress
))
412 return DAG
.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG
.getDataLayout()));
417 /// This returns the relocation base for the given PIC jumptable, the same as
418 /// getPICJumpTableRelocBase, but as an MCExpr.
420 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction
*MF
,
421 unsigned JTI
,MCContext
&Ctx
) const{
422 // The normal PIC reloc base is the label at the start of the jump table.
423 return MCSymbolRefExpr::create(MF
->getJTISymbol(JTI
, Ctx
), Ctx
);
427 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode
*GA
) const {
428 const TargetMachine
&TM
= getTargetMachine();
429 const GlobalValue
*GV
= GA
->getGlobal();
431 // If the address is not even local to this DSO we will have to load it from
432 // a got and then add the offset.
433 if (!TM
.shouldAssumeDSOLocal(*GV
->getParent(), GV
))
436 // If the code is position independent we will have to add a base register.
437 if (isPositionIndependent())
440 // Otherwise we can do it.
444 //===----------------------------------------------------------------------===//
445 // Optimization Methods
446 //===----------------------------------------------------------------------===//
448 /// If the specified instruction has a constant integer operand and there are
449 /// bits set in that constant that are not demanded, then clear those bits and
451 bool TargetLowering::ShrinkDemandedConstant(SDValue Op
, const APInt
&Demanded
,
452 TargetLoweringOpt
&TLO
) const {
454 unsigned Opcode
= Op
.getOpcode();
456 // Do target-specific constant optimization.
457 if (targetShrinkDemandedConstant(Op
, Demanded
, TLO
))
458 return TLO
.New
.getNode();
460 // FIXME: ISD::SELECT, ISD::SELECT_CC
467 auto *Op1C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
471 // If this is a 'not' op, don't touch it because that's a canonical form.
472 const APInt
&C
= Op1C
->getAPIntValue();
473 if (Opcode
== ISD::XOR
&& Demanded
.isSubsetOf(C
))
476 if (!C
.isSubsetOf(Demanded
)) {
477 EVT VT
= Op
.getValueType();
478 SDValue NewC
= TLO
.DAG
.getConstant(Demanded
& C
, DL
, VT
);
479 SDValue NewOp
= TLO
.DAG
.getNode(Opcode
, DL
, VT
, Op
.getOperand(0), NewC
);
480 return TLO
.CombineTo(Op
, NewOp
);
490 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
491 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
492 /// generalized for targets with other types of implicit widening casts.
493 bool TargetLowering::ShrinkDemandedOp(SDValue Op
, unsigned BitWidth
,
494 const APInt
&Demanded
,
495 TargetLoweringOpt
&TLO
) const {
496 assert(Op
.getNumOperands() == 2 &&
497 "ShrinkDemandedOp only supports binary operators!");
498 assert(Op
.getNode()->getNumValues() == 1 &&
499 "ShrinkDemandedOp only supports nodes with one result!");
501 SelectionDAG
&DAG
= TLO
.DAG
;
504 // Early return, as this function cannot handle vector types.
505 if (Op
.getValueType().isVector())
508 // Don't do this if the node has another user, which may require the
510 if (!Op
.getNode()->hasOneUse())
513 // Search for the smallest integer type with free casts to and from
514 // Op's type. For expedience, just check power-of-2 integer types.
515 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
516 unsigned DemandedSize
= Demanded
.getActiveBits();
517 unsigned SmallVTBits
= DemandedSize
;
518 if (!isPowerOf2_32(SmallVTBits
))
519 SmallVTBits
= NextPowerOf2(SmallVTBits
);
520 for (; SmallVTBits
< BitWidth
; SmallVTBits
= NextPowerOf2(SmallVTBits
)) {
521 EVT SmallVT
= EVT::getIntegerVT(*DAG
.getContext(), SmallVTBits
);
522 if (TLI
.isTruncateFree(Op
.getValueType(), SmallVT
) &&
523 TLI
.isZExtFree(SmallVT
, Op
.getValueType())) {
524 // We found a type with free casts.
525 SDValue X
= DAG
.getNode(
526 Op
.getOpcode(), dl
, SmallVT
,
527 DAG
.getNode(ISD::TRUNCATE
, dl
, SmallVT
, Op
.getOperand(0)),
528 DAG
.getNode(ISD::TRUNCATE
, dl
, SmallVT
, Op
.getOperand(1)));
529 assert(DemandedSize
<= SmallVTBits
&& "Narrowed below demanded bits?");
530 SDValue Z
= DAG
.getNode(ISD::ANY_EXTEND
, dl
, Op
.getValueType(), X
);
531 return TLO
.CombineTo(Op
, Z
);
537 bool TargetLowering::SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedBits
,
538 DAGCombinerInfo
&DCI
) const {
539 SelectionDAG
&DAG
= DCI
.DAG
;
540 TargetLoweringOpt
TLO(DAG
, !DCI
.isBeforeLegalize(),
541 !DCI
.isBeforeLegalizeOps());
544 bool Simplified
= SimplifyDemandedBits(Op
, DemandedBits
, Known
, TLO
);
546 DCI
.AddToWorklist(Op
.getNode());
547 DCI
.CommitTargetLoweringOpt(TLO
);
552 bool TargetLowering::SimplifyDemandedBits(SDValue Op
, const APInt
&DemandedBits
,
554 TargetLoweringOpt
&TLO
,
556 bool AssumeSingleUse
) const {
557 EVT VT
= Op
.getValueType();
558 APInt DemandedElts
= VT
.isVector()
559 ? APInt::getAllOnesValue(VT
.getVectorNumElements())
561 return SimplifyDemandedBits(Op
, DemandedBits
, DemandedElts
, Known
, TLO
, Depth
,
565 // TODO: Can we merge SelectionDAG::GetDemandedBits into this?
566 // TODO: Under what circumstances can we create nodes? Constant folding?
567 SDValue
TargetLowering::SimplifyMultipleUseDemandedBits(
568 SDValue Op
, const APInt
&DemandedBits
, const APInt
&DemandedElts
,
569 SelectionDAG
&DAG
, unsigned Depth
) const {
570 // Limit search depth.
578 // Not demanding any bits/elts from Op.
579 if (DemandedBits
== 0 || DemandedElts
== 0)
580 return DAG
.getUNDEF(Op
.getValueType());
582 unsigned NumElts
= DemandedElts
.getBitWidth();
583 KnownBits LHSKnown
, RHSKnown
;
584 switch (Op
.getOpcode()) {
586 SDValue Src
= peekThroughBitcasts(Op
.getOperand(0));
587 EVT SrcVT
= Src
.getValueType();
588 EVT DstVT
= Op
.getValueType();
589 unsigned NumSrcEltBits
= SrcVT
.getScalarSizeInBits();
590 unsigned NumDstEltBits
= DstVT
.getScalarSizeInBits();
592 if (NumSrcEltBits
== NumDstEltBits
)
593 if (SDValue V
= SimplifyMultipleUseDemandedBits(
594 Src
, DemandedBits
, DemandedElts
, DAG
, Depth
+ 1))
595 return DAG
.getBitcast(DstVT
, V
);
597 // TODO - bigendian once we have test coverage.
598 if (SrcVT
.isVector() && (NumDstEltBits
% NumSrcEltBits
) == 0 &&
599 DAG
.getDataLayout().isLittleEndian()) {
600 unsigned Scale
= NumDstEltBits
/ NumSrcEltBits
;
601 unsigned NumSrcElts
= SrcVT
.getVectorNumElements();
602 APInt DemandedSrcBits
= APInt::getNullValue(NumSrcEltBits
);
603 APInt DemandedSrcElts
= APInt::getNullValue(NumSrcElts
);
604 for (unsigned i
= 0; i
!= Scale
; ++i
) {
605 unsigned Offset
= i
* NumSrcEltBits
;
606 APInt Sub
= DemandedBits
.extractBits(NumSrcEltBits
, Offset
);
607 if (!Sub
.isNullValue()) {
608 DemandedSrcBits
|= Sub
;
609 for (unsigned j
= 0; j
!= NumElts
; ++j
)
611 DemandedSrcElts
.setBit((j
* Scale
) + i
);
615 if (SDValue V
= SimplifyMultipleUseDemandedBits(
616 Src
, DemandedSrcBits
, DemandedSrcElts
, DAG
, Depth
+ 1))
617 return DAG
.getBitcast(DstVT
, V
);
620 // TODO - bigendian once we have test coverage.
621 if ((NumSrcEltBits
% NumDstEltBits
) == 0 &&
622 DAG
.getDataLayout().isLittleEndian()) {
623 unsigned Scale
= NumSrcEltBits
/ NumDstEltBits
;
624 unsigned NumSrcElts
= SrcVT
.isVector() ? SrcVT
.getVectorNumElements() : 1;
625 APInt DemandedSrcBits
= APInt::getNullValue(NumSrcEltBits
);
626 APInt DemandedSrcElts
= APInt::getNullValue(NumSrcElts
);
627 for (unsigned i
= 0; i
!= NumElts
; ++i
)
628 if (DemandedElts
[i
]) {
629 unsigned Offset
= (i
% Scale
) * NumDstEltBits
;
630 DemandedSrcBits
.insertBits(DemandedBits
, Offset
);
631 DemandedSrcElts
.setBit(i
/ Scale
);
634 if (SDValue V
= SimplifyMultipleUseDemandedBits(
635 Src
, DemandedSrcBits
, DemandedSrcElts
, DAG
, Depth
+ 1))
636 return DAG
.getBitcast(DstVT
, V
);
642 LHSKnown
= DAG
.computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
643 RHSKnown
= DAG
.computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
645 // If all of the demanded bits are known 1 on one side, return the other.
646 // These bits cannot contribute to the result of the 'and' in this
648 if (DemandedBits
.isSubsetOf(LHSKnown
.Zero
| RHSKnown
.One
))
649 return Op
.getOperand(0);
650 if (DemandedBits
.isSubsetOf(RHSKnown
.Zero
| LHSKnown
.One
))
651 return Op
.getOperand(1);
655 LHSKnown
= DAG
.computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
656 RHSKnown
= DAG
.computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
658 // If all of the demanded bits are known zero on one side, return the
659 // other. These bits cannot contribute to the result of the 'or' in this
661 if (DemandedBits
.isSubsetOf(LHSKnown
.One
| RHSKnown
.Zero
))
662 return Op
.getOperand(0);
663 if (DemandedBits
.isSubsetOf(RHSKnown
.One
| LHSKnown
.Zero
))
664 return Op
.getOperand(1);
668 LHSKnown
= DAG
.computeKnownBits(Op
.getOperand(0), DemandedElts
, Depth
+ 1);
669 RHSKnown
= DAG
.computeKnownBits(Op
.getOperand(1), DemandedElts
, Depth
+ 1);
671 // If all of the demanded bits are known zero on one side, return the
673 if (DemandedBits
.isSubsetOf(RHSKnown
.Zero
))
674 return Op
.getOperand(0);
675 if (DemandedBits
.isSubsetOf(LHSKnown
.Zero
))
676 return Op
.getOperand(1);
679 case ISD::SIGN_EXTEND_INREG
: {
680 // If none of the extended bits are demanded, eliminate the sextinreg.
681 EVT ExVT
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT();
682 if (DemandedBits
.getActiveBits() <= ExVT
.getScalarSizeInBits())
683 return Op
.getOperand(0);
686 case ISD::INSERT_VECTOR_ELT
: {
687 // If we don't demand the inserted element, return the base vector.
688 SDValue Vec
= Op
.getOperand(0);
689 auto *CIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
690 EVT VecVT
= Vec
.getValueType();
691 if (CIdx
&& CIdx
->getAPIntValue().ult(VecVT
.getVectorNumElements()) &&
692 !DemandedElts
[CIdx
->getZExtValue()])
696 case ISD::VECTOR_SHUFFLE
: {
697 ArrayRef
<int> ShuffleMask
= cast
<ShuffleVectorSDNode
>(Op
)->getMask();
699 // If all the demanded elts are from one operand and are inline,
700 // then we can use the operand directly.
701 bool AllUndef
= true, IdentityLHS
= true, IdentityRHS
= true;
702 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
703 int M
= ShuffleMask
[i
];
704 if (M
< 0 || !DemandedElts
[i
])
707 IdentityLHS
&= (M
== (int)i
);
708 IdentityRHS
&= ((M
- NumElts
) == i
);
712 return DAG
.getUNDEF(Op
.getValueType());
714 return Op
.getOperand(0);
716 return Op
.getOperand(1);
720 if (Op
.getOpcode() >= ISD::BUILTIN_OP_END
)
721 if (SDValue V
= SimplifyMultipleUseDemandedBitsForTargetNode(
722 Op
, DemandedBits
, DemandedElts
, DAG
, Depth
))
729 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
730 /// result of Op are ever used downstream. If we can use this information to
731 /// simplify Op, create a new simplified DAG node and return true, returning the
732 /// original and new nodes in Old and New. Otherwise, analyze the expression and
733 /// return a mask of Known bits for the expression (used to simplify the
734 /// caller). The Known bits may only be accurate for those bits in the
735 /// OriginalDemandedBits and OriginalDemandedElts.
736 bool TargetLowering::SimplifyDemandedBits(
737 SDValue Op
, const APInt
&OriginalDemandedBits
,
738 const APInt
&OriginalDemandedElts
, KnownBits
&Known
, TargetLoweringOpt
&TLO
,
739 unsigned Depth
, bool AssumeSingleUse
) const {
740 unsigned BitWidth
= OriginalDemandedBits
.getBitWidth();
741 assert(Op
.getScalarValueSizeInBits() == BitWidth
&&
742 "Mask size mismatches value type size!");
744 unsigned NumElts
= OriginalDemandedElts
.getBitWidth();
745 assert((!Op
.getValueType().isVector() ||
746 NumElts
== Op
.getValueType().getVectorNumElements()) &&
747 "Unexpected vector size");
749 APInt DemandedBits
= OriginalDemandedBits
;
750 APInt DemandedElts
= OriginalDemandedElts
;
752 auto &DL
= TLO
.DAG
.getDataLayout();
754 // Don't know anything.
755 Known
= KnownBits(BitWidth
);
761 if (Op
.getOpcode() == ISD::Constant
) {
762 // We know all of the bits for a constant!
763 Known
.One
= cast
<ConstantSDNode
>(Op
)->getAPIntValue();
764 Known
.Zero
= ~Known
.One
;
768 // Other users may use these bits.
769 EVT VT
= Op
.getValueType();
770 if (!Op
.getNode()->hasOneUse() && !AssumeSingleUse
) {
772 // If not at the root, Just compute the Known bits to
773 // simplify things downstream.
774 Known
= TLO
.DAG
.computeKnownBits(Op
, DemandedElts
, Depth
);
777 // If this is the root being simplified, allow it to have multiple uses,
778 // just set the DemandedBits/Elts to all bits.
779 DemandedBits
= APInt::getAllOnesValue(BitWidth
);
780 DemandedElts
= APInt::getAllOnesValue(NumElts
);
781 } else if (OriginalDemandedBits
== 0 || OriginalDemandedElts
== 0) {
782 // Not demanding any bits/elts from Op.
783 return TLO
.CombineTo(Op
, TLO
.DAG
.getUNDEF(VT
));
784 } else if (Depth
>= 6) { // Limit search depth.
788 KnownBits Known2
, KnownOut
;
789 switch (Op
.getOpcode()) {
790 case ISD::SCALAR_TO_VECTOR
: {
791 if (!DemandedElts
[0])
792 return TLO
.CombineTo(Op
, TLO
.DAG
.getUNDEF(VT
));
795 SDValue Src
= Op
.getOperand(0);
796 unsigned SrcBitWidth
= Src
.getScalarValueSizeInBits();
797 APInt SrcDemandedBits
= DemandedBits
.zextOrSelf(SrcBitWidth
);
798 if (SimplifyDemandedBits(Src
, SrcDemandedBits
, SrcKnown
, TLO
, Depth
+ 1))
800 Known
= SrcKnown
.zextOrTrunc(BitWidth
, false);
803 case ISD::BUILD_VECTOR
:
804 // Collect the known bits that are shared by every demanded element.
805 // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
806 Known
= TLO
.DAG
.computeKnownBits(Op
, DemandedElts
, Depth
);
807 return false; // Don't fall through, will infinitely loop.
809 LoadSDNode
*LD
= cast
<LoadSDNode
>(Op
);
810 if (getTargetConstantFromLoad(LD
)) {
811 Known
= TLO
.DAG
.computeKnownBits(Op
, DemandedElts
, Depth
);
812 return false; // Don't fall through, will infinitely loop.
816 case ISD::INSERT_VECTOR_ELT
: {
817 SDValue Vec
= Op
.getOperand(0);
818 SDValue Scl
= Op
.getOperand(1);
819 auto *CIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
820 EVT VecVT
= Vec
.getValueType();
822 // If index isn't constant, assume we need all vector elements AND the
824 APInt
DemandedVecElts(DemandedElts
);
825 if (CIdx
&& CIdx
->getAPIntValue().ult(VecVT
.getVectorNumElements())) {
826 unsigned Idx
= CIdx
->getZExtValue();
827 DemandedVecElts
.clearBit(Idx
);
829 // Inserted element is not required.
830 if (!DemandedElts
[Idx
])
831 return TLO
.CombineTo(Op
, Vec
);
835 unsigned NumSclBits
= Scl
.getScalarValueSizeInBits();
836 APInt DemandedSclBits
= DemandedBits
.zextOrTrunc(NumSclBits
);
837 if (SimplifyDemandedBits(Scl
, DemandedSclBits
, KnownScl
, TLO
, Depth
+ 1))
840 Known
= KnownScl
.zextOrTrunc(BitWidth
, false);
843 if (SimplifyDemandedBits(Vec
, DemandedBits
, DemandedVecElts
, KnownVec
, TLO
,
847 if (!!DemandedVecElts
) {
848 Known
.One
&= KnownVec
.One
;
849 Known
.Zero
&= KnownVec
.Zero
;
854 case ISD::INSERT_SUBVECTOR
: {
855 SDValue Base
= Op
.getOperand(0);
856 SDValue Sub
= Op
.getOperand(1);
857 EVT SubVT
= Sub
.getValueType();
858 unsigned NumSubElts
= SubVT
.getVectorNumElements();
860 // If index isn't constant, assume we need the original demanded base
861 // elements and ALL the inserted subvector elements.
862 APInt BaseElts
= DemandedElts
;
863 APInt SubElts
= APInt::getAllOnesValue(NumSubElts
);
864 if (isa
<ConstantSDNode
>(Op
.getOperand(2))) {
865 const APInt
&Idx
= Op
.getConstantOperandAPInt(2);
866 if (Idx
.ule(NumElts
- NumSubElts
)) {
867 unsigned SubIdx
= Idx
.getZExtValue();
868 SubElts
= DemandedElts
.extractBits(NumSubElts
, SubIdx
);
869 BaseElts
.insertBits(APInt::getNullValue(NumSubElts
), SubIdx
);
873 KnownBits KnownSub
, KnownBase
;
874 if (SimplifyDemandedBits(Sub
, DemandedBits
, SubElts
, KnownSub
, TLO
,
877 if (SimplifyDemandedBits(Base
, DemandedBits
, BaseElts
, KnownBase
, TLO
,
881 Known
.Zero
.setAllBits();
882 Known
.One
.setAllBits();
884 Known
.One
&= KnownSub
.One
;
885 Known
.Zero
&= KnownSub
.Zero
;
888 Known
.One
&= KnownBase
.One
;
889 Known
.Zero
&= KnownBase
.Zero
;
893 case ISD::CONCAT_VECTORS
: {
894 Known
.Zero
.setAllBits();
895 Known
.One
.setAllBits();
896 EVT SubVT
= Op
.getOperand(0).getValueType();
897 unsigned NumSubVecs
= Op
.getNumOperands();
898 unsigned NumSubElts
= SubVT
.getVectorNumElements();
899 for (unsigned i
= 0; i
!= NumSubVecs
; ++i
) {
900 APInt DemandedSubElts
=
901 DemandedElts
.extractBits(NumSubElts
, i
* NumSubElts
);
902 if (SimplifyDemandedBits(Op
.getOperand(i
), DemandedBits
, DemandedSubElts
,
903 Known2
, TLO
, Depth
+ 1))
905 // Known bits are shared by every demanded subvector element.
906 if (!!DemandedSubElts
) {
907 Known
.One
&= Known2
.One
;
908 Known
.Zero
&= Known2
.Zero
;
913 case ISD::VECTOR_SHUFFLE
: {
914 ArrayRef
<int> ShuffleMask
= cast
<ShuffleVectorSDNode
>(Op
)->getMask();
916 // Collect demanded elements from shuffle operands..
917 APInt
DemandedLHS(NumElts
, 0);
918 APInt
DemandedRHS(NumElts
, 0);
919 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
920 if (!DemandedElts
[i
])
922 int M
= ShuffleMask
[i
];
924 // For UNDEF elements, we don't know anything about the common state of
925 // the shuffle result.
926 DemandedLHS
.clearAllBits();
927 DemandedRHS
.clearAllBits();
930 assert(0 <= M
&& M
< (int)(2 * NumElts
) && "Shuffle index out of range");
931 if (M
< (int)NumElts
)
932 DemandedLHS
.setBit(M
);
934 DemandedRHS
.setBit(M
- NumElts
);
937 if (!!DemandedLHS
|| !!DemandedRHS
) {
938 SDValue Op0
= Op
.getOperand(0);
939 SDValue Op1
= Op
.getOperand(1);
941 Known
.Zero
.setAllBits();
942 Known
.One
.setAllBits();
944 if (SimplifyDemandedBits(Op0
, DemandedBits
, DemandedLHS
, Known2
, TLO
,
947 Known
.One
&= Known2
.One
;
948 Known
.Zero
&= Known2
.Zero
;
951 if (SimplifyDemandedBits(Op1
, DemandedBits
, DemandedRHS
, Known2
, TLO
,
954 Known
.One
&= Known2
.One
;
955 Known
.Zero
&= Known2
.Zero
;
958 // Attempt to avoid multi-use ops if we don't need anything from them.
959 SDValue DemandedOp0
= SimplifyMultipleUseDemandedBits(
960 Op0
, DemandedBits
, DemandedLHS
, TLO
.DAG
, Depth
+ 1);
961 SDValue DemandedOp1
= SimplifyMultipleUseDemandedBits(
962 Op1
, DemandedBits
, DemandedRHS
, TLO
.DAG
, Depth
+ 1);
963 if (DemandedOp0
|| DemandedOp1
) {
964 Op0
= DemandedOp0
? DemandedOp0
: Op0
;
965 Op1
= DemandedOp1
? DemandedOp1
: Op1
;
966 SDValue NewOp
= TLO
.DAG
.getVectorShuffle(VT
, dl
, Op0
, Op1
, ShuffleMask
);
967 return TLO
.CombineTo(Op
, NewOp
);
973 SDValue Op0
= Op
.getOperand(0);
974 SDValue Op1
= Op
.getOperand(1);
976 // If the RHS is a constant, check to see if the LHS would be zero without
977 // using the bits from the RHS. Below, we use knowledge about the RHS to
978 // simplify the LHS, here we're using information from the LHS to simplify
980 if (ConstantSDNode
*RHSC
= isConstOrConstSplat(Op1
)) {
981 // Do not increment Depth here; that can cause an infinite loop.
982 KnownBits LHSKnown
= TLO
.DAG
.computeKnownBits(Op0
, DemandedElts
, Depth
);
983 // If the LHS already has zeros where RHSC does, this 'and' is dead.
984 if ((LHSKnown
.Zero
& DemandedBits
) ==
985 (~RHSC
->getAPIntValue() & DemandedBits
))
986 return TLO
.CombineTo(Op
, Op0
);
988 // If any of the set bits in the RHS are known zero on the LHS, shrink
990 if (ShrinkDemandedConstant(Op
, ~LHSKnown
.Zero
& DemandedBits
, TLO
))
993 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
994 // constant, but if this 'and' is only clearing bits that were just set by
995 // the xor, then this 'and' can be eliminated by shrinking the mask of
996 // the xor. For example, for a 32-bit X:
997 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
998 if (isBitwiseNot(Op0
) && Op0
.hasOneUse() &&
999 LHSKnown
.One
== ~RHSC
->getAPIntValue()) {
1000 SDValue Xor
= TLO
.DAG
.getNode(ISD::XOR
, dl
, VT
, Op0
.getOperand(0), Op1
);
1001 return TLO
.CombineTo(Op
, Xor
);
1005 if (SimplifyDemandedBits(Op1
, DemandedBits
, DemandedElts
, Known
, TLO
,
1008 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1009 if (SimplifyDemandedBits(Op0
, ~Known
.Zero
& DemandedBits
, DemandedElts
,
1010 Known2
, TLO
, Depth
+ 1))
1012 assert(!Known2
.hasConflict() && "Bits known to be one AND zero?");
1014 // Attempt to avoid multi-use ops if we don't need anything from them.
1015 if (!DemandedBits
.isAllOnesValue() || !DemandedElts
.isAllOnesValue()) {
1016 SDValue DemandedOp0
= SimplifyMultipleUseDemandedBits(
1017 Op0
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1018 SDValue DemandedOp1
= SimplifyMultipleUseDemandedBits(
1019 Op1
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1020 if (DemandedOp0
|| DemandedOp1
) {
1021 Op0
= DemandedOp0
? DemandedOp0
: Op0
;
1022 Op1
= DemandedOp1
? DemandedOp1
: Op1
;
1023 SDValue NewOp
= TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Op1
);
1024 return TLO
.CombineTo(Op
, NewOp
);
1028 // If all of the demanded bits are known one on one side, return the other.
1029 // These bits cannot contribute to the result of the 'and'.
1030 if (DemandedBits
.isSubsetOf(Known2
.Zero
| Known
.One
))
1031 return TLO
.CombineTo(Op
, Op0
);
1032 if (DemandedBits
.isSubsetOf(Known
.Zero
| Known2
.One
))
1033 return TLO
.CombineTo(Op
, Op1
);
1034 // If all of the demanded bits in the inputs are known zeros, return zero.
1035 if (DemandedBits
.isSubsetOf(Known
.Zero
| Known2
.Zero
))
1036 return TLO
.CombineTo(Op
, TLO
.DAG
.getConstant(0, dl
, VT
));
1037 // If the RHS is a constant, see if we can simplify it.
1038 if (ShrinkDemandedConstant(Op
, ~Known2
.Zero
& DemandedBits
, TLO
))
1040 // If the operation can be done in a smaller type, do so.
1041 if (ShrinkDemandedOp(Op
, BitWidth
, DemandedBits
, TLO
))
1044 // Output known-1 bits are only known if set in both the LHS & RHS.
1045 Known
.One
&= Known2
.One
;
1046 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1047 Known
.Zero
|= Known2
.Zero
;
1051 SDValue Op0
= Op
.getOperand(0);
1052 SDValue Op1
= Op
.getOperand(1);
1054 if (SimplifyDemandedBits(Op1
, DemandedBits
, DemandedElts
, Known
, TLO
,
1057 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1058 if (SimplifyDemandedBits(Op0
, ~Known
.One
& DemandedBits
, DemandedElts
,
1059 Known2
, TLO
, Depth
+ 1))
1061 assert(!Known2
.hasConflict() && "Bits known to be one AND zero?");
1063 // Attempt to avoid multi-use ops if we don't need anything from them.
1064 if (!DemandedBits
.isAllOnesValue() || !DemandedElts
.isAllOnesValue()) {
1065 SDValue DemandedOp0
= SimplifyMultipleUseDemandedBits(
1066 Op0
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1067 SDValue DemandedOp1
= SimplifyMultipleUseDemandedBits(
1068 Op1
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1069 if (DemandedOp0
|| DemandedOp1
) {
1070 Op0
= DemandedOp0
? DemandedOp0
: Op0
;
1071 Op1
= DemandedOp1
? DemandedOp1
: Op1
;
1072 SDValue NewOp
= TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Op1
);
1073 return TLO
.CombineTo(Op
, NewOp
);
1077 // If all of the demanded bits are known zero on one side, return the other.
1078 // These bits cannot contribute to the result of the 'or'.
1079 if (DemandedBits
.isSubsetOf(Known2
.One
| Known
.Zero
))
1080 return TLO
.CombineTo(Op
, Op0
);
1081 if (DemandedBits
.isSubsetOf(Known
.One
| Known2
.Zero
))
1082 return TLO
.CombineTo(Op
, Op1
);
1083 // If the RHS is a constant, see if we can simplify it.
1084 if (ShrinkDemandedConstant(Op
, DemandedBits
, TLO
))
1086 // If the operation can be done in a smaller type, do so.
1087 if (ShrinkDemandedOp(Op
, BitWidth
, DemandedBits
, TLO
))
1090 // Output known-0 bits are only known if clear in both the LHS & RHS.
1091 Known
.Zero
&= Known2
.Zero
;
1092 // Output known-1 are known to be set if set in either the LHS | RHS.
1093 Known
.One
|= Known2
.One
;
1097 SDValue Op0
= Op
.getOperand(0);
1098 SDValue Op1
= Op
.getOperand(1);
1100 if (SimplifyDemandedBits(Op1
, DemandedBits
, DemandedElts
, Known
, TLO
,
1103 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1104 if (SimplifyDemandedBits(Op0
, DemandedBits
, DemandedElts
, Known2
, TLO
,
1107 assert(!Known2
.hasConflict() && "Bits known to be one AND zero?");
1109 // Attempt to avoid multi-use ops if we don't need anything from them.
1110 if (!DemandedBits
.isAllOnesValue() || !DemandedElts
.isAllOnesValue()) {
1111 SDValue DemandedOp0
= SimplifyMultipleUseDemandedBits(
1112 Op0
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1113 SDValue DemandedOp1
= SimplifyMultipleUseDemandedBits(
1114 Op1
, DemandedBits
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1115 if (DemandedOp0
|| DemandedOp1
) {
1116 Op0
= DemandedOp0
? DemandedOp0
: Op0
;
1117 Op1
= DemandedOp1
? DemandedOp1
: Op1
;
1118 SDValue NewOp
= TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Op1
);
1119 return TLO
.CombineTo(Op
, NewOp
);
1123 // If all of the demanded bits are known zero on one side, return the other.
1124 // These bits cannot contribute to the result of the 'xor'.
1125 if (DemandedBits
.isSubsetOf(Known
.Zero
))
1126 return TLO
.CombineTo(Op
, Op0
);
1127 if (DemandedBits
.isSubsetOf(Known2
.Zero
))
1128 return TLO
.CombineTo(Op
, Op1
);
1129 // If the operation can be done in a smaller type, do so.
1130 if (ShrinkDemandedOp(Op
, BitWidth
, DemandedBits
, TLO
))
1133 // If all of the unknown bits are known to be zero on one side or the other
1134 // (but not both) turn this into an *inclusive* or.
1135 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1136 if (DemandedBits
.isSubsetOf(Known
.Zero
| Known2
.Zero
))
1137 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(ISD::OR
, dl
, VT
, Op0
, Op1
));
1139 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1140 KnownOut
.Zero
= (Known
.Zero
& Known2
.Zero
) | (Known
.One
& Known2
.One
);
1141 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1142 KnownOut
.One
= (Known
.Zero
& Known2
.One
) | (Known
.One
& Known2
.Zero
);
1144 if (ConstantSDNode
*C
= isConstOrConstSplat(Op1
)) {
1145 // If one side is a constant, and all of the known set bits on the other
1146 // side are also set in the constant, turn this into an AND, as we know
1147 // the bits will be cleared.
1148 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1149 // NB: it is okay if more bits are known than are requested
1150 if (C
->getAPIntValue() == Known2
.One
) {
1152 TLO
.DAG
.getConstant(~C
->getAPIntValue() & DemandedBits
, dl
, VT
);
1153 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(ISD::AND
, dl
, VT
, Op0
, ANDC
));
1156 // If the RHS is a constant, see if we can change it. Don't alter a -1
1157 // constant because that's a 'not' op, and that is better for combining
1159 if (!C
->isAllOnesValue()) {
1160 if (DemandedBits
.isSubsetOf(C
->getAPIntValue())) {
1161 // We're flipping all demanded bits. Flip the undemanded bits too.
1162 SDValue New
= TLO
.DAG
.getNOT(dl
, Op0
, VT
);
1163 return TLO
.CombineTo(Op
, New
);
1165 // If we can't turn this into a 'not', try to shrink the constant.
1166 if (ShrinkDemandedConstant(Op
, DemandedBits
, TLO
))
1171 Known
= std::move(KnownOut
);
1175 if (SimplifyDemandedBits(Op
.getOperand(2), DemandedBits
, Known
, TLO
,
1178 if (SimplifyDemandedBits(Op
.getOperand(1), DemandedBits
, Known2
, TLO
,
1181 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1182 assert(!Known2
.hasConflict() && "Bits known to be one AND zero?");
1184 // If the operands are constants, see if we can simplify them.
1185 if (ShrinkDemandedConstant(Op
, DemandedBits
, TLO
))
1188 // Only known if known in both the LHS and RHS.
1189 Known
.One
&= Known2
.One
;
1190 Known
.Zero
&= Known2
.Zero
;
1192 case ISD::SELECT_CC
:
1193 if (SimplifyDemandedBits(Op
.getOperand(3), DemandedBits
, Known
, TLO
,
1196 if (SimplifyDemandedBits(Op
.getOperand(2), DemandedBits
, Known2
, TLO
,
1199 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1200 assert(!Known2
.hasConflict() && "Bits known to be one AND zero?");
1202 // If the operands are constants, see if we can simplify them.
1203 if (ShrinkDemandedConstant(Op
, DemandedBits
, TLO
))
1206 // Only known if known in both the LHS and RHS.
1207 Known
.One
&= Known2
.One
;
1208 Known
.Zero
&= Known2
.Zero
;
1211 SDValue Op0
= Op
.getOperand(0);
1212 SDValue Op1
= Op
.getOperand(1);
1213 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
1214 // If (1) we only need the sign-bit, (2) the setcc operands are the same
1215 // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1216 // -1, we may be able to bypass the setcc.
1217 if (DemandedBits
.isSignMask() &&
1218 Op0
.getScalarValueSizeInBits() == BitWidth
&&
1219 getBooleanContents(VT
) ==
1220 BooleanContent::ZeroOrNegativeOneBooleanContent
) {
1221 // If we're testing X < 0, then this compare isn't needed - just use X!
1222 // FIXME: We're limiting to integer types here, but this should also work
1223 // if we don't care about FP signed-zero. The use of SETLT with FP means
1224 // that we don't care about NaNs.
1225 if (CC
== ISD::SETLT
&& Op1
.getValueType().isInteger() &&
1226 (isNullConstant(Op1
) || ISD::isBuildVectorAllZeros(Op1
.getNode())))
1227 return TLO
.CombineTo(Op
, Op0
);
1229 // TODO: Should we check for other forms of sign-bit comparisons?
1230 // Examples: X <= -1, X >= 0
1232 if (getBooleanContents(Op0
.getValueType()) ==
1233 TargetLowering::ZeroOrOneBooleanContent
&&
1235 Known
.Zero
.setBitsFrom(1);
1239 SDValue Op0
= Op
.getOperand(0);
1240 SDValue Op1
= Op
.getOperand(1);
1242 if (ConstantSDNode
*SA
= isConstOrConstSplat(Op1
, DemandedElts
)) {
1243 // If the shift count is an invalid immediate, don't do anything.
1244 if (SA
->getAPIntValue().uge(BitWidth
))
1247 unsigned ShAmt
= SA
->getZExtValue();
1249 return TLO
.CombineTo(Op
, Op0
);
1251 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1252 // single shift. We can do this if the bottom bits (which are shifted
1253 // out) are never demanded.
1254 // TODO - support non-uniform vector amounts.
1255 if (Op0
.getOpcode() == ISD::SRL
) {
1256 if ((DemandedBits
& APInt::getLowBitsSet(BitWidth
, ShAmt
)) == 0) {
1257 if (ConstantSDNode
*SA2
=
1258 isConstOrConstSplat(Op0
.getOperand(1), DemandedElts
)) {
1259 if (SA2
->getAPIntValue().ult(BitWidth
)) {
1260 unsigned C1
= SA2
->getZExtValue();
1261 unsigned Opc
= ISD::SHL
;
1262 int Diff
= ShAmt
- C1
;
1268 SDValue NewSA
= TLO
.DAG
.getConstant(Diff
, dl
, Op1
.getValueType());
1269 return TLO
.CombineTo(
1270 Op
, TLO
.DAG
.getNode(Opc
, dl
, VT
, Op0
.getOperand(0), NewSA
));
1276 if (SimplifyDemandedBits(Op0
, DemandedBits
.lshr(ShAmt
), DemandedElts
,
1277 Known
, TLO
, Depth
+ 1))
1280 // Try shrinking the operation as long as the shift amount will still be
1282 if ((ShAmt
< DemandedBits
.getActiveBits()) &&
1283 ShrinkDemandedOp(Op
, BitWidth
, DemandedBits
, TLO
))
1286 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1287 // are not demanded. This will likely allow the anyext to be folded away.
1288 if (Op0
.getOpcode() == ISD::ANY_EXTEND
) {
1289 SDValue InnerOp
= Op0
.getOperand(0);
1290 EVT InnerVT
= InnerOp
.getValueType();
1291 unsigned InnerBits
= InnerVT
.getScalarSizeInBits();
1292 if (ShAmt
< InnerBits
&& DemandedBits
.getActiveBits() <= InnerBits
&&
1293 isTypeDesirableForOp(ISD::SHL
, InnerVT
)) {
1294 EVT ShTy
= getShiftAmountTy(InnerVT
, DL
);
1295 if (!APInt(BitWidth
, ShAmt
).isIntN(ShTy
.getSizeInBits()))
1298 TLO
.DAG
.getNode(ISD::SHL
, dl
, InnerVT
, InnerOp
,
1299 TLO
.DAG
.getConstant(ShAmt
, dl
, ShTy
));
1300 return TLO
.CombineTo(
1301 Op
, TLO
.DAG
.getNode(ISD::ANY_EXTEND
, dl
, VT
, NarrowShl
));
1303 // Repeat the SHL optimization above in cases where an extension
1304 // intervenes: (shl (anyext (shr x, c1)), c2) to
1305 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
1306 // aren't demanded (as above) and that the shifted upper c1 bits of
1307 // x aren't demanded.
1308 if (Op0
.hasOneUse() && InnerOp
.getOpcode() == ISD::SRL
&&
1309 InnerOp
.hasOneUse()) {
1310 if (ConstantSDNode
*SA2
=
1311 isConstOrConstSplat(InnerOp
.getOperand(1))) {
1312 unsigned InnerShAmt
= SA2
->getLimitedValue(InnerBits
);
1313 if (InnerShAmt
< ShAmt
&& InnerShAmt
< InnerBits
&&
1314 DemandedBits
.getActiveBits() <=
1315 (InnerBits
- InnerShAmt
+ ShAmt
) &&
1316 DemandedBits
.countTrailingZeros() >= ShAmt
) {
1317 SDValue NewSA
= TLO
.DAG
.getConstant(ShAmt
- InnerShAmt
, dl
,
1318 Op1
.getValueType());
1319 SDValue NewExt
= TLO
.DAG
.getNode(ISD::ANY_EXTEND
, dl
, VT
,
1320 InnerOp
.getOperand(0));
1321 return TLO
.CombineTo(
1322 Op
, TLO
.DAG
.getNode(ISD::SHL
, dl
, VT
, NewExt
, NewSA
));
1328 Known
.Zero
<<= ShAmt
;
1329 Known
.One
<<= ShAmt
;
1330 // low bits known zero.
1331 Known
.Zero
.setLowBits(ShAmt
);
1336 SDValue Op0
= Op
.getOperand(0);
1337 SDValue Op1
= Op
.getOperand(1);
1339 if (ConstantSDNode
*SA
= isConstOrConstSplat(Op1
, DemandedElts
)) {
1340 // If the shift count is an invalid immediate, don't do anything.
1341 if (SA
->getAPIntValue().uge(BitWidth
))
1344 unsigned ShAmt
= SA
->getZExtValue();
1346 return TLO
.CombineTo(Op
, Op0
);
1348 EVT ShiftVT
= Op1
.getValueType();
1349 APInt InDemandedMask
= (DemandedBits
<< ShAmt
);
1351 // If the shift is exact, then it does demand the low bits (and knows that
1353 if (Op
->getFlags().hasExact())
1354 InDemandedMask
.setLowBits(ShAmt
);
1356 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1357 // single shift. We can do this if the top bits (which are shifted out)
1358 // are never demanded.
1359 // TODO - support non-uniform vector amounts.
1360 if (Op0
.getOpcode() == ISD::SHL
) {
1361 if (ConstantSDNode
*SA2
=
1362 isConstOrConstSplat(Op0
.getOperand(1), DemandedElts
)) {
1363 if ((DemandedBits
& APInt::getHighBitsSet(BitWidth
, ShAmt
)) == 0) {
1364 if (SA2
->getAPIntValue().ult(BitWidth
)) {
1365 unsigned C1
= SA2
->getZExtValue();
1366 unsigned Opc
= ISD::SRL
;
1367 int Diff
= ShAmt
- C1
;
1373 SDValue NewSA
= TLO
.DAG
.getConstant(Diff
, dl
, ShiftVT
);
1374 return TLO
.CombineTo(
1375 Op
, TLO
.DAG
.getNode(Opc
, dl
, VT
, Op0
.getOperand(0), NewSA
));
1381 // Compute the new bits that are at the top now.
1382 if (SimplifyDemandedBits(Op0
, InDemandedMask
, DemandedElts
, Known
, TLO
,
1385 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1386 Known
.Zero
.lshrInPlace(ShAmt
);
1387 Known
.One
.lshrInPlace(ShAmt
);
1389 Known
.Zero
.setHighBits(ShAmt
); // High bits known zero.
1394 SDValue Op0
= Op
.getOperand(0);
1395 SDValue Op1
= Op
.getOperand(1);
1397 // If this is an arithmetic shift right and only the low-bit is set, we can
1398 // always convert this into a logical shr, even if the shift amount is
1399 // variable. The low bit of the shift cannot be an input sign bit unless
1400 // the shift amount is >= the size of the datatype, which is undefined.
1401 if (DemandedBits
.isOneValue())
1402 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(ISD::SRL
, dl
, VT
, Op0
, Op1
));
1404 if (ConstantSDNode
*SA
= isConstOrConstSplat(Op1
, DemandedElts
)) {
1405 // If the shift count is an invalid immediate, don't do anything.
1406 if (SA
->getAPIntValue().uge(BitWidth
))
1409 unsigned ShAmt
= SA
->getZExtValue();
1411 return TLO
.CombineTo(Op
, Op0
);
1413 APInt InDemandedMask
= (DemandedBits
<< ShAmt
);
1415 // If the shift is exact, then it does demand the low bits (and knows that
1417 if (Op
->getFlags().hasExact())
1418 InDemandedMask
.setLowBits(ShAmt
);
1420 // If any of the demanded bits are produced by the sign extension, we also
1421 // demand the input sign bit.
1422 if (DemandedBits
.countLeadingZeros() < ShAmt
)
1423 InDemandedMask
.setSignBit();
1425 if (SimplifyDemandedBits(Op0
, InDemandedMask
, DemandedElts
, Known
, TLO
,
1428 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1429 Known
.Zero
.lshrInPlace(ShAmt
);
1430 Known
.One
.lshrInPlace(ShAmt
);
1432 // If the input sign bit is known to be zero, or if none of the top bits
1433 // are demanded, turn this into an unsigned shift right.
1434 if (Known
.Zero
[BitWidth
- ShAmt
- 1] ||
1435 DemandedBits
.countLeadingZeros() >= ShAmt
) {
1437 Flags
.setExact(Op
->getFlags().hasExact());
1438 return TLO
.CombineTo(
1439 Op
, TLO
.DAG
.getNode(ISD::SRL
, dl
, VT
, Op0
, Op1
, Flags
));
1442 int Log2
= DemandedBits
.exactLogBase2();
1444 // The bit must come from the sign.
1446 TLO
.DAG
.getConstant(BitWidth
- 1 - Log2
, dl
, Op1
.getValueType());
1447 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(ISD::SRL
, dl
, VT
, Op0
, NewSA
));
1450 if (Known
.One
[BitWidth
- ShAmt
- 1])
1451 // New bits are known one.
1452 Known
.One
.setHighBits(ShAmt
);
1458 SDValue Op0
= Op
.getOperand(0);
1459 SDValue Op1
= Op
.getOperand(1);
1460 SDValue Op2
= Op
.getOperand(2);
1461 bool IsFSHL
= (Op
.getOpcode() == ISD::FSHL
);
1463 if (ConstantSDNode
*SA
= isConstOrConstSplat(Op2
, DemandedElts
)) {
1464 unsigned Amt
= SA
->getAPIntValue().urem(BitWidth
);
1466 // For fshl, 0-shift returns the 1st arg.
1467 // For fshr, 0-shift returns the 2nd arg.
1469 if (SimplifyDemandedBits(IsFSHL
? Op0
: Op1
, DemandedBits
, DemandedElts
,
1470 Known
, TLO
, Depth
+ 1))
1475 // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1476 // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1477 APInt Demanded0
= DemandedBits
.lshr(IsFSHL
? Amt
: (BitWidth
- Amt
));
1478 APInt Demanded1
= DemandedBits
<< (IsFSHL
? (BitWidth
- Amt
) : Amt
);
1479 if (SimplifyDemandedBits(Op0
, Demanded0
, DemandedElts
, Known2
, TLO
,
1482 if (SimplifyDemandedBits(Op1
, Demanded1
, DemandedElts
, Known
, TLO
,
1486 Known2
.One
<<= (IsFSHL
? Amt
: (BitWidth
- Amt
));
1487 Known2
.Zero
<<= (IsFSHL
? Amt
: (BitWidth
- Amt
));
1488 Known
.One
.lshrInPlace(IsFSHL
? (BitWidth
- Amt
) : Amt
);
1489 Known
.Zero
.lshrInPlace(IsFSHL
? (BitWidth
- Amt
) : Amt
);
1490 Known
.One
|= Known2
.One
;
1491 Known
.Zero
|= Known2
.Zero
;
1495 case ISD::BITREVERSE
: {
1496 SDValue Src
= Op
.getOperand(0);
1497 APInt DemandedSrcBits
= DemandedBits
.reverseBits();
1498 if (SimplifyDemandedBits(Src
, DemandedSrcBits
, DemandedElts
, Known2
, TLO
,
1501 Known
.One
= Known2
.One
.reverseBits();
1502 Known
.Zero
= Known2
.Zero
.reverseBits();
1505 case ISD::SIGN_EXTEND_INREG
: {
1506 SDValue Op0
= Op
.getOperand(0);
1507 EVT ExVT
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT();
1508 unsigned ExVTBits
= ExVT
.getScalarSizeInBits();
1510 // If we only care about the highest bit, don't bother shifting right.
1511 if (DemandedBits
.isSignMask()) {
1512 unsigned NumSignBits
= TLO
.DAG
.ComputeNumSignBits(Op0
);
1513 bool AlreadySignExtended
= NumSignBits
>= BitWidth
- ExVTBits
+ 1;
1514 // However if the input is already sign extended we expect the sign
1515 // extension to be dropped altogether later and do not simplify.
1516 if (!AlreadySignExtended
) {
1517 // Compute the correct shift amount type, which must be getShiftAmountTy
1518 // for scalar types after legalization.
1519 EVT ShiftAmtTy
= VT
;
1520 if (TLO
.LegalTypes() && !ShiftAmtTy
.isVector())
1521 ShiftAmtTy
= getShiftAmountTy(ShiftAmtTy
, DL
);
1524 TLO
.DAG
.getConstant(BitWidth
- ExVTBits
, dl
, ShiftAmtTy
);
1525 return TLO
.CombineTo(Op
,
1526 TLO
.DAG
.getNode(ISD::SHL
, dl
, VT
, Op0
, ShiftAmt
));
1530 // If none of the extended bits are demanded, eliminate the sextinreg.
1531 if (DemandedBits
.getActiveBits() <= ExVTBits
)
1532 return TLO
.CombineTo(Op
, Op0
);
1534 APInt InputDemandedBits
= DemandedBits
.getLoBits(ExVTBits
);
1536 // Since the sign extended bits are demanded, we know that the sign
1538 InputDemandedBits
.setBit(ExVTBits
- 1);
1540 if (SimplifyDemandedBits(Op0
, InputDemandedBits
, Known
, TLO
, Depth
+ 1))
1542 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1544 // If the sign bit of the input is known set or clear, then we know the
1545 // top bits of the result.
1547 // If the input sign bit is known zero, convert this into a zero extension.
1548 if (Known
.Zero
[ExVTBits
- 1])
1549 return TLO
.CombineTo(
1550 Op
, TLO
.DAG
.getZeroExtendInReg(Op0
, dl
, ExVT
.getScalarType()));
1552 APInt Mask
= APInt::getLowBitsSet(BitWidth
, ExVTBits
);
1553 if (Known
.One
[ExVTBits
- 1]) { // Input sign bit known set
1554 Known
.One
.setBitsFrom(ExVTBits
);
1556 } else { // Input sign bit unknown
1562 case ISD::BUILD_PAIR
: {
1563 EVT HalfVT
= Op
.getOperand(0).getValueType();
1564 unsigned HalfBitWidth
= HalfVT
.getScalarSizeInBits();
1566 APInt MaskLo
= DemandedBits
.getLoBits(HalfBitWidth
).trunc(HalfBitWidth
);
1567 APInt MaskHi
= DemandedBits
.getHiBits(HalfBitWidth
).trunc(HalfBitWidth
);
1569 KnownBits KnownLo
, KnownHi
;
1571 if (SimplifyDemandedBits(Op
.getOperand(0), MaskLo
, KnownLo
, TLO
, Depth
+ 1))
1574 if (SimplifyDemandedBits(Op
.getOperand(1), MaskHi
, KnownHi
, TLO
, Depth
+ 1))
1577 Known
.Zero
= KnownLo
.Zero
.zext(BitWidth
) |
1578 KnownHi
.Zero
.zext(BitWidth
).shl(HalfBitWidth
);
1580 Known
.One
= KnownLo
.One
.zext(BitWidth
) |
1581 KnownHi
.One
.zext(BitWidth
).shl(HalfBitWidth
);
1584 case ISD::ZERO_EXTEND
:
1585 case ISD::ZERO_EXTEND_VECTOR_INREG
: {
1586 SDValue Src
= Op
.getOperand(0);
1587 EVT SrcVT
= Src
.getValueType();
1588 unsigned InBits
= SrcVT
.getScalarSizeInBits();
1589 unsigned InElts
= SrcVT
.isVector() ? SrcVT
.getVectorNumElements() : 1;
1590 bool IsVecInReg
= Op
.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG
;
1592 // If none of the top bits are demanded, convert this into an any_extend.
1593 if (DemandedBits
.getActiveBits() <= InBits
) {
1594 // If we only need the non-extended bits of the bottom element
1595 // then we can just bitcast to the result.
1596 if (IsVecInReg
&& DemandedElts
== 1 &&
1597 VT
.getSizeInBits() == SrcVT
.getSizeInBits() &&
1598 TLO
.DAG
.getDataLayout().isLittleEndian())
1599 return TLO
.CombineTo(Op
, TLO
.DAG
.getBitcast(VT
, Src
));
1602 IsVecInReg
? ISD::ANY_EXTEND_VECTOR_INREG
: ISD::ANY_EXTEND
;
1603 if (!TLO
.LegalOperations() || isOperationLegal(Opc
, VT
))
1604 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(Opc
, dl
, VT
, Src
));
1607 APInt InDemandedBits
= DemandedBits
.trunc(InBits
);
1608 APInt InDemandedElts
= DemandedElts
.zextOrSelf(InElts
);
1609 if (SimplifyDemandedBits(Src
, InDemandedBits
, InDemandedElts
, Known
, TLO
,
1612 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1613 assert(Known
.getBitWidth() == InBits
&& "Src width has changed?");
1614 Known
= Known
.zext(BitWidth
, true /* ExtendedBitsAreKnownZero */);
1617 case ISD::SIGN_EXTEND
:
1618 case ISD::SIGN_EXTEND_VECTOR_INREG
: {
1619 SDValue Src
= Op
.getOperand(0);
1620 EVT SrcVT
= Src
.getValueType();
1621 unsigned InBits
= SrcVT
.getScalarSizeInBits();
1622 unsigned InElts
= SrcVT
.isVector() ? SrcVT
.getVectorNumElements() : 1;
1623 bool IsVecInReg
= Op
.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG
;
1625 // If none of the top bits are demanded, convert this into an any_extend.
1626 if (DemandedBits
.getActiveBits() <= InBits
) {
1627 // If we only need the non-extended bits of the bottom element
1628 // then we can just bitcast to the result.
1629 if (IsVecInReg
&& DemandedElts
== 1 &&
1630 VT
.getSizeInBits() == SrcVT
.getSizeInBits() &&
1631 TLO
.DAG
.getDataLayout().isLittleEndian())
1632 return TLO
.CombineTo(Op
, TLO
.DAG
.getBitcast(VT
, Src
));
1635 IsVecInReg
? ISD::ANY_EXTEND_VECTOR_INREG
: ISD::ANY_EXTEND
;
1636 if (!TLO
.LegalOperations() || isOperationLegal(Opc
, VT
))
1637 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(Opc
, dl
, VT
, Src
));
1640 APInt InDemandedBits
= DemandedBits
.trunc(InBits
);
1641 APInt InDemandedElts
= DemandedElts
.zextOrSelf(InElts
);
1643 // Since some of the sign extended bits are demanded, we know that the sign
1645 InDemandedBits
.setBit(InBits
- 1);
1647 if (SimplifyDemandedBits(Src
, InDemandedBits
, InDemandedElts
, Known
, TLO
,
1650 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1651 assert(Known
.getBitWidth() == InBits
&& "Src width has changed?");
1653 // If the sign bit is known one, the top bits match.
1654 Known
= Known
.sext(BitWidth
);
1656 // If the sign bit is known zero, convert this to a zero extend.
1657 if (Known
.isNonNegative()) {
1659 IsVecInReg
? ISD::ZERO_EXTEND_VECTOR_INREG
: ISD::ZERO_EXTEND
;
1660 if (!TLO
.LegalOperations() || isOperationLegal(Opc
, VT
))
1661 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(Opc
, dl
, VT
, Src
));
1665 case ISD::ANY_EXTEND
:
1666 case ISD::ANY_EXTEND_VECTOR_INREG
: {
1667 SDValue Src
= Op
.getOperand(0);
1668 EVT SrcVT
= Src
.getValueType();
1669 unsigned InBits
= SrcVT
.getScalarSizeInBits();
1670 unsigned InElts
= SrcVT
.isVector() ? SrcVT
.getVectorNumElements() : 1;
1671 bool IsVecInReg
= Op
.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG
;
1673 // If we only need the bottom element then we can just bitcast.
1674 // TODO: Handle ANY_EXTEND?
1675 if (IsVecInReg
&& DemandedElts
== 1 &&
1676 VT
.getSizeInBits() == SrcVT
.getSizeInBits() &&
1677 TLO
.DAG
.getDataLayout().isLittleEndian())
1678 return TLO
.CombineTo(Op
, TLO
.DAG
.getBitcast(VT
, Src
));
1680 APInt InDemandedBits
= DemandedBits
.trunc(InBits
);
1681 APInt InDemandedElts
= DemandedElts
.zextOrSelf(InElts
);
1682 if (SimplifyDemandedBits(Src
, InDemandedBits
, InDemandedElts
, Known
, TLO
,
1685 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1686 assert(Known
.getBitWidth() == InBits
&& "Src width has changed?");
1687 Known
= Known
.zext(BitWidth
, false /* => any extend */);
1690 case ISD::TRUNCATE
: {
1691 SDValue Src
= Op
.getOperand(0);
1693 // Simplify the input, using demanded bit information, and compute the known
1694 // zero/one bits live out.
1695 unsigned OperandBitWidth
= Src
.getScalarValueSizeInBits();
1696 APInt TruncMask
= DemandedBits
.zext(OperandBitWidth
);
1697 if (SimplifyDemandedBits(Src
, TruncMask
, Known
, TLO
, Depth
+ 1))
1699 Known
= Known
.trunc(BitWidth
);
1701 // Attempt to avoid multi-use ops if we don't need anything from them.
1702 if (SDValue NewSrc
= SimplifyMultipleUseDemandedBits(
1703 Src
, TruncMask
, DemandedElts
, TLO
.DAG
, Depth
+ 1))
1704 return TLO
.CombineTo(Op
, TLO
.DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, NewSrc
));
1706 // If the input is only used by this truncate, see if we can shrink it based
1707 // on the known demanded bits.
1708 if (Src
.getNode()->hasOneUse()) {
1709 switch (Src
.getOpcode()) {
1713 // Shrink SRL by a constant if none of the high bits shifted in are
1715 if (TLO
.LegalTypes() && !isTypeDesirableForOp(ISD::SRL
, VT
))
1716 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1720 auto *ShAmt
= dyn_cast
<ConstantSDNode
>(Src
.getOperand(1));
1721 if (!ShAmt
|| ShAmt
->getAPIntValue().uge(BitWidth
))
1724 SDValue Shift
= Src
.getOperand(1);
1725 uint64_t ShVal
= ShAmt
->getZExtValue();
1727 if (TLO
.LegalTypes())
1728 Shift
= TLO
.DAG
.getConstant(ShVal
, dl
, getShiftAmountTy(VT
, DL
));
1731 APInt::getHighBitsSet(OperandBitWidth
, OperandBitWidth
- BitWidth
);
1732 HighBits
.lshrInPlace(ShVal
);
1733 HighBits
= HighBits
.trunc(BitWidth
);
1735 if (!(HighBits
& DemandedBits
)) {
1736 // None of the shifted in bits are needed. Add a truncate of the
1737 // shift input, then shift it.
1739 TLO
.DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, Src
.getOperand(0));
1740 return TLO
.CombineTo(
1741 Op
, TLO
.DAG
.getNode(ISD::SRL
, dl
, VT
, NewTrunc
, Shift
));
1747 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1750 case ISD::AssertZext
: {
1751 // AssertZext demands all of the high bits, plus any of the low bits
1752 // demanded by its users.
1753 EVT ZVT
= cast
<VTSDNode
>(Op
.getOperand(1))->getVT();
1754 APInt InMask
= APInt::getLowBitsSet(BitWidth
, ZVT
.getSizeInBits());
1755 if (SimplifyDemandedBits(Op
.getOperand(0), ~InMask
| DemandedBits
, Known
,
1758 assert(!Known
.hasConflict() && "Bits known to be one AND zero?");
1760 Known
.Zero
|= ~InMask
;
1763 case ISD::EXTRACT_VECTOR_ELT
: {
1764 SDValue Src
= Op
.getOperand(0);
1765 SDValue Idx
= Op
.getOperand(1);
1766 unsigned NumSrcElts
= Src
.getValueType().getVectorNumElements();
1767 unsigned EltBitWidth
= Src
.getScalarValueSizeInBits();
1769 // Demand the bits from every vector element without a constant index.
1770 APInt DemandedSrcElts
= APInt::getAllOnesValue(NumSrcElts
);
1771 if (auto *CIdx
= dyn_cast
<ConstantSDNode
>(Idx
))
1772 if (CIdx
->getAPIntValue().ult(NumSrcElts
))
1773 DemandedSrcElts
= APInt::getOneBitSet(NumSrcElts
, CIdx
->getZExtValue());
1775 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
1776 // anything about the extended bits.
1777 APInt DemandedSrcBits
= DemandedBits
;
1778 if (BitWidth
> EltBitWidth
)
1779 DemandedSrcBits
= DemandedSrcBits
.trunc(EltBitWidth
);
1781 if (SimplifyDemandedBits(Src
, DemandedSrcBits
, DemandedSrcElts
, Known2
, TLO
,
1786 if (BitWidth
> EltBitWidth
)
1787 Known
= Known
.zext(BitWidth
, false /* => any extend */);
1790 case ISD::BITCAST
: {
1791 SDValue Src
= Op
.getOperand(0);
1792 EVT SrcVT
= Src
.getValueType();
1793 unsigned NumSrcEltBits
= SrcVT
.getScalarSizeInBits();
1795 // If this is an FP->Int bitcast and if the sign bit is the only
1796 // thing demanded, turn this into a FGETSIGN.
1797 if (!TLO
.LegalOperations() && !VT
.isVector() && !SrcVT
.isVector() &&
1798 DemandedBits
== APInt::getSignMask(Op
.getValueSizeInBits()) &&
1799 SrcVT
.isFloatingPoint()) {
1800 bool OpVTLegal
= isOperationLegalOrCustom(ISD::FGETSIGN
, VT
);
1801 bool i32Legal
= isOperationLegalOrCustom(ISD::FGETSIGN
, MVT::i32
);
1802 if ((OpVTLegal
|| i32Legal
) && VT
.isSimple() && SrcVT
!= MVT::f16
&&
1803 SrcVT
!= MVT::f128
) {
1804 // Cannot eliminate/lower SHL for f128 yet.
1805 EVT Ty
= OpVTLegal
? VT
: MVT::i32
;
1806 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1807 // place. We expect the SHL to be eliminated by other optimizations.
1808 SDValue Sign
= TLO
.DAG
.getNode(ISD::FGETSIGN
, dl
, Ty
, Src
);
1809 unsigned OpVTSizeInBits
= Op
.getValueSizeInBits();
1810 if (!OpVTLegal
&& OpVTSizeInBits
> 32)
1811 Sign
= TLO
.DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, Sign
);
1812 unsigned ShVal
= Op
.getValueSizeInBits() - 1;
1813 SDValue ShAmt
= TLO
.DAG
.getConstant(ShVal
, dl
, VT
);
1814 return TLO
.CombineTo(Op
,
1815 TLO
.DAG
.getNode(ISD::SHL
, dl
, VT
, Sign
, ShAmt
));
1819 // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
1820 // Demand the elt/bit if any of the original elts/bits are demanded.
1821 // TODO - bigendian once we have test coverage.
1822 if (SrcVT
.isVector() && (BitWidth
% NumSrcEltBits
) == 0 &&
1823 TLO
.DAG
.getDataLayout().isLittleEndian()) {
1824 unsigned Scale
= BitWidth
/ NumSrcEltBits
;
1825 unsigned NumSrcElts
= SrcVT
.getVectorNumElements();
1826 APInt DemandedSrcBits
= APInt::getNullValue(NumSrcEltBits
);
1827 APInt DemandedSrcElts
= APInt::getNullValue(NumSrcElts
);
1828 for (unsigned i
= 0; i
!= Scale
; ++i
) {
1829 unsigned Offset
= i
* NumSrcEltBits
;
1830 APInt Sub
= DemandedBits
.extractBits(NumSrcEltBits
, Offset
);
1831 if (!Sub
.isNullValue()) {
1832 DemandedSrcBits
|= Sub
;
1833 for (unsigned j
= 0; j
!= NumElts
; ++j
)
1834 if (DemandedElts
[j
])
1835 DemandedSrcElts
.setBit((j
* Scale
) + i
);
1839 APInt KnownSrcUndef
, KnownSrcZero
;
1840 if (SimplifyDemandedVectorElts(Src
, DemandedSrcElts
, KnownSrcUndef
,
1841 KnownSrcZero
, TLO
, Depth
+ 1))
1844 KnownBits KnownSrcBits
;
1845 if (SimplifyDemandedBits(Src
, DemandedSrcBits
, DemandedSrcElts
,
1846 KnownSrcBits
, TLO
, Depth
+ 1))
1848 } else if ((NumSrcEltBits
% BitWidth
) == 0 &&
1849 TLO
.DAG
.getDataLayout().isLittleEndian()) {
1850 unsigned Scale
= NumSrcEltBits
/ BitWidth
;
1851 unsigned NumSrcElts
= SrcVT
.isVector() ? SrcVT
.getVectorNumElements() : 1;
1852 APInt DemandedSrcBits
= APInt::getNullValue(NumSrcEltBits
);
1853 APInt DemandedSrcElts
= APInt::getNullValue(NumSrcElts
);
1854 for (unsigned i
= 0; i
!= NumElts
; ++i
)
1855 if (DemandedElts
[i
]) {
1856 unsigned Offset
= (i
% Scale
) * BitWidth
;
1857 DemandedSrcBits
.insertBits(DemandedBits
, Offset
);
1858 DemandedSrcElts
.setBit(i
/ Scale
);
1861 if (SrcVT
.isVector()) {
1862 APInt KnownSrcUndef
, KnownSrcZero
;
1863 if (SimplifyDemandedVectorElts(Src
, DemandedSrcElts
, KnownSrcUndef
,
1864 KnownSrcZero
, TLO
, Depth
+ 1))
1868 KnownBits KnownSrcBits
;
1869 if (SimplifyDemandedBits(Src
, DemandedSrcBits
, DemandedSrcElts
,
1870 KnownSrcBits
, TLO
, Depth
+ 1))
1874 // If this is a bitcast, let computeKnownBits handle it. Only do this on a
1875 // recursive call where Known may be useful to the caller.
1877 Known
= TLO
.DAG
.computeKnownBits(Op
, DemandedElts
, Depth
);
1885 // Add, Sub, and Mul don't demand any bits in positions beyond that
1886 // of the highest bit demanded of them.
1887 SDValue Op0
= Op
.getOperand(0), Op1
= Op
.getOperand(1);
1888 SDNodeFlags Flags
= Op
.getNode()->getFlags();
1889 unsigned DemandedBitsLZ
= DemandedBits
.countLeadingZeros();
1890 APInt LoMask
= APInt::getLowBitsSet(BitWidth
, BitWidth
- DemandedBitsLZ
);
1891 if (SimplifyDemandedBits(Op0
, LoMask
, DemandedElts
, Known2
, TLO
,
1893 SimplifyDemandedBits(Op1
, LoMask
, DemandedElts
, Known2
, TLO
,
1895 // See if the operation should be performed at a smaller bit width.
1896 ShrinkDemandedOp(Op
, BitWidth
, DemandedBits
, TLO
)) {
1897 if (Flags
.hasNoSignedWrap() || Flags
.hasNoUnsignedWrap()) {
1898 // Disable the nsw and nuw flags. We can no longer guarantee that we
1899 // won't wrap after simplification.
1900 Flags
.setNoSignedWrap(false);
1901 Flags
.setNoUnsignedWrap(false);
1903 TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Op1
, Flags
);
1904 return TLO
.CombineTo(Op
, NewOp
);
1909 // Attempt to avoid multi-use ops if we don't need anything from them.
1910 if (!LoMask
.isAllOnesValue() || !DemandedElts
.isAllOnesValue()) {
1911 SDValue DemandedOp0
= SimplifyMultipleUseDemandedBits(
1912 Op0
, LoMask
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1913 SDValue DemandedOp1
= SimplifyMultipleUseDemandedBits(
1914 Op1
, LoMask
, DemandedElts
, TLO
.DAG
, Depth
+ 1);
1915 if (DemandedOp0
|| DemandedOp1
) {
1916 Flags
.setNoSignedWrap(false);
1917 Flags
.setNoUnsignedWrap(false);
1918 Op0
= DemandedOp0
? DemandedOp0
: Op0
;
1919 Op1
= DemandedOp1
? DemandedOp1
: Op1
;
1921 TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Op1
, Flags
);
1922 return TLO
.CombineTo(Op
, NewOp
);
1926 // If we have a constant operand, we may be able to turn it into -1 if we
1927 // do not demand the high bits. This can make the constant smaller to
1928 // encode, allow more general folding, or match specialized instruction
1929 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
1930 // is probably not useful (and could be detrimental).
1931 ConstantSDNode
*C
= isConstOrConstSplat(Op1
);
1932 APInt HighMask
= APInt::getHighBitsSet(BitWidth
, DemandedBitsLZ
);
1933 if (C
&& !C
->isAllOnesValue() && !C
->isOne() &&
1934 (C
->getAPIntValue() | HighMask
).isAllOnesValue()) {
1935 SDValue Neg1
= TLO
.DAG
.getAllOnesConstant(dl
, VT
);
1936 // We can't guarantee that the new math op doesn't wrap, so explicitly
1937 // clear those flags to prevent folding with a potential existing node
1938 // that has those flags set.
1940 Flags
.setNoSignedWrap(false);
1941 Flags
.setNoUnsignedWrap(false);
1942 SDValue NewOp
= TLO
.DAG
.getNode(Op
.getOpcode(), dl
, VT
, Op0
, Neg1
, Flags
);
1943 return TLO
.CombineTo(Op
, NewOp
);
1949 if (Op
.getOpcode() >= ISD::BUILTIN_OP_END
) {
1950 if (SimplifyDemandedBitsForTargetNode(Op
, DemandedBits
, DemandedElts
,
1956 // Just use computeKnownBits to compute output bits.
1957 Known
= TLO
.DAG
.computeKnownBits(Op
, DemandedElts
, Depth
);
1961 // If we know the value of all of the demanded bits, return this as a
1963 if (DemandedBits
.isSubsetOf(Known
.Zero
| Known
.One
)) {
1964 // Avoid folding to a constant if any OpaqueConstant is involved.
1965 const SDNode
*N
= Op
.getNode();
1966 for (SDNodeIterator I
= SDNodeIterator::begin(N
),
1967 E
= SDNodeIterator::end(N
);
1970 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
))
1974 // TODO: Handle float bits as well.
1976 return TLO
.CombineTo(Op
, TLO
.DAG
.getConstant(Known
.One
, dl
, VT
));
1982 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op
,
1983 const APInt
&DemandedElts
,
1986 DAGCombinerInfo
&DCI
) const {
1987 SelectionDAG
&DAG
= DCI
.DAG
;
1988 TargetLoweringOpt
TLO(DAG
, !DCI
.isBeforeLegalize(),
1989 !DCI
.isBeforeLegalizeOps());
1992 SimplifyDemandedVectorElts(Op
, DemandedElts
, KnownUndef
, KnownZero
, TLO
);
1994 DCI
.AddToWorklist(Op
.getNode());
1995 DCI
.CommitTargetLoweringOpt(TLO
);
2001 /// Given a vector binary operation and known undefined elements for each input
2002 /// operand, compute whether each element of the output is undefined.
2003 static APInt
getKnownUndefForVectorBinop(SDValue BO
, SelectionDAG
&DAG
,
2004 const APInt
&UndefOp0
,
2005 const APInt
&UndefOp1
) {
2006 EVT VT
= BO
.getValueType();
2007 assert(DAG
.getTargetLoweringInfo().isBinOp(BO
.getOpcode()) && VT
.isVector() &&
2008 "Vector binop only");
2010 EVT EltVT
= VT
.getVectorElementType();
2011 unsigned NumElts
= VT
.getVectorNumElements();
2012 assert(UndefOp0
.getBitWidth() == NumElts
&&
2013 UndefOp1
.getBitWidth() == NumElts
&& "Bad type for undef analysis");
2015 auto getUndefOrConstantElt
= [&](SDValue V
, unsigned Index
,
2016 const APInt
&UndefVals
) {
2017 if (UndefVals
[Index
])
2018 return DAG
.getUNDEF(EltVT
);
2020 if (auto *BV
= dyn_cast
<BuildVectorSDNode
>(V
)) {
2021 // Try hard to make sure that the getNode() call is not creating temporary
2022 // nodes. Ignore opaque integers because they do not constant fold.
2023 SDValue Elt
= BV
->getOperand(Index
);
2024 auto *C
= dyn_cast
<ConstantSDNode
>(Elt
);
2025 if (isa
<ConstantFPSDNode
>(Elt
) || Elt
.isUndef() || (C
&& !C
->isOpaque()))
2032 APInt KnownUndef
= APInt::getNullValue(NumElts
);
2033 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2034 // If both inputs for this element are either constant or undef and match
2035 // the element type, compute the constant/undef result for this element of
2037 // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2038 // not handle FP constants. The code within getNode() should be refactored
2039 // to avoid the danger of creating a bogus temporary node here.
2040 SDValue C0
= getUndefOrConstantElt(BO
.getOperand(0), i
, UndefOp0
);
2041 SDValue C1
= getUndefOrConstantElt(BO
.getOperand(1), i
, UndefOp1
);
2042 if (C0
&& C1
&& C0
.getValueType() == EltVT
&& C1
.getValueType() == EltVT
)
2043 if (DAG
.getNode(BO
.getOpcode(), SDLoc(BO
), EltVT
, C0
, C1
).isUndef())
2044 KnownUndef
.setBit(i
);
2049 bool TargetLowering::SimplifyDemandedVectorElts(
2050 SDValue Op
, const APInt
&OriginalDemandedElts
, APInt
&KnownUndef
,
2051 APInt
&KnownZero
, TargetLoweringOpt
&TLO
, unsigned Depth
,
2052 bool AssumeSingleUse
) const {
2053 EVT VT
= Op
.getValueType();
2054 APInt DemandedElts
= OriginalDemandedElts
;
2055 unsigned NumElts
= DemandedElts
.getBitWidth();
2056 assert(VT
.isVector() && "Expected vector op");
2057 assert(VT
.getVectorNumElements() == NumElts
&&
2058 "Mask size mismatches value type element count!");
2060 KnownUndef
= KnownZero
= APInt::getNullValue(NumElts
);
2064 KnownUndef
.setAllBits();
2068 // If Op has other users, assume that all elements are needed.
2069 if (!Op
.getNode()->hasOneUse() && !AssumeSingleUse
)
2070 DemandedElts
.setAllBits();
2072 // Not demanding any elements from Op.
2073 if (DemandedElts
== 0) {
2074 KnownUndef
.setAllBits();
2075 return TLO
.CombineTo(Op
, TLO
.DAG
.getUNDEF(VT
));
2078 // Limit search depth.
2083 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
2085 switch (Op
.getOpcode()) {
2086 case ISD::SCALAR_TO_VECTOR
: {
2087 if (!DemandedElts
[0]) {
2088 KnownUndef
.setAllBits();
2089 return TLO
.CombineTo(Op
, TLO
.DAG
.getUNDEF(VT
));
2091 KnownUndef
.setHighBits(NumElts
- 1);
2094 case ISD::BITCAST
: {
2095 SDValue Src
= Op
.getOperand(0);
2096 EVT SrcVT
= Src
.getValueType();
2098 // We only handle vectors here.
2099 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
2100 if (!SrcVT
.isVector())
2103 // Fast handling of 'identity' bitcasts.
2104 unsigned NumSrcElts
= SrcVT
.getVectorNumElements();
2105 if (NumSrcElts
== NumElts
)
2106 return SimplifyDemandedVectorElts(Src
, DemandedElts
, KnownUndef
,
2107 KnownZero
, TLO
, Depth
+ 1);
2109 APInt SrcZero
, SrcUndef
;
2110 APInt SrcDemandedElts
= APInt::getNullValue(NumSrcElts
);
2112 // Bitcast from 'large element' src vector to 'small element' vector, we
2113 // must demand a source element if any DemandedElt maps to it.
2114 if ((NumElts
% NumSrcElts
) == 0) {
2115 unsigned Scale
= NumElts
/ NumSrcElts
;
2116 for (unsigned i
= 0; i
!= NumElts
; ++i
)
2117 if (DemandedElts
[i
])
2118 SrcDemandedElts
.setBit(i
/ Scale
);
2120 if (SimplifyDemandedVectorElts(Src
, SrcDemandedElts
, SrcUndef
, SrcZero
,
2124 // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2125 // of the large element.
2126 // TODO - bigendian once we have test coverage.
2127 if (TLO
.DAG
.getDataLayout().isLittleEndian()) {
2128 unsigned SrcEltSizeInBits
= SrcVT
.getScalarSizeInBits();
2129 APInt SrcDemandedBits
= APInt::getNullValue(SrcEltSizeInBits
);
2130 for (unsigned i
= 0; i
!= NumElts
; ++i
)
2131 if (DemandedElts
[i
]) {
2132 unsigned Ofs
= (i
% Scale
) * EltSizeInBits
;
2133 SrcDemandedBits
.setBits(Ofs
, Ofs
+ EltSizeInBits
);
2137 if (SimplifyDemandedBits(Src
, SrcDemandedBits
, Known
, TLO
, Depth
+ 1))
2141 // If the src element is zero/undef then all the output elements will be -
2142 // only demanded elements are guaranteed to be correct.
2143 for (unsigned i
= 0; i
!= NumSrcElts
; ++i
) {
2144 if (SrcDemandedElts
[i
]) {
2146 KnownZero
.setBits(i
* Scale
, (i
+ 1) * Scale
);
2148 KnownUndef
.setBits(i
* Scale
, (i
+ 1) * Scale
);
2153 // Bitcast from 'small element' src vector to 'large element' vector, we
2154 // demand all smaller source elements covered by the larger demanded element
2156 if ((NumSrcElts
% NumElts
) == 0) {
2157 unsigned Scale
= NumSrcElts
/ NumElts
;
2158 for (unsigned i
= 0; i
!= NumElts
; ++i
)
2159 if (DemandedElts
[i
])
2160 SrcDemandedElts
.setBits(i
* Scale
, (i
+ 1) * Scale
);
2162 if (SimplifyDemandedVectorElts(Src
, SrcDemandedElts
, SrcUndef
, SrcZero
,
2166 // If all the src elements covering an output element are zero/undef, then
2167 // the output element will be as well, assuming it was demanded.
2168 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2169 if (DemandedElts
[i
]) {
2170 if (SrcZero
.extractBits(Scale
, i
* Scale
).isAllOnesValue())
2171 KnownZero
.setBit(i
);
2172 if (SrcUndef
.extractBits(Scale
, i
* Scale
).isAllOnesValue())
2173 KnownUndef
.setBit(i
);
2179 case ISD::BUILD_VECTOR
: {
2180 // Check all elements and simplify any unused elements with UNDEF.
2181 if (!DemandedElts
.isAllOnesValue()) {
2182 // Don't simplify BROADCASTS.
2183 if (llvm::any_of(Op
->op_values(),
2184 [&](SDValue Elt
) { return Op
.getOperand(0) != Elt
; })) {
2185 SmallVector
<SDValue
, 32> Ops(Op
->op_begin(), Op
->op_end());
2186 bool Updated
= false;
2187 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2188 if (!DemandedElts
[i
] && !Ops
[i
].isUndef()) {
2189 Ops
[i
] = TLO
.DAG
.getUNDEF(Ops
[0].getValueType());
2190 KnownUndef
.setBit(i
);
2195 return TLO
.CombineTo(Op
, TLO
.DAG
.getBuildVector(VT
, DL
, Ops
));
2198 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2199 SDValue SrcOp
= Op
.getOperand(i
);
2200 if (SrcOp
.isUndef()) {
2201 KnownUndef
.setBit(i
);
2202 } else if (EltSizeInBits
== SrcOp
.getScalarValueSizeInBits() &&
2203 (isNullConstant(SrcOp
) || isNullFPConstant(SrcOp
))) {
2204 KnownZero
.setBit(i
);
2209 case ISD::CONCAT_VECTORS
: {
2210 EVT SubVT
= Op
.getOperand(0).getValueType();
2211 unsigned NumSubVecs
= Op
.getNumOperands();
2212 unsigned NumSubElts
= SubVT
.getVectorNumElements();
2213 for (unsigned i
= 0; i
!= NumSubVecs
; ++i
) {
2214 SDValue SubOp
= Op
.getOperand(i
);
2215 APInt SubElts
= DemandedElts
.extractBits(NumSubElts
, i
* NumSubElts
);
2216 APInt SubUndef
, SubZero
;
2217 if (SimplifyDemandedVectorElts(SubOp
, SubElts
, SubUndef
, SubZero
, TLO
,
2220 KnownUndef
.insertBits(SubUndef
, i
* NumSubElts
);
2221 KnownZero
.insertBits(SubZero
, i
* NumSubElts
);
2225 case ISD::INSERT_SUBVECTOR
: {
2226 if (!isa
<ConstantSDNode
>(Op
.getOperand(2)))
2228 SDValue Base
= Op
.getOperand(0);
2229 SDValue Sub
= Op
.getOperand(1);
2230 EVT SubVT
= Sub
.getValueType();
2231 unsigned NumSubElts
= SubVT
.getVectorNumElements();
2232 const APInt
&Idx
= Op
.getConstantOperandAPInt(2);
2233 if (Idx
.ugt(NumElts
- NumSubElts
))
2235 unsigned SubIdx
= Idx
.getZExtValue();
2236 APInt SubElts
= DemandedElts
.extractBits(NumSubElts
, SubIdx
);
2237 APInt SubUndef
, SubZero
;
2238 if (SimplifyDemandedVectorElts(Sub
, SubElts
, SubUndef
, SubZero
, TLO
,
2241 APInt BaseElts
= DemandedElts
;
2242 BaseElts
.insertBits(APInt::getNullValue(NumSubElts
), SubIdx
);
2244 // If none of the base operand elements are demanded, replace it with undef.
2245 if (!BaseElts
&& !Base
.isUndef())
2246 return TLO
.CombineTo(Op
,
2247 TLO
.DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, VT
,
2248 TLO
.DAG
.getUNDEF(VT
),
2252 if (SimplifyDemandedVectorElts(Base
, BaseElts
, KnownUndef
, KnownZero
, TLO
,
2255 KnownUndef
.insertBits(SubUndef
, SubIdx
);
2256 KnownZero
.insertBits(SubZero
, SubIdx
);
2259 case ISD::EXTRACT_SUBVECTOR
: {
2260 SDValue Src
= Op
.getOperand(0);
2261 ConstantSDNode
*SubIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
2262 unsigned NumSrcElts
= Src
.getValueType().getVectorNumElements();
2263 if (SubIdx
&& SubIdx
->getAPIntValue().ule(NumSrcElts
- NumElts
)) {
2264 // Offset the demanded elts by the subvector index.
2265 uint64_t Idx
= SubIdx
->getZExtValue();
2266 APInt SrcElts
= DemandedElts
.zextOrSelf(NumSrcElts
).shl(Idx
);
2267 APInt SrcUndef
, SrcZero
;
2268 if (SimplifyDemandedVectorElts(Src
, SrcElts
, SrcUndef
, SrcZero
, TLO
,
2271 KnownUndef
= SrcUndef
.extractBits(NumElts
, Idx
);
2272 KnownZero
= SrcZero
.extractBits(NumElts
, Idx
);
2276 case ISD::INSERT_VECTOR_ELT
: {
2277 SDValue Vec
= Op
.getOperand(0);
2278 SDValue Scl
= Op
.getOperand(1);
2279 auto *CIdx
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
2281 // For a legal, constant insertion index, if we don't need this insertion
2282 // then strip it, else remove it from the demanded elts.
2283 if (CIdx
&& CIdx
->getAPIntValue().ult(NumElts
)) {
2284 unsigned Idx
= CIdx
->getZExtValue();
2285 if (!DemandedElts
[Idx
])
2286 return TLO
.CombineTo(Op
, Vec
);
2288 APInt
DemandedVecElts(DemandedElts
);
2289 DemandedVecElts
.clearBit(Idx
);
2290 if (SimplifyDemandedVectorElts(Vec
, DemandedVecElts
, KnownUndef
,
2291 KnownZero
, TLO
, Depth
+ 1))
2294 KnownUndef
.clearBit(Idx
);
2296 KnownUndef
.setBit(Idx
);
2298 KnownZero
.clearBit(Idx
);
2299 if (isNullConstant(Scl
) || isNullFPConstant(Scl
))
2300 KnownZero
.setBit(Idx
);
2304 APInt VecUndef
, VecZero
;
2305 if (SimplifyDemandedVectorElts(Vec
, DemandedElts
, VecUndef
, VecZero
, TLO
,
2308 // Without knowing the insertion index we can't set KnownUndef/KnownZero.
2311 case ISD::VSELECT
: {
2312 // Try to transform the select condition based on the current demanded
2314 // TODO: If a condition element is undef, we can choose from one arm of the
2315 // select (and if one arm is undef, then we can propagate that to the
2317 // TODO - add support for constant vselect masks (see IR version of this).
2318 APInt UnusedUndef
, UnusedZero
;
2319 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedElts
, UnusedUndef
,
2320 UnusedZero
, TLO
, Depth
+ 1))
2323 // See if we can simplify either vselect operand.
2324 APInt
DemandedLHS(DemandedElts
);
2325 APInt
DemandedRHS(DemandedElts
);
2326 APInt UndefLHS
, ZeroLHS
;
2327 APInt UndefRHS
, ZeroRHS
;
2328 if (SimplifyDemandedVectorElts(Op
.getOperand(1), DemandedLHS
, UndefLHS
,
2329 ZeroLHS
, TLO
, Depth
+ 1))
2331 if (SimplifyDemandedVectorElts(Op
.getOperand(2), DemandedRHS
, UndefRHS
,
2332 ZeroRHS
, TLO
, Depth
+ 1))
2335 KnownUndef
= UndefLHS
& UndefRHS
;
2336 KnownZero
= ZeroLHS
& ZeroRHS
;
2339 case ISD::VECTOR_SHUFFLE
: {
2340 ArrayRef
<int> ShuffleMask
= cast
<ShuffleVectorSDNode
>(Op
)->getMask();
2342 // Collect demanded elements from shuffle operands..
2343 APInt
DemandedLHS(NumElts
, 0);
2344 APInt
DemandedRHS(NumElts
, 0);
2345 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2346 int M
= ShuffleMask
[i
];
2347 if (M
< 0 || !DemandedElts
[i
])
2349 assert(0 <= M
&& M
< (int)(2 * NumElts
) && "Shuffle index out of range");
2350 if (M
< (int)NumElts
)
2351 DemandedLHS
.setBit(M
);
2353 DemandedRHS
.setBit(M
- NumElts
);
2356 // See if we can simplify either shuffle operand.
2357 APInt UndefLHS
, ZeroLHS
;
2358 APInt UndefRHS
, ZeroRHS
;
2359 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedLHS
, UndefLHS
,
2360 ZeroLHS
, TLO
, Depth
+ 1))
2362 if (SimplifyDemandedVectorElts(Op
.getOperand(1), DemandedRHS
, UndefRHS
,
2363 ZeroRHS
, TLO
, Depth
+ 1))
2366 // Simplify mask using undef elements from LHS/RHS.
2367 bool Updated
= false;
2368 bool IdentityLHS
= true, IdentityRHS
= true;
2369 SmallVector
<int, 32> NewMask(ShuffleMask
.begin(), ShuffleMask
.end());
2370 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2371 int &M
= NewMask
[i
];
2374 if (!DemandedElts
[i
] || (M
< (int)NumElts
&& UndefLHS
[M
]) ||
2375 (M
>= (int)NumElts
&& UndefRHS
[M
- NumElts
])) {
2379 IdentityLHS
&= (M
< 0) || (M
== (int)i
);
2380 IdentityRHS
&= (M
< 0) || ((M
- NumElts
) == i
);
2383 // Update legal shuffle masks based on demanded elements if it won't reduce
2384 // to Identity which can cause premature removal of the shuffle mask.
2385 if (Updated
&& !IdentityLHS
&& !IdentityRHS
&& !TLO
.LegalOps
&&
2386 isShuffleMaskLegal(NewMask
, VT
))
2387 return TLO
.CombineTo(Op
,
2388 TLO
.DAG
.getVectorShuffle(VT
, DL
, Op
.getOperand(0),
2389 Op
.getOperand(1), NewMask
));
2391 // Propagate undef/zero elements from LHS/RHS.
2392 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2393 int M
= ShuffleMask
[i
];
2395 KnownUndef
.setBit(i
);
2396 } else if (M
< (int)NumElts
) {
2398 KnownUndef
.setBit(i
);
2400 KnownZero
.setBit(i
);
2402 if (UndefRHS
[M
- NumElts
])
2403 KnownUndef
.setBit(i
);
2404 if (ZeroRHS
[M
- NumElts
])
2405 KnownZero
.setBit(i
);
2410 case ISD::ANY_EXTEND_VECTOR_INREG
:
2411 case ISD::SIGN_EXTEND_VECTOR_INREG
:
2412 case ISD::ZERO_EXTEND_VECTOR_INREG
: {
2413 APInt SrcUndef
, SrcZero
;
2414 SDValue Src
= Op
.getOperand(0);
2415 unsigned NumSrcElts
= Src
.getValueType().getVectorNumElements();
2416 APInt DemandedSrcElts
= DemandedElts
.zextOrSelf(NumSrcElts
);
2417 if (SimplifyDemandedVectorElts(Src
, DemandedSrcElts
, SrcUndef
, SrcZero
, TLO
,
2420 KnownZero
= SrcZero
.zextOrTrunc(NumElts
);
2421 KnownUndef
= SrcUndef
.zextOrTrunc(NumElts
);
2423 if (Op
.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG
&&
2424 Op
.getValueSizeInBits() == Src
.getValueSizeInBits() &&
2425 DemandedSrcElts
== 1 && TLO
.DAG
.getDataLayout().isLittleEndian()) {
2426 // aext - if we just need the bottom element then we can bitcast.
2427 return TLO
.CombineTo(Op
, TLO
.DAG
.getBitcast(VT
, Src
));
2430 if (Op
.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG
) {
2431 // zext(undef) upper bits are guaranteed to be zero.
2432 if (DemandedElts
.isSubsetOf(KnownUndef
))
2433 return TLO
.CombineTo(Op
, TLO
.DAG
.getConstant(0, SDLoc(Op
), VT
));
2434 KnownUndef
.clearAllBits();
2439 // TODO: There are more binop opcodes that could be handled here - MUL, MIN,
2440 // MAX, saturated math, etc.
2450 APInt UndefRHS
, ZeroRHS
;
2451 if (SimplifyDemandedVectorElts(Op
.getOperand(1), DemandedElts
, UndefRHS
,
2452 ZeroRHS
, TLO
, Depth
+ 1))
2454 APInt UndefLHS
, ZeroLHS
;
2455 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedElts
, UndefLHS
,
2456 ZeroLHS
, TLO
, Depth
+ 1))
2459 KnownZero
= ZeroLHS
& ZeroRHS
;
2460 KnownUndef
= getKnownUndefForVectorBinop(Op
, TLO
.DAG
, UndefLHS
, UndefRHS
);
2468 APInt UndefRHS
, ZeroRHS
;
2469 if (SimplifyDemandedVectorElts(Op
.getOperand(1), DemandedElts
, UndefRHS
,
2470 ZeroRHS
, TLO
, Depth
+ 1))
2472 APInt UndefLHS
, ZeroLHS
;
2473 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedElts
, UndefLHS
,
2474 ZeroLHS
, TLO
, Depth
+ 1))
2477 KnownZero
= ZeroLHS
;
2478 KnownUndef
= UndefLHS
& UndefRHS
; // TODO: use getKnownUndefForVectorBinop?
2483 APInt SrcUndef
, SrcZero
;
2484 if (SimplifyDemandedVectorElts(Op
.getOperand(1), DemandedElts
, SrcUndef
,
2485 SrcZero
, TLO
, Depth
+ 1))
2487 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedElts
, KnownUndef
,
2488 KnownZero
, TLO
, Depth
+ 1))
2491 // If either side has a zero element, then the result element is zero, even
2492 // if the other is an UNDEF.
2493 // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
2494 // and then handle 'and' nodes with the rest of the binop opcodes.
2495 KnownZero
|= SrcZero
;
2496 KnownUndef
&= SrcUndef
;
2497 KnownUndef
&= ~KnownZero
;
2501 case ISD::SIGN_EXTEND
:
2502 case ISD::ZERO_EXTEND
:
2503 if (SimplifyDemandedVectorElts(Op
.getOperand(0), DemandedElts
, KnownUndef
,
2504 KnownZero
, TLO
, Depth
+ 1))
2507 if (Op
.getOpcode() == ISD::ZERO_EXTEND
) {
2508 // zext(undef) upper bits are guaranteed to be zero.
2509 if (DemandedElts
.isSubsetOf(KnownUndef
))
2510 return TLO
.CombineTo(Op
, TLO
.DAG
.getConstant(0, SDLoc(Op
), VT
));
2511 KnownUndef
.clearAllBits();
2515 if (Op
.getOpcode() >= ISD::BUILTIN_OP_END
) {
2516 if (SimplifyDemandedVectorEltsForTargetNode(Op
, DemandedElts
, KnownUndef
,
2517 KnownZero
, TLO
, Depth
))
2521 APInt DemandedBits
= APInt::getAllOnesValue(EltSizeInBits
);
2522 if (SimplifyDemandedBits(Op
, DemandedBits
, OriginalDemandedElts
, Known
,
2523 TLO
, Depth
, AssumeSingleUse
))
2529 assert((KnownUndef
& KnownZero
) == 0 && "Elements flagged as undef AND zero");
2531 // Constant fold all undef cases.
2532 // TODO: Handle zero cases as well.
2533 if (DemandedElts
.isSubsetOf(KnownUndef
))
2534 return TLO
.CombineTo(Op
, TLO
.DAG
.getUNDEF(VT
));
2539 /// Determine which of the bits specified in Mask are known to be either zero or
2540 /// one and return them in the Known.
2541 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op
,
2543 const APInt
&DemandedElts
,
2544 const SelectionDAG
&DAG
,
2545 unsigned Depth
) const {
2546 assert((Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2547 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2548 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2549 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2550 "Should use MaskedValueIsZero if you don't know whether Op"
2551 " is a target node!");
2555 void TargetLowering::computeKnownBitsForTargetInstr(
2556 Register R
, KnownBits
&Known
, const APInt
&DemandedElts
,
2557 const MachineRegisterInfo
&MRI
, unsigned Depth
) const {
2561 void TargetLowering::computeKnownBitsForFrameIndex(const SDValue Op
,
2563 const APInt
&DemandedElts
,
2564 const SelectionDAG
&DAG
,
2565 unsigned Depth
) const {
2566 assert(isa
<FrameIndexSDNode
>(Op
) && "expected FrameIndex");
2568 if (unsigned Align
= DAG
.InferPtrAlignment(Op
)) {
2569 // The low bits are known zero if the pointer is aligned.
2570 Known
.Zero
.setLowBits(Log2_32(Align
));
2574 /// This method can be implemented by targets that want to expose additional
2575 /// information about sign bits to the DAG Combiner.
2576 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op
,
2578 const SelectionDAG
&,
2579 unsigned Depth
) const {
2580 assert((Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2581 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2582 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2583 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2584 "Should use ComputeNumSignBits if you don't know whether Op"
2585 " is a target node!");
2589 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
2590 SDValue Op
, const APInt
&DemandedElts
, APInt
&KnownUndef
, APInt
&KnownZero
,
2591 TargetLoweringOpt
&TLO
, unsigned Depth
) const {
2592 assert((Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2593 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2594 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2595 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2596 "Should use SimplifyDemandedVectorElts if you don't know whether Op"
2597 " is a target node!");
2601 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
2602 SDValue Op
, const APInt
&DemandedBits
, const APInt
&DemandedElts
,
2603 KnownBits
&Known
, TargetLoweringOpt
&TLO
, unsigned Depth
) const {
2604 assert((Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2605 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2606 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2607 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2608 "Should use SimplifyDemandedBits if you don't know whether Op"
2609 " is a target node!");
2610 computeKnownBitsForTargetNode(Op
, Known
, DemandedElts
, TLO
.DAG
, Depth
);
2614 SDValue
TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
2615 SDValue Op
, const APInt
&DemandedBits
, const APInt
&DemandedElts
,
2616 SelectionDAG
&DAG
, unsigned Depth
) const {
2618 (Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2619 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2620 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2621 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2622 "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
2623 " is a target node!");
2627 const Constant
*TargetLowering::getTargetConstantFromLoad(LoadSDNode
*) const {
2631 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op
,
2632 const SelectionDAG
&DAG
,
2634 unsigned Depth
) const {
2635 assert((Op
.getOpcode() >= ISD::BUILTIN_OP_END
||
2636 Op
.getOpcode() == ISD::INTRINSIC_WO_CHAIN
||
2637 Op
.getOpcode() == ISD::INTRINSIC_W_CHAIN
||
2638 Op
.getOpcode() == ISD::INTRINSIC_VOID
) &&
2639 "Should use isKnownNeverNaN if you don't know whether Op"
2640 " is a target node!");
2644 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
2645 // work with truncating build vectors and vectors with elements of less than
2647 bool TargetLowering::isConstTrueVal(const SDNode
*N
) const {
2652 if (auto *CN
= dyn_cast
<ConstantSDNode
>(N
)) {
2653 CVal
= CN
->getAPIntValue();
2654 } else if (auto *BV
= dyn_cast
<BuildVectorSDNode
>(N
)) {
2655 auto *CN
= BV
->getConstantSplatNode();
2659 // If this is a truncating build vector, truncate the splat value.
2660 // Otherwise, we may fail to match the expected values below.
2661 unsigned BVEltWidth
= BV
->getValueType(0).getScalarSizeInBits();
2662 CVal
= CN
->getAPIntValue();
2663 if (BVEltWidth
< CVal
.getBitWidth())
2664 CVal
= CVal
.trunc(BVEltWidth
);
2669 switch (getBooleanContents(N
->getValueType(0))) {
2670 case UndefinedBooleanContent
:
2672 case ZeroOrOneBooleanContent
:
2673 return CVal
.isOneValue();
2674 case ZeroOrNegativeOneBooleanContent
:
2675 return CVal
.isAllOnesValue();
2678 llvm_unreachable("Invalid boolean contents");
2681 bool TargetLowering::isConstFalseVal(const SDNode
*N
) const {
2685 const ConstantSDNode
*CN
= dyn_cast
<ConstantSDNode
>(N
);
2687 const BuildVectorSDNode
*BV
= dyn_cast
<BuildVectorSDNode
>(N
);
2691 // Only interested in constant splats, we don't care about undef
2692 // elements in identifying boolean constants and getConstantSplatNode
2693 // returns NULL if all ops are undef;
2694 CN
= BV
->getConstantSplatNode();
2699 if (getBooleanContents(N
->getValueType(0)) == UndefinedBooleanContent
)
2700 return !CN
->getAPIntValue()[0];
2702 return CN
->isNullValue();
2705 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode
*N
, EVT VT
,
2710 TargetLowering::BooleanContent Cnt
= getBooleanContents(VT
);
2712 case TargetLowering::ZeroOrOneBooleanContent
:
2713 // An extended value of 1 is always true, unless its original type is i1,
2714 // in which case it will be sign extended to -1.
2715 return (N
->isOne() && !SExt
) || (SExt
&& (N
->getValueType(0) != MVT::i1
));
2716 case TargetLowering::UndefinedBooleanContent
:
2717 case TargetLowering::ZeroOrNegativeOneBooleanContent
:
2718 return N
->isAllOnesValue() && SExt
;
2720 llvm_unreachable("Unexpected enumeration.");
2723 /// This helper function of SimplifySetCC tries to optimize the comparison when
2724 /// either operand of the SetCC node is a bitwise-and instruction.
2725 SDValue
TargetLowering::foldSetCCWithAnd(EVT VT
, SDValue N0
, SDValue N1
,
2726 ISD::CondCode Cond
, const SDLoc
&DL
,
2727 DAGCombinerInfo
&DCI
) const {
2728 // Match these patterns in any of their permutations:
2731 if (N1
.getOpcode() == ISD::AND
&& N0
.getOpcode() != ISD::AND
)
2734 EVT OpVT
= N0
.getValueType();
2735 if (N0
.getOpcode() != ISD::AND
|| !OpVT
.isInteger() ||
2736 (Cond
!= ISD::SETEQ
&& Cond
!= ISD::SETNE
))
2740 if (N0
.getOperand(0) == N1
) {
2741 X
= N0
.getOperand(1);
2742 Y
= N0
.getOperand(0);
2743 } else if (N0
.getOperand(1) == N1
) {
2744 X
= N0
.getOperand(0);
2745 Y
= N0
.getOperand(1);
2750 SelectionDAG
&DAG
= DCI
.DAG
;
2751 SDValue Zero
= DAG
.getConstant(0, DL
, OpVT
);
2752 if (DAG
.isKnownToBeAPowerOfTwo(Y
)) {
2753 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
2754 // Note that where Y is variable and is known to have at most one bit set
2755 // (for example, if it is Z & 1) we cannot do this; the expressions are not
2756 // equivalent when Y == 0.
2757 Cond
= ISD::getSetCCInverse(Cond
, /*isInteger=*/true);
2758 if (DCI
.isBeforeLegalizeOps() ||
2759 isCondCodeLegal(Cond
, N0
.getSimpleValueType()))
2760 return DAG
.getSetCC(DL
, VT
, N0
, Zero
, Cond
);
2761 } else if (N0
.hasOneUse() && hasAndNotCompare(Y
)) {
2762 // If the target supports an 'and-not' or 'and-complement' logic operation,
2763 // try to use that to make a comparison operation more efficient.
2764 // But don't do this transform if the mask is a single bit because there are
2765 // more efficient ways to deal with that case (for example, 'bt' on x86 or
2766 // 'rlwinm' on PPC).
2768 // Bail out if the compare operand that we want to turn into a zero is
2769 // already a zero (otherwise, infinite loop).
2770 auto *YConst
= dyn_cast
<ConstantSDNode
>(Y
);
2771 if (YConst
&& YConst
->isNullValue())
2774 // Transform this into: ~X & Y == 0.
2775 SDValue NotX
= DAG
.getNOT(SDLoc(X
), X
, OpVT
);
2776 SDValue NewAnd
= DAG
.getNode(ISD::AND
, SDLoc(N0
), OpVT
, NotX
, Y
);
2777 return DAG
.getSetCC(DL
, VT
, NewAnd
, Zero
, Cond
);
2783 /// There are multiple IR patterns that could be checking whether certain
2784 /// truncation of a signed number would be lossy or not. The pattern which is
2785 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
2786 /// We are looking for the following pattern: (KeptBits is a constant)
2787 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
2788 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
2789 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0
2790 /// We will unfold it into the natural trunc+sext pattern:
2791 /// ((%x << C) a>> C) dstcond %x
2792 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x)
2793 SDValue
TargetLowering::optimizeSetCCOfSignedTruncationCheck(
2794 EVT SCCVT
, SDValue N0
, SDValue N1
, ISD::CondCode Cond
, DAGCombinerInfo
&DCI
,
2795 const SDLoc
&DL
) const {
2796 // We must be comparing with a constant.
2798 if (!(C1
= dyn_cast
<ConstantSDNode
>(N1
)))
2801 // N0 should be: add %x, (1 << (KeptBits-1))
2802 if (N0
->getOpcode() != ISD::ADD
)
2805 // And we must be 'add'ing a constant.
2806 ConstantSDNode
*C01
;
2807 if (!(C01
= dyn_cast
<ConstantSDNode
>(N0
->getOperand(1))))
2810 SDValue X
= N0
->getOperand(0);
2811 EVT XVT
= X
.getValueType();
2813 // Validate constants ...
2815 APInt I1
= C1
->getAPIntValue();
2817 ISD::CondCode NewCond
;
2818 if (Cond
== ISD::CondCode::SETULT
) {
2819 NewCond
= ISD::CondCode::SETEQ
;
2820 } else if (Cond
== ISD::CondCode::SETULE
) {
2821 NewCond
= ISD::CondCode::SETEQ
;
2822 // But need to 'canonicalize' the constant.
2824 } else if (Cond
== ISD::CondCode::SETUGT
) {
2825 NewCond
= ISD::CondCode::SETNE
;
2826 // But need to 'canonicalize' the constant.
2828 } else if (Cond
== ISD::CondCode::SETUGE
) {
2829 NewCond
= ISD::CondCode::SETNE
;
2833 APInt I01
= C01
->getAPIntValue();
2835 auto checkConstants
= [&I1
, &I01
]() -> bool {
2836 // Both of them must be power-of-two, and the constant from setcc is bigger.
2837 return I1
.ugt(I01
) && I1
.isPowerOf2() && I01
.isPowerOf2();
2840 if (checkConstants()) {
2841 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256
2843 // What if we invert constants? (and the target predicate)
2846 NewCond
= getSetCCInverse(NewCond
, /*isInteger=*/true);
2847 if (!checkConstants())
2849 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256
2852 // They are power-of-two, so which bit is set?
2853 const unsigned KeptBits
= I1
.logBase2();
2854 const unsigned KeptBitsMinusOne
= I01
.logBase2();
2857 if (KeptBits
!= (KeptBitsMinusOne
+ 1))
2859 assert(KeptBits
> 0 && KeptBits
< XVT
.getSizeInBits() && "unreachable");
2861 // We don't want to do this in every single case.
2862 SelectionDAG
&DAG
= DCI
.DAG
;
2863 if (!DAG
.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
2867 const unsigned MaskedBits
= XVT
.getSizeInBits() - KeptBits
;
2868 assert(MaskedBits
> 0 && MaskedBits
< XVT
.getSizeInBits() && "unreachable");
2870 // Unfold into: ((%x << C) a>> C) cond %x
2871 // Where 'cond' will be either 'eq' or 'ne'.
2872 SDValue ShiftAmt
= DAG
.getConstant(MaskedBits
, DL
, XVT
);
2873 SDValue T0
= DAG
.getNode(ISD::SHL
, DL
, XVT
, X
, ShiftAmt
);
2874 SDValue T1
= DAG
.getNode(ISD::SRA
, DL
, XVT
, T0
, ShiftAmt
);
2875 SDValue T2
= DAG
.getSetCC(DL
, SCCVT
, T1
, X
, NewCond
);
2880 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
2881 SDValue
TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
2882 EVT SCCVT
, SDValue N0
, SDValue N1C
, ISD::CondCode Cond
,
2883 DAGCombinerInfo
&DCI
, const SDLoc
&DL
) const {
2884 assert(isConstOrConstSplat(N1C
) &&
2885 isConstOrConstSplat(N1C
)->getAPIntValue().isNullValue() &&
2886 "Should be a comparison with 0.");
2887 assert((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
2888 "Valid only for [in]equality comparisons.");
2890 unsigned NewShiftOpcode
;
2893 SelectionDAG
&DAG
= DCI
.DAG
;
2894 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
2896 // Look for '(C l>>/<< Y)'.
2897 auto Match
= [&NewShiftOpcode
, &X
, &C
, &Y
, &TLI
, &DAG
](SDValue V
) {
2898 // The shift should be one-use.
2901 unsigned OldShiftOpcode
= V
.getOpcode();
2902 switch (OldShiftOpcode
) {
2904 NewShiftOpcode
= ISD::SRL
;
2907 NewShiftOpcode
= ISD::SHL
;
2910 return false; // must be a logical shift.
2912 // We should be shifting a constant.
2913 // FIXME: best to use isConstantOrConstantVector().
2914 C
= V
.getOperand(0);
2915 ConstantSDNode
*CC
=
2916 isConstOrConstSplat(C
, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
2919 Y
= V
.getOperand(1);
2921 ConstantSDNode
*XC
=
2922 isConstOrConstSplat(X
, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
2923 return TLI
.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
2924 X
, XC
, CC
, Y
, OldShiftOpcode
, NewShiftOpcode
, DAG
);
2927 // LHS of comparison should be an one-use 'and'.
2928 if (N0
.getOpcode() != ISD::AND
|| !N0
.hasOneUse())
2931 X
= N0
.getOperand(0);
2932 SDValue Mask
= N0
.getOperand(1);
2934 // 'and' is commutative!
2941 EVT VT
= X
.getValueType();
2944 // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
2945 SDValue T0
= DAG
.getNode(NewShiftOpcode
, DL
, VT
, X
, Y
);
2946 SDValue T1
= DAG
.getNode(ISD::AND
, DL
, VT
, T0
, C
);
2947 SDValue T2
= DAG
.getSetCC(DL
, SCCVT
, T1
, N1C
, Cond
);
2951 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
2952 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
2953 /// handle the commuted versions of these patterns.
2954 SDValue
TargetLowering::foldSetCCWithBinOp(EVT VT
, SDValue N0
, SDValue N1
,
2955 ISD::CondCode Cond
, const SDLoc
&DL
,
2956 DAGCombinerInfo
&DCI
) const {
2957 unsigned BOpcode
= N0
.getOpcode();
2958 assert((BOpcode
== ISD::ADD
|| BOpcode
== ISD::SUB
|| BOpcode
== ISD::XOR
) &&
2959 "Unexpected binop");
2960 assert((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) && "Unexpected condcode");
2962 // (X + Y) == X --> Y == 0
2963 // (X - Y) == X --> Y == 0
2964 // (X ^ Y) == X --> Y == 0
2965 SelectionDAG
&DAG
= DCI
.DAG
;
2966 EVT OpVT
= N0
.getValueType();
2967 SDValue X
= N0
.getOperand(0);
2968 SDValue Y
= N0
.getOperand(1);
2970 return DAG
.getSetCC(DL
, VT
, Y
, DAG
.getConstant(0, DL
, OpVT
), Cond
);
2975 // (X + Y) == Y --> X == 0
2976 // (X ^ Y) == Y --> X == 0
2977 if (BOpcode
== ISD::ADD
|| BOpcode
== ISD::XOR
)
2978 return DAG
.getSetCC(DL
, VT
, X
, DAG
.getConstant(0, DL
, OpVT
), Cond
);
2980 // The shift would not be valid if the operands are boolean (i1).
2981 if (!N0
.hasOneUse() || OpVT
.getScalarSizeInBits() == 1)
2984 // (X - Y) == Y --> X == Y << 1
2985 EVT ShiftVT
= getShiftAmountTy(OpVT
, DAG
.getDataLayout(),
2986 !DCI
.isBeforeLegalize());
2987 SDValue One
= DAG
.getConstant(1, DL
, ShiftVT
);
2988 SDValue YShl1
= DAG
.getNode(ISD::SHL
, DL
, N1
.getValueType(), Y
, One
);
2989 if (!DCI
.isCalledByLegalizer())
2990 DCI
.AddToWorklist(YShl1
.getNode());
2991 return DAG
.getSetCC(DL
, VT
, X
, YShl1
, Cond
);
2994 /// Try to simplify a setcc built with the specified operands and cc. If it is
2995 /// unable to simplify it, return a null SDValue.
2996 SDValue
TargetLowering::SimplifySetCC(EVT VT
, SDValue N0
, SDValue N1
,
2997 ISD::CondCode Cond
, bool foldBooleans
,
2998 DAGCombinerInfo
&DCI
,
2999 const SDLoc
&dl
) const {
3000 SelectionDAG
&DAG
= DCI
.DAG
;
3001 EVT OpVT
= N0
.getValueType();
3003 // Constant fold or commute setcc.
3004 if (SDValue Fold
= DAG
.FoldSetCC(VT
, N0
, N1
, Cond
, dl
))
3007 // Ensure that the constant occurs on the RHS and fold constant comparisons.
3008 // TODO: Handle non-splat vector constants. All undef causes trouble.
3009 ISD::CondCode SwappedCC
= ISD::getSetCCSwappedOperands(Cond
);
3010 if (isConstOrConstSplat(N0
) &&
3011 (DCI
.isBeforeLegalizeOps() ||
3012 isCondCodeLegal(SwappedCC
, N0
.getSimpleValueType())))
3013 return DAG
.getSetCC(dl
, VT
, N1
, N0
, SwappedCC
);
3015 // If we have a subtract with the same 2 non-constant operands as this setcc
3016 // -- but in reverse order -- then try to commute the operands of this setcc
3017 // to match. A matching pair of setcc (cmp) and sub may be combined into 1
3018 // instruction on some targets.
3019 if (!isConstOrConstSplat(N0
) && !isConstOrConstSplat(N1
) &&
3020 (DCI
.isBeforeLegalizeOps() ||
3021 isCondCodeLegal(SwappedCC
, N0
.getSimpleValueType())) &&
3022 DAG
.getNodeIfExists(ISD::SUB
, DAG
.getVTList(OpVT
), { N1
, N0
} ) &&
3023 !DAG
.getNodeIfExists(ISD::SUB
, DAG
.getVTList(OpVT
), { N0
, N1
} ))
3024 return DAG
.getSetCC(dl
, VT
, N1
, N0
, SwappedCC
);
3026 if (auto *N1C
= dyn_cast
<ConstantSDNode
>(N1
.getNode())) {
3027 const APInt
&C1
= N1C
->getAPIntValue();
3029 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3030 // equality comparison, then we're just comparing whether X itself is
3032 if (N0
.getOpcode() == ISD::SRL
&& (C1
.isNullValue() || C1
.isOneValue()) &&
3033 N0
.getOperand(0).getOpcode() == ISD::CTLZ
&&
3034 N0
.getOperand(1).getOpcode() == ISD::Constant
) {
3035 const APInt
&ShAmt
= N0
.getConstantOperandAPInt(1);
3036 if ((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
3037 ShAmt
== Log2_32(N0
.getValueSizeInBits())) {
3038 if ((C1
== 0) == (Cond
== ISD::SETEQ
)) {
3039 // (srl (ctlz x), 5) == 0 -> X != 0
3040 // (srl (ctlz x), 5) != 1 -> X != 0
3043 // (srl (ctlz x), 5) != 0 -> X == 0
3044 // (srl (ctlz x), 5) == 1 -> X == 0
3047 SDValue Zero
= DAG
.getConstant(0, dl
, N0
.getValueType());
3048 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0).getOperand(0),
3054 // Look through truncs that don't change the value of a ctpop.
3055 if (N0
.hasOneUse() && N0
.getOpcode() == ISD::TRUNCATE
)
3056 CTPOP
= N0
.getOperand(0);
3058 if (CTPOP
.hasOneUse() && CTPOP
.getOpcode() == ISD::CTPOP
&&
3060 N0
.getValueSizeInBits() > Log2_32_Ceil(CTPOP
.getValueSizeInBits()))) {
3061 EVT CTVT
= CTPOP
.getValueType();
3062 SDValue CTOp
= CTPOP
.getOperand(0);
3064 // (ctpop x) u< 2 -> (x & x-1) == 0
3065 // (ctpop x) u> 1 -> (x & x-1) != 0
3066 if ((Cond
== ISD::SETULT
&& C1
== 2) || (Cond
== ISD::SETUGT
&& C1
== 1)){
3067 SDValue NegOne
= DAG
.getAllOnesConstant(dl
, CTVT
);
3068 SDValue Add
= DAG
.getNode(ISD::ADD
, dl
, CTVT
, CTOp
, NegOne
);
3069 SDValue And
= DAG
.getNode(ISD::AND
, dl
, CTVT
, CTOp
, Add
);
3070 ISD::CondCode CC
= Cond
== ISD::SETULT
? ISD::SETEQ
: ISD::SETNE
;
3071 return DAG
.getSetCC(dl
, VT
, And
, DAG
.getConstant(0, dl
, CTVT
), CC
);
3074 // If ctpop is not supported, expand a power-of-2 comparison based on it.
3075 if (C1
== 1 && !isOperationLegalOrCustom(ISD::CTPOP
, CTVT
) &&
3076 (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
)) {
3077 // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3078 // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3079 SDValue Zero
= DAG
.getConstant(0, dl
, CTVT
);
3080 SDValue NegOne
= DAG
.getAllOnesConstant(dl
, CTVT
);
3081 ISD::CondCode InvCond
= ISD::getSetCCInverse(Cond
, true);
3082 SDValue Add
= DAG
.getNode(ISD::ADD
, dl
, CTVT
, CTOp
, NegOne
);
3083 SDValue And
= DAG
.getNode(ISD::AND
, dl
, CTVT
, CTOp
, Add
);
3084 SDValue LHS
= DAG
.getSetCC(dl
, VT
, CTOp
, Zero
, InvCond
);
3085 SDValue RHS
= DAG
.getSetCC(dl
, VT
, And
, Zero
, Cond
);
3086 unsigned LogicOpcode
= Cond
== ISD::SETEQ
? ISD::AND
: ISD::OR
;
3087 return DAG
.getNode(LogicOpcode
, dl
, VT
, LHS
, RHS
);
3091 // (zext x) == C --> x == (trunc C)
3092 // (sext x) == C --> x == (trunc C)
3093 if ((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
3094 DCI
.isBeforeLegalize() && N0
->hasOneUse()) {
3095 unsigned MinBits
= N0
.getValueSizeInBits();
3097 bool Signed
= false;
3098 if (N0
->getOpcode() == ISD::ZERO_EXTEND
) {
3100 MinBits
= N0
->getOperand(0).getValueSizeInBits();
3101 PreExt
= N0
->getOperand(0);
3102 } else if (N0
->getOpcode() == ISD::AND
) {
3103 // DAGCombine turns costly ZExts into ANDs
3104 if (auto *C
= dyn_cast
<ConstantSDNode
>(N0
->getOperand(1)))
3105 if ((C
->getAPIntValue()+1).isPowerOf2()) {
3106 MinBits
= C
->getAPIntValue().countTrailingOnes();
3107 PreExt
= N0
->getOperand(0);
3109 } else if (N0
->getOpcode() == ISD::SIGN_EXTEND
) {
3111 MinBits
= N0
->getOperand(0).getValueSizeInBits();
3112 PreExt
= N0
->getOperand(0);
3114 } else if (auto *LN0
= dyn_cast
<LoadSDNode
>(N0
)) {
3115 // ZEXTLOAD / SEXTLOAD
3116 if (LN0
->getExtensionType() == ISD::ZEXTLOAD
) {
3117 MinBits
= LN0
->getMemoryVT().getSizeInBits();
3119 } else if (LN0
->getExtensionType() == ISD::SEXTLOAD
) {
3121 MinBits
= LN0
->getMemoryVT().getSizeInBits();
3126 // Figure out how many bits we need to preserve this constant.
3127 unsigned ReqdBits
= Signed
?
3128 C1
.getBitWidth() - C1
.getNumSignBits() + 1 :
3131 // Make sure we're not losing bits from the constant.
3133 MinBits
< C1
.getBitWidth() &&
3134 MinBits
>= ReqdBits
) {
3135 EVT MinVT
= EVT::getIntegerVT(*DAG
.getContext(), MinBits
);
3136 if (isTypeDesirableForOp(ISD::SETCC
, MinVT
)) {
3137 // Will get folded away.
3138 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, dl
, MinVT
, PreExt
);
3139 if (MinBits
== 1 && C1
== 1)
3140 // Invert the condition.
3141 return DAG
.getSetCC(dl
, VT
, Trunc
, DAG
.getConstant(0, dl
, MVT::i1
),
3142 Cond
== ISD::SETEQ
? ISD::SETNE
: ISD::SETEQ
);
3143 SDValue C
= DAG
.getConstant(C1
.trunc(MinBits
), dl
, MinVT
);
3144 return DAG
.getSetCC(dl
, VT
, Trunc
, C
, Cond
);
3147 // If truncating the setcc operands is not desirable, we can still
3148 // simplify the expression in some cases:
3149 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
3150 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
3151 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
3152 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
3153 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
3154 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
3155 SDValue TopSetCC
= N0
->getOperand(0);
3156 unsigned N0Opc
= N0
->getOpcode();
3157 bool SExt
= (N0Opc
== ISD::SIGN_EXTEND
);
3158 if (TopSetCC
.getValueType() == MVT::i1
&& VT
== MVT::i1
&&
3159 TopSetCC
.getOpcode() == ISD::SETCC
&&
3160 (N0Opc
== ISD::ZERO_EXTEND
|| N0Opc
== ISD::SIGN_EXTEND
) &&
3161 (isConstFalseVal(N1C
) ||
3162 isExtendedTrueVal(N1C
, N0
->getValueType(0), SExt
))) {
3164 bool Inverse
= (N1C
->isNullValue() && Cond
== ISD::SETEQ
) ||
3165 (!N1C
->isNullValue() && Cond
== ISD::SETNE
);
3170 ISD::CondCode InvCond
= ISD::getSetCCInverse(
3171 cast
<CondCodeSDNode
>(TopSetCC
.getOperand(2))->get(),
3172 TopSetCC
.getOperand(0).getValueType().isInteger());
3173 return DAG
.getSetCC(dl
, VT
, TopSetCC
.getOperand(0),
3174 TopSetCC
.getOperand(1),
3180 // If the LHS is '(and load, const)', the RHS is 0, the test is for
3181 // equality or unsigned, and all 1 bits of the const are in the same
3182 // partial word, see if we can shorten the load.
3183 if (DCI
.isBeforeLegalize() &&
3184 !ISD::isSignedIntSetCC(Cond
) &&
3185 N0
.getOpcode() == ISD::AND
&& C1
== 0 &&
3186 N0
.getNode()->hasOneUse() &&
3187 isa
<LoadSDNode
>(N0
.getOperand(0)) &&
3188 N0
.getOperand(0).getNode()->hasOneUse() &&
3189 isa
<ConstantSDNode
>(N0
.getOperand(1))) {
3190 LoadSDNode
*Lod
= cast
<LoadSDNode
>(N0
.getOperand(0));
3192 unsigned bestWidth
= 0, bestOffset
= 0;
3193 if (!Lod
->isVolatile() && Lod
->isUnindexed()) {
3194 unsigned origWidth
= N0
.getValueSizeInBits();
3195 unsigned maskWidth
= origWidth
;
3196 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
3197 // 8 bits, but have to be careful...
3198 if (Lod
->getExtensionType() != ISD::NON_EXTLOAD
)
3199 origWidth
= Lod
->getMemoryVT().getSizeInBits();
3200 const APInt
&Mask
= N0
.getConstantOperandAPInt(1);
3201 for (unsigned width
= origWidth
/ 2; width
>=8; width
/= 2) {
3202 APInt newMask
= APInt::getLowBitsSet(maskWidth
, width
);
3203 for (unsigned offset
=0; offset
<origWidth
/width
; offset
++) {
3204 if (Mask
.isSubsetOf(newMask
)) {
3205 if (DAG
.getDataLayout().isLittleEndian())
3206 bestOffset
= (uint64_t)offset
* (width
/8);
3208 bestOffset
= (origWidth
/width
- offset
- 1) * (width
/8);
3209 bestMask
= Mask
.lshr(offset
* (width
/8) * 8);
3218 EVT newVT
= EVT::getIntegerVT(*DAG
.getContext(), bestWidth
);
3219 if (newVT
.isRound() &&
3220 shouldReduceLoadWidth(Lod
, ISD::NON_EXTLOAD
, newVT
)) {
3221 EVT PtrType
= Lod
->getOperand(1).getValueType();
3222 SDValue Ptr
= Lod
->getBasePtr();
3223 if (bestOffset
!= 0)
3224 Ptr
= DAG
.getNode(ISD::ADD
, dl
, PtrType
, Lod
->getBasePtr(),
3225 DAG
.getConstant(bestOffset
, dl
, PtrType
));
3226 unsigned NewAlign
= MinAlign(Lod
->getAlignment(), bestOffset
);
3227 SDValue NewLoad
= DAG
.getLoad(
3228 newVT
, dl
, Lod
->getChain(), Ptr
,
3229 Lod
->getPointerInfo().getWithOffset(bestOffset
), NewAlign
);
3230 return DAG
.getSetCC(dl
, VT
,
3231 DAG
.getNode(ISD::AND
, dl
, newVT
, NewLoad
,
3232 DAG
.getConstant(bestMask
.trunc(bestWidth
),
3234 DAG
.getConstant(0LL, dl
, newVT
), Cond
);
3239 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3240 if (N0
.getOpcode() == ISD::ZERO_EXTEND
) {
3241 unsigned InSize
= N0
.getOperand(0).getValueSizeInBits();
3243 // If the comparison constant has bits in the upper part, the
3244 // zero-extended value could never match.
3245 if (C1
.intersects(APInt::getHighBitsSet(C1
.getBitWidth(),
3246 C1
.getBitWidth() - InSize
))) {
3251 return DAG
.getConstant(0, dl
, VT
);
3255 return DAG
.getConstant(1, dl
, VT
);
3258 // True if the sign bit of C1 is set.
3259 return DAG
.getConstant(C1
.isNegative(), dl
, VT
);
3262 // True if the sign bit of C1 isn't set.
3263 return DAG
.getConstant(C1
.isNonNegative(), dl
, VT
);
3269 // Otherwise, we can perform the comparison with the low bits.
3277 EVT newVT
= N0
.getOperand(0).getValueType();
3278 if (DCI
.isBeforeLegalizeOps() ||
3279 (isOperationLegal(ISD::SETCC
, newVT
) &&
3280 isCondCodeLegal(Cond
, newVT
.getSimpleVT()))) {
3282 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), newVT
);
3283 SDValue NewConst
= DAG
.getConstant(C1
.trunc(InSize
), dl
, newVT
);
3285 SDValue NewSetCC
= DAG
.getSetCC(dl
, NewSetCCVT
, N0
.getOperand(0),
3287 return DAG
.getBoolExtOrTrunc(NewSetCC
, dl
, VT
, N0
.getValueType());
3292 break; // todo, be more careful with signed comparisons
3294 } else if (N0
.getOpcode() == ISD::SIGN_EXTEND_INREG
&&
3295 (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
)) {
3296 EVT ExtSrcTy
= cast
<VTSDNode
>(N0
.getOperand(1))->getVT();
3297 unsigned ExtSrcTyBits
= ExtSrcTy
.getSizeInBits();
3298 EVT ExtDstTy
= N0
.getValueType();
3299 unsigned ExtDstTyBits
= ExtDstTy
.getSizeInBits();
3301 // If the constant doesn't fit into the number of bits for the source of
3302 // the sign extension, it is impossible for both sides to be equal.
3303 if (C1
.getMinSignedBits() > ExtSrcTyBits
)
3304 return DAG
.getConstant(Cond
== ISD::SETNE
, dl
, VT
);
3307 EVT Op0Ty
= N0
.getOperand(0).getValueType();
3308 if (Op0Ty
== ExtSrcTy
) {
3309 ZextOp
= N0
.getOperand(0);
3311 APInt Imm
= APInt::getLowBitsSet(ExtDstTyBits
, ExtSrcTyBits
);
3312 ZextOp
= DAG
.getNode(ISD::AND
, dl
, Op0Ty
, N0
.getOperand(0),
3313 DAG
.getConstant(Imm
, dl
, Op0Ty
));
3315 if (!DCI
.isCalledByLegalizer())
3316 DCI
.AddToWorklist(ZextOp
.getNode());
3317 // Otherwise, make this a use of a zext.
3318 return DAG
.getSetCC(dl
, VT
, ZextOp
,
3319 DAG
.getConstant(C1
& APInt::getLowBitsSet(
3324 } else if ((N1C
->isNullValue() || N1C
->isOne()) &&
3325 (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
)) {
3326 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
3327 if (N0
.getOpcode() == ISD::SETCC
&&
3328 isTypeLegal(VT
) && VT
.bitsLE(N0
.getValueType())) {
3329 bool TrueWhenTrue
= (Cond
== ISD::SETEQ
) ^ (!N1C
->isOne());
3331 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, N0
);
3332 // Invert the condition.
3333 ISD::CondCode CC
= cast
<CondCodeSDNode
>(N0
.getOperand(2))->get();
3334 CC
= ISD::getSetCCInverse(CC
,
3335 N0
.getOperand(0).getValueType().isInteger());
3336 if (DCI
.isBeforeLegalizeOps() ||
3337 isCondCodeLegal(CC
, N0
.getOperand(0).getSimpleValueType()))
3338 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0), N0
.getOperand(1), CC
);
3341 if ((N0
.getOpcode() == ISD::XOR
||
3342 (N0
.getOpcode() == ISD::AND
&&
3343 N0
.getOperand(0).getOpcode() == ISD::XOR
&&
3344 N0
.getOperand(1) == N0
.getOperand(0).getOperand(1))) &&
3345 isa
<ConstantSDNode
>(N0
.getOperand(1)) &&
3346 cast
<ConstantSDNode
>(N0
.getOperand(1))->isOne()) {
3347 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
3348 // can only do this if the top bits are known zero.
3349 unsigned BitWidth
= N0
.getValueSizeInBits();
3350 if (DAG
.MaskedValueIsZero(N0
,
3351 APInt::getHighBitsSet(BitWidth
,
3353 // Okay, get the un-inverted input value.
3355 if (N0
.getOpcode() == ISD::XOR
) {
3356 Val
= N0
.getOperand(0);
3358 assert(N0
.getOpcode() == ISD::AND
&&
3359 N0
.getOperand(0).getOpcode() == ISD::XOR
);
3360 // ((X^1)&1)^1 -> X & 1
3361 Val
= DAG
.getNode(ISD::AND
, dl
, N0
.getValueType(),
3362 N0
.getOperand(0).getOperand(0),
3366 return DAG
.getSetCC(dl
, VT
, Val
, N1
,
3367 Cond
== ISD::SETEQ
? ISD::SETNE
: ISD::SETEQ
);
3369 } else if (N1C
->isOne() &&
3371 getBooleanContents(N0
->getValueType(0)) ==
3372 ZeroOrOneBooleanContent
)) {
3374 if (Op0
.getOpcode() == ISD::TRUNCATE
)
3375 Op0
= Op0
.getOperand(0);
3377 if ((Op0
.getOpcode() == ISD::XOR
) &&
3378 Op0
.getOperand(0).getOpcode() == ISD::SETCC
&&
3379 Op0
.getOperand(1).getOpcode() == ISD::SETCC
) {
3380 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
3381 Cond
= (Cond
== ISD::SETEQ
) ? ISD::SETNE
: ISD::SETEQ
;
3382 return DAG
.getSetCC(dl
, VT
, Op0
.getOperand(0), Op0
.getOperand(1),
3385 if (Op0
.getOpcode() == ISD::AND
&&
3386 isa
<ConstantSDNode
>(Op0
.getOperand(1)) &&
3387 cast
<ConstantSDNode
>(Op0
.getOperand(1))->isOne()) {
3388 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
3389 if (Op0
.getValueType().bitsGT(VT
))
3390 Op0
= DAG
.getNode(ISD::AND
, dl
, VT
,
3391 DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, Op0
.getOperand(0)),
3392 DAG
.getConstant(1, dl
, VT
));
3393 else if (Op0
.getValueType().bitsLT(VT
))
3394 Op0
= DAG
.getNode(ISD::AND
, dl
, VT
,
3395 DAG
.getNode(ISD::ANY_EXTEND
, dl
, VT
, Op0
.getOperand(0)),
3396 DAG
.getConstant(1, dl
, VT
));
3398 return DAG
.getSetCC(dl
, VT
, Op0
,
3399 DAG
.getConstant(0, dl
, Op0
.getValueType()),
3400 Cond
== ISD::SETEQ
? ISD::SETNE
: ISD::SETEQ
);
3402 if (Op0
.getOpcode() == ISD::AssertZext
&&
3403 cast
<VTSDNode
>(Op0
.getOperand(1))->getVT() == MVT::i1
)
3404 return DAG
.getSetCC(dl
, VT
, Op0
,
3405 DAG
.getConstant(0, dl
, Op0
.getValueType()),
3406 Cond
== ISD::SETEQ
? ISD::SETNE
: ISD::SETEQ
);
3411 // icmp eq/ne (urem %x, %y), 0
3412 // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
3414 if (N0
.getOpcode() == ISD::UREM
&& N1C
->isNullValue() &&
3415 (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
)) {
3416 KnownBits XKnown
= DAG
.computeKnownBits(N0
.getOperand(0));
3417 KnownBits YKnown
= DAG
.computeKnownBits(N0
.getOperand(1));
3418 if (XKnown
.countMaxPopulation() == 1 && YKnown
.countMinPopulation() >= 2)
3419 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0), N1
, Cond
);
3423 optimizeSetCCOfSignedTruncationCheck(VT
, N0
, N1
, Cond
, DCI
, dl
))
3427 // These simplifications apply to splat vectors as well.
3428 // TODO: Handle more splat vector cases.
3429 if (auto *N1C
= isConstOrConstSplat(N1
)) {
3430 const APInt
&C1
= N1C
->getAPIntValue();
3432 APInt MinVal
, MaxVal
;
3433 unsigned OperandBitSize
= N1C
->getValueType(0).getScalarSizeInBits();
3434 if (ISD::isSignedIntSetCC(Cond
)) {
3435 MinVal
= APInt::getSignedMinValue(OperandBitSize
);
3436 MaxVal
= APInt::getSignedMaxValue(OperandBitSize
);
3438 MinVal
= APInt::getMinValue(OperandBitSize
);
3439 MaxVal
= APInt::getMaxValue(OperandBitSize
);
3442 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3443 if (Cond
== ISD::SETGE
|| Cond
== ISD::SETUGE
) {
3444 // X >= MIN --> true
3446 return DAG
.getBoolConstant(true, dl
, VT
, OpVT
);
3448 if (!VT
.isVector()) { // TODO: Support this for vectors.
3449 // X >= C0 --> X > (C0 - 1)
3451 ISD::CondCode NewCC
= (Cond
== ISD::SETGE
) ? ISD::SETGT
: ISD::SETUGT
;
3452 if ((DCI
.isBeforeLegalizeOps() ||
3453 isCondCodeLegal(NewCC
, VT
.getSimpleVT())) &&
3454 (!N1C
->isOpaque() || (C
.getBitWidth() <= 64 &&
3455 isLegalICmpImmediate(C
.getSExtValue())))) {
3456 return DAG
.getSetCC(dl
, VT
, N0
,
3457 DAG
.getConstant(C
, dl
, N1
.getValueType()),
3463 if (Cond
== ISD::SETLE
|| Cond
== ISD::SETULE
) {
3464 // X <= MAX --> true
3466 return DAG
.getBoolConstant(true, dl
, VT
, OpVT
);
3468 // X <= C0 --> X < (C0 + 1)
3469 if (!VT
.isVector()) { // TODO: Support this for vectors.
3471 ISD::CondCode NewCC
= (Cond
== ISD::SETLE
) ? ISD::SETLT
: ISD::SETULT
;
3472 if ((DCI
.isBeforeLegalizeOps() ||
3473 isCondCodeLegal(NewCC
, VT
.getSimpleVT())) &&
3474 (!N1C
->isOpaque() || (C
.getBitWidth() <= 64 &&
3475 isLegalICmpImmediate(C
.getSExtValue())))) {
3476 return DAG
.getSetCC(dl
, VT
, N0
,
3477 DAG
.getConstant(C
, dl
, N1
.getValueType()),
3483 if (Cond
== ISD::SETLT
|| Cond
== ISD::SETULT
) {
3485 return DAG
.getBoolConstant(false, dl
, VT
, OpVT
); // X < MIN --> false
3487 // TODO: Support this for vectors after legalize ops.
3488 if (!VT
.isVector() || DCI
.isBeforeLegalizeOps()) {
3489 // Canonicalize setlt X, Max --> setne X, Max
3491 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETNE
);
3493 // If we have setult X, 1, turn it into seteq X, 0
3495 return DAG
.getSetCC(dl
, VT
, N0
,
3496 DAG
.getConstant(MinVal
, dl
, N0
.getValueType()),
3501 if (Cond
== ISD::SETGT
|| Cond
== ISD::SETUGT
) {
3503 return DAG
.getBoolConstant(false, dl
, VT
, OpVT
); // X > MAX --> false
3505 // TODO: Support this for vectors after legalize ops.
3506 if (!VT
.isVector() || DCI
.isBeforeLegalizeOps()) {
3507 // Canonicalize setgt X, Min --> setne X, Min
3509 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETNE
);
3511 // If we have setugt X, Max-1, turn it into seteq X, Max
3513 return DAG
.getSetCC(dl
, VT
, N0
,
3514 DAG
.getConstant(MaxVal
, dl
, N0
.getValueType()),
3519 if (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) {
3520 // (X & (C l>>/<< Y)) ==/!= 0 --> ((X <</l>> Y) & C) ==/!= 0
3521 if (C1
.isNullValue())
3522 if (SDValue CC
= optimizeSetCCByHoistingAndByConstFromLogicalShift(
3523 VT
, N0
, N1
, Cond
, DCI
, dl
))
3527 // If we have "setcc X, C0", check to see if we can shrink the immediate
3529 // TODO: Support this for vectors after legalize ops.
3530 if (!VT
.isVector() || DCI
.isBeforeLegalizeOps()) {
3531 // SETUGT X, SINTMAX -> SETLT X, 0
3532 if (Cond
== ISD::SETUGT
&&
3533 C1
== APInt::getSignedMaxValue(OperandBitSize
))
3534 return DAG
.getSetCC(dl
, VT
, N0
,
3535 DAG
.getConstant(0, dl
, N1
.getValueType()),
3538 // SETULT X, SINTMIN -> SETGT X, -1
3539 if (Cond
== ISD::SETULT
&&
3540 C1
== APInt::getSignedMinValue(OperandBitSize
)) {
3541 SDValue ConstMinusOne
=
3542 DAG
.getConstant(APInt::getAllOnesValue(OperandBitSize
), dl
,
3544 return DAG
.getSetCC(dl
, VT
, N0
, ConstMinusOne
, ISD::SETGT
);
3549 // Back to non-vector simplifications.
3550 // TODO: Can we do these for vector splats?
3551 if (auto *N1C
= dyn_cast
<ConstantSDNode
>(N1
.getNode())) {
3552 const APInt
&C1
= N1C
->getAPIntValue();
3554 // Fold bit comparisons when we can.
3555 if ((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
3556 (VT
== N0
.getValueType() ||
3557 (isTypeLegal(VT
) && VT
.bitsLE(N0
.getValueType()))) &&
3558 N0
.getOpcode() == ISD::AND
) {
3559 auto &DL
= DAG
.getDataLayout();
3560 if (auto *AndRHS
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
3561 EVT ShiftTy
= getShiftAmountTy(N0
.getValueType(), DL
,
3562 !DCI
.isBeforeLegalize());
3563 if (Cond
== ISD::SETNE
&& C1
== 0) {// (X & 8) != 0 --> (X & 8) >> 3
3564 // Perform the xform if the AND RHS is a single bit.
3565 if (AndRHS
->getAPIntValue().isPowerOf2()) {
3566 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
,
3567 DAG
.getNode(ISD::SRL
, dl
, N0
.getValueType(), N0
,
3568 DAG
.getConstant(AndRHS
->getAPIntValue().logBase2(), dl
,
3571 } else if (Cond
== ISD::SETEQ
&& C1
== AndRHS
->getAPIntValue()) {
3572 // (X & 8) == 8 --> (X & 8) >> 3
3573 // Perform the xform if C1 is a single bit.
3574 if (C1
.isPowerOf2()) {
3575 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
,
3576 DAG
.getNode(ISD::SRL
, dl
, N0
.getValueType(), N0
,
3577 DAG
.getConstant(C1
.logBase2(), dl
,
3584 if (C1
.getMinSignedBits() <= 64 &&
3585 !isLegalICmpImmediate(C1
.getSExtValue())) {
3586 // (X & -256) == 256 -> (X >> 8) == 1
3587 if ((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
3588 N0
.getOpcode() == ISD::AND
&& N0
.hasOneUse()) {
3589 if (auto *AndRHS
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
3590 const APInt
&AndRHSC
= AndRHS
->getAPIntValue();
3591 if ((-AndRHSC
).isPowerOf2() && (AndRHSC
& C1
) == C1
) {
3592 unsigned ShiftBits
= AndRHSC
.countTrailingZeros();
3593 auto &DL
= DAG
.getDataLayout();
3594 EVT ShiftTy
= getShiftAmountTy(N0
.getValueType(), DL
,
3595 !DCI
.isBeforeLegalize());
3596 EVT CmpTy
= N0
.getValueType();
3597 SDValue Shift
= DAG
.getNode(ISD::SRL
, dl
, CmpTy
, N0
.getOperand(0),
3598 DAG
.getConstant(ShiftBits
, dl
,
3600 SDValue CmpRHS
= DAG
.getConstant(C1
.lshr(ShiftBits
), dl
, CmpTy
);
3601 return DAG
.getSetCC(dl
, VT
, Shift
, CmpRHS
, Cond
);
3604 } else if (Cond
== ISD::SETULT
|| Cond
== ISD::SETUGE
||
3605 Cond
== ISD::SETULE
|| Cond
== ISD::SETUGT
) {
3606 bool AdjOne
= (Cond
== ISD::SETULE
|| Cond
== ISD::SETUGT
);
3607 // X < 0x100000000 -> (X >> 32) < 1
3608 // X >= 0x100000000 -> (X >> 32) >= 1
3609 // X <= 0x0ffffffff -> (X >> 32) < 1
3610 // X > 0x0ffffffff -> (X >> 32) >= 1
3613 ISD::CondCode NewCond
= Cond
;
3615 ShiftBits
= C1
.countTrailingOnes();
3617 NewCond
= (Cond
== ISD::SETULE
) ? ISD::SETULT
: ISD::SETUGE
;
3619 ShiftBits
= C1
.countTrailingZeros();
3621 NewC
.lshrInPlace(ShiftBits
);
3622 if (ShiftBits
&& NewC
.getMinSignedBits() <= 64 &&
3623 isLegalICmpImmediate(NewC
.getSExtValue())) {
3624 auto &DL
= DAG
.getDataLayout();
3625 EVT ShiftTy
= getShiftAmountTy(N0
.getValueType(), DL
,
3626 !DCI
.isBeforeLegalize());
3627 EVT CmpTy
= N0
.getValueType();
3628 SDValue Shift
= DAG
.getNode(ISD::SRL
, dl
, CmpTy
, N0
,
3629 DAG
.getConstant(ShiftBits
, dl
, ShiftTy
));
3630 SDValue CmpRHS
= DAG
.getConstant(NewC
, dl
, CmpTy
);
3631 return DAG
.getSetCC(dl
, VT
, Shift
, CmpRHS
, NewCond
);
3637 if (!isa
<ConstantFPSDNode
>(N0
) && isa
<ConstantFPSDNode
>(N1
)) {
3638 auto *CFP
= cast
<ConstantFPSDNode
>(N1
);
3639 assert(!CFP
->getValueAPF().isNaN() && "Unexpected NaN value");
3641 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
3642 // constant if knowing that the operand is non-nan is enough. We prefer to
3643 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
3645 if (Cond
== ISD::SETO
|| Cond
== ISD::SETUO
)
3646 return DAG
.getSetCC(dl
, VT
, N0
, N0
, Cond
);
3648 // setcc (fneg x), C -> setcc swap(pred) x, -C
3649 if (N0
.getOpcode() == ISD::FNEG
) {
3650 ISD::CondCode SwapCond
= ISD::getSetCCSwappedOperands(Cond
);
3651 if (DCI
.isBeforeLegalizeOps() ||
3652 isCondCodeLegal(SwapCond
, N0
.getSimpleValueType())) {
3653 SDValue NegN1
= DAG
.getNode(ISD::FNEG
, dl
, N0
.getValueType(), N1
);
3654 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0), NegN1
, SwapCond
);
3658 // If the condition is not legal, see if we can find an equivalent one
3660 if (!isCondCodeLegal(Cond
, N0
.getSimpleValueType())) {
3661 // If the comparison was an awkward floating-point == or != and one of
3662 // the comparison operands is infinity or negative infinity, convert the
3663 // condition to a less-awkward <= or >=.
3664 if (CFP
->getValueAPF().isInfinity()) {
3665 if (CFP
->getValueAPF().isNegative()) {
3666 if (Cond
== ISD::SETOEQ
&&
3667 isCondCodeLegal(ISD::SETOLE
, N0
.getSimpleValueType()))
3668 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETOLE
);
3669 if (Cond
== ISD::SETUEQ
&&
3670 isCondCodeLegal(ISD::SETOLE
, N0
.getSimpleValueType()))
3671 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETULE
);
3672 if (Cond
== ISD::SETUNE
&&
3673 isCondCodeLegal(ISD::SETUGT
, N0
.getSimpleValueType()))
3674 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETUGT
);
3675 if (Cond
== ISD::SETONE
&&
3676 isCondCodeLegal(ISD::SETUGT
, N0
.getSimpleValueType()))
3677 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETOGT
);
3679 if (Cond
== ISD::SETOEQ
&&
3680 isCondCodeLegal(ISD::SETOGE
, N0
.getSimpleValueType()))
3681 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETOGE
);
3682 if (Cond
== ISD::SETUEQ
&&
3683 isCondCodeLegal(ISD::SETOGE
, N0
.getSimpleValueType()))
3684 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETUGE
);
3685 if (Cond
== ISD::SETUNE
&&
3686 isCondCodeLegal(ISD::SETULT
, N0
.getSimpleValueType()))
3687 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETULT
);
3688 if (Cond
== ISD::SETONE
&&
3689 isCondCodeLegal(ISD::SETULT
, N0
.getSimpleValueType()))
3690 return DAG
.getSetCC(dl
, VT
, N0
, N1
, ISD::SETOLT
);
3697 // The sext(setcc()) => setcc() optimization relies on the appropriate
3698 // constant being emitted.
3699 assert(!N0
.getValueType().isInteger() &&
3700 "Integer types should be handled by FoldSetCC");
3702 bool EqTrue
= ISD::isTrueWhenEqual(Cond
);
3703 unsigned UOF
= ISD::getUnorderedFlavor(Cond
);
3704 if (UOF
== 2) // FP operators that are undefined on NaNs.
3705 return DAG
.getBoolConstant(EqTrue
, dl
, VT
, OpVT
);
3706 if (UOF
== unsigned(EqTrue
))
3707 return DAG
.getBoolConstant(EqTrue
, dl
, VT
, OpVT
);
3708 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
3709 // if it is not already.
3710 ISD::CondCode NewCond
= UOF
== 0 ? ISD::SETO
: ISD::SETUO
;
3711 if (NewCond
!= Cond
&&
3712 (DCI
.isBeforeLegalizeOps() ||
3713 isCondCodeLegal(NewCond
, N0
.getSimpleValueType())))
3714 return DAG
.getSetCC(dl
, VT
, N0
, N1
, NewCond
);
3717 if ((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
3718 N0
.getValueType().isInteger()) {
3719 if (N0
.getOpcode() == ISD::ADD
|| N0
.getOpcode() == ISD::SUB
||
3720 N0
.getOpcode() == ISD::XOR
) {
3721 // Simplify (X+Y) == (X+Z) --> Y == Z
3722 if (N0
.getOpcode() == N1
.getOpcode()) {
3723 if (N0
.getOperand(0) == N1
.getOperand(0))
3724 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(1), N1
.getOperand(1), Cond
);
3725 if (N0
.getOperand(1) == N1
.getOperand(1))
3726 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0), N1
.getOperand(0), Cond
);
3727 if (isCommutativeBinOp(N0
.getOpcode())) {
3728 // If X op Y == Y op X, try other combinations.
3729 if (N0
.getOperand(0) == N1
.getOperand(1))
3730 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(1), N1
.getOperand(0),
3732 if (N0
.getOperand(1) == N1
.getOperand(0))
3733 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0), N1
.getOperand(1),
3738 // If RHS is a legal immediate value for a compare instruction, we need
3739 // to be careful about increasing register pressure needlessly.
3740 bool LegalRHSImm
= false;
3742 if (auto *RHSC
= dyn_cast
<ConstantSDNode
>(N1
)) {
3743 if (auto *LHSR
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(1))) {
3744 // Turn (X+C1) == C2 --> X == C2-C1
3745 if (N0
.getOpcode() == ISD::ADD
&& N0
.getNode()->hasOneUse()) {
3746 return DAG
.getSetCC(dl
, VT
, N0
.getOperand(0),
3747 DAG
.getConstant(RHSC
->getAPIntValue()-
3748 LHSR
->getAPIntValue(),
3749 dl
, N0
.getValueType()), Cond
);
3752 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
3753 if (N0
.getOpcode() == ISD::XOR
)
3754 // If we know that all of the inverted bits are zero, don't bother
3755 // performing the inversion.
3756 if (DAG
.MaskedValueIsZero(N0
.getOperand(0), ~LHSR
->getAPIntValue()))
3758 DAG
.getSetCC(dl
, VT
, N0
.getOperand(0),
3759 DAG
.getConstant(LHSR
->getAPIntValue() ^
3760 RHSC
->getAPIntValue(),
3761 dl
, N0
.getValueType()),
3765 // Turn (C1-X) == C2 --> X == C1-C2
3766 if (auto *SUBC
= dyn_cast
<ConstantSDNode
>(N0
.getOperand(0))) {
3767 if (N0
.getOpcode() == ISD::SUB
&& N0
.getNode()->hasOneUse()) {
3769 DAG
.getSetCC(dl
, VT
, N0
.getOperand(1),
3770 DAG
.getConstant(SUBC
->getAPIntValue() -
3771 RHSC
->getAPIntValue(),
3772 dl
, N0
.getValueType()),
3777 // Could RHSC fold directly into a compare?
3778 if (RHSC
->getValueType(0).getSizeInBits() <= 64)
3779 LegalRHSImm
= isLegalICmpImmediate(RHSC
->getSExtValue());
3782 // (X+Y) == X --> Y == 0 and similar folds.
3783 // Don't do this if X is an immediate that can fold into a cmp
3784 // instruction and X+Y has other uses. It could be an induction variable
3785 // chain, and the transform would increase register pressure.
3786 if (!LegalRHSImm
|| N0
.hasOneUse())
3787 if (SDValue V
= foldSetCCWithBinOp(VT
, N0
, N1
, Cond
, dl
, DCI
))
3791 if (N1
.getOpcode() == ISD::ADD
|| N1
.getOpcode() == ISD::SUB
||
3792 N1
.getOpcode() == ISD::XOR
)
3793 if (SDValue V
= foldSetCCWithBinOp(VT
, N1
, N0
, Cond
, dl
, DCI
))
3796 if (SDValue V
= foldSetCCWithAnd(VT
, N0
, N1
, Cond
, dl
, DCI
))
3800 // Fold remainder of division by a constant.
3801 if ((N0
.getOpcode() == ISD::UREM
|| N0
.getOpcode() == ISD::SREM
) &&
3802 N0
.hasOneUse() && (Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
)) {
3803 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
3805 // When division is cheap or optimizing for minimum size,
3806 // fall through to DIVREM creation by skipping this fold.
3807 if (!isIntDivCheap(VT
, Attr
) && !Attr
.hasFnAttribute(Attribute::MinSize
)) {
3808 if (N0
.getOpcode() == ISD::UREM
) {
3809 if (SDValue Folded
= buildUREMEqFold(VT
, N0
, N1
, Cond
, DCI
, dl
))
3811 } else if (N0
.getOpcode() == ISD::SREM
) {
3812 if (SDValue Folded
= buildSREMEqFold(VT
, N0
, N1
, Cond
, DCI
, dl
))
3818 // Fold away ALL boolean setcc's.
3819 if (N0
.getValueType().getScalarType() == MVT::i1
&& foldBooleans
) {
3822 default: llvm_unreachable("Unknown integer setcc!");
3823 case ISD::SETEQ
: // X == Y -> ~(X^Y)
3824 Temp
= DAG
.getNode(ISD::XOR
, dl
, OpVT
, N0
, N1
);
3825 N0
= DAG
.getNOT(dl
, Temp
, OpVT
);
3826 if (!DCI
.isCalledByLegalizer())
3827 DCI
.AddToWorklist(Temp
.getNode());
3829 case ISD::SETNE
: // X != Y --> (X^Y)
3830 N0
= DAG
.getNode(ISD::XOR
, dl
, OpVT
, N0
, N1
);
3832 case ISD::SETGT
: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
3833 case ISD::SETULT
: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
3834 Temp
= DAG
.getNOT(dl
, N0
, OpVT
);
3835 N0
= DAG
.getNode(ISD::AND
, dl
, OpVT
, N1
, Temp
);
3836 if (!DCI
.isCalledByLegalizer())
3837 DCI
.AddToWorklist(Temp
.getNode());
3839 case ISD::SETLT
: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
3840 case ISD::SETUGT
: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
3841 Temp
= DAG
.getNOT(dl
, N1
, OpVT
);
3842 N0
= DAG
.getNode(ISD::AND
, dl
, OpVT
, N0
, Temp
);
3843 if (!DCI
.isCalledByLegalizer())
3844 DCI
.AddToWorklist(Temp
.getNode());
3846 case ISD::SETULE
: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
3847 case ISD::SETGE
: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
3848 Temp
= DAG
.getNOT(dl
, N0
, OpVT
);
3849 N0
= DAG
.getNode(ISD::OR
, dl
, OpVT
, N1
, Temp
);
3850 if (!DCI
.isCalledByLegalizer())
3851 DCI
.AddToWorklist(Temp
.getNode());
3853 case ISD::SETUGE
: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
3854 case ISD::SETLE
: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
3855 Temp
= DAG
.getNOT(dl
, N1
, OpVT
);
3856 N0
= DAG
.getNode(ISD::OR
, dl
, OpVT
, N0
, Temp
);
3859 if (VT
.getScalarType() != MVT::i1
) {
3860 if (!DCI
.isCalledByLegalizer())
3861 DCI
.AddToWorklist(N0
.getNode());
3862 // FIXME: If running after legalize, we probably can't do this.
3863 ISD::NodeType ExtendCode
= getExtendForContent(getBooleanContents(OpVT
));
3864 N0
= DAG
.getNode(ExtendCode
, dl
, VT
, N0
);
3869 // Could not fold it.
3873 /// Returns true (and the GlobalValue and the offset) if the node is a
3874 /// GlobalAddress + offset.
3875 bool TargetLowering::isGAPlusOffset(SDNode
*WN
, const GlobalValue
*&GA
,
3876 int64_t &Offset
) const {
3878 SDNode
*N
= unwrapAddress(SDValue(WN
, 0)).getNode();
3880 if (auto *GASD
= dyn_cast
<GlobalAddressSDNode
>(N
)) {
3881 GA
= GASD
->getGlobal();
3882 Offset
+= GASD
->getOffset();
3886 if (N
->getOpcode() == ISD::ADD
) {
3887 SDValue N1
= N
->getOperand(0);
3888 SDValue N2
= N
->getOperand(1);
3889 if (isGAPlusOffset(N1
.getNode(), GA
, Offset
)) {
3890 if (auto *V
= dyn_cast
<ConstantSDNode
>(N2
)) {
3891 Offset
+= V
->getSExtValue();
3894 } else if (isGAPlusOffset(N2
.getNode(), GA
, Offset
)) {
3895 if (auto *V
= dyn_cast
<ConstantSDNode
>(N1
)) {
3896 Offset
+= V
->getSExtValue();
3905 SDValue
TargetLowering::PerformDAGCombine(SDNode
*N
,
3906 DAGCombinerInfo
&DCI
) const {
3907 // Default implementation: no optimization.
3911 //===----------------------------------------------------------------------===//
3912 // Inline Assembler Implementation Methods
3913 //===----------------------------------------------------------------------===//
3915 TargetLowering::ConstraintType
3916 TargetLowering::getConstraintType(StringRef Constraint
) const {
3917 unsigned S
= Constraint
.size();
3920 switch (Constraint
[0]) {
3923 return C_RegisterClass
;
3925 case 'o': // offsetable
3926 case 'V': // not offsetable
3928 case 'n': // Simple Integer
3929 case 'E': // Floating Point Constant
3930 case 'F': // Floating Point Constant
3932 case 'i': // Simple Integer or Relocatable Constant
3933 case 's': // Relocatable Constant
3934 case 'p': // Address.
3935 case 'X': // Allow ANY value.
3936 case 'I': // Target registers.
3950 if (S
> 1 && Constraint
[0] == '{' && Constraint
[S
- 1] == '}') {
3951 if (S
== 8 && Constraint
.substr(1, 6) == "memory") // "{memory}"
3958 /// Try to replace an X constraint, which matches anything, with another that
3959 /// has more specific requirements based on the type of the corresponding
3961 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT
) const {
3962 if (ConstraintVT
.isInteger())
3964 if (ConstraintVT
.isFloatingPoint())
3965 return "f"; // works for many targets
3969 SDValue
TargetLowering::LowerAsmOutputForConstraint(
3970 SDValue
&Chain
, SDValue
&Flag
, SDLoc DL
, const AsmOperandInfo
&OpInfo
,
3971 SelectionDAG
&DAG
) const {
3975 /// Lower the specified operand into the Ops vector.
3976 /// If it is invalid, don't add anything to Ops.
3977 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op
,
3978 std::string
&Constraint
,
3979 std::vector
<SDValue
> &Ops
,
3980 SelectionDAG
&DAG
) const {
3982 if (Constraint
.length() > 1) return;
3984 char ConstraintLetter
= Constraint
[0];
3985 switch (ConstraintLetter
) {
3987 case 'X': // Allows any operand; labels (basic block) use this.
3988 if (Op
.getOpcode() == ISD::BasicBlock
||
3989 Op
.getOpcode() == ISD::TargetBlockAddress
) {
3994 case 'i': // Simple Integer or Relocatable Constant
3995 case 'n': // Simple Integer
3996 case 's': { // Relocatable Constant
3998 GlobalAddressSDNode
*GA
;
4000 BlockAddressSDNode
*BA
;
4001 uint64_t Offset
= 0;
4003 // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
4004 // etc., since getelementpointer is variadic. We can't use
4005 // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
4006 // while in this case the GA may be furthest from the root node which is
4007 // likely an ISD::ADD.
4009 if ((GA
= dyn_cast
<GlobalAddressSDNode
>(Op
)) && ConstraintLetter
!= 'n') {
4010 Ops
.push_back(DAG
.getTargetGlobalAddress(GA
->getGlobal(), SDLoc(Op
),
4011 GA
->getValueType(0),
4012 Offset
+ GA
->getOffset()));
4014 } else if ((C
= dyn_cast
<ConstantSDNode
>(Op
)) &&
4015 ConstraintLetter
!= 's') {
4016 // gcc prints these as sign extended. Sign extend value to 64 bits
4017 // now; without this it would get ZExt'd later in
4018 // ScheduleDAGSDNodes::EmitNode, which is very generic.
4019 bool IsBool
= C
->getConstantIntValue()->getBitWidth() == 1;
4020 BooleanContent BCont
= getBooleanContents(MVT::i64
);
4021 ISD::NodeType ExtOpc
= IsBool
? getExtendForContent(BCont
)
4023 int64_t ExtVal
= ExtOpc
== ISD::ZERO_EXTEND
? C
->getZExtValue()
4024 : C
->getSExtValue();
4025 Ops
.push_back(DAG
.getTargetConstant(Offset
+ ExtVal
,
4026 SDLoc(C
), MVT::i64
));
4028 } else if ((BA
= dyn_cast
<BlockAddressSDNode
>(Op
)) &&
4029 ConstraintLetter
!= 'n') {
4030 Ops
.push_back(DAG
.getTargetBlockAddress(
4031 BA
->getBlockAddress(), BA
->getValueType(0),
4032 Offset
+ BA
->getOffset(), BA
->getTargetFlags()));
4035 const unsigned OpCode
= Op
.getOpcode();
4036 if (OpCode
== ISD::ADD
|| OpCode
== ISD::SUB
) {
4037 if ((C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(0))))
4038 Op
= Op
.getOperand(1);
4039 // Subtraction is not commutative.
4040 else if (OpCode
== ISD::ADD
&&
4041 (C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1))))
4042 Op
= Op
.getOperand(0);
4045 Offset
+= (OpCode
== ISD::ADD
? 1 : -1) * C
->getSExtValue();
4056 std::pair
<unsigned, const TargetRegisterClass
*>
4057 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo
*RI
,
4058 StringRef Constraint
,
4060 if (Constraint
.empty() || Constraint
[0] != '{')
4061 return std::make_pair(0u, static_cast<TargetRegisterClass
*>(nullptr));
4062 assert(*(Constraint
.end() - 1) == '}' && "Not a brace enclosed constraint?");
4064 // Remove the braces from around the name.
4065 StringRef
RegName(Constraint
.data() + 1, Constraint
.size() - 2);
4067 std::pair
<unsigned, const TargetRegisterClass
*> R
=
4068 std::make_pair(0u, static_cast<const TargetRegisterClass
*>(nullptr));
4070 // Figure out which register class contains this reg.
4071 for (const TargetRegisterClass
*RC
: RI
->regclasses()) {
4072 // If none of the value types for this register class are valid, we
4073 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4074 if (!isLegalRC(*RI
, *RC
))
4077 for (TargetRegisterClass::iterator I
= RC
->begin(), E
= RC
->end();
4079 if (RegName
.equals_lower(RI
->getRegAsmName(*I
))) {
4080 std::pair
<unsigned, const TargetRegisterClass
*> S
=
4081 std::make_pair(*I
, RC
);
4083 // If this register class has the requested value type, return it,
4084 // otherwise keep searching and return the first class found
4085 // if no other is found which explicitly has the requested type.
4086 if (RI
->isTypeLegalForClass(*RC
, VT
))
4097 //===----------------------------------------------------------------------===//
4098 // Constraint Selection.
4100 /// Return true of this is an input operand that is a matching constraint like
4102 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
4103 assert(!ConstraintCode
.empty() && "No known constraint!");
4104 return isdigit(static_cast<unsigned char>(ConstraintCode
[0]));
4107 /// If this is an input matching constraint, this method returns the output
4108 /// operand it matches.
4109 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
4110 assert(!ConstraintCode
.empty() && "No known constraint!");
4111 return atoi(ConstraintCode
.c_str());
4114 /// Split up the constraint string from the inline assembly value into the
4115 /// specific constraints and their prefixes, and also tie in the associated
4117 /// If this returns an empty vector, and if the constraint string itself
4118 /// isn't empty, there was an error parsing.
4119 TargetLowering::AsmOperandInfoVector
4120 TargetLowering::ParseConstraints(const DataLayout
&DL
,
4121 const TargetRegisterInfo
*TRI
,
4122 ImmutableCallSite CS
) const {
4123 /// Information about all of the constraints.
4124 AsmOperandInfoVector ConstraintOperands
;
4125 const InlineAsm
*IA
= cast
<InlineAsm
>(CS
.getCalledValue());
4126 unsigned maCount
= 0; // Largest number of multiple alternative constraints.
4128 // Do a prepass over the constraints, canonicalizing them, and building up the
4129 // ConstraintOperands list.
4130 unsigned ArgNo
= 0; // ArgNo - The argument of the CallInst.
4131 unsigned ResNo
= 0; // ResNo - The result number of the next output.
4133 for (InlineAsm::ConstraintInfo
&CI
: IA
->ParseConstraints()) {
4134 ConstraintOperands
.emplace_back(std::move(CI
));
4135 AsmOperandInfo
&OpInfo
= ConstraintOperands
.back();
4137 // Update multiple alternative constraint count.
4138 if (OpInfo
.multipleAlternatives
.size() > maCount
)
4139 maCount
= OpInfo
.multipleAlternatives
.size();
4141 OpInfo
.ConstraintVT
= MVT::Other
;
4143 // Compute the value type for each operand.
4144 switch (OpInfo
.Type
) {
4145 case InlineAsm::isOutput
:
4146 // Indirect outputs just consume an argument.
4147 if (OpInfo
.isIndirect
) {
4148 OpInfo
.CallOperandVal
= const_cast<Value
*>(CS
.getArgument(ArgNo
++));
4152 // The return value of the call is this value. As such, there is no
4153 // corresponding argument.
4154 assert(!CS
.getType()->isVoidTy() &&
4156 if (StructType
*STy
= dyn_cast
<StructType
>(CS
.getType())) {
4157 OpInfo
.ConstraintVT
=
4158 getSimpleValueType(DL
, STy
->getElementType(ResNo
));
4160 assert(ResNo
== 0 && "Asm only has one result!");
4161 OpInfo
.ConstraintVT
= getSimpleValueType(DL
, CS
.getType());
4165 case InlineAsm::isInput
:
4166 OpInfo
.CallOperandVal
= const_cast<Value
*>(CS
.getArgument(ArgNo
++));
4168 case InlineAsm::isClobber
:
4173 if (OpInfo
.CallOperandVal
) {
4174 llvm::Type
*OpTy
= OpInfo
.CallOperandVal
->getType();
4175 if (OpInfo
.isIndirect
) {
4176 llvm::PointerType
*PtrTy
= dyn_cast
<PointerType
>(OpTy
);
4178 report_fatal_error("Indirect operand for inline asm not a pointer!");
4179 OpTy
= PtrTy
->getElementType();
4182 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
4183 if (StructType
*STy
= dyn_cast
<StructType
>(OpTy
))
4184 if (STy
->getNumElements() == 1)
4185 OpTy
= STy
->getElementType(0);
4187 // If OpTy is not a single value, it may be a struct/union that we
4188 // can tile with integers.
4189 if (!OpTy
->isSingleValueType() && OpTy
->isSized()) {
4190 unsigned BitSize
= DL
.getTypeSizeInBits(OpTy
);
4199 OpInfo
.ConstraintVT
=
4200 MVT::getVT(IntegerType::get(OpTy
->getContext(), BitSize
), true);
4203 } else if (PointerType
*PT
= dyn_cast
<PointerType
>(OpTy
)) {
4204 unsigned PtrSize
= DL
.getPointerSizeInBits(PT
->getAddressSpace());
4205 OpInfo
.ConstraintVT
= MVT::getIntegerVT(PtrSize
);
4207 OpInfo
.ConstraintVT
= MVT::getVT(OpTy
, true);
4212 // If we have multiple alternative constraints, select the best alternative.
4213 if (!ConstraintOperands
.empty()) {
4215 unsigned bestMAIndex
= 0;
4216 int bestWeight
= -1;
4217 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
4220 // Compute the sums of the weights for each alternative, keeping track
4221 // of the best (highest weight) one so far.
4222 for (maIndex
= 0; maIndex
< maCount
; ++maIndex
) {
4224 for (unsigned cIndex
= 0, eIndex
= ConstraintOperands
.size();
4225 cIndex
!= eIndex
; ++cIndex
) {
4226 AsmOperandInfo
&OpInfo
= ConstraintOperands
[cIndex
];
4227 if (OpInfo
.Type
== InlineAsm::isClobber
)
4230 // If this is an output operand with a matching input operand,
4231 // look up the matching input. If their types mismatch, e.g. one
4232 // is an integer, the other is floating point, or their sizes are
4233 // different, flag it as an maCantMatch.
4234 if (OpInfo
.hasMatchingInput()) {
4235 AsmOperandInfo
&Input
= ConstraintOperands
[OpInfo
.MatchingInput
];
4236 if (OpInfo
.ConstraintVT
!= Input
.ConstraintVT
) {
4237 if ((OpInfo
.ConstraintVT
.isInteger() !=
4238 Input
.ConstraintVT
.isInteger()) ||
4239 (OpInfo
.ConstraintVT
.getSizeInBits() !=
4240 Input
.ConstraintVT
.getSizeInBits())) {
4241 weightSum
= -1; // Can't match.
4246 weight
= getMultipleConstraintMatchWeight(OpInfo
, maIndex
);
4251 weightSum
+= weight
;
4254 if (weightSum
> bestWeight
) {
4255 bestWeight
= weightSum
;
4256 bestMAIndex
= maIndex
;
4260 // Now select chosen alternative in each constraint.
4261 for (unsigned cIndex
= 0, eIndex
= ConstraintOperands
.size();
4262 cIndex
!= eIndex
; ++cIndex
) {
4263 AsmOperandInfo
&cInfo
= ConstraintOperands
[cIndex
];
4264 if (cInfo
.Type
== InlineAsm::isClobber
)
4266 cInfo
.selectAlternative(bestMAIndex
);
4271 // Check and hook up tied operands, choose constraint code to use.
4272 for (unsigned cIndex
= 0, eIndex
= ConstraintOperands
.size();
4273 cIndex
!= eIndex
; ++cIndex
) {
4274 AsmOperandInfo
&OpInfo
= ConstraintOperands
[cIndex
];
4276 // If this is an output operand with a matching input operand, look up the
4277 // matching input. If their types mismatch, e.g. one is an integer, the
4278 // other is floating point, or their sizes are different, flag it as an
4280 if (OpInfo
.hasMatchingInput()) {
4281 AsmOperandInfo
&Input
= ConstraintOperands
[OpInfo
.MatchingInput
];
4283 if (OpInfo
.ConstraintVT
!= Input
.ConstraintVT
) {
4284 std::pair
<unsigned, const TargetRegisterClass
*> MatchRC
=
4285 getRegForInlineAsmConstraint(TRI
, OpInfo
.ConstraintCode
,
4286 OpInfo
.ConstraintVT
);
4287 std::pair
<unsigned, const TargetRegisterClass
*> InputRC
=
4288 getRegForInlineAsmConstraint(TRI
, Input
.ConstraintCode
,
4289 Input
.ConstraintVT
);
4290 if ((OpInfo
.ConstraintVT
.isInteger() !=
4291 Input
.ConstraintVT
.isInteger()) ||
4292 (MatchRC
.second
!= InputRC
.second
)) {
4293 report_fatal_error("Unsupported asm: input constraint"
4294 " with a matching output constraint of"
4295 " incompatible type!");
4301 return ConstraintOperands
;
4304 /// Return an integer indicating how general CT is.
4305 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT
) {
4307 case TargetLowering::C_Immediate
:
4308 case TargetLowering::C_Other
:
4309 case TargetLowering::C_Unknown
:
4311 case TargetLowering::C_Register
:
4313 case TargetLowering::C_RegisterClass
:
4315 case TargetLowering::C_Memory
:
4318 llvm_unreachable("Invalid constraint type");
4321 /// Examine constraint type and operand type and determine a weight value.
4322 /// This object must already have been set up with the operand type
4323 /// and the current alternative constraint selected.
4324 TargetLowering::ConstraintWeight
4325 TargetLowering::getMultipleConstraintMatchWeight(
4326 AsmOperandInfo
&info
, int maIndex
) const {
4327 InlineAsm::ConstraintCodeVector
*rCodes
;
4328 if (maIndex
>= (int)info
.multipleAlternatives
.size())
4329 rCodes
= &info
.Codes
;
4331 rCodes
= &info
.multipleAlternatives
[maIndex
].Codes
;
4332 ConstraintWeight BestWeight
= CW_Invalid
;
4334 // Loop over the options, keeping track of the most general one.
4335 for (unsigned i
= 0, e
= rCodes
->size(); i
!= e
; ++i
) {
4336 ConstraintWeight weight
=
4337 getSingleConstraintMatchWeight(info
, (*rCodes
)[i
].c_str());
4338 if (weight
> BestWeight
)
4339 BestWeight
= weight
;
4345 /// Examine constraint type and operand type and determine a weight value.
4346 /// This object must already have been set up with the operand type
4347 /// and the current alternative constraint selected.
4348 TargetLowering::ConstraintWeight
4349 TargetLowering::getSingleConstraintMatchWeight(
4350 AsmOperandInfo
&info
, const char *constraint
) const {
4351 ConstraintWeight weight
= CW_Invalid
;
4352 Value
*CallOperandVal
= info
.CallOperandVal
;
4353 // If we don't have a value, we can't do a match,
4354 // but allow it at the lowest weight.
4355 if (!CallOperandVal
)
4357 // Look at the constraint type.
4358 switch (*constraint
) {
4359 case 'i': // immediate integer.
4360 case 'n': // immediate integer with a known value.
4361 if (isa
<ConstantInt
>(CallOperandVal
))
4362 weight
= CW_Constant
;
4364 case 's': // non-explicit intregal immediate.
4365 if (isa
<GlobalValue
>(CallOperandVal
))
4366 weight
= CW_Constant
;
4368 case 'E': // immediate float if host format.
4369 case 'F': // immediate float.
4370 if (isa
<ConstantFP
>(CallOperandVal
))
4371 weight
= CW_Constant
;
4373 case '<': // memory operand with autodecrement.
4374 case '>': // memory operand with autoincrement.
4375 case 'm': // memory operand.
4376 case 'o': // offsettable memory operand
4377 case 'V': // non-offsettable memory operand
4380 case 'r': // general register.
4381 case 'g': // general register, memory operand or immediate integer.
4382 // note: Clang converts "g" to "imr".
4383 if (CallOperandVal
->getType()->isIntegerTy())
4384 weight
= CW_Register
;
4386 case 'X': // any operand.
4388 weight
= CW_Default
;
4394 /// If there are multiple different constraints that we could pick for this
4395 /// operand (e.g. "imr") try to pick the 'best' one.
4396 /// This is somewhat tricky: constraints fall into four classes:
4397 /// Other -> immediates and magic values
4398 /// Register -> one specific register
4399 /// RegisterClass -> a group of regs
4400 /// Memory -> memory
4401 /// Ideally, we would pick the most specific constraint possible: if we have
4402 /// something that fits into a register, we would pick it. The problem here
4403 /// is that if we have something that could either be in a register or in
4404 /// memory that use of the register could cause selection of *other*
4405 /// operands to fail: they might only succeed if we pick memory. Because of
4406 /// this the heuristic we use is:
4408 /// 1) If there is an 'other' constraint, and if the operand is valid for
4409 /// that constraint, use it. This makes us take advantage of 'i'
4410 /// constraints when available.
4411 /// 2) Otherwise, pick the most general constraint present. This prefers
4412 /// 'm' over 'r', for example.
4414 static void ChooseConstraint(TargetLowering::AsmOperandInfo
&OpInfo
,
4415 const TargetLowering
&TLI
,
4416 SDValue Op
, SelectionDAG
*DAG
) {
4417 assert(OpInfo
.Codes
.size() > 1 && "Doesn't have multiple constraint options");
4418 unsigned BestIdx
= 0;
4419 TargetLowering::ConstraintType BestType
= TargetLowering::C_Unknown
;
4420 int BestGenerality
= -1;
4422 // Loop over the options, keeping track of the most general one.
4423 for (unsigned i
= 0, e
= OpInfo
.Codes
.size(); i
!= e
; ++i
) {
4424 TargetLowering::ConstraintType CType
=
4425 TLI
.getConstraintType(OpInfo
.Codes
[i
]);
4427 // If this is an 'other' or 'immediate' constraint, see if the operand is
4428 // valid for it. For example, on X86 we might have an 'rI' constraint. If
4429 // the operand is an integer in the range [0..31] we want to use I (saving a
4430 // load of a register), otherwise we must use 'r'.
4431 if ((CType
== TargetLowering::C_Other
||
4432 CType
== TargetLowering::C_Immediate
) && Op
.getNode()) {
4433 assert(OpInfo
.Codes
[i
].size() == 1 &&
4434 "Unhandled multi-letter 'other' constraint");
4435 std::vector
<SDValue
> ResultOps
;
4436 TLI
.LowerAsmOperandForConstraint(Op
, OpInfo
.Codes
[i
],
4438 if (!ResultOps
.empty()) {
4445 // Things with matching constraints can only be registers, per gcc
4446 // documentation. This mainly affects "g" constraints.
4447 if (CType
== TargetLowering::C_Memory
&& OpInfo
.hasMatchingInput())
4450 // This constraint letter is more general than the previous one, use it.
4451 int Generality
= getConstraintGenerality(CType
);
4452 if (Generality
> BestGenerality
) {
4455 BestGenerality
= Generality
;
4459 OpInfo
.ConstraintCode
= OpInfo
.Codes
[BestIdx
];
4460 OpInfo
.ConstraintType
= BestType
;
4463 /// Determines the constraint code and constraint type to use for the specific
4464 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
4465 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo
&OpInfo
,
4467 SelectionDAG
*DAG
) const {
4468 assert(!OpInfo
.Codes
.empty() && "Must have at least one constraint");
4470 // Single-letter constraints ('r') are very common.
4471 if (OpInfo
.Codes
.size() == 1) {
4472 OpInfo
.ConstraintCode
= OpInfo
.Codes
[0];
4473 OpInfo
.ConstraintType
= getConstraintType(OpInfo
.ConstraintCode
);
4475 ChooseConstraint(OpInfo
, *this, Op
, DAG
);
4478 // 'X' matches anything.
4479 if (OpInfo
.ConstraintCode
== "X" && OpInfo
.CallOperandVal
) {
4480 // Labels and constants are handled elsewhere ('X' is the only thing
4481 // that matches labels). For Functions, the type here is the type of
4482 // the result, which is not what we want to look at; leave them alone.
4483 Value
*v
= OpInfo
.CallOperandVal
;
4484 if (isa
<BasicBlock
>(v
) || isa
<ConstantInt
>(v
) || isa
<Function
>(v
)) {
4485 OpInfo
.CallOperandVal
= v
;
4489 if (Op
.getNode() && Op
.getOpcode() == ISD::TargetBlockAddress
)
4492 // Otherwise, try to resolve it to something we know about by looking at
4493 // the actual operand type.
4494 if (const char *Repl
= LowerXConstraint(OpInfo
.ConstraintVT
)) {
4495 OpInfo
.ConstraintCode
= Repl
;
4496 OpInfo
.ConstraintType
= getConstraintType(OpInfo
.ConstraintCode
);
4501 /// Given an exact SDIV by a constant, create a multiplication
4502 /// with the multiplicative inverse of the constant.
4503 static SDValue
BuildExactSDIV(const TargetLowering
&TLI
, SDNode
*N
,
4504 const SDLoc
&dl
, SelectionDAG
&DAG
,
4505 SmallVectorImpl
<SDNode
*> &Created
) {
4506 SDValue Op0
= N
->getOperand(0);
4507 SDValue Op1
= N
->getOperand(1);
4508 EVT VT
= N
->getValueType(0);
4509 EVT SVT
= VT
.getScalarType();
4510 EVT ShVT
= TLI
.getShiftAmountTy(VT
, DAG
.getDataLayout());
4511 EVT ShSVT
= ShVT
.getScalarType();
4513 bool UseSRA
= false;
4514 SmallVector
<SDValue
, 16> Shifts
, Factors
;
4516 auto BuildSDIVPattern
= [&](ConstantSDNode
*C
) {
4517 if (C
->isNullValue())
4519 APInt Divisor
= C
->getAPIntValue();
4520 unsigned Shift
= Divisor
.countTrailingZeros();
4522 Divisor
.ashrInPlace(Shift
);
4525 // Calculate the multiplicative inverse, using Newton's method.
4527 APInt Factor
= Divisor
;
4528 while ((t
= Divisor
* Factor
) != 1)
4529 Factor
*= APInt(Divisor
.getBitWidth(), 2) - t
;
4530 Shifts
.push_back(DAG
.getConstant(Shift
, dl
, ShSVT
));
4531 Factors
.push_back(DAG
.getConstant(Factor
, dl
, SVT
));
4535 // Collect all magic values from the build vector.
4536 if (!ISD::matchUnaryPredicate(Op1
, BuildSDIVPattern
))
4539 SDValue Shift
, Factor
;
4540 if (VT
.isVector()) {
4541 Shift
= DAG
.getBuildVector(ShVT
, dl
, Shifts
);
4542 Factor
= DAG
.getBuildVector(VT
, dl
, Factors
);
4545 Factor
= Factors
[0];
4550 // Shift the value upfront if it is even, so the LSB is one.
4552 // TODO: For UDIV use SRL instead of SRA.
4554 Flags
.setExact(true);
4555 Res
= DAG
.getNode(ISD::SRA
, dl
, VT
, Res
, Shift
, Flags
);
4556 Created
.push_back(Res
.getNode());
4559 return DAG
.getNode(ISD::MUL
, dl
, VT
, Res
, Factor
);
4562 SDValue
TargetLowering::BuildSDIVPow2(SDNode
*N
, const APInt
&Divisor
,
4564 SmallVectorImpl
<SDNode
*> &Created
) const {
4565 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
4566 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
4567 if (TLI
.isIntDivCheap(N
->getValueType(0), Attr
))
4568 return SDValue(N
, 0); // Lower SDIV as SDIV
4572 /// Given an ISD::SDIV node expressing a divide by constant,
4573 /// return a DAG expression to select that will generate the same value by
4574 /// multiplying by a magic number.
4575 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4576 SDValue
TargetLowering::BuildSDIV(SDNode
*N
, SelectionDAG
&DAG
,
4577 bool IsAfterLegalization
,
4578 SmallVectorImpl
<SDNode
*> &Created
) const {
4580 EVT VT
= N
->getValueType(0);
4581 EVT SVT
= VT
.getScalarType();
4582 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
4583 EVT ShSVT
= ShVT
.getScalarType();
4584 unsigned EltBits
= VT
.getScalarSizeInBits();
4586 // Check to see if we can do this.
4587 // FIXME: We should be more aggressive here.
4588 if (!isTypeLegal(VT
))
4591 // If the sdiv has an 'exact' bit we can use a simpler lowering.
4592 if (N
->getFlags().hasExact())
4593 return BuildExactSDIV(*this, N
, dl
, DAG
, Created
);
4595 SmallVector
<SDValue
, 16> MagicFactors
, Factors
, Shifts
, ShiftMasks
;
4597 auto BuildSDIVPattern
= [&](ConstantSDNode
*C
) {
4598 if (C
->isNullValue())
4601 const APInt
&Divisor
= C
->getAPIntValue();
4602 APInt::ms magics
= Divisor
.magic();
4603 int NumeratorFactor
= 0;
4606 if (Divisor
.isOneValue() || Divisor
.isAllOnesValue()) {
4607 // If d is +1/-1, we just multiply the numerator by +1/-1.
4608 NumeratorFactor
= Divisor
.getSExtValue();
4612 } else if (Divisor
.isStrictlyPositive() && magics
.m
.isNegative()) {
4613 // If d > 0 and m < 0, add the numerator.
4614 NumeratorFactor
= 1;
4615 } else if (Divisor
.isNegative() && magics
.m
.isStrictlyPositive()) {
4616 // If d < 0 and m > 0, subtract the numerator.
4617 NumeratorFactor
= -1;
4620 MagicFactors
.push_back(DAG
.getConstant(magics
.m
, dl
, SVT
));
4621 Factors
.push_back(DAG
.getConstant(NumeratorFactor
, dl
, SVT
));
4622 Shifts
.push_back(DAG
.getConstant(magics
.s
, dl
, ShSVT
));
4623 ShiftMasks
.push_back(DAG
.getConstant(ShiftMask
, dl
, SVT
));
4627 SDValue N0
= N
->getOperand(0);
4628 SDValue N1
= N
->getOperand(1);
4630 // Collect the shifts / magic values from each element.
4631 if (!ISD::matchUnaryPredicate(N1
, BuildSDIVPattern
))
4634 SDValue MagicFactor
, Factor
, Shift
, ShiftMask
;
4635 if (VT
.isVector()) {
4636 MagicFactor
= DAG
.getBuildVector(VT
, dl
, MagicFactors
);
4637 Factor
= DAG
.getBuildVector(VT
, dl
, Factors
);
4638 Shift
= DAG
.getBuildVector(ShVT
, dl
, Shifts
);
4639 ShiftMask
= DAG
.getBuildVector(VT
, dl
, ShiftMasks
);
4641 MagicFactor
= MagicFactors
[0];
4642 Factor
= Factors
[0];
4644 ShiftMask
= ShiftMasks
[0];
4647 // Multiply the numerator (operand 0) by the magic value.
4648 // FIXME: We should support doing a MUL in a wider type.
4650 if (IsAfterLegalization
? isOperationLegal(ISD::MULHS
, VT
)
4651 : isOperationLegalOrCustom(ISD::MULHS
, VT
))
4652 Q
= DAG
.getNode(ISD::MULHS
, dl
, VT
, N0
, MagicFactor
);
4653 else if (IsAfterLegalization
? isOperationLegal(ISD::SMUL_LOHI
, VT
)
4654 : isOperationLegalOrCustom(ISD::SMUL_LOHI
, VT
)) {
4656 DAG
.getNode(ISD::SMUL_LOHI
, dl
, DAG
.getVTList(VT
, VT
), N0
, MagicFactor
);
4657 Q
= SDValue(LoHi
.getNode(), 1);
4659 return SDValue(); // No mulhs or equivalent.
4660 Created
.push_back(Q
.getNode());
4662 // (Optionally) Add/subtract the numerator using Factor.
4663 Factor
= DAG
.getNode(ISD::MUL
, dl
, VT
, N0
, Factor
);
4664 Created
.push_back(Factor
.getNode());
4665 Q
= DAG
.getNode(ISD::ADD
, dl
, VT
, Q
, Factor
);
4666 Created
.push_back(Q
.getNode());
4668 // Shift right algebraic by shift value.
4669 Q
= DAG
.getNode(ISD::SRA
, dl
, VT
, Q
, Shift
);
4670 Created
.push_back(Q
.getNode());
4672 // Extract the sign bit, mask it and add it to the quotient.
4673 SDValue SignShift
= DAG
.getConstant(EltBits
- 1, dl
, ShVT
);
4674 SDValue T
= DAG
.getNode(ISD::SRL
, dl
, VT
, Q
, SignShift
);
4675 Created
.push_back(T
.getNode());
4676 T
= DAG
.getNode(ISD::AND
, dl
, VT
, T
, ShiftMask
);
4677 Created
.push_back(T
.getNode());
4678 return DAG
.getNode(ISD::ADD
, dl
, VT
, Q
, T
);
4681 /// Given an ISD::UDIV node expressing a divide by constant,
4682 /// return a DAG expression to select that will generate the same value by
4683 /// multiplying by a magic number.
4684 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4685 SDValue
TargetLowering::BuildUDIV(SDNode
*N
, SelectionDAG
&DAG
,
4686 bool IsAfterLegalization
,
4687 SmallVectorImpl
<SDNode
*> &Created
) const {
4689 EVT VT
= N
->getValueType(0);
4690 EVT SVT
= VT
.getScalarType();
4691 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
4692 EVT ShSVT
= ShVT
.getScalarType();
4693 unsigned EltBits
= VT
.getScalarSizeInBits();
4695 // Check to see if we can do this.
4696 // FIXME: We should be more aggressive here.
4697 if (!isTypeLegal(VT
))
4700 bool UseNPQ
= false;
4701 SmallVector
<SDValue
, 16> PreShifts
, PostShifts
, MagicFactors
, NPQFactors
;
4703 auto BuildUDIVPattern
= [&](ConstantSDNode
*C
) {
4704 if (C
->isNullValue())
4706 // FIXME: We should use a narrower constant when the upper
4707 // bits are known to be zero.
4708 APInt Divisor
= C
->getAPIntValue();
4709 APInt::mu magics
= Divisor
.magicu();
4710 unsigned PreShift
= 0, PostShift
= 0;
4712 // If the divisor is even, we can avoid using the expensive fixup by
4713 // shifting the divided value upfront.
4714 if (magics
.a
!= 0 && !Divisor
[0]) {
4715 PreShift
= Divisor
.countTrailingZeros();
4716 // Get magic number for the shifted divisor.
4717 magics
= Divisor
.lshr(PreShift
).magicu(PreShift
);
4718 assert(magics
.a
== 0 && "Should use cheap fixup now");
4721 APInt Magic
= magics
.m
;
4724 if (magics
.a
== 0 || Divisor
.isOneValue()) {
4725 assert(magics
.s
< Divisor
.getBitWidth() &&
4726 "We shouldn't generate an undefined shift!");
4727 PostShift
= magics
.s
;
4730 PostShift
= magics
.s
- 1;
4734 PreShifts
.push_back(DAG
.getConstant(PreShift
, dl
, ShSVT
));
4735 MagicFactors
.push_back(DAG
.getConstant(Magic
, dl
, SVT
));
4736 NPQFactors
.push_back(
4737 DAG
.getConstant(SelNPQ
? APInt::getOneBitSet(EltBits
, EltBits
- 1)
4738 : APInt::getNullValue(EltBits
),
4740 PostShifts
.push_back(DAG
.getConstant(PostShift
, dl
, ShSVT
));
4745 SDValue N0
= N
->getOperand(0);
4746 SDValue N1
= N
->getOperand(1);
4748 // Collect the shifts/magic values from each element.
4749 if (!ISD::matchUnaryPredicate(N1
, BuildUDIVPattern
))
4752 SDValue PreShift
, PostShift
, MagicFactor
, NPQFactor
;
4753 if (VT
.isVector()) {
4754 PreShift
= DAG
.getBuildVector(ShVT
, dl
, PreShifts
);
4755 MagicFactor
= DAG
.getBuildVector(VT
, dl
, MagicFactors
);
4756 NPQFactor
= DAG
.getBuildVector(VT
, dl
, NPQFactors
);
4757 PostShift
= DAG
.getBuildVector(ShVT
, dl
, PostShifts
);
4759 PreShift
= PreShifts
[0];
4760 MagicFactor
= MagicFactors
[0];
4761 PostShift
= PostShifts
[0];
4765 Q
= DAG
.getNode(ISD::SRL
, dl
, VT
, Q
, PreShift
);
4766 Created
.push_back(Q
.getNode());
4768 // FIXME: We should support doing a MUL in a wider type.
4769 auto GetMULHU
= [&](SDValue X
, SDValue Y
) {
4770 if (IsAfterLegalization
? isOperationLegal(ISD::MULHU
, VT
)
4771 : isOperationLegalOrCustom(ISD::MULHU
, VT
))
4772 return DAG
.getNode(ISD::MULHU
, dl
, VT
, X
, Y
);
4773 if (IsAfterLegalization
? isOperationLegal(ISD::UMUL_LOHI
, VT
)
4774 : isOperationLegalOrCustom(ISD::UMUL_LOHI
, VT
)) {
4776 DAG
.getNode(ISD::UMUL_LOHI
, dl
, DAG
.getVTList(VT
, VT
), X
, Y
);
4777 return SDValue(LoHi
.getNode(), 1);
4779 return SDValue(); // No mulhu or equivalent
4782 // Multiply the numerator (operand 0) by the magic value.
4783 Q
= GetMULHU(Q
, MagicFactor
);
4787 Created
.push_back(Q
.getNode());
4790 SDValue NPQ
= DAG
.getNode(ISD::SUB
, dl
, VT
, N0
, Q
);
4791 Created
.push_back(NPQ
.getNode());
4793 // For vectors we might have a mix of non-NPQ/NPQ paths, so use
4794 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
4796 NPQ
= GetMULHU(NPQ
, NPQFactor
);
4798 NPQ
= DAG
.getNode(ISD::SRL
, dl
, VT
, NPQ
, DAG
.getConstant(1, dl
, ShVT
));
4800 Created
.push_back(NPQ
.getNode());
4802 Q
= DAG
.getNode(ISD::ADD
, dl
, VT
, NPQ
, Q
);
4803 Created
.push_back(Q
.getNode());
4806 Q
= DAG
.getNode(ISD::SRL
, dl
, VT
, Q
, PostShift
);
4807 Created
.push_back(Q
.getNode());
4809 SDValue One
= DAG
.getConstant(1, dl
, VT
);
4810 SDValue IsOne
= DAG
.getSetCC(dl
, VT
, N1
, One
, ISD::SETEQ
);
4811 return DAG
.getSelect(dl
, VT
, IsOne
, N0
, Q
);
4814 /// If all values in Values that *don't* match the predicate are same 'splat'
4815 /// value, then replace all values with that splat value.
4816 /// Else, if AlternativeReplacement was provided, then replace all values that
4817 /// do match predicate with AlternativeReplacement value.
4819 turnVectorIntoSplatVector(MutableArrayRef
<SDValue
> Values
,
4820 std::function
<bool(SDValue
)> Predicate
,
4821 SDValue AlternativeReplacement
= SDValue()) {
4822 SDValue Replacement
;
4823 // Is there a value for which the Predicate does *NOT* match? What is it?
4824 auto SplatValue
= llvm::find_if_not(Values
, Predicate
);
4825 if (SplatValue
!= Values
.end()) {
4826 // Does Values consist only of SplatValue's and values matching Predicate?
4827 if (llvm::all_of(Values
, [Predicate
, SplatValue
](SDValue Value
) {
4828 return Value
== *SplatValue
|| Predicate(Value
);
4829 })) // Then we shall replace values matching predicate with SplatValue.
4830 Replacement
= *SplatValue
;
4833 // Oops, we did not find the "baseline" splat value.
4834 if (!AlternativeReplacement
)
4835 return; // Nothing to do.
4836 // Let's replace with provided value then.
4837 Replacement
= AlternativeReplacement
;
4839 std::replace_if(Values
.begin(), Values
.end(), Predicate
, Replacement
);
4842 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
4843 /// where the divisor is constant and the comparison target is zero,
4844 /// return a DAG expression that will generate the same comparison result
4845 /// using only multiplications, additions and shifts/rotations.
4846 /// Ref: "Hacker's Delight" 10-17.
4847 SDValue
TargetLowering::buildUREMEqFold(EVT SETCCVT
, SDValue REMNode
,
4848 SDValue CompTargetNode
,
4850 DAGCombinerInfo
&DCI
,
4851 const SDLoc
&DL
) const {
4852 SmallVector
<SDNode
*, 2> Built
;
4853 if (SDValue Folded
= prepareUREMEqFold(SETCCVT
, REMNode
, CompTargetNode
, Cond
,
4855 for (SDNode
*N
: Built
)
4856 DCI
.AddToWorklist(N
);
4864 TargetLowering::prepareUREMEqFold(EVT SETCCVT
, SDValue REMNode
,
4865 SDValue CompTargetNode
, ISD::CondCode Cond
,
4866 DAGCombinerInfo
&DCI
, const SDLoc
&DL
,
4867 SmallVectorImpl
<SDNode
*> &Created
) const {
4868 // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
4869 // - D must be constant, with D = D0 * 2^K where D0 is odd
4870 // - P is the multiplicative inverse of D0 modulo 2^W
4871 // - Q = floor(((2^W) - 1) / D)
4872 // where W is the width of the common type of N and D.
4873 assert((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
4874 "Only applicable for (in)equality comparisons.");
4876 SelectionDAG
&DAG
= DCI
.DAG
;
4878 EVT VT
= REMNode
.getValueType();
4879 EVT SVT
= VT
.getScalarType();
4880 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
4881 EVT ShSVT
= ShVT
.getScalarType();
4883 // If MUL is unavailable, we cannot proceed in any case.
4884 if (!isOperationLegalOrCustom(ISD::MUL
, VT
))
4887 // TODO: Could support comparing with non-zero too.
4888 ConstantSDNode
*CompTarget
= isConstOrConstSplat(CompTargetNode
);
4889 if (!CompTarget
|| !CompTarget
->isNullValue())
4892 bool HadOneDivisor
= false;
4893 bool AllDivisorsAreOnes
= true;
4894 bool HadEvenDivisor
= false;
4895 bool AllDivisorsArePowerOfTwo
= true;
4896 SmallVector
<SDValue
, 16> PAmts
, KAmts
, QAmts
;
4898 auto BuildUREMPattern
= [&](ConstantSDNode
*C
) {
4899 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
4900 if (C
->isNullValue())
4903 const APInt
&D
= C
->getAPIntValue();
4904 // If all divisors are ones, we will prefer to avoid the fold.
4905 HadOneDivisor
|= D
.isOneValue();
4906 AllDivisorsAreOnes
&= D
.isOneValue();
4908 // Decompose D into D0 * 2^K
4909 unsigned K
= D
.countTrailingZeros();
4910 assert((!D
.isOneValue() || (K
== 0)) && "For divisor '1' we won't rotate.");
4911 APInt D0
= D
.lshr(K
);
4913 // D is even if it has trailing zeros.
4914 HadEvenDivisor
|= (K
!= 0);
4915 // D is a power-of-two if D0 is one.
4916 // If all divisors are power-of-two, we will prefer to avoid the fold.
4917 AllDivisorsArePowerOfTwo
&= D0
.isOneValue();
4920 // 2^W requires W + 1 bits, so we have to extend and then truncate.
4921 unsigned W
= D
.getBitWidth();
4922 APInt P
= D0
.zext(W
+ 1)
4923 .multiplicativeInverse(APInt::getSignedMinValue(W
+ 1))
4925 assert(!P
.isNullValue() && "No multiplicative inverse!"); // unreachable
4926 assert((D0
* P
).isOneValue() && "Multiplicative inverse sanity check.");
4928 // Q = floor((2^W - 1) / D)
4929 APInt Q
= APInt::getAllOnesValue(W
).udiv(D
);
4931 assert(APInt::getAllOnesValue(ShSVT
.getSizeInBits()).ugt(K
) &&
4932 "We are expecting that K is always less than all-ones for ShSVT");
4934 // If the divisor is 1 the result can be constant-folded.
4935 if (D
.isOneValue()) {
4936 // Set P and K amount to a bogus values so we can try to splat them.
4939 assert(Q
.isAllOnesValue() &&
4940 "Expecting all-ones comparison for one divisor");
4943 PAmts
.push_back(DAG
.getConstant(P
, DL
, SVT
));
4945 DAG
.getConstant(APInt(ShSVT
.getSizeInBits(), K
), DL
, ShSVT
));
4946 QAmts
.push_back(DAG
.getConstant(Q
, DL
, SVT
));
4950 SDValue N
= REMNode
.getOperand(0);
4951 SDValue D
= REMNode
.getOperand(1);
4953 // Collect the values from each element.
4954 if (!ISD::matchUnaryPredicate(D
, BuildUREMPattern
))
4957 // If this is a urem by a one, avoid the fold since it can be constant-folded.
4958 if (AllDivisorsAreOnes
)
4961 // If this is a urem by a powers-of-two, avoid the fold since it can be
4962 // best implemented as a bit test.
4963 if (AllDivisorsArePowerOfTwo
)
4966 SDValue PVal
, KVal
, QVal
;
4967 if (VT
.isVector()) {
4968 if (HadOneDivisor
) {
4969 // Try to turn PAmts into a splat, since we don't care about the values
4970 // that are currently '0'. If we can't, just keep '0'`s.
4971 turnVectorIntoSplatVector(PAmts
, isNullConstant
);
4972 // Try to turn KAmts into a splat, since we don't care about the values
4973 // that are currently '-1'. If we can't, change them to '0'`s.
4974 turnVectorIntoSplatVector(KAmts
, isAllOnesConstant
,
4975 DAG
.getConstant(0, DL
, ShSVT
));
4978 PVal
= DAG
.getBuildVector(VT
, DL
, PAmts
);
4979 KVal
= DAG
.getBuildVector(ShVT
, DL
, KAmts
);
4980 QVal
= DAG
.getBuildVector(VT
, DL
, QAmts
);
4988 SDValue Op0
= DAG
.getNode(ISD::MUL
, DL
, VT
, N
, PVal
);
4989 Created
.push_back(Op0
.getNode());
4991 // Rotate right only if any divisor was even. We avoid rotates for all-odd
4992 // divisors as a performance improvement, since rotating by 0 is a no-op.
4993 if (HadEvenDivisor
) {
4994 // We need ROTR to do this.
4995 if (!isOperationLegalOrCustom(ISD::ROTR
, VT
))
4998 Flags
.setExact(true);
4999 // UREM: (rotr (mul N, P), K)
5000 Op0
= DAG
.getNode(ISD::ROTR
, DL
, VT
, Op0
, KVal
, Flags
);
5001 Created
.push_back(Op0
.getNode());
5004 // UREM: (setule/setugt (rotr (mul N, P), K), Q)
5005 return DAG
.getSetCC(DL
, SETCCVT
, Op0
, QVal
,
5006 ((Cond
== ISD::SETEQ
) ? ISD::SETULE
: ISD::SETUGT
));
5009 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
5010 /// where the divisor is constant and the comparison target is zero,
5011 /// return a DAG expression that will generate the same comparison result
5012 /// using only multiplications, additions and shifts/rotations.
5013 /// Ref: "Hacker's Delight" 10-17.
5014 SDValue
TargetLowering::buildSREMEqFold(EVT SETCCVT
, SDValue REMNode
,
5015 SDValue CompTargetNode
,
5017 DAGCombinerInfo
&DCI
,
5018 const SDLoc
&DL
) const {
5019 SmallVector
<SDNode
*, 7> Built
;
5020 if (SDValue Folded
= prepareSREMEqFold(SETCCVT
, REMNode
, CompTargetNode
, Cond
,
5022 assert(Built
.size() <= 7 && "Max size prediction failed.");
5023 for (SDNode
*N
: Built
)
5024 DCI
.AddToWorklist(N
);
5032 TargetLowering::prepareSREMEqFold(EVT SETCCVT
, SDValue REMNode
,
5033 SDValue CompTargetNode
, ISD::CondCode Cond
,
5034 DAGCombinerInfo
&DCI
, const SDLoc
&DL
,
5035 SmallVectorImpl
<SDNode
*> &Created
) const {
5037 // (seteq/ne (srem N, D), 0)
5039 // (setule/ugt (rotr (add (mul N, P), A), K), Q)
5041 // - D must be constant, with D = D0 * 2^K where D0 is odd
5042 // - P is the multiplicative inverse of D0 modulo 2^W
5043 // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
5044 // - Q = floor((2 * A) / (2^K))
5045 // where W is the width of the common type of N and D.
5046 assert((Cond
== ISD::SETEQ
|| Cond
== ISD::SETNE
) &&
5047 "Only applicable for (in)equality comparisons.");
5049 SelectionDAG
&DAG
= DCI
.DAG
;
5051 EVT VT
= REMNode
.getValueType();
5052 EVT SVT
= VT
.getScalarType();
5053 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
5054 EVT ShSVT
= ShVT
.getScalarType();
5056 // If MUL is unavailable, we cannot proceed in any case.
5057 if (!isOperationLegalOrCustom(ISD::MUL
, VT
))
5060 // TODO: Could support comparing with non-zero too.
5061 ConstantSDNode
*CompTarget
= isConstOrConstSplat(CompTargetNode
);
5062 if (!CompTarget
|| !CompTarget
->isNullValue())
5065 bool HadIntMinDivisor
= false;
5066 bool HadOneDivisor
= false;
5067 bool AllDivisorsAreOnes
= true;
5068 bool HadEvenDivisor
= false;
5069 bool NeedToApplyOffset
= false;
5070 bool AllDivisorsArePowerOfTwo
= true;
5071 SmallVector
<SDValue
, 16> PAmts
, AAmts
, KAmts
, QAmts
;
5073 auto BuildSREMPattern
= [&](ConstantSDNode
*C
) {
5074 // Division by 0 is UB. Leave it to be constant-folded elsewhere.
5075 if (C
->isNullValue())
5078 // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
5080 // WARNING: this fold is only valid for positive divisors!
5081 APInt D
= C
->getAPIntValue();
5083 D
.negate(); // `rem %X, -C` is equivalent to `rem %X, C`
5085 HadIntMinDivisor
|= D
.isMinSignedValue();
5087 // If all divisors are ones, we will prefer to avoid the fold.
5088 HadOneDivisor
|= D
.isOneValue();
5089 AllDivisorsAreOnes
&= D
.isOneValue();
5091 // Decompose D into D0 * 2^K
5092 unsigned K
= D
.countTrailingZeros();
5093 assert((!D
.isOneValue() || (K
== 0)) && "For divisor '1' we won't rotate.");
5094 APInt D0
= D
.lshr(K
);
5096 if (!D
.isMinSignedValue()) {
5097 // D is even if it has trailing zeros; unless it's INT_MIN, in which case
5098 // we don't care about this lane in this fold, we'll special-handle it.
5099 HadEvenDivisor
|= (K
!= 0);
5102 // D is a power-of-two if D0 is one. This includes INT_MIN.
5103 // If all divisors are power-of-two, we will prefer to avoid the fold.
5104 AllDivisorsArePowerOfTwo
&= D0
.isOneValue();
5107 // 2^W requires W + 1 bits, so we have to extend and then truncate.
5108 unsigned W
= D
.getBitWidth();
5109 APInt P
= D0
.zext(W
+ 1)
5110 .multiplicativeInverse(APInt::getSignedMinValue(W
+ 1))
5112 assert(!P
.isNullValue() && "No multiplicative inverse!"); // unreachable
5113 assert((D0
* P
).isOneValue() && "Multiplicative inverse sanity check.");
5115 // A = floor((2^(W - 1) - 1) / D0) & -2^K
5116 APInt A
= APInt::getSignedMaxValue(W
).udiv(D0
);
5119 if (!D
.isMinSignedValue()) {
5120 // If divisor INT_MIN, then we don't care about this lane in this fold,
5121 // we'll special-handle it.
5122 NeedToApplyOffset
|= A
!= 0;
5125 // Q = floor((2 * A) / (2^K))
5126 APInt Q
= (2 * A
).udiv(APInt::getOneBitSet(W
, K
));
5128 assert(APInt::getAllOnesValue(SVT
.getSizeInBits()).ugt(A
) &&
5129 "We are expecting that A is always less than all-ones for SVT");
5130 assert(APInt::getAllOnesValue(ShSVT
.getSizeInBits()).ugt(K
) &&
5131 "We are expecting that K is always less than all-ones for ShSVT");
5133 // If the divisor is 1 the result can be constant-folded. Likewise, we
5134 // don't care about INT_MIN lanes, those can be set to undef if appropriate.
5135 if (D
.isOneValue()) {
5136 // Set P, A and K to a bogus values so we can try to splat them.
5141 // x ?% 1 == 0 <--> true <--> x u<= -1
5145 PAmts
.push_back(DAG
.getConstant(P
, DL
, SVT
));
5146 AAmts
.push_back(DAG
.getConstant(A
, DL
, SVT
));
5148 DAG
.getConstant(APInt(ShSVT
.getSizeInBits(), K
), DL
, ShSVT
));
5149 QAmts
.push_back(DAG
.getConstant(Q
, DL
, SVT
));
5153 SDValue N
= REMNode
.getOperand(0);
5154 SDValue D
= REMNode
.getOperand(1);
5156 // Collect the values from each element.
5157 if (!ISD::matchUnaryPredicate(D
, BuildSREMPattern
))
5160 // If this is a srem by a one, avoid the fold since it can be constant-folded.
5161 if (AllDivisorsAreOnes
)
5164 // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
5165 // since it can be best implemented as a bit test.
5166 if (AllDivisorsArePowerOfTwo
)
5169 SDValue PVal
, AVal
, KVal
, QVal
;
5170 if (VT
.isVector()) {
5171 if (HadOneDivisor
) {
5172 // Try to turn PAmts into a splat, since we don't care about the values
5173 // that are currently '0'. If we can't, just keep '0'`s.
5174 turnVectorIntoSplatVector(PAmts
, isNullConstant
);
5175 // Try to turn AAmts into a splat, since we don't care about the
5176 // values that are currently '-1'. If we can't, change them to '0'`s.
5177 turnVectorIntoSplatVector(AAmts
, isAllOnesConstant
,
5178 DAG
.getConstant(0, DL
, SVT
));
5179 // Try to turn KAmts into a splat, since we don't care about the values
5180 // that are currently '-1'. If we can't, change them to '0'`s.
5181 turnVectorIntoSplatVector(KAmts
, isAllOnesConstant
,
5182 DAG
.getConstant(0, DL
, ShSVT
));
5185 PVal
= DAG
.getBuildVector(VT
, DL
, PAmts
);
5186 AVal
= DAG
.getBuildVector(VT
, DL
, AAmts
);
5187 KVal
= DAG
.getBuildVector(ShVT
, DL
, KAmts
);
5188 QVal
= DAG
.getBuildVector(VT
, DL
, QAmts
);
5197 SDValue Op0
= DAG
.getNode(ISD::MUL
, DL
, VT
, N
, PVal
);
5198 Created
.push_back(Op0
.getNode());
5200 if (NeedToApplyOffset
) {
5201 // We need ADD to do this.
5202 if (!isOperationLegalOrCustom(ISD::ADD
, VT
))
5205 // (add (mul N, P), A)
5206 Op0
= DAG
.getNode(ISD::ADD
, DL
, VT
, Op0
, AVal
);
5207 Created
.push_back(Op0
.getNode());
5210 // Rotate right only if any divisor was even. We avoid rotates for all-odd
5211 // divisors as a performance improvement, since rotating by 0 is a no-op.
5212 if (HadEvenDivisor
) {
5213 // We need ROTR to do this.
5214 if (!isOperationLegalOrCustom(ISD::ROTR
, VT
))
5217 Flags
.setExact(true);
5218 // SREM: (rotr (add (mul N, P), A), K)
5219 Op0
= DAG
.getNode(ISD::ROTR
, DL
, VT
, Op0
, KVal
, Flags
);
5220 Created
.push_back(Op0
.getNode());
5223 // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
5225 DAG
.getSetCC(DL
, SETCCVT
, Op0
, QVal
,
5226 ((Cond
== ISD::SETEQ
) ? ISD::SETULE
: ISD::SETUGT
));
5228 // If we didn't have lanes with INT_MIN divisor, then we're done.
5229 if (!HadIntMinDivisor
)
5232 // That fold is only valid for positive divisors. Which effectively means,
5233 // it is invalid for INT_MIN divisors. So if we have such a lane,
5234 // we must fix-up results for said lanes.
5235 assert(VT
.isVector() && "Can/should only get here for vectors.");
5237 if (!isOperationLegalOrCustom(ISD::SETEQ
, VT
) ||
5238 !isOperationLegalOrCustom(ISD::AND
, VT
) ||
5239 !isOperationLegalOrCustom(Cond
, VT
) ||
5240 !isOperationLegalOrCustom(ISD::VSELECT
, VT
))
5243 Created
.push_back(Fold
.getNode());
5245 SDValue IntMin
= DAG
.getConstant(
5246 APInt::getSignedMinValue(SVT
.getScalarSizeInBits()), DL
, VT
);
5247 SDValue IntMax
= DAG
.getConstant(
5248 APInt::getSignedMaxValue(SVT
.getScalarSizeInBits()), DL
, VT
);
5250 DAG
.getConstant(APInt::getNullValue(SVT
.getScalarSizeInBits()), DL
, VT
);
5252 // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
5253 SDValue DivisorIsIntMin
= DAG
.getSetCC(DL
, SETCCVT
, D
, IntMin
, ISD::SETEQ
);
5254 Created
.push_back(DivisorIsIntMin
.getNode());
5256 // (N s% INT_MIN) ==/!= 0 <--> (N & INT_MAX) ==/!= 0
5257 SDValue Masked
= DAG
.getNode(ISD::AND
, DL
, VT
, N
, IntMax
);
5258 Created
.push_back(Masked
.getNode());
5259 SDValue MaskedIsZero
= DAG
.getSetCC(DL
, SETCCVT
, Masked
, Zero
, Cond
);
5260 Created
.push_back(MaskedIsZero
.getNode());
5262 // To produce final result we need to blend 2 vectors: 'SetCC' and
5263 // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
5264 // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
5265 // constant-folded, select can get lowered to a shuffle with constant mask.
5267 DAG
.getNode(ISD::VSELECT
, DL
, VT
, DivisorIsIntMin
, MaskedIsZero
, Fold
);
5272 bool TargetLowering::
5273 verifyReturnAddressArgumentIsConstant(SDValue Op
, SelectionDAG
&DAG
) const {
5274 if (!isa
<ConstantSDNode
>(Op
.getOperand(0))) {
5275 DAG
.getContext()->emitError("argument to '__builtin_return_address' must "
5276 "be a constant integer");
5283 //===----------------------------------------------------------------------===//
5284 // Legalization Utilities
5285 //===----------------------------------------------------------------------===//
5287 bool TargetLowering::expandMUL_LOHI(unsigned Opcode
, EVT VT
, SDLoc dl
,
5288 SDValue LHS
, SDValue RHS
,
5289 SmallVectorImpl
<SDValue
> &Result
,
5290 EVT HiLoVT
, SelectionDAG
&DAG
,
5291 MulExpansionKind Kind
, SDValue LL
,
5292 SDValue LH
, SDValue RL
, SDValue RH
) const {
5293 assert(Opcode
== ISD::MUL
|| Opcode
== ISD::UMUL_LOHI
||
5294 Opcode
== ISD::SMUL_LOHI
);
5296 bool HasMULHS
= (Kind
== MulExpansionKind::Always
) ||
5297 isOperationLegalOrCustom(ISD::MULHS
, HiLoVT
);
5298 bool HasMULHU
= (Kind
== MulExpansionKind::Always
) ||
5299 isOperationLegalOrCustom(ISD::MULHU
, HiLoVT
);
5300 bool HasSMUL_LOHI
= (Kind
== MulExpansionKind::Always
) ||
5301 isOperationLegalOrCustom(ISD::SMUL_LOHI
, HiLoVT
);
5302 bool HasUMUL_LOHI
= (Kind
== MulExpansionKind::Always
) ||
5303 isOperationLegalOrCustom(ISD::UMUL_LOHI
, HiLoVT
);
5305 if (!HasMULHU
&& !HasMULHS
&& !HasUMUL_LOHI
&& !HasSMUL_LOHI
)
5308 unsigned OuterBitSize
= VT
.getScalarSizeInBits();
5309 unsigned InnerBitSize
= HiLoVT
.getScalarSizeInBits();
5310 unsigned LHSSB
= DAG
.ComputeNumSignBits(LHS
);
5311 unsigned RHSSB
= DAG
.ComputeNumSignBits(RHS
);
5313 // LL, LH, RL, and RH must be either all NULL or all set to a value.
5314 assert((LL
.getNode() && LH
.getNode() && RL
.getNode() && RH
.getNode()) ||
5315 (!LL
.getNode() && !LH
.getNode() && !RL
.getNode() && !RH
.getNode()));
5317 SDVTList VTs
= DAG
.getVTList(HiLoVT
, HiLoVT
);
5318 auto MakeMUL_LOHI
= [&](SDValue L
, SDValue R
, SDValue
&Lo
, SDValue
&Hi
,
5319 bool Signed
) -> bool {
5320 if ((Signed
&& HasSMUL_LOHI
) || (!Signed
&& HasUMUL_LOHI
)) {
5321 Lo
= DAG
.getNode(Signed
? ISD::SMUL_LOHI
: ISD::UMUL_LOHI
, dl
, VTs
, L
, R
);
5322 Hi
= SDValue(Lo
.getNode(), 1);
5325 if ((Signed
&& HasMULHS
) || (!Signed
&& HasMULHU
)) {
5326 Lo
= DAG
.getNode(ISD::MUL
, dl
, HiLoVT
, L
, R
);
5327 Hi
= DAG
.getNode(Signed
? ISD::MULHS
: ISD::MULHU
, dl
, HiLoVT
, L
, R
);
5335 if (!LL
.getNode() && !RL
.getNode() &&
5336 isOperationLegalOrCustom(ISD::TRUNCATE
, HiLoVT
)) {
5337 LL
= DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, LHS
);
5338 RL
= DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, RHS
);
5344 APInt HighMask
= APInt::getHighBitsSet(OuterBitSize
, InnerBitSize
);
5345 if (DAG
.MaskedValueIsZero(LHS
, HighMask
) &&
5346 DAG
.MaskedValueIsZero(RHS
, HighMask
)) {
5347 // The inputs are both zero-extended.
5348 if (MakeMUL_LOHI(LL
, RL
, Lo
, Hi
, false)) {
5349 Result
.push_back(Lo
);
5350 Result
.push_back(Hi
);
5351 if (Opcode
!= ISD::MUL
) {
5352 SDValue Zero
= DAG
.getConstant(0, dl
, HiLoVT
);
5353 Result
.push_back(Zero
);
5354 Result
.push_back(Zero
);
5360 if (!VT
.isVector() && Opcode
== ISD::MUL
&& LHSSB
> InnerBitSize
&&
5361 RHSSB
> InnerBitSize
) {
5362 // The input values are both sign-extended.
5363 // TODO non-MUL case?
5364 if (MakeMUL_LOHI(LL
, RL
, Lo
, Hi
, true)) {
5365 Result
.push_back(Lo
);
5366 Result
.push_back(Hi
);
5371 unsigned ShiftAmount
= OuterBitSize
- InnerBitSize
;
5372 EVT ShiftAmountTy
= getShiftAmountTy(VT
, DAG
.getDataLayout());
5373 if (APInt::getMaxValue(ShiftAmountTy
.getSizeInBits()).ult(ShiftAmount
)) {
5374 // FIXME getShiftAmountTy does not always return a sensible result when VT
5375 // is an illegal type, and so the type may be too small to fit the shift
5376 // amount. Override it with i32. The shift will have to be legalized.
5377 ShiftAmountTy
= MVT::i32
;
5379 SDValue Shift
= DAG
.getConstant(ShiftAmount
, dl
, ShiftAmountTy
);
5381 if (!LH
.getNode() && !RH
.getNode() &&
5382 isOperationLegalOrCustom(ISD::SRL
, VT
) &&
5383 isOperationLegalOrCustom(ISD::TRUNCATE
, HiLoVT
)) {
5384 LH
= DAG
.getNode(ISD::SRL
, dl
, VT
, LHS
, Shift
);
5385 LH
= DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, LH
);
5386 RH
= DAG
.getNode(ISD::SRL
, dl
, VT
, RHS
, Shift
);
5387 RH
= DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, RH
);
5393 if (!MakeMUL_LOHI(LL
, RL
, Lo
, Hi
, false))
5396 Result
.push_back(Lo
);
5398 if (Opcode
== ISD::MUL
) {
5399 RH
= DAG
.getNode(ISD::MUL
, dl
, HiLoVT
, LL
, RH
);
5400 LH
= DAG
.getNode(ISD::MUL
, dl
, HiLoVT
, LH
, RL
);
5401 Hi
= DAG
.getNode(ISD::ADD
, dl
, HiLoVT
, Hi
, RH
);
5402 Hi
= DAG
.getNode(ISD::ADD
, dl
, HiLoVT
, Hi
, LH
);
5403 Result
.push_back(Hi
);
5407 // Compute the full width result.
5408 auto Merge
= [&](SDValue Lo
, SDValue Hi
) -> SDValue
{
5409 Lo
= DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, Lo
);
5410 Hi
= DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, Hi
);
5411 Hi
= DAG
.getNode(ISD::SHL
, dl
, VT
, Hi
, Shift
);
5412 return DAG
.getNode(ISD::OR
, dl
, VT
, Lo
, Hi
);
5415 SDValue Next
= DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, Hi
);
5416 if (!MakeMUL_LOHI(LL
, RH
, Lo
, Hi
, false))
5419 // This is effectively the add part of a multiply-add of half-sized operands,
5420 // so it cannot overflow.
5421 Next
= DAG
.getNode(ISD::ADD
, dl
, VT
, Next
, Merge(Lo
, Hi
));
5423 if (!MakeMUL_LOHI(LH
, RL
, Lo
, Hi
, false))
5426 SDValue Zero
= DAG
.getConstant(0, dl
, HiLoVT
);
5427 EVT BoolType
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
5429 bool UseGlue
= (isOperationLegalOrCustom(ISD::ADDC
, VT
) &&
5430 isOperationLegalOrCustom(ISD::ADDE
, VT
));
5432 Next
= DAG
.getNode(ISD::ADDC
, dl
, DAG
.getVTList(VT
, MVT::Glue
), Next
,
5435 Next
= DAG
.getNode(ISD::ADDCARRY
, dl
, DAG
.getVTList(VT
, BoolType
), Next
,
5436 Merge(Lo
, Hi
), DAG
.getConstant(0, dl
, BoolType
));
5438 SDValue Carry
= Next
.getValue(1);
5439 Result
.push_back(DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, Next
));
5440 Next
= DAG
.getNode(ISD::SRL
, dl
, VT
, Next
, Shift
);
5442 if (!MakeMUL_LOHI(LH
, RH
, Lo
, Hi
, Opcode
== ISD::SMUL_LOHI
))
5446 Hi
= DAG
.getNode(ISD::ADDE
, dl
, DAG
.getVTList(HiLoVT
, MVT::Glue
), Hi
, Zero
,
5449 Hi
= DAG
.getNode(ISD::ADDCARRY
, dl
, DAG
.getVTList(HiLoVT
, BoolType
), Hi
,
5452 Next
= DAG
.getNode(ISD::ADD
, dl
, VT
, Next
, Merge(Lo
, Hi
));
5454 if (Opcode
== ISD::SMUL_LOHI
) {
5455 SDValue NextSub
= DAG
.getNode(ISD::SUB
, dl
, VT
, Next
,
5456 DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, RL
));
5457 Next
= DAG
.getSelectCC(dl
, LH
, Zero
, NextSub
, Next
, ISD::SETLT
);
5459 NextSub
= DAG
.getNode(ISD::SUB
, dl
, VT
, Next
,
5460 DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, LL
));
5461 Next
= DAG
.getSelectCC(dl
, RH
, Zero
, NextSub
, Next
, ISD::SETLT
);
5464 Result
.push_back(DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, Next
));
5465 Next
= DAG
.getNode(ISD::SRL
, dl
, VT
, Next
, Shift
);
5466 Result
.push_back(DAG
.getNode(ISD::TRUNCATE
, dl
, HiLoVT
, Next
));
5470 bool TargetLowering::expandMUL(SDNode
*N
, SDValue
&Lo
, SDValue
&Hi
, EVT HiLoVT
,
5471 SelectionDAG
&DAG
, MulExpansionKind Kind
,
5472 SDValue LL
, SDValue LH
, SDValue RL
,
5474 SmallVector
<SDValue
, 2> Result
;
5475 bool Ok
= expandMUL_LOHI(N
->getOpcode(), N
->getValueType(0), N
,
5476 N
->getOperand(0), N
->getOperand(1), Result
, HiLoVT
,
5477 DAG
, Kind
, LL
, LH
, RL
, RH
);
5479 assert(Result
.size() == 2);
5486 bool TargetLowering::expandFunnelShift(SDNode
*Node
, SDValue
&Result
,
5487 SelectionDAG
&DAG
) const {
5488 EVT VT
= Node
->getValueType(0);
5490 if (VT
.isVector() && (!isOperationLegalOrCustom(ISD::SHL
, VT
) ||
5491 !isOperationLegalOrCustom(ISD::SRL
, VT
) ||
5492 !isOperationLegalOrCustom(ISD::SUB
, VT
) ||
5493 !isOperationLegalOrCustomOrPromote(ISD::OR
, VT
)))
5496 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5497 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5498 SDValue X
= Node
->getOperand(0);
5499 SDValue Y
= Node
->getOperand(1);
5500 SDValue Z
= Node
->getOperand(2);
5502 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
5503 bool IsFSHL
= Node
->getOpcode() == ISD::FSHL
;
5504 SDLoc
DL(SDValue(Node
, 0));
5506 EVT ShVT
= Z
.getValueType();
5507 SDValue BitWidthC
= DAG
.getConstant(EltSizeInBits
, DL
, ShVT
);
5508 SDValue Zero
= DAG
.getConstant(0, DL
, ShVT
);
5511 if (isPowerOf2_32(EltSizeInBits
)) {
5512 SDValue Mask
= DAG
.getConstant(EltSizeInBits
- 1, DL
, ShVT
);
5513 ShAmt
= DAG
.getNode(ISD::AND
, DL
, ShVT
, Z
, Mask
);
5515 ShAmt
= DAG
.getNode(ISD::UREM
, DL
, ShVT
, Z
, BitWidthC
);
5518 SDValue InvShAmt
= DAG
.getNode(ISD::SUB
, DL
, ShVT
, BitWidthC
, ShAmt
);
5519 SDValue ShX
= DAG
.getNode(ISD::SHL
, DL
, VT
, X
, IsFSHL
? ShAmt
: InvShAmt
);
5520 SDValue ShY
= DAG
.getNode(ISD::SRL
, DL
, VT
, Y
, IsFSHL
? InvShAmt
: ShAmt
);
5521 SDValue Or
= DAG
.getNode(ISD::OR
, DL
, VT
, ShX
, ShY
);
5523 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5524 // and that is undefined. We must compare and select to avoid UB.
5525 EVT CCVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), ShVT
);
5527 // For fshl, 0-shift returns the 1st arg (X).
5528 // For fshr, 0-shift returns the 2nd arg (Y).
5529 SDValue IsZeroShift
= DAG
.getSetCC(DL
, CCVT
, ShAmt
, Zero
, ISD::SETEQ
);
5530 Result
= DAG
.getSelect(DL
, VT
, IsZeroShift
, IsFSHL
? X
: Y
, Or
);
5534 // TODO: Merge with expandFunnelShift.
5535 bool TargetLowering::expandROT(SDNode
*Node
, SDValue
&Result
,
5536 SelectionDAG
&DAG
) const {
5537 EVT VT
= Node
->getValueType(0);
5538 unsigned EltSizeInBits
= VT
.getScalarSizeInBits();
5539 bool IsLeft
= Node
->getOpcode() == ISD::ROTL
;
5540 SDValue Op0
= Node
->getOperand(0);
5541 SDValue Op1
= Node
->getOperand(1);
5542 SDLoc
DL(SDValue(Node
, 0));
5544 EVT ShVT
= Op1
.getValueType();
5545 SDValue BitWidthC
= DAG
.getConstant(EltSizeInBits
, DL
, ShVT
);
5547 // If a rotate in the other direction is legal, use it.
5548 unsigned RevRot
= IsLeft
? ISD::ROTR
: ISD::ROTL
;
5549 if (isOperationLegal(RevRot
, VT
)) {
5550 SDValue Sub
= DAG
.getNode(ISD::SUB
, DL
, ShVT
, BitWidthC
, Op1
);
5551 Result
= DAG
.getNode(RevRot
, DL
, VT
, Op0
, Sub
);
5555 if (VT
.isVector() && (!isOperationLegalOrCustom(ISD::SHL
, VT
) ||
5556 !isOperationLegalOrCustom(ISD::SRL
, VT
) ||
5557 !isOperationLegalOrCustom(ISD::SUB
, VT
) ||
5558 !isOperationLegalOrCustomOrPromote(ISD::OR
, VT
) ||
5559 !isOperationLegalOrCustomOrPromote(ISD::AND
, VT
)))
5563 // (rotl x, c) -> (or (shl x, (and c, w-1)), (srl x, (and w-c, w-1)))
5564 // (rotr x, c) -> (or (srl x, (and c, w-1)), (shl x, (and w-c, w-1)))
5566 assert(isPowerOf2_32(EltSizeInBits
) && EltSizeInBits
> 1 &&
5567 "Expecting the type bitwidth to be a power of 2");
5568 unsigned ShOpc
= IsLeft
? ISD::SHL
: ISD::SRL
;
5569 unsigned HsOpc
= IsLeft
? ISD::SRL
: ISD::SHL
;
5570 SDValue BitWidthMinusOneC
= DAG
.getConstant(EltSizeInBits
- 1, DL
, ShVT
);
5571 SDValue NegOp1
= DAG
.getNode(ISD::SUB
, DL
, ShVT
, BitWidthC
, Op1
);
5572 SDValue And0
= DAG
.getNode(ISD::AND
, DL
, ShVT
, Op1
, BitWidthMinusOneC
);
5573 SDValue And1
= DAG
.getNode(ISD::AND
, DL
, ShVT
, NegOp1
, BitWidthMinusOneC
);
5574 Result
= DAG
.getNode(ISD::OR
, DL
, VT
, DAG
.getNode(ShOpc
, DL
, VT
, Op0
, And0
),
5575 DAG
.getNode(HsOpc
, DL
, VT
, Op0
, And1
));
5579 bool TargetLowering::expandFP_TO_SINT(SDNode
*Node
, SDValue
&Result
,
5580 SelectionDAG
&DAG
) const {
5581 SDValue Src
= Node
->getOperand(0);
5582 EVT SrcVT
= Src
.getValueType();
5583 EVT DstVT
= Node
->getValueType(0);
5584 SDLoc
dl(SDValue(Node
, 0));
5586 // FIXME: Only f32 to i64 conversions are supported.
5587 if (SrcVT
!= MVT::f32
|| DstVT
!= MVT::i64
)
5590 // Expand f32 -> i64 conversion
5591 // This algorithm comes from compiler-rt's implementation of fixsfdi:
5592 // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c
5593 unsigned SrcEltBits
= SrcVT
.getScalarSizeInBits();
5594 EVT IntVT
= SrcVT
.changeTypeToInteger();
5595 EVT IntShVT
= getShiftAmountTy(IntVT
, DAG
.getDataLayout());
5597 SDValue ExponentMask
= DAG
.getConstant(0x7F800000, dl
, IntVT
);
5598 SDValue ExponentLoBit
= DAG
.getConstant(23, dl
, IntVT
);
5599 SDValue Bias
= DAG
.getConstant(127, dl
, IntVT
);
5600 SDValue SignMask
= DAG
.getConstant(APInt::getSignMask(SrcEltBits
), dl
, IntVT
);
5601 SDValue SignLowBit
= DAG
.getConstant(SrcEltBits
- 1, dl
, IntVT
);
5602 SDValue MantissaMask
= DAG
.getConstant(0x007FFFFF, dl
, IntVT
);
5604 SDValue Bits
= DAG
.getNode(ISD::BITCAST
, dl
, IntVT
, Src
);
5606 SDValue ExponentBits
= DAG
.getNode(
5607 ISD::SRL
, dl
, IntVT
, DAG
.getNode(ISD::AND
, dl
, IntVT
, Bits
, ExponentMask
),
5608 DAG
.getZExtOrTrunc(ExponentLoBit
, dl
, IntShVT
));
5609 SDValue Exponent
= DAG
.getNode(ISD::SUB
, dl
, IntVT
, ExponentBits
, Bias
);
5611 SDValue Sign
= DAG
.getNode(ISD::SRA
, dl
, IntVT
,
5612 DAG
.getNode(ISD::AND
, dl
, IntVT
, Bits
, SignMask
),
5613 DAG
.getZExtOrTrunc(SignLowBit
, dl
, IntShVT
));
5614 Sign
= DAG
.getSExtOrTrunc(Sign
, dl
, DstVT
);
5616 SDValue R
= DAG
.getNode(ISD::OR
, dl
, IntVT
,
5617 DAG
.getNode(ISD::AND
, dl
, IntVT
, Bits
, MantissaMask
),
5618 DAG
.getConstant(0x00800000, dl
, IntVT
));
5620 R
= DAG
.getZExtOrTrunc(R
, dl
, DstVT
);
5622 R
= DAG
.getSelectCC(
5623 dl
, Exponent
, ExponentLoBit
,
5624 DAG
.getNode(ISD::SHL
, dl
, DstVT
, R
,
5626 DAG
.getNode(ISD::SUB
, dl
, IntVT
, Exponent
, ExponentLoBit
),
5628 DAG
.getNode(ISD::SRL
, dl
, DstVT
, R
,
5630 DAG
.getNode(ISD::SUB
, dl
, IntVT
, ExponentLoBit
, Exponent
),
5634 SDValue Ret
= DAG
.getNode(ISD::SUB
, dl
, DstVT
,
5635 DAG
.getNode(ISD::XOR
, dl
, DstVT
, R
, Sign
), Sign
);
5637 Result
= DAG
.getSelectCC(dl
, Exponent
, DAG
.getConstant(0, dl
, IntVT
),
5638 DAG
.getConstant(0, dl
, DstVT
), Ret
, ISD::SETLT
);
5642 bool TargetLowering::expandFP_TO_UINT(SDNode
*Node
, SDValue
&Result
,
5643 SelectionDAG
&DAG
) const {
5644 SDLoc
dl(SDValue(Node
, 0));
5645 SDValue Src
= Node
->getOperand(0);
5647 EVT SrcVT
= Src
.getValueType();
5648 EVT DstVT
= Node
->getValueType(0);
5650 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), SrcVT
);
5652 // Only expand vector types if we have the appropriate vector bit operations.
5653 if (DstVT
.isVector() && (!isOperationLegalOrCustom(ISD::FP_TO_SINT
, DstVT
) ||
5654 !isOperationLegalOrCustomOrPromote(ISD::XOR
, SrcVT
)))
5657 // If the maximum float value is smaller then the signed integer range,
5658 // the destination signmask can't be represented by the float, so we can
5659 // just use FP_TO_SINT directly.
5660 const fltSemantics
&APFSem
= DAG
.EVTToAPFloatSemantics(SrcVT
);
5661 APFloat
APF(APFSem
, APInt::getNullValue(SrcVT
.getScalarSizeInBits()));
5662 APInt SignMask
= APInt::getSignMask(DstVT
.getScalarSizeInBits());
5663 if (APFloat::opOverflow
&
5664 APF
.convertFromAPInt(SignMask
, false, APFloat::rmNearestTiesToEven
)) {
5665 Result
= DAG
.getNode(ISD::FP_TO_SINT
, dl
, DstVT
, Src
);
5669 SDValue Cst
= DAG
.getConstantFP(APF
, dl
, SrcVT
);
5670 SDValue Sel
= DAG
.getSetCC(dl
, SetCCVT
, Src
, Cst
, ISD::SETLT
);
5672 bool Strict
= shouldUseStrictFP_TO_INT(SrcVT
, DstVT
, /*IsSigned*/ false);
5674 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
5675 // signmask then offset (the result of which should be fully representable).
5676 // Sel = Src < 0x8000000000000000
5677 // Val = select Sel, Src, Src - 0x8000000000000000
5678 // Ofs = select Sel, 0, 0x8000000000000000
5679 // Result = fp_to_sint(Val) ^ Ofs
5681 // TODO: Should any fast-math-flags be set for the FSUB?
5682 SDValue Val
= DAG
.getSelect(dl
, SrcVT
, Sel
, Src
,
5683 DAG
.getNode(ISD::FSUB
, dl
, SrcVT
, Src
, Cst
));
5684 SDValue Ofs
= DAG
.getSelect(dl
, DstVT
, Sel
, DAG
.getConstant(0, dl
, DstVT
),
5685 DAG
.getConstant(SignMask
, dl
, DstVT
));
5686 Result
= DAG
.getNode(ISD::XOR
, dl
, DstVT
,
5687 DAG
.getNode(ISD::FP_TO_SINT
, dl
, DstVT
, Val
), Ofs
);
5689 // Expand based on maximum range of FP_TO_SINT:
5690 // True = fp_to_sint(Src)
5691 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
5692 // Result = select (Src < 0x8000000000000000), True, False
5694 SDValue True
= DAG
.getNode(ISD::FP_TO_SINT
, dl
, DstVT
, Src
);
5695 // TODO: Should any fast-math-flags be set for the FSUB?
5696 SDValue False
= DAG
.getNode(ISD::FP_TO_SINT
, dl
, DstVT
,
5697 DAG
.getNode(ISD::FSUB
, dl
, SrcVT
, Src
, Cst
));
5698 False
= DAG
.getNode(ISD::XOR
, dl
, DstVT
, False
,
5699 DAG
.getConstant(SignMask
, dl
, DstVT
));
5700 Result
= DAG
.getSelect(dl
, DstVT
, Sel
, True
, False
);
5705 bool TargetLowering::expandUINT_TO_FP(SDNode
*Node
, SDValue
&Result
,
5706 SelectionDAG
&DAG
) const {
5707 SDValue Src
= Node
->getOperand(0);
5708 EVT SrcVT
= Src
.getValueType();
5709 EVT DstVT
= Node
->getValueType(0);
5711 if (SrcVT
.getScalarType() != MVT::i64
)
5714 SDLoc
dl(SDValue(Node
, 0));
5715 EVT ShiftVT
= getShiftAmountTy(SrcVT
, DAG
.getDataLayout());
5717 if (DstVT
.getScalarType() == MVT::f32
) {
5718 // Only expand vector types if we have the appropriate vector bit
5720 if (SrcVT
.isVector() &&
5721 (!isOperationLegalOrCustom(ISD::SRL
, SrcVT
) ||
5722 !isOperationLegalOrCustom(ISD::FADD
, DstVT
) ||
5723 !isOperationLegalOrCustom(ISD::SINT_TO_FP
, SrcVT
) ||
5724 !isOperationLegalOrCustomOrPromote(ISD::OR
, SrcVT
) ||
5725 !isOperationLegalOrCustomOrPromote(ISD::AND
, SrcVT
)))
5728 // For unsigned conversions, convert them to signed conversions using the
5729 // algorithm from the x86_64 __floatundidf in compiler_rt.
5730 SDValue Fast
= DAG
.getNode(ISD::SINT_TO_FP
, dl
, DstVT
, Src
);
5732 SDValue ShiftConst
= DAG
.getConstant(1, dl
, ShiftVT
);
5733 SDValue Shr
= DAG
.getNode(ISD::SRL
, dl
, SrcVT
, Src
, ShiftConst
);
5734 SDValue AndConst
= DAG
.getConstant(1, dl
, SrcVT
);
5735 SDValue And
= DAG
.getNode(ISD::AND
, dl
, SrcVT
, Src
, AndConst
);
5736 SDValue Or
= DAG
.getNode(ISD::OR
, dl
, SrcVT
, And
, Shr
);
5738 SDValue SignCvt
= DAG
.getNode(ISD::SINT_TO_FP
, dl
, DstVT
, Or
);
5739 SDValue Slow
= DAG
.getNode(ISD::FADD
, dl
, DstVT
, SignCvt
, SignCvt
);
5741 // TODO: This really should be implemented using a branch rather than a
5742 // select. We happen to get lucky and machinesink does the right
5743 // thing most of the time. This would be a good candidate for a
5744 // pseudo-op, or, even better, for whole-function isel.
5746 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), SrcVT
);
5748 SDValue SignBitTest
= DAG
.getSetCC(
5749 dl
, SetCCVT
, Src
, DAG
.getConstant(0, dl
, SrcVT
), ISD::SETLT
);
5750 Result
= DAG
.getSelect(dl
, DstVT
, SignBitTest
, Slow
, Fast
);
5754 if (DstVT
.getScalarType() == MVT::f64
) {
5755 // Only expand vector types if we have the appropriate vector bit
5757 if (SrcVT
.isVector() &&
5758 (!isOperationLegalOrCustom(ISD::SRL
, SrcVT
) ||
5759 !isOperationLegalOrCustom(ISD::FADD
, DstVT
) ||
5760 !isOperationLegalOrCustom(ISD::FSUB
, DstVT
) ||
5761 !isOperationLegalOrCustomOrPromote(ISD::OR
, SrcVT
) ||
5762 !isOperationLegalOrCustomOrPromote(ISD::AND
, SrcVT
)))
5765 // Implementation of unsigned i64 to f64 following the algorithm in
5766 // __floatundidf in compiler_rt. This implementation has the advantage
5767 // of performing rounding correctly, both in the default rounding mode
5768 // and in all alternate rounding modes.
5769 SDValue TwoP52
= DAG
.getConstant(UINT64_C(0x4330000000000000), dl
, SrcVT
);
5770 SDValue TwoP84PlusTwoP52
= DAG
.getConstantFP(
5771 BitsToDouble(UINT64_C(0x4530000000100000)), dl
, DstVT
);
5772 SDValue TwoP84
= DAG
.getConstant(UINT64_C(0x4530000000000000), dl
, SrcVT
);
5773 SDValue LoMask
= DAG
.getConstant(UINT64_C(0x00000000FFFFFFFF), dl
, SrcVT
);
5774 SDValue HiShift
= DAG
.getConstant(32, dl
, ShiftVT
);
5776 SDValue Lo
= DAG
.getNode(ISD::AND
, dl
, SrcVT
, Src
, LoMask
);
5777 SDValue Hi
= DAG
.getNode(ISD::SRL
, dl
, SrcVT
, Src
, HiShift
);
5778 SDValue LoOr
= DAG
.getNode(ISD::OR
, dl
, SrcVT
, Lo
, TwoP52
);
5779 SDValue HiOr
= DAG
.getNode(ISD::OR
, dl
, SrcVT
, Hi
, TwoP84
);
5780 SDValue LoFlt
= DAG
.getBitcast(DstVT
, LoOr
);
5781 SDValue HiFlt
= DAG
.getBitcast(DstVT
, HiOr
);
5782 SDValue HiSub
= DAG
.getNode(ISD::FSUB
, dl
, DstVT
, HiFlt
, TwoP84PlusTwoP52
);
5783 Result
= DAG
.getNode(ISD::FADD
, dl
, DstVT
, LoFlt
, HiSub
);
5790 SDValue
TargetLowering::expandFMINNUM_FMAXNUM(SDNode
*Node
,
5791 SelectionDAG
&DAG
) const {
5793 unsigned NewOp
= Node
->getOpcode() == ISD::FMINNUM
?
5794 ISD::FMINNUM_IEEE
: ISD::FMAXNUM_IEEE
;
5795 EVT VT
= Node
->getValueType(0);
5796 if (isOperationLegalOrCustom(NewOp
, VT
)) {
5797 SDValue Quiet0
= Node
->getOperand(0);
5798 SDValue Quiet1
= Node
->getOperand(1);
5800 if (!Node
->getFlags().hasNoNaNs()) {
5801 // Insert canonicalizes if it's possible we need to quiet to get correct
5803 if (!DAG
.isKnownNeverSNaN(Quiet0
)) {
5804 Quiet0
= DAG
.getNode(ISD::FCANONICALIZE
, dl
, VT
, Quiet0
,
5807 if (!DAG
.isKnownNeverSNaN(Quiet1
)) {
5808 Quiet1
= DAG
.getNode(ISD::FCANONICALIZE
, dl
, VT
, Quiet1
,
5813 return DAG
.getNode(NewOp
, dl
, VT
, Quiet0
, Quiet1
, Node
->getFlags());
5816 // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
5817 // instead if there are no NaNs.
5818 if (Node
->getFlags().hasNoNaNs()) {
5819 unsigned IEEE2018Op
=
5820 Node
->getOpcode() == ISD::FMINNUM
? ISD::FMINIMUM
: ISD::FMAXIMUM
;
5821 if (isOperationLegalOrCustom(IEEE2018Op
, VT
)) {
5822 return DAG
.getNode(IEEE2018Op
, dl
, VT
, Node
->getOperand(0),
5823 Node
->getOperand(1), Node
->getFlags());
5830 bool TargetLowering::expandCTPOP(SDNode
*Node
, SDValue
&Result
,
5831 SelectionDAG
&DAG
) const {
5833 EVT VT
= Node
->getValueType(0);
5834 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
5835 SDValue Op
= Node
->getOperand(0);
5836 unsigned Len
= VT
.getScalarSizeInBits();
5837 assert(VT
.isInteger() && "CTPOP not implemented for this type.");
5839 // TODO: Add support for irregular type lengths.
5840 if (!(Len
<= 128 && Len
% 8 == 0))
5843 // Only expand vector types if we have the appropriate vector bit operations.
5844 if (VT
.isVector() && (!isOperationLegalOrCustom(ISD::ADD
, VT
) ||
5845 !isOperationLegalOrCustom(ISD::SUB
, VT
) ||
5846 !isOperationLegalOrCustom(ISD::SRL
, VT
) ||
5847 (Len
!= 8 && !isOperationLegalOrCustom(ISD::MUL
, VT
)) ||
5848 !isOperationLegalOrCustomOrPromote(ISD::AND
, VT
)))
5851 // This is the "best" algorithm from
5852 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
5854 DAG
.getConstant(APInt::getSplat(Len
, APInt(8, 0x55)), dl
, VT
);
5856 DAG
.getConstant(APInt::getSplat(Len
, APInt(8, 0x33)), dl
, VT
);
5858 DAG
.getConstant(APInt::getSplat(Len
, APInt(8, 0x0F)), dl
, VT
);
5860 DAG
.getConstant(APInt::getSplat(Len
, APInt(8, 0x01)), dl
, VT
);
5862 // v = v - ((v >> 1) & 0x55555555...)
5863 Op
= DAG
.getNode(ISD::SUB
, dl
, VT
, Op
,
5864 DAG
.getNode(ISD::AND
, dl
, VT
,
5865 DAG
.getNode(ISD::SRL
, dl
, VT
, Op
,
5866 DAG
.getConstant(1, dl
, ShVT
)),
5868 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
5869 Op
= DAG
.getNode(ISD::ADD
, dl
, VT
, DAG
.getNode(ISD::AND
, dl
, VT
, Op
, Mask33
),
5870 DAG
.getNode(ISD::AND
, dl
, VT
,
5871 DAG
.getNode(ISD::SRL
, dl
, VT
, Op
,
5872 DAG
.getConstant(2, dl
, ShVT
)),
5874 // v = (v + (v >> 4)) & 0x0F0F0F0F...
5875 Op
= DAG
.getNode(ISD::AND
, dl
, VT
,
5876 DAG
.getNode(ISD::ADD
, dl
, VT
, Op
,
5877 DAG
.getNode(ISD::SRL
, dl
, VT
, Op
,
5878 DAG
.getConstant(4, dl
, ShVT
))),
5880 // v = (v * 0x01010101...) >> (Len - 8)
5883 DAG
.getNode(ISD::SRL
, dl
, VT
, DAG
.getNode(ISD::MUL
, dl
, VT
, Op
, Mask01
),
5884 DAG
.getConstant(Len
- 8, dl
, ShVT
));
5890 bool TargetLowering::expandCTLZ(SDNode
*Node
, SDValue
&Result
,
5891 SelectionDAG
&DAG
) const {
5893 EVT VT
= Node
->getValueType(0);
5894 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
5895 SDValue Op
= Node
->getOperand(0);
5896 unsigned NumBitsPerElt
= VT
.getScalarSizeInBits();
5898 // If the non-ZERO_UNDEF version is supported we can use that instead.
5899 if (Node
->getOpcode() == ISD::CTLZ_ZERO_UNDEF
&&
5900 isOperationLegalOrCustom(ISD::CTLZ
, VT
)) {
5901 Result
= DAG
.getNode(ISD::CTLZ
, dl
, VT
, Op
);
5905 // If the ZERO_UNDEF version is supported use that and handle the zero case.
5906 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF
, VT
)) {
5908 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
5909 SDValue CTLZ
= DAG
.getNode(ISD::CTLZ_ZERO_UNDEF
, dl
, VT
, Op
);
5910 SDValue Zero
= DAG
.getConstant(0, dl
, VT
);
5911 SDValue SrcIsZero
= DAG
.getSetCC(dl
, SetCCVT
, Op
, Zero
, ISD::SETEQ
);
5912 Result
= DAG
.getNode(ISD::SELECT
, dl
, VT
, SrcIsZero
,
5913 DAG
.getConstant(NumBitsPerElt
, dl
, VT
), CTLZ
);
5917 // Only expand vector types if we have the appropriate vector bit operations.
5918 if (VT
.isVector() && (!isPowerOf2_32(NumBitsPerElt
) ||
5919 !isOperationLegalOrCustom(ISD::CTPOP
, VT
) ||
5920 !isOperationLegalOrCustom(ISD::SRL
, VT
) ||
5921 !isOperationLegalOrCustomOrPromote(ISD::OR
, VT
)))
5924 // for now, we do this:
5925 // x = x | (x >> 1);
5926 // x = x | (x >> 2);
5928 // x = x | (x >>16);
5929 // x = x | (x >>32); // for 64-bit input
5930 // return popcount(~x);
5932 // Ref: "Hacker's Delight" by Henry Warren
5933 for (unsigned i
= 0; (1U << i
) <= (NumBitsPerElt
/ 2); ++i
) {
5934 SDValue Tmp
= DAG
.getConstant(1ULL << i
, dl
, ShVT
);
5935 Op
= DAG
.getNode(ISD::OR
, dl
, VT
, Op
,
5936 DAG
.getNode(ISD::SRL
, dl
, VT
, Op
, Tmp
));
5938 Op
= DAG
.getNOT(dl
, Op
, VT
);
5939 Result
= DAG
.getNode(ISD::CTPOP
, dl
, VT
, Op
);
5943 bool TargetLowering::expandCTTZ(SDNode
*Node
, SDValue
&Result
,
5944 SelectionDAG
&DAG
) const {
5946 EVT VT
= Node
->getValueType(0);
5947 SDValue Op
= Node
->getOperand(0);
5948 unsigned NumBitsPerElt
= VT
.getScalarSizeInBits();
5950 // If the non-ZERO_UNDEF version is supported we can use that instead.
5951 if (Node
->getOpcode() == ISD::CTTZ_ZERO_UNDEF
&&
5952 isOperationLegalOrCustom(ISD::CTTZ
, VT
)) {
5953 Result
= DAG
.getNode(ISD::CTTZ
, dl
, VT
, Op
);
5957 // If the ZERO_UNDEF version is supported use that and handle the zero case.
5958 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF
, VT
)) {
5960 getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
5961 SDValue CTTZ
= DAG
.getNode(ISD::CTTZ_ZERO_UNDEF
, dl
, VT
, Op
);
5962 SDValue Zero
= DAG
.getConstant(0, dl
, VT
);
5963 SDValue SrcIsZero
= DAG
.getSetCC(dl
, SetCCVT
, Op
, Zero
, ISD::SETEQ
);
5964 Result
= DAG
.getNode(ISD::SELECT
, dl
, VT
, SrcIsZero
,
5965 DAG
.getConstant(NumBitsPerElt
, dl
, VT
), CTTZ
);
5969 // Only expand vector types if we have the appropriate vector bit operations.
5970 if (VT
.isVector() && (!isPowerOf2_32(NumBitsPerElt
) ||
5971 (!isOperationLegalOrCustom(ISD::CTPOP
, VT
) &&
5972 !isOperationLegalOrCustom(ISD::CTLZ
, VT
)) ||
5973 !isOperationLegalOrCustom(ISD::SUB
, VT
) ||
5974 !isOperationLegalOrCustomOrPromote(ISD::AND
, VT
) ||
5975 !isOperationLegalOrCustomOrPromote(ISD::XOR
, VT
)))
5978 // for now, we use: { return popcount(~x & (x - 1)); }
5979 // unless the target has ctlz but not ctpop, in which case we use:
5980 // { return 32 - nlz(~x & (x-1)); }
5981 // Ref: "Hacker's Delight" by Henry Warren
5982 SDValue Tmp
= DAG
.getNode(
5983 ISD::AND
, dl
, VT
, DAG
.getNOT(dl
, Op
, VT
),
5984 DAG
.getNode(ISD::SUB
, dl
, VT
, Op
, DAG
.getConstant(1, dl
, VT
)));
5986 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
5987 if (isOperationLegal(ISD::CTLZ
, VT
) && !isOperationLegal(ISD::CTPOP
, VT
)) {
5989 DAG
.getNode(ISD::SUB
, dl
, VT
, DAG
.getConstant(NumBitsPerElt
, dl
, VT
),
5990 DAG
.getNode(ISD::CTLZ
, dl
, VT
, Tmp
));
5994 Result
= DAG
.getNode(ISD::CTPOP
, dl
, VT
, Tmp
);
5998 bool TargetLowering::expandABS(SDNode
*N
, SDValue
&Result
,
5999 SelectionDAG
&DAG
) const {
6001 EVT VT
= N
->getValueType(0);
6002 EVT ShVT
= getShiftAmountTy(VT
, DAG
.getDataLayout());
6003 SDValue Op
= N
->getOperand(0);
6005 // Only expand vector types if we have the appropriate vector operations.
6006 if (VT
.isVector() && (!isOperationLegalOrCustom(ISD::SRA
, VT
) ||
6007 !isOperationLegalOrCustom(ISD::ADD
, VT
) ||
6008 !isOperationLegalOrCustomOrPromote(ISD::XOR
, VT
)))
6012 DAG
.getNode(ISD::SRA
, dl
, VT
, Op
,
6013 DAG
.getConstant(VT
.getScalarSizeInBits() - 1, dl
, ShVT
));
6014 SDValue Add
= DAG
.getNode(ISD::ADD
, dl
, VT
, Op
, Shift
);
6015 Result
= DAG
.getNode(ISD::XOR
, dl
, VT
, Add
, Shift
);
6019 SDValue
TargetLowering::scalarizeVectorLoad(LoadSDNode
*LD
,
6020 SelectionDAG
&DAG
) const {
6022 SDValue Chain
= LD
->getChain();
6023 SDValue BasePTR
= LD
->getBasePtr();
6024 EVT SrcVT
= LD
->getMemoryVT();
6025 ISD::LoadExtType ExtType
= LD
->getExtensionType();
6027 unsigned NumElem
= SrcVT
.getVectorNumElements();
6029 EVT SrcEltVT
= SrcVT
.getScalarType();
6030 EVT DstEltVT
= LD
->getValueType(0).getScalarType();
6032 unsigned Stride
= SrcEltVT
.getSizeInBits() / 8;
6033 assert(SrcEltVT
.isByteSized());
6035 SmallVector
<SDValue
, 8> Vals
;
6036 SmallVector
<SDValue
, 8> LoadChains
;
6038 for (unsigned Idx
= 0; Idx
< NumElem
; ++Idx
) {
6039 SDValue ScalarLoad
=
6040 DAG
.getExtLoad(ExtType
, SL
, DstEltVT
, Chain
, BasePTR
,
6041 LD
->getPointerInfo().getWithOffset(Idx
* Stride
),
6042 SrcEltVT
, MinAlign(LD
->getAlignment(), Idx
* Stride
),
6043 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
6045 BasePTR
= DAG
.getObjectPtrOffset(SL
, BasePTR
, Stride
);
6047 Vals
.push_back(ScalarLoad
.getValue(0));
6048 LoadChains
.push_back(ScalarLoad
.getValue(1));
6051 SDValue NewChain
= DAG
.getNode(ISD::TokenFactor
, SL
, MVT::Other
, LoadChains
);
6052 SDValue Value
= DAG
.getBuildVector(LD
->getValueType(0), SL
, Vals
);
6054 return DAG
.getMergeValues({Value
, NewChain
}, SL
);
6057 SDValue
TargetLowering::scalarizeVectorStore(StoreSDNode
*ST
,
6058 SelectionDAG
&DAG
) const {
6061 SDValue Chain
= ST
->getChain();
6062 SDValue BasePtr
= ST
->getBasePtr();
6063 SDValue Value
= ST
->getValue();
6064 EVT StVT
= ST
->getMemoryVT();
6066 // The type of the data we want to save
6067 EVT RegVT
= Value
.getValueType();
6068 EVT RegSclVT
= RegVT
.getScalarType();
6070 // The type of data as saved in memory.
6071 EVT MemSclVT
= StVT
.getScalarType();
6073 EVT IdxVT
= getVectorIdxTy(DAG
.getDataLayout());
6074 unsigned NumElem
= StVT
.getVectorNumElements();
6076 // A vector must always be stored in memory as-is, i.e. without any padding
6077 // between the elements, since various code depend on it, e.g. in the
6078 // handling of a bitcast of a vector type to int, which may be done with a
6079 // vector store followed by an integer load. A vector that does not have
6080 // elements that are byte-sized must therefore be stored as an integer
6081 // built out of the extracted vector elements.
6082 if (!MemSclVT
.isByteSized()) {
6083 unsigned NumBits
= StVT
.getSizeInBits();
6084 EVT IntVT
= EVT::getIntegerVT(*DAG
.getContext(), NumBits
);
6086 SDValue CurrVal
= DAG
.getConstant(0, SL
, IntVT
);
6088 for (unsigned Idx
= 0; Idx
< NumElem
; ++Idx
) {
6089 SDValue Elt
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, SL
, RegSclVT
, Value
,
6090 DAG
.getConstant(Idx
, SL
, IdxVT
));
6091 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, SL
, MemSclVT
, Elt
);
6092 SDValue ExtElt
= DAG
.getNode(ISD::ZERO_EXTEND
, SL
, IntVT
, Trunc
);
6093 unsigned ShiftIntoIdx
=
6094 (DAG
.getDataLayout().isBigEndian() ? (NumElem
- 1) - Idx
: Idx
);
6095 SDValue ShiftAmount
=
6096 DAG
.getConstant(ShiftIntoIdx
* MemSclVT
.getSizeInBits(), SL
, IntVT
);
6097 SDValue ShiftedElt
=
6098 DAG
.getNode(ISD::SHL
, SL
, IntVT
, ExtElt
, ShiftAmount
);
6099 CurrVal
= DAG
.getNode(ISD::OR
, SL
, IntVT
, CurrVal
, ShiftedElt
);
6102 return DAG
.getStore(Chain
, SL
, CurrVal
, BasePtr
, ST
->getPointerInfo(),
6103 ST
->getAlignment(), ST
->getMemOperand()->getFlags(),
6107 // Store Stride in bytes
6108 unsigned Stride
= MemSclVT
.getSizeInBits() / 8;
6109 assert(Stride
&& "Zero stride!");
6110 // Extract each of the elements from the original vector and save them into
6111 // memory individually.
6112 SmallVector
<SDValue
, 8> Stores
;
6113 for (unsigned Idx
= 0; Idx
< NumElem
; ++Idx
) {
6114 SDValue Elt
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, SL
, RegSclVT
, Value
,
6115 DAG
.getConstant(Idx
, SL
, IdxVT
));
6117 SDValue Ptr
= DAG
.getObjectPtrOffset(SL
, BasePtr
, Idx
* Stride
);
6119 // This scalar TruncStore may be illegal, but we legalize it later.
6120 SDValue Store
= DAG
.getTruncStore(
6121 Chain
, SL
, Elt
, Ptr
, ST
->getPointerInfo().getWithOffset(Idx
* Stride
),
6122 MemSclVT
, MinAlign(ST
->getAlignment(), Idx
* Stride
),
6123 ST
->getMemOperand()->getFlags(), ST
->getAAInfo());
6125 Stores
.push_back(Store
);
6128 return DAG
.getNode(ISD::TokenFactor
, SL
, MVT::Other
, Stores
);
6131 std::pair
<SDValue
, SDValue
>
6132 TargetLowering::expandUnalignedLoad(LoadSDNode
*LD
, SelectionDAG
&DAG
) const {
6133 assert(LD
->getAddressingMode() == ISD::UNINDEXED
&&
6134 "unaligned indexed loads not implemented!");
6135 SDValue Chain
= LD
->getChain();
6136 SDValue Ptr
= LD
->getBasePtr();
6137 EVT VT
= LD
->getValueType(0);
6138 EVT LoadedVT
= LD
->getMemoryVT();
6140 auto &MF
= DAG
.getMachineFunction();
6142 if (VT
.isFloatingPoint() || VT
.isVector()) {
6143 EVT intVT
= EVT::getIntegerVT(*DAG
.getContext(), LoadedVT
.getSizeInBits());
6144 if (isTypeLegal(intVT
) && isTypeLegal(LoadedVT
)) {
6145 if (!isOperationLegalOrCustom(ISD::LOAD
, intVT
) &&
6146 LoadedVT
.isVector()) {
6147 // Scalarize the load and let the individual components be handled.
6148 SDValue Scalarized
= scalarizeVectorLoad(LD
, DAG
);
6149 if (Scalarized
->getOpcode() == ISD::MERGE_VALUES
)
6150 return std::make_pair(Scalarized
.getOperand(0), Scalarized
.getOperand(1));
6151 return std::make_pair(Scalarized
.getValue(0), Scalarized
.getValue(1));
6154 // Expand to a (misaligned) integer load of the same size,
6155 // then bitconvert to floating point or vector.
6156 SDValue newLoad
= DAG
.getLoad(intVT
, dl
, Chain
, Ptr
,
6157 LD
->getMemOperand());
6158 SDValue Result
= DAG
.getNode(ISD::BITCAST
, dl
, LoadedVT
, newLoad
);
6160 Result
= DAG
.getNode(VT
.isFloatingPoint() ? ISD::FP_EXTEND
:
6161 ISD::ANY_EXTEND
, dl
, VT
, Result
);
6163 return std::make_pair(Result
, newLoad
.getValue(1));
6166 // Copy the value to a (aligned) stack slot using (unaligned) integer
6167 // loads and stores, then do a (aligned) load from the stack slot.
6168 MVT RegVT
= getRegisterType(*DAG
.getContext(), intVT
);
6169 unsigned LoadedBytes
= LoadedVT
.getStoreSize();
6170 unsigned RegBytes
= RegVT
.getSizeInBits() / 8;
6171 unsigned NumRegs
= (LoadedBytes
+ RegBytes
- 1) / RegBytes
;
6173 // Make sure the stack slot is also aligned for the register type.
6174 SDValue StackBase
= DAG
.CreateStackTemporary(LoadedVT
, RegVT
);
6175 auto FrameIndex
= cast
<FrameIndexSDNode
>(StackBase
.getNode())->getIndex();
6176 SmallVector
<SDValue
, 8> Stores
;
6177 SDValue StackPtr
= StackBase
;
6178 unsigned Offset
= 0;
6180 EVT PtrVT
= Ptr
.getValueType();
6181 EVT StackPtrVT
= StackPtr
.getValueType();
6183 SDValue PtrIncrement
= DAG
.getConstant(RegBytes
, dl
, PtrVT
);
6184 SDValue StackPtrIncrement
= DAG
.getConstant(RegBytes
, dl
, StackPtrVT
);
6186 // Do all but one copies using the full register width.
6187 for (unsigned i
= 1; i
< NumRegs
; i
++) {
6188 // Load one integer register's worth from the original location.
6189 SDValue Load
= DAG
.getLoad(
6190 RegVT
, dl
, Chain
, Ptr
, LD
->getPointerInfo().getWithOffset(Offset
),
6191 MinAlign(LD
->getAlignment(), Offset
), LD
->getMemOperand()->getFlags(),
6193 // Follow the load with a store to the stack slot. Remember the store.
6194 Stores
.push_back(DAG
.getStore(
6195 Load
.getValue(1), dl
, Load
, StackPtr
,
6196 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, Offset
)));
6197 // Increment the pointers.
6200 Ptr
= DAG
.getObjectPtrOffset(dl
, Ptr
, PtrIncrement
);
6201 StackPtr
= DAG
.getObjectPtrOffset(dl
, StackPtr
, StackPtrIncrement
);
6204 // The last copy may be partial. Do an extending load.
6205 EVT MemVT
= EVT::getIntegerVT(*DAG
.getContext(),
6206 8 * (LoadedBytes
- Offset
));
6208 DAG
.getExtLoad(ISD::EXTLOAD
, dl
, RegVT
, Chain
, Ptr
,
6209 LD
->getPointerInfo().getWithOffset(Offset
), MemVT
,
6210 MinAlign(LD
->getAlignment(), Offset
),
6211 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
6212 // Follow the load with a store to the stack slot. Remember the store.
6213 // On big-endian machines this requires a truncating store to ensure
6214 // that the bits end up in the right place.
6215 Stores
.push_back(DAG
.getTruncStore(
6216 Load
.getValue(1), dl
, Load
, StackPtr
,
6217 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, Offset
), MemVT
));
6219 // The order of the stores doesn't matter - say it with a TokenFactor.
6220 SDValue TF
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, Stores
);
6222 // Finally, perform the original load only redirected to the stack slot.
6223 Load
= DAG
.getExtLoad(LD
->getExtensionType(), dl
, VT
, TF
, StackBase
,
6224 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, 0),
6227 // Callers expect a MERGE_VALUES node.
6228 return std::make_pair(Load
, TF
);
6231 assert(LoadedVT
.isInteger() && !LoadedVT
.isVector() &&
6232 "Unaligned load of unsupported type.");
6234 // Compute the new VT that is half the size of the old one. This is an
6236 unsigned NumBits
= LoadedVT
.getSizeInBits();
6238 NewLoadedVT
= EVT::getIntegerVT(*DAG
.getContext(), NumBits
/2);
6241 unsigned Alignment
= LD
->getAlignment();
6242 unsigned IncrementSize
= NumBits
/ 8;
6243 ISD::LoadExtType HiExtType
= LD
->getExtensionType();
6245 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
6246 if (HiExtType
== ISD::NON_EXTLOAD
)
6247 HiExtType
= ISD::ZEXTLOAD
;
6249 // Load the value in two parts
6251 if (DAG
.getDataLayout().isLittleEndian()) {
6252 Lo
= DAG
.getExtLoad(ISD::ZEXTLOAD
, dl
, VT
, Chain
, Ptr
, LD
->getPointerInfo(),
6253 NewLoadedVT
, Alignment
, LD
->getMemOperand()->getFlags(),
6256 Ptr
= DAG
.getObjectPtrOffset(dl
, Ptr
, IncrementSize
);
6257 Hi
= DAG
.getExtLoad(HiExtType
, dl
, VT
, Chain
, Ptr
,
6258 LD
->getPointerInfo().getWithOffset(IncrementSize
),
6259 NewLoadedVT
, MinAlign(Alignment
, IncrementSize
),
6260 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
6262 Hi
= DAG
.getExtLoad(HiExtType
, dl
, VT
, Chain
, Ptr
, LD
->getPointerInfo(),
6263 NewLoadedVT
, Alignment
, LD
->getMemOperand()->getFlags(),
6266 Ptr
= DAG
.getObjectPtrOffset(dl
, Ptr
, IncrementSize
);
6267 Lo
= DAG
.getExtLoad(ISD::ZEXTLOAD
, dl
, VT
, Chain
, Ptr
,
6268 LD
->getPointerInfo().getWithOffset(IncrementSize
),
6269 NewLoadedVT
, MinAlign(Alignment
, IncrementSize
),
6270 LD
->getMemOperand()->getFlags(), LD
->getAAInfo());
6273 // aggregate the two parts
6274 SDValue ShiftAmount
=
6275 DAG
.getConstant(NumBits
, dl
, getShiftAmountTy(Hi
.getValueType(),
6276 DAG
.getDataLayout()));
6277 SDValue Result
= DAG
.getNode(ISD::SHL
, dl
, VT
, Hi
, ShiftAmount
);
6278 Result
= DAG
.getNode(ISD::OR
, dl
, VT
, Result
, Lo
);
6280 SDValue TF
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, Lo
.getValue(1),
6283 return std::make_pair(Result
, TF
);
6286 SDValue
TargetLowering::expandUnalignedStore(StoreSDNode
*ST
,
6287 SelectionDAG
&DAG
) const {
6288 assert(ST
->getAddressingMode() == ISD::UNINDEXED
&&
6289 "unaligned indexed stores not implemented!");
6290 SDValue Chain
= ST
->getChain();
6291 SDValue Ptr
= ST
->getBasePtr();
6292 SDValue Val
= ST
->getValue();
6293 EVT VT
= Val
.getValueType();
6294 int Alignment
= ST
->getAlignment();
6295 auto &MF
= DAG
.getMachineFunction();
6296 EVT StoreMemVT
= ST
->getMemoryVT();
6299 if (StoreMemVT
.isFloatingPoint() || StoreMemVT
.isVector()) {
6300 EVT intVT
= EVT::getIntegerVT(*DAG
.getContext(), VT
.getSizeInBits());
6301 if (isTypeLegal(intVT
)) {
6302 if (!isOperationLegalOrCustom(ISD::STORE
, intVT
) &&
6303 StoreMemVT
.isVector()) {
6304 // Scalarize the store and let the individual components be handled.
6305 SDValue Result
= scalarizeVectorStore(ST
, DAG
);
6308 // Expand to a bitconvert of the value to the integer type of the
6309 // same size, then a (misaligned) int store.
6310 // FIXME: Does not handle truncating floating point stores!
6311 SDValue Result
= DAG
.getNode(ISD::BITCAST
, dl
, intVT
, Val
);
6312 Result
= DAG
.getStore(Chain
, dl
, Result
, Ptr
, ST
->getPointerInfo(),
6313 Alignment
, ST
->getMemOperand()->getFlags());
6316 // Do a (aligned) store to a stack slot, then copy from the stack slot
6317 // to the final destination using (unaligned) integer loads and stores.
6318 MVT RegVT
= getRegisterType(
6320 EVT::getIntegerVT(*DAG
.getContext(), StoreMemVT
.getSizeInBits()));
6321 EVT PtrVT
= Ptr
.getValueType();
6322 unsigned StoredBytes
= StoreMemVT
.getStoreSize();
6323 unsigned RegBytes
= RegVT
.getSizeInBits() / 8;
6324 unsigned NumRegs
= (StoredBytes
+ RegBytes
- 1) / RegBytes
;
6326 // Make sure the stack slot is also aligned for the register type.
6327 SDValue StackPtr
= DAG
.CreateStackTemporary(StoreMemVT
, RegVT
);
6328 auto FrameIndex
= cast
<FrameIndexSDNode
>(StackPtr
.getNode())->getIndex();
6330 // Perform the original store, only redirected to the stack slot.
6331 SDValue Store
= DAG
.getTruncStore(
6332 Chain
, dl
, Val
, StackPtr
,
6333 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, 0), StoreMemVT
);
6335 EVT StackPtrVT
= StackPtr
.getValueType();
6337 SDValue PtrIncrement
= DAG
.getConstant(RegBytes
, dl
, PtrVT
);
6338 SDValue StackPtrIncrement
= DAG
.getConstant(RegBytes
, dl
, StackPtrVT
);
6339 SmallVector
<SDValue
, 8> Stores
;
6340 unsigned Offset
= 0;
6342 // Do all but one copies using the full register width.
6343 for (unsigned i
= 1; i
< NumRegs
; i
++) {
6344 // Load one integer register's worth from the stack slot.
6345 SDValue Load
= DAG
.getLoad(
6346 RegVT
, dl
, Store
, StackPtr
,
6347 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, Offset
));
6348 // Store it to the final location. Remember the store.
6349 Stores
.push_back(DAG
.getStore(Load
.getValue(1), dl
, Load
, Ptr
,
6350 ST
->getPointerInfo().getWithOffset(Offset
),
6351 MinAlign(ST
->getAlignment(), Offset
),
6352 ST
->getMemOperand()->getFlags()));
6353 // Increment the pointers.
6355 StackPtr
= DAG
.getObjectPtrOffset(dl
, StackPtr
, StackPtrIncrement
);
6356 Ptr
= DAG
.getObjectPtrOffset(dl
, Ptr
, PtrIncrement
);
6359 // The last store may be partial. Do a truncating store. On big-endian
6360 // machines this requires an extending load from the stack slot to ensure
6361 // that the bits are in the right place.
6363 EVT::getIntegerVT(*DAG
.getContext(), 8 * (StoredBytes
- Offset
));
6365 // Load from the stack slot.
6366 SDValue Load
= DAG
.getExtLoad(
6367 ISD::EXTLOAD
, dl
, RegVT
, Store
, StackPtr
,
6368 MachinePointerInfo::getFixedStack(MF
, FrameIndex
, Offset
), LoadMemVT
);
6371 DAG
.getTruncStore(Load
.getValue(1), dl
, Load
, Ptr
,
6372 ST
->getPointerInfo().getWithOffset(Offset
), LoadMemVT
,
6373 MinAlign(ST
->getAlignment(), Offset
),
6374 ST
->getMemOperand()->getFlags(), ST
->getAAInfo()));
6375 // The order of the stores doesn't matter - say it with a TokenFactor.
6376 SDValue Result
= DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, Stores
);
6380 assert(StoreMemVT
.isInteger() && !StoreMemVT
.isVector() &&
6381 "Unaligned store of unknown type.");
6382 // Get the half-size VT
6383 EVT NewStoredVT
= StoreMemVT
.getHalfSizedIntegerVT(*DAG
.getContext());
6384 int NumBits
= NewStoredVT
.getSizeInBits();
6385 int IncrementSize
= NumBits
/ 8;
6387 // Divide the stored value in two parts.
6388 SDValue ShiftAmount
= DAG
.getConstant(
6389 NumBits
, dl
, getShiftAmountTy(Val
.getValueType(), DAG
.getDataLayout()));
6391 SDValue Hi
= DAG
.getNode(ISD::SRL
, dl
, VT
, Val
, ShiftAmount
);
6393 // Store the two parts
6394 SDValue Store1
, Store2
;
6395 Store1
= DAG
.getTruncStore(Chain
, dl
,
6396 DAG
.getDataLayout().isLittleEndian() ? Lo
: Hi
,
6397 Ptr
, ST
->getPointerInfo(), NewStoredVT
, Alignment
,
6398 ST
->getMemOperand()->getFlags());
6400 Ptr
= DAG
.getObjectPtrOffset(dl
, Ptr
, IncrementSize
);
6401 Alignment
= MinAlign(Alignment
, IncrementSize
);
6402 Store2
= DAG
.getTruncStore(
6403 Chain
, dl
, DAG
.getDataLayout().isLittleEndian() ? Hi
: Lo
, Ptr
,
6404 ST
->getPointerInfo().getWithOffset(IncrementSize
), NewStoredVT
, Alignment
,
6405 ST
->getMemOperand()->getFlags(), ST
->getAAInfo());
6408 DAG
.getNode(ISD::TokenFactor
, dl
, MVT::Other
, Store1
, Store2
);
6413 TargetLowering::IncrementMemoryAddress(SDValue Addr
, SDValue Mask
,
6414 const SDLoc
&DL
, EVT DataVT
,
6416 bool IsCompressedMemory
) const {
6418 EVT AddrVT
= Addr
.getValueType();
6419 EVT MaskVT
= Mask
.getValueType();
6420 assert(DataVT
.getVectorNumElements() == MaskVT
.getVectorNumElements() &&
6421 "Incompatible types of Data and Mask");
6422 if (IsCompressedMemory
) {
6423 // Incrementing the pointer according to number of '1's in the mask.
6424 EVT MaskIntVT
= EVT::getIntegerVT(*DAG
.getContext(), MaskVT
.getSizeInBits());
6425 SDValue MaskInIntReg
= DAG
.getBitcast(MaskIntVT
, Mask
);
6426 if (MaskIntVT
.getSizeInBits() < 32) {
6427 MaskInIntReg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i32
, MaskInIntReg
);
6428 MaskIntVT
= MVT::i32
;
6431 // Count '1's with POPCNT.
6432 Increment
= DAG
.getNode(ISD::CTPOP
, DL
, MaskIntVT
, MaskInIntReg
);
6433 Increment
= DAG
.getZExtOrTrunc(Increment
, DL
, AddrVT
);
6434 // Scale is an element size in bytes.
6435 SDValue Scale
= DAG
.getConstant(DataVT
.getScalarSizeInBits() / 8, DL
,
6437 Increment
= DAG
.getNode(ISD::MUL
, DL
, AddrVT
, Increment
, Scale
);
6439 Increment
= DAG
.getConstant(DataVT
.getStoreSize(), DL
, AddrVT
);
6441 return DAG
.getNode(ISD::ADD
, DL
, AddrVT
, Addr
, Increment
);
6444 static SDValue
clampDynamicVectorIndex(SelectionDAG
&DAG
,
6448 if (isa
<ConstantSDNode
>(Idx
))
6451 EVT IdxVT
= Idx
.getValueType();
6452 unsigned NElts
= VecVT
.getVectorNumElements();
6453 if (isPowerOf2_32(NElts
)) {
6454 APInt Imm
= APInt::getLowBitsSet(IdxVT
.getSizeInBits(),
6456 return DAG
.getNode(ISD::AND
, dl
, IdxVT
, Idx
,
6457 DAG
.getConstant(Imm
, dl
, IdxVT
));
6460 return DAG
.getNode(ISD::UMIN
, dl
, IdxVT
, Idx
,
6461 DAG
.getConstant(NElts
- 1, dl
, IdxVT
));
6464 SDValue
TargetLowering::getVectorElementPointer(SelectionDAG
&DAG
,
6465 SDValue VecPtr
, EVT VecVT
,
6466 SDValue Index
) const {
6468 // Make sure the index type is big enough to compute in.
6469 Index
= DAG
.getZExtOrTrunc(Index
, dl
, VecPtr
.getValueType());
6471 EVT EltVT
= VecVT
.getVectorElementType();
6473 // Calculate the element offset and add it to the pointer.
6474 unsigned EltSize
= EltVT
.getSizeInBits() / 8; // FIXME: should be ABI size.
6475 assert(EltSize
* 8 == EltVT
.getSizeInBits() &&
6476 "Converting bits to bytes lost precision");
6478 Index
= clampDynamicVectorIndex(DAG
, Index
, VecVT
, dl
);
6480 EVT IdxVT
= Index
.getValueType();
6482 Index
= DAG
.getNode(ISD::MUL
, dl
, IdxVT
, Index
,
6483 DAG
.getConstant(EltSize
, dl
, IdxVT
));
6484 return DAG
.getNode(ISD::ADD
, dl
, IdxVT
, VecPtr
, Index
);
6487 //===----------------------------------------------------------------------===//
6488 // Implementation of Emulated TLS Model
6489 //===----------------------------------------------------------------------===//
6491 SDValue
TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode
*GA
,
6492 SelectionDAG
&DAG
) const {
6493 // Access to address of TLS varialbe xyz is lowered to a function call:
6494 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
6495 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
6496 PointerType
*VoidPtrType
= Type::getInt8PtrTy(*DAG
.getContext());
6501 std::string NameString
= ("__emutls_v." + GA
->getGlobal()->getName()).str();
6502 Module
*VariableModule
= const_cast<Module
*>(GA
->getGlobal()->getParent());
6503 StringRef
EmuTlsVarName(NameString
);
6504 GlobalVariable
*EmuTlsVar
= VariableModule
->getNamedGlobal(EmuTlsVarName
);
6505 assert(EmuTlsVar
&& "Cannot find EmuTlsVar ");
6506 Entry
.Node
= DAG
.getGlobalAddress(EmuTlsVar
, dl
, PtrVT
);
6507 Entry
.Ty
= VoidPtrType
;
6508 Args
.push_back(Entry
);
6510 SDValue EmuTlsGetAddr
= DAG
.getExternalSymbol("__emutls_get_address", PtrVT
);
6512 TargetLowering::CallLoweringInfo
CLI(DAG
);
6513 CLI
.setDebugLoc(dl
).setChain(DAG
.getEntryNode());
6514 CLI
.setLibCallee(CallingConv::C
, VoidPtrType
, EmuTlsGetAddr
, std::move(Args
));
6515 std::pair
<SDValue
, SDValue
> CallResult
= LowerCallTo(CLI
);
6517 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6518 // At last for X86 targets, maybe good for other targets too?
6519 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
6520 MFI
.setAdjustsStack(true); // Is this only for X86 target?
6521 MFI
.setHasCalls(true);
6523 assert((GA
->getOffset() == 0) &&
6524 "Emulated TLS must have zero offset in GlobalAddressSDNode");
6525 return CallResult
.first
;
6528 SDValue
TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op
,
6529 SelectionDAG
&DAG
) const {
6530 assert((Op
->getOpcode() == ISD::SETCC
) && "Input has to be a SETCC node.");
6533 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
6535 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1))) {
6536 if (C
->isNullValue() && CC
== ISD::SETEQ
) {
6537 EVT VT
= Op
.getOperand(0).getValueType();
6538 SDValue Zext
= Op
.getOperand(0);
6539 if (VT
.bitsLT(MVT::i32
)) {
6541 Zext
= DAG
.getNode(ISD::ZERO_EXTEND
, dl
, VT
, Op
.getOperand(0));
6543 unsigned Log2b
= Log2_32(VT
.getSizeInBits());
6544 SDValue Clz
= DAG
.getNode(ISD::CTLZ
, dl
, VT
, Zext
);
6545 SDValue Scc
= DAG
.getNode(ISD::SRL
, dl
, VT
, Clz
,
6546 DAG
.getConstant(Log2b
, dl
, MVT::i32
));
6547 return DAG
.getNode(ISD::TRUNCATE
, dl
, MVT::i32
, Scc
);
6553 SDValue
TargetLowering::expandAddSubSat(SDNode
*Node
, SelectionDAG
&DAG
) const {
6554 unsigned Opcode
= Node
->getOpcode();
6555 SDValue LHS
= Node
->getOperand(0);
6556 SDValue RHS
= Node
->getOperand(1);
6557 EVT VT
= LHS
.getValueType();
6560 assert(VT
== RHS
.getValueType() && "Expected operands to be the same type");
6561 assert(VT
.isInteger() && "Expected operands to be integers");
6563 // usub.sat(a, b) -> umax(a, b) - b
6564 if (Opcode
== ISD::USUBSAT
&& isOperationLegalOrCustom(ISD::UMAX
, VT
)) {
6565 SDValue Max
= DAG
.getNode(ISD::UMAX
, dl
, VT
, LHS
, RHS
);
6566 return DAG
.getNode(ISD::SUB
, dl
, VT
, Max
, RHS
);
6569 if (Opcode
== ISD::UADDSAT
&& isOperationLegalOrCustom(ISD::UMIN
, VT
)) {
6570 SDValue InvRHS
= DAG
.getNOT(dl
, RHS
, VT
);
6571 SDValue Min
= DAG
.getNode(ISD::UMIN
, dl
, VT
, LHS
, InvRHS
);
6572 return DAG
.getNode(ISD::ADD
, dl
, VT
, Min
, RHS
);
6575 unsigned OverflowOp
;
6578 OverflowOp
= ISD::SADDO
;
6581 OverflowOp
= ISD::UADDO
;
6584 OverflowOp
= ISD::SSUBO
;
6587 OverflowOp
= ISD::USUBO
;
6590 llvm_unreachable("Expected method to receive signed or unsigned saturation "
6591 "addition or subtraction node.");
6594 unsigned BitWidth
= LHS
.getScalarValueSizeInBits();
6595 EVT BoolVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
6596 SDValue Result
= DAG
.getNode(OverflowOp
, dl
, DAG
.getVTList(VT
, BoolVT
),
6598 SDValue SumDiff
= Result
.getValue(0);
6599 SDValue Overflow
= Result
.getValue(1);
6600 SDValue Zero
= DAG
.getConstant(0, dl
, VT
);
6601 SDValue AllOnes
= DAG
.getAllOnesConstant(dl
, VT
);
6603 if (Opcode
== ISD::UADDSAT
) {
6604 if (getBooleanContents(VT
) == ZeroOrNegativeOneBooleanContent
) {
6605 // (LHS + RHS) | OverflowMask
6606 SDValue OverflowMask
= DAG
.getSExtOrTrunc(Overflow
, dl
, VT
);
6607 return DAG
.getNode(ISD::OR
, dl
, VT
, SumDiff
, OverflowMask
);
6609 // Overflow ? 0xffff.... : (LHS + RHS)
6610 return DAG
.getSelect(dl
, VT
, Overflow
, AllOnes
, SumDiff
);
6611 } else if (Opcode
== ISD::USUBSAT
) {
6612 if (getBooleanContents(VT
) == ZeroOrNegativeOneBooleanContent
) {
6613 // (LHS - RHS) & ~OverflowMask
6614 SDValue OverflowMask
= DAG
.getSExtOrTrunc(Overflow
, dl
, VT
);
6615 SDValue Not
= DAG
.getNOT(dl
, OverflowMask
, VT
);
6616 return DAG
.getNode(ISD::AND
, dl
, VT
, SumDiff
, Not
);
6618 // Overflow ? 0 : (LHS - RHS)
6619 return DAG
.getSelect(dl
, VT
, Overflow
, Zero
, SumDiff
);
6621 // SatMax -> Overflow && SumDiff < 0
6622 // SatMin -> Overflow && SumDiff >= 0
6623 APInt MinVal
= APInt::getSignedMinValue(BitWidth
);
6624 APInt MaxVal
= APInt::getSignedMaxValue(BitWidth
);
6625 SDValue SatMin
= DAG
.getConstant(MinVal
, dl
, VT
);
6626 SDValue SatMax
= DAG
.getConstant(MaxVal
, dl
, VT
);
6627 SDValue SumNeg
= DAG
.getSetCC(dl
, BoolVT
, SumDiff
, Zero
, ISD::SETLT
);
6628 Result
= DAG
.getSelect(dl
, VT
, SumNeg
, SatMax
, SatMin
);
6629 return DAG
.getSelect(dl
, VT
, Overflow
, Result
, SumDiff
);
6634 TargetLowering::expandFixedPointMul(SDNode
*Node
, SelectionDAG
&DAG
) const {
6635 assert((Node
->getOpcode() == ISD::SMULFIX
||
6636 Node
->getOpcode() == ISD::UMULFIX
||
6637 Node
->getOpcode() == ISD::SMULFIXSAT
) &&
6638 "Expected a fixed point multiplication opcode");
6641 SDValue LHS
= Node
->getOperand(0);
6642 SDValue RHS
= Node
->getOperand(1);
6643 EVT VT
= LHS
.getValueType();
6644 unsigned Scale
= Node
->getConstantOperandVal(2);
6645 bool Saturating
= Node
->getOpcode() == ISD::SMULFIXSAT
;
6646 EVT BoolVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
6647 unsigned VTSize
= VT
.getScalarSizeInBits();
6650 // [us]mul.fix(a, b, 0) -> mul(a, b)
6651 if (!Saturating
&& isOperationLegalOrCustom(ISD::MUL
, VT
)) {
6652 return DAG
.getNode(ISD::MUL
, dl
, VT
, LHS
, RHS
);
6653 } else if (Saturating
&& isOperationLegalOrCustom(ISD::SMULO
, VT
)) {
6655 DAG
.getNode(ISD::SMULO
, dl
, DAG
.getVTList(VT
, BoolVT
), LHS
, RHS
);
6656 SDValue Product
= Result
.getValue(0);
6657 SDValue Overflow
= Result
.getValue(1);
6658 SDValue Zero
= DAG
.getConstant(0, dl
, VT
);
6660 APInt MinVal
= APInt::getSignedMinValue(VTSize
);
6661 APInt MaxVal
= APInt::getSignedMaxValue(VTSize
);
6662 SDValue SatMin
= DAG
.getConstant(MinVal
, dl
, VT
);
6663 SDValue SatMax
= DAG
.getConstant(MaxVal
, dl
, VT
);
6664 SDValue ProdNeg
= DAG
.getSetCC(dl
, BoolVT
, Product
, Zero
, ISD::SETLT
);
6665 Result
= DAG
.getSelect(dl
, VT
, ProdNeg
, SatMax
, SatMin
);
6666 return DAG
.getSelect(dl
, VT
, Overflow
, Result
, Product
);
6671 Node
->getOpcode() == ISD::SMULFIX
|| Node
->getOpcode() == ISD::SMULFIXSAT
;
6672 assert(((Signed
&& Scale
< VTSize
) || (!Signed
&& Scale
<= VTSize
)) &&
6673 "Expected scale to be less than the number of bits if signed or at "
6674 "most the number of bits if unsigned.");
6675 assert(LHS
.getValueType() == RHS
.getValueType() &&
6676 "Expected both operands to be the same type");
6678 // Get the upper and lower bits of the result.
6680 unsigned LoHiOp
= Signed
? ISD::SMUL_LOHI
: ISD::UMUL_LOHI
;
6681 unsigned HiOp
= Signed
? ISD::MULHS
: ISD::MULHU
;
6682 if (isOperationLegalOrCustom(LoHiOp
, VT
)) {
6683 SDValue Result
= DAG
.getNode(LoHiOp
, dl
, DAG
.getVTList(VT
, VT
), LHS
, RHS
);
6684 Lo
= Result
.getValue(0);
6685 Hi
= Result
.getValue(1);
6686 } else if (isOperationLegalOrCustom(HiOp
, VT
)) {
6687 Lo
= DAG
.getNode(ISD::MUL
, dl
, VT
, LHS
, RHS
);
6688 Hi
= DAG
.getNode(HiOp
, dl
, VT
, LHS
, RHS
);
6689 } else if (VT
.isVector()) {
6692 report_fatal_error("Unable to expand fixed point multiplication.");
6695 if (Scale
== VTSize
)
6696 // Result is just the top half since we'd be shifting by the width of the
6700 // The result will need to be shifted right by the scale since both operands
6701 // are scaled. The result is given to us in 2 halves, so we only want part of
6702 // both in the result.
6703 EVT ShiftTy
= getShiftAmountTy(VT
, DAG
.getDataLayout());
6704 SDValue Result
= DAG
.getNode(ISD::FSHR
, dl
, VT
, Hi
, Lo
,
6705 DAG
.getConstant(Scale
, dl
, ShiftTy
));
6709 unsigned OverflowBits
= VTSize
- Scale
+ 1; // +1 for the sign
6711 DAG
.getConstant(APInt::getHighBitsSet(VTSize
, OverflowBits
), dl
, VT
);
6712 SDValue LoMask
= DAG
.getConstant(
6713 APInt::getLowBitsSet(VTSize
, VTSize
- OverflowBits
), dl
, VT
);
6714 APInt MaxVal
= APInt::getSignedMaxValue(VTSize
);
6715 APInt MinVal
= APInt::getSignedMinValue(VTSize
);
6717 Result
= DAG
.getSelectCC(dl
, Hi
, LoMask
,
6718 DAG
.getConstant(MaxVal
, dl
, VT
), Result
,
6720 return DAG
.getSelectCC(dl
, Hi
, HiMask
,
6721 DAG
.getConstant(MinVal
, dl
, VT
), Result
,
6725 void TargetLowering::expandUADDSUBO(
6726 SDNode
*Node
, SDValue
&Result
, SDValue
&Overflow
, SelectionDAG
&DAG
) const {
6728 SDValue LHS
= Node
->getOperand(0);
6729 SDValue RHS
= Node
->getOperand(1);
6730 bool IsAdd
= Node
->getOpcode() == ISD::UADDO
;
6732 // If ADD/SUBCARRY is legal, use that instead.
6733 unsigned OpcCarry
= IsAdd
? ISD::ADDCARRY
: ISD::SUBCARRY
;
6734 if (isOperationLegalOrCustom(OpcCarry
, Node
->getValueType(0))) {
6735 SDValue CarryIn
= DAG
.getConstant(0, dl
, Node
->getValueType(1));
6736 SDValue NodeCarry
= DAG
.getNode(OpcCarry
, dl
, Node
->getVTList(),
6737 { LHS
, RHS
, CarryIn
});
6738 Result
= SDValue(NodeCarry
.getNode(), 0);
6739 Overflow
= SDValue(NodeCarry
.getNode(), 1);
6743 Result
= DAG
.getNode(IsAdd
? ISD::ADD
: ISD::SUB
, dl
,
6744 LHS
.getValueType(), LHS
, RHS
);
6746 EVT ResultType
= Node
->getValueType(1);
6747 EVT SetCCType
= getSetCCResultType(
6748 DAG
.getDataLayout(), *DAG
.getContext(), Node
->getValueType(0));
6749 ISD::CondCode CC
= IsAdd
? ISD::SETULT
: ISD::SETUGT
;
6750 SDValue SetCC
= DAG
.getSetCC(dl
, SetCCType
, Result
, LHS
, CC
);
6751 Overflow
= DAG
.getBoolExtOrTrunc(SetCC
, dl
, ResultType
, ResultType
);
6754 void TargetLowering::expandSADDSUBO(
6755 SDNode
*Node
, SDValue
&Result
, SDValue
&Overflow
, SelectionDAG
&DAG
) const {
6757 SDValue LHS
= Node
->getOperand(0);
6758 SDValue RHS
= Node
->getOperand(1);
6759 bool IsAdd
= Node
->getOpcode() == ISD::SADDO
;
6761 Result
= DAG
.getNode(IsAdd
? ISD::ADD
: ISD::SUB
, dl
,
6762 LHS
.getValueType(), LHS
, RHS
);
6764 EVT ResultType
= Node
->getValueType(1);
6765 EVT OType
= getSetCCResultType(
6766 DAG
.getDataLayout(), *DAG
.getContext(), Node
->getValueType(0));
6768 // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
6769 unsigned OpcSat
= IsAdd
? ISD::SADDSAT
: ISD::SSUBSAT
;
6770 if (isOperationLegalOrCustom(OpcSat
, LHS
.getValueType())) {
6771 SDValue Sat
= DAG
.getNode(OpcSat
, dl
, LHS
.getValueType(), LHS
, RHS
);
6772 SDValue SetCC
= DAG
.getSetCC(dl
, OType
, Result
, Sat
, ISD::SETNE
);
6773 Overflow
= DAG
.getBoolExtOrTrunc(SetCC
, dl
, ResultType
, ResultType
);
6777 SDValue Zero
= DAG
.getConstant(0, dl
, LHS
.getValueType());
6779 // LHSSign -> LHS >= 0
6780 // RHSSign -> RHS >= 0
6781 // SumSign -> Result >= 0
6784 // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
6786 // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
6787 SDValue LHSSign
= DAG
.getSetCC(dl
, OType
, LHS
, Zero
, ISD::SETGE
);
6788 SDValue RHSSign
= DAG
.getSetCC(dl
, OType
, RHS
, Zero
, ISD::SETGE
);
6789 SDValue SignsMatch
= DAG
.getSetCC(dl
, OType
, LHSSign
, RHSSign
,
6790 IsAdd
? ISD::SETEQ
: ISD::SETNE
);
6792 SDValue SumSign
= DAG
.getSetCC(dl
, OType
, Result
, Zero
, ISD::SETGE
);
6793 SDValue SumSignNE
= DAG
.getSetCC(dl
, OType
, LHSSign
, SumSign
, ISD::SETNE
);
6795 SDValue Cmp
= DAG
.getNode(ISD::AND
, dl
, OType
, SignsMatch
, SumSignNE
);
6796 Overflow
= DAG
.getBoolExtOrTrunc(Cmp
, dl
, ResultType
, ResultType
);
6799 bool TargetLowering::expandMULO(SDNode
*Node
, SDValue
&Result
,
6800 SDValue
&Overflow
, SelectionDAG
&DAG
) const {
6802 EVT VT
= Node
->getValueType(0);
6803 EVT SetCCVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(), VT
);
6804 SDValue LHS
= Node
->getOperand(0);
6805 SDValue RHS
= Node
->getOperand(1);
6806 bool isSigned
= Node
->getOpcode() == ISD::SMULO
;
6808 // For power-of-two multiplications we can use a simpler shift expansion.
6809 if (ConstantSDNode
*RHSC
= isConstOrConstSplat(RHS
)) {
6810 const APInt
&C
= RHSC
->getAPIntValue();
6811 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
6812 if (C
.isPowerOf2()) {
6813 // smulo(x, signed_min) is same as umulo(x, signed_min).
6814 bool UseArithShift
= isSigned
&& !C
.isMinSignedValue();
6815 EVT ShiftAmtTy
= getShiftAmountTy(VT
, DAG
.getDataLayout());
6816 SDValue ShiftAmt
= DAG
.getConstant(C
.logBase2(), dl
, ShiftAmtTy
);
6817 Result
= DAG
.getNode(ISD::SHL
, dl
, VT
, LHS
, ShiftAmt
);
6818 Overflow
= DAG
.getSetCC(dl
, SetCCVT
,
6819 DAG
.getNode(UseArithShift
? ISD::SRA
: ISD::SRL
,
6820 dl
, VT
, Result
, ShiftAmt
),
6826 EVT WideVT
= EVT::getIntegerVT(*DAG
.getContext(), VT
.getScalarSizeInBits() * 2);
6828 WideVT
= EVT::getVectorVT(*DAG
.getContext(), WideVT
,
6829 VT
.getVectorNumElements());
6833 static const unsigned Ops
[2][3] =
6834 { { ISD::MULHU
, ISD::UMUL_LOHI
, ISD::ZERO_EXTEND
},
6835 { ISD::MULHS
, ISD::SMUL_LOHI
, ISD::SIGN_EXTEND
}};
6836 if (isOperationLegalOrCustom(Ops
[isSigned
][0], VT
)) {
6837 BottomHalf
= DAG
.getNode(ISD::MUL
, dl
, VT
, LHS
, RHS
);
6838 TopHalf
= DAG
.getNode(Ops
[isSigned
][0], dl
, VT
, LHS
, RHS
);
6839 } else if (isOperationLegalOrCustom(Ops
[isSigned
][1], VT
)) {
6840 BottomHalf
= DAG
.getNode(Ops
[isSigned
][1], dl
, DAG
.getVTList(VT
, VT
), LHS
,
6842 TopHalf
= BottomHalf
.getValue(1);
6843 } else if (isTypeLegal(WideVT
)) {
6844 LHS
= DAG
.getNode(Ops
[isSigned
][2], dl
, WideVT
, LHS
);
6845 RHS
= DAG
.getNode(Ops
[isSigned
][2], dl
, WideVT
, RHS
);
6846 SDValue Mul
= DAG
.getNode(ISD::MUL
, dl
, WideVT
, LHS
, RHS
);
6847 BottomHalf
= DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, Mul
);
6848 SDValue ShiftAmt
= DAG
.getConstant(VT
.getScalarSizeInBits(), dl
,
6849 getShiftAmountTy(WideVT
, DAG
.getDataLayout()));
6850 TopHalf
= DAG
.getNode(ISD::TRUNCATE
, dl
, VT
,
6851 DAG
.getNode(ISD::SRL
, dl
, WideVT
, Mul
, ShiftAmt
));
6856 // We can fall back to a libcall with an illegal type for the MUL if we
6857 // have a libcall big enough.
6858 // Also, we can fall back to a division in some cases, but that's a big
6859 // performance hit in the general case.
6860 RTLIB::Libcall LC
= RTLIB::UNKNOWN_LIBCALL
;
6861 if (WideVT
== MVT::i16
)
6862 LC
= RTLIB::MUL_I16
;
6863 else if (WideVT
== MVT::i32
)
6864 LC
= RTLIB::MUL_I32
;
6865 else if (WideVT
== MVT::i64
)
6866 LC
= RTLIB::MUL_I64
;
6867 else if (WideVT
== MVT::i128
)
6868 LC
= RTLIB::MUL_I128
;
6869 assert(LC
!= RTLIB::UNKNOWN_LIBCALL
&& "Cannot expand this operation!");
6874 // The high part is obtained by SRA'ing all but one of the bits of low
6876 unsigned LoSize
= VT
.getSizeInBits();
6878 DAG
.getNode(ISD::SRA
, dl
, VT
, LHS
,
6879 DAG
.getConstant(LoSize
- 1, dl
,
6880 getPointerTy(DAG
.getDataLayout())));
6882 DAG
.getNode(ISD::SRA
, dl
, VT
, RHS
,
6883 DAG
.getConstant(LoSize
- 1, dl
,
6884 getPointerTy(DAG
.getDataLayout())));
6886 HiLHS
= DAG
.getConstant(0, dl
, VT
);
6887 HiRHS
= DAG
.getConstant(0, dl
, VT
);
6890 // Here we're passing the 2 arguments explicitly as 4 arguments that are
6891 // pre-lowered to the correct types. This all depends upon WideVT not
6892 // being a legal type for the architecture and thus has to be split to
6895 TargetLowering::MakeLibCallOptions CallOptions
;
6896 CallOptions
.setSExt(isSigned
);
6897 CallOptions
.setIsPostTypeLegalization(true);
6898 if (shouldSplitFunctionArgumentsAsLittleEndian(DAG
.getDataLayout())) {
6899 // Halves of WideVT are packed into registers in different order
6900 // depending on platform endianness. This is usually handled by
6901 // the C calling convention, but we can't defer to it in
6903 SDValue Args
[] = { LHS
, HiLHS
, RHS
, HiRHS
};
6904 Ret
= makeLibCall(DAG
, LC
, WideVT
, Args
, CallOptions
, dl
).first
;
6906 SDValue Args
[] = { HiLHS
, LHS
, HiRHS
, RHS
};
6907 Ret
= makeLibCall(DAG
, LC
, WideVT
, Args
, CallOptions
, dl
).first
;
6909 assert(Ret
.getOpcode() == ISD::MERGE_VALUES
&&
6910 "Ret value is a collection of constituent nodes holding result.");
6911 if (DAG
.getDataLayout().isLittleEndian()) {
6913 BottomHalf
= Ret
.getOperand(0);
6914 TopHalf
= Ret
.getOperand(1);
6916 BottomHalf
= Ret
.getOperand(1);
6917 TopHalf
= Ret
.getOperand(0);
6921 Result
= BottomHalf
;
6923 SDValue ShiftAmt
= DAG
.getConstant(
6924 VT
.getScalarSizeInBits() - 1, dl
,
6925 getShiftAmountTy(BottomHalf
.getValueType(), DAG
.getDataLayout()));
6926 SDValue Sign
= DAG
.getNode(ISD::SRA
, dl
, VT
, BottomHalf
, ShiftAmt
);
6927 Overflow
= DAG
.getSetCC(dl
, SetCCVT
, TopHalf
, Sign
, ISD::SETNE
);
6929 Overflow
= DAG
.getSetCC(dl
, SetCCVT
, TopHalf
,
6930 DAG
.getConstant(0, dl
, VT
), ISD::SETNE
);
6933 // Truncate the result if SetCC returns a larger type than needed.
6934 EVT RType
= Node
->getValueType(1);
6935 if (RType
.getSizeInBits() < Overflow
.getValueSizeInBits())
6936 Overflow
= DAG
.getNode(ISD::TRUNCATE
, dl
, RType
, Overflow
);
6938 assert(RType
.getSizeInBits() == Overflow
.getValueSizeInBits() &&
6939 "Unexpected result type for S/UMULO legalization");
6943 SDValue
TargetLowering::expandVecReduce(SDNode
*Node
, SelectionDAG
&DAG
) const {
6945 bool NoNaN
= Node
->getFlags().hasNoNaNs();
6946 unsigned BaseOpcode
= 0;
6947 switch (Node
->getOpcode()) {
6948 default: llvm_unreachable("Expected VECREDUCE opcode");
6949 case ISD::VECREDUCE_FADD
: BaseOpcode
= ISD::FADD
; break;
6950 case ISD::VECREDUCE_FMUL
: BaseOpcode
= ISD::FMUL
; break;
6951 case ISD::VECREDUCE_ADD
: BaseOpcode
= ISD::ADD
; break;
6952 case ISD::VECREDUCE_MUL
: BaseOpcode
= ISD::MUL
; break;
6953 case ISD::VECREDUCE_AND
: BaseOpcode
= ISD::AND
; break;
6954 case ISD::VECREDUCE_OR
: BaseOpcode
= ISD::OR
; break;
6955 case ISD::VECREDUCE_XOR
: BaseOpcode
= ISD::XOR
; break;
6956 case ISD::VECREDUCE_SMAX
: BaseOpcode
= ISD::SMAX
; break;
6957 case ISD::VECREDUCE_SMIN
: BaseOpcode
= ISD::SMIN
; break;
6958 case ISD::VECREDUCE_UMAX
: BaseOpcode
= ISD::UMAX
; break;
6959 case ISD::VECREDUCE_UMIN
: BaseOpcode
= ISD::UMIN
; break;
6960 case ISD::VECREDUCE_FMAX
:
6961 BaseOpcode
= NoNaN
? ISD::FMAXNUM
: ISD::FMAXIMUM
;
6963 case ISD::VECREDUCE_FMIN
:
6964 BaseOpcode
= NoNaN
? ISD::FMINNUM
: ISD::FMINIMUM
;
6968 SDValue Op
= Node
->getOperand(0);
6969 EVT VT
= Op
.getValueType();
6971 // Try to use a shuffle reduction for power of two vectors.
6972 if (VT
.isPow2VectorType()) {
6973 while (VT
.getVectorNumElements() > 1) {
6974 EVT HalfVT
= VT
.getHalfNumVectorElementsVT(*DAG
.getContext());
6975 if (!isOperationLegalOrCustom(BaseOpcode
, HalfVT
))
6979 std::tie(Lo
, Hi
) = DAG
.SplitVector(Op
, dl
);
6980 Op
= DAG
.getNode(BaseOpcode
, dl
, HalfVT
, Lo
, Hi
);
6985 EVT EltVT
= VT
.getVectorElementType();
6986 unsigned NumElts
= VT
.getVectorNumElements();
6988 SmallVector
<SDValue
, 8> Ops
;
6989 DAG
.ExtractVectorElements(Op
, Ops
, 0, NumElts
);
6991 SDValue Res
= Ops
[0];
6992 for (unsigned i
= 1; i
< NumElts
; i
++)
6993 Res
= DAG
.getNode(BaseOpcode
, dl
, EltVT
, Res
, Ops
[i
], Node
->getFlags());
6995 // Result type may be wider than element type.
6996 if (EltVT
!= Node
->getValueType(0))
6997 Res
= DAG
.getNode(ISD::ANY_EXTEND
, dl
, Node
->getValueType(0), Res
);