1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Target/TargetLowering.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/CodeGen/CallingConvLower.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.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/MathExtras.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
38 /// NOTE: The TargetMachine owns TLOF.
39 TargetLowering::TargetLowering(const TargetMachine &tm)
40 : TargetLoweringBase(tm) {}
42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
46 bool TargetLowering::isPositionIndependent() const {
47 return getTargetMachine().isPositionIndependent();
50 /// Check whether a given call node is in tail position within its function. If
51 /// so, it sets Chain to the input chain of the tail call.
52 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
53 SDValue &Chain) const {
54 const Function *F = DAG.getMachineFunction().getFunction();
56 // Conservatively require the attributes of the call to match those of
57 // the return. Ignore noalias because it doesn't affect the call sequence.
58 AttributeSet CallerAttrs = F->getAttributes();
59 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
60 .removeAttribute(Attribute::NoAlias).hasAttributes())
63 // It's not safe to eliminate the sign / zero extension of the return value.
64 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
65 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
68 // Check if the only use is a function return node.
69 return isUsedByReturnOnly(Node, Chain);
72 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
73 const uint32_t *CallerPreservedMask,
74 const SmallVectorImpl<CCValAssign> &ArgLocs,
75 const SmallVectorImpl<SDValue> &OutVals) const {
76 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
77 const CCValAssign &ArgLoc = ArgLocs[I];
78 if (!ArgLoc.isRegLoc())
80 unsigned Reg = ArgLoc.getLocReg();
81 // Only look at callee saved registers.
82 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
84 // Check that we pass the value used for the caller.
85 // (We look for a CopyFromReg reading a virtual register that is used
86 // for the function live-in value of register Reg)
87 SDValue Value = OutVals[I];
88 if (Value->getOpcode() != ISD::CopyFromReg)
90 unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
91 if (MRI.getLiveInPhysReg(ArgReg) != Reg)
97 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
98 /// and called function attributes.
99 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
101 isSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt);
102 isZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
103 isInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg);
104 isSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
105 isNest = CS->paramHasAttr(AttrIdx, Attribute::Nest);
106 isByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
107 isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
108 isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
109 isSwiftSelf = CS->paramHasAttr(AttrIdx, Attribute::SwiftSelf);
110 isSwiftError = CS->paramHasAttr(AttrIdx, Attribute::SwiftError);
111 Alignment = CS->getParamAlignment(AttrIdx);
114 /// Generate a libcall taking the given operands as arguments and returning a
115 /// result of type RetVT.
116 std::pair<SDValue, SDValue>
117 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
118 ArrayRef<SDValue> Ops, bool isSigned,
119 const SDLoc &dl, bool doesNotReturn,
120 bool isReturnValueUsed) const {
121 TargetLowering::ArgListTy Args;
122 Args.reserve(Ops.size());
124 TargetLowering::ArgListEntry Entry;
125 for (SDValue Op : Ops) {
127 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
128 Entry.isSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
129 Entry.isZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
130 Args.push_back(Entry);
133 if (LC == RTLIB::UNKNOWN_LIBCALL)
134 report_fatal_error("Unsupported library call operation!");
135 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
136 getPointerTy(DAG.getDataLayout()));
138 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
139 TargetLowering::CallLoweringInfo CLI(DAG);
140 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
141 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
142 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
143 .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed)
144 .setSExtResult(signExtend).setZExtResult(!signExtend);
145 return LowerCallTo(CLI);
148 /// Soften the operands of a comparison. This code is shared among BR_CC,
149 /// SELECT_CC, and SETCC handlers.
150 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
151 SDValue &NewLHS, SDValue &NewRHS,
152 ISD::CondCode &CCCode,
153 const SDLoc &dl) const {
154 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
155 && "Unsupported setcc type!");
157 // Expand into one or more soft-fp libcall(s).
158 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
159 bool ShouldInvertCC = false;
163 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
164 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
165 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
169 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
170 (VT == MVT::f64) ? RTLIB::UNE_F64 :
171 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
175 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
176 (VT == MVT::f64) ? RTLIB::OGE_F64 :
177 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
181 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
182 (VT == MVT::f64) ? RTLIB::OLT_F64 :
183 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
187 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
188 (VT == MVT::f64) ? RTLIB::OLE_F64 :
189 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
193 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
194 (VT == MVT::f64) ? RTLIB::OGT_F64 :
195 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
198 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
199 (VT == MVT::f64) ? RTLIB::UO_F64 :
200 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
203 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
204 (VT == MVT::f64) ? RTLIB::O_F64 :
205 (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
208 // SETONE = SETOLT | SETOGT
209 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
210 (VT == MVT::f64) ? RTLIB::OLT_F64 :
211 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
212 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
213 (VT == MVT::f64) ? RTLIB::OGT_F64 :
214 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
217 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
218 (VT == MVT::f64) ? RTLIB::UO_F64 :
219 (VT == MVT::f128) ? RTLIB::UO_F64 : RTLIB::UO_PPCF128;
220 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
221 (VT == MVT::f64) ? RTLIB::OEQ_F64 :
222 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
225 // Invert CC for unordered comparisons
226 ShouldInvertCC = true;
229 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
230 (VT == MVT::f64) ? RTLIB::OGE_F64 :
231 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
234 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
235 (VT == MVT::f64) ? RTLIB::OGT_F64 :
236 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
239 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
240 (VT == MVT::f64) ? RTLIB::OLE_F64 :
241 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
244 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
245 (VT == MVT::f64) ? RTLIB::OLT_F64 :
246 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
248 default: llvm_unreachable("Do not know how to soften this setcc!");
252 // Use the target specific return value for comparions lib calls.
253 EVT RetVT = getCmpLibcallReturnType();
254 SDValue Ops[2] = {NewLHS, NewRHS};
255 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
257 NewRHS = DAG.getConstant(0, dl, RetVT);
259 CCCode = getCmpLibcallCC(LC1);
261 CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
263 if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
264 SDValue Tmp = DAG.getNode(
266 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
267 NewLHS, NewRHS, DAG.getCondCode(CCCode));
268 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
270 NewLHS = DAG.getNode(
272 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
273 NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
274 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
279 /// Return the entry encoding for a jump table in the current function. The
280 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
281 unsigned TargetLowering::getJumpTableEncoding() const {
282 // In non-pic modes, just use the address of a block.
283 if (!isPositionIndependent())
284 return MachineJumpTableInfo::EK_BlockAddress;
286 // In PIC mode, if the target supports a GPRel32 directive, use it.
287 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
288 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
290 // Otherwise, use a label difference.
291 return MachineJumpTableInfo::EK_LabelDifference32;
294 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
295 SelectionDAG &DAG) const {
296 // If our PIC model is GP relative, use the global offset table as the base.
297 unsigned JTEncoding = getJumpTableEncoding();
299 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
300 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
301 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
306 /// This returns the relocation base for the given PIC jumptable, the same as
307 /// getPICJumpTableRelocBase, but as an MCExpr.
309 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
310 unsigned JTI,MCContext &Ctx) const{
311 // The normal PIC reloc base is the label at the start of the jump table.
312 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
316 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
317 const TargetMachine &TM = getTargetMachine();
318 const GlobalValue *GV = GA->getGlobal();
320 // If the address is not even local to this DSO we will have to load it from
321 // a got and then add the offset.
322 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
325 // If the code is position independent we will have to add a base register.
326 if (isPositionIndependent())
329 // Otherwise we can do it.
333 //===----------------------------------------------------------------------===//
334 // Optimization Methods
335 //===----------------------------------------------------------------------===//
337 /// Check to see if the specified operand of the specified instruction is a
338 /// constant integer. If so, check to see if there are any bits set in the
339 /// constant that are not demanded. If so, shrink the constant and return true.
340 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
341 const APInt &Demanded) {
344 // FIXME: ISD::SELECT, ISD::SELECT_CC
345 switch (Op.getOpcode()) {
350 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
351 if (!C) return false;
353 if (Op.getOpcode() == ISD::XOR &&
354 (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
357 // if we can expand it to have all bits set, do it
358 if (C->getAPIntValue().intersects(~Demanded)) {
359 EVT VT = Op.getValueType();
360 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
361 DAG.getConstant(Demanded &
364 return CombineTo(Op, New);
374 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
375 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
376 /// generalized for targets with other types of implicit widening casts.
377 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
379 const APInt &Demanded,
381 assert(Op.getNumOperands() == 2 &&
382 "ShrinkDemandedOp only supports binary operators!");
383 assert(Op.getNode()->getNumValues() == 1 &&
384 "ShrinkDemandedOp only supports nodes with one result!");
386 // Early return, as this function cannot handle vector types.
387 if (Op.getValueType().isVector())
390 // Don't do this if the node has another user, which may require the
392 if (!Op.getNode()->hasOneUse())
395 // Search for the smallest integer type with free casts to and from
396 // Op's type. For expedience, just check power-of-2 integer types.
397 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
398 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
399 unsigned SmallVTBits = DemandedSize;
400 if (!isPowerOf2_32(SmallVTBits))
401 SmallVTBits = NextPowerOf2(SmallVTBits);
402 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
403 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
404 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
405 TLI.isZExtFree(SmallVT, Op.getValueType())) {
406 // We found a type with free casts.
407 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
408 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
409 Op.getNode()->getOperand(0)),
410 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
411 Op.getNode()->getOperand(1)));
412 bool NeedZext = DemandedSize > SmallVTBits;
413 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
414 dl, Op.getValueType(), X);
415 return CombineTo(Op, Z);
421 /// Look at Op. At this point, we know that only the DemandedMask bits of the
422 /// result of Op are ever used downstream. If we can use this information to
423 /// simplify Op, create a new simplified DAG node and return true, returning the
424 /// original and new nodes in Old and New. Otherwise, analyze the expression and
425 /// return a mask of KnownOne and KnownZero bits for the expression (used to
426 /// simplify the caller). The KnownZero/One bits may only be accurate for those
427 /// bits in the DemandedMask.
428 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
429 const APInt &DemandedMask,
432 TargetLoweringOpt &TLO,
433 unsigned Depth) const {
434 unsigned BitWidth = DemandedMask.getBitWidth();
435 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
436 "Mask size mismatches value type size!");
437 APInt NewMask = DemandedMask;
439 auto &DL = TLO.DAG.getDataLayout();
441 // Don't know anything.
442 KnownZero = KnownOne = APInt(BitWidth, 0);
444 // Other users may use these bits.
445 if (!Op.getNode()->hasOneUse()) {
447 // If not at the root, Just compute the KnownZero/KnownOne bits to
448 // simplify things downstream.
449 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
452 // If this is the root being simplified, allow it to have multiple uses,
453 // just set the NewMask to all bits.
454 NewMask = APInt::getAllOnesValue(BitWidth);
455 } else if (DemandedMask == 0) {
456 // Not demanding any bits from Op.
458 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
460 } else if (Depth == 6) { // Limit search depth.
464 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
465 switch (Op.getOpcode()) {
467 // We know all of the bits for a constant!
468 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
469 KnownZero = ~KnownOne;
470 return false; // Don't fall through, will infinitely loop.
472 // If the RHS is a constant, check to see if the LHS would be zero without
473 // using the bits from the RHS. Below, we use knowledge about the RHS to
474 // simplify the LHS, here we're using information from the LHS to simplify
476 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
477 APInt LHSZero, LHSOne;
478 // Do not increment Depth here; that can cause an infinite loop.
479 TLO.DAG.computeKnownBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
480 // If the LHS already has zeros where RHSC does, this and is dead.
481 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
482 return TLO.CombineTo(Op, Op.getOperand(0));
483 // If any of the set bits in the RHS are known zero on the LHS, shrink
485 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
489 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
490 KnownOne, TLO, Depth+1))
492 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
493 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
494 KnownZero2, KnownOne2, TLO, Depth+1))
496 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
498 // If all of the demanded bits are known one on one side, return the other.
499 // These bits cannot contribute to the result of the 'and'.
500 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
501 return TLO.CombineTo(Op, Op.getOperand(0));
502 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
503 return TLO.CombineTo(Op, Op.getOperand(1));
504 // If all of the demanded bits in the inputs are known zeros, return zero.
505 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
506 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
507 // If the RHS is a constant, see if we can simplify it.
508 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
510 // If the operation can be done in a smaller type, do so.
511 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
514 // Output known-1 bits are only known if set in both the LHS & RHS.
515 KnownOne &= KnownOne2;
516 // Output known-0 are known to be clear if zero in either the LHS | RHS.
517 KnownZero |= KnownZero2;
520 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
521 KnownOne, TLO, Depth+1))
523 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
524 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
525 KnownZero2, KnownOne2, TLO, Depth+1))
527 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
529 // If all of the demanded bits are known zero on one side, return the other.
530 // These bits cannot contribute to the result of the 'or'.
531 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
532 return TLO.CombineTo(Op, Op.getOperand(0));
533 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
534 return TLO.CombineTo(Op, Op.getOperand(1));
535 // If all of the potentially set bits on one side are known to be set on
536 // the other side, just use the 'other' side.
537 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
538 return TLO.CombineTo(Op, Op.getOperand(0));
539 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
540 return TLO.CombineTo(Op, Op.getOperand(1));
541 // If the RHS is a constant, see if we can simplify it.
542 if (TLO.ShrinkDemandedConstant(Op, NewMask))
544 // If the operation can be done in a smaller type, do so.
545 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
548 // Output known-0 bits are only known if clear in both the LHS & RHS.
549 KnownZero &= KnownZero2;
550 // Output known-1 are known to be set if set in either the LHS | RHS.
551 KnownOne |= KnownOne2;
554 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
555 KnownOne, TLO, Depth+1))
557 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
558 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
559 KnownOne2, TLO, Depth+1))
561 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
563 // If all of the demanded bits are known zero on one side, return the other.
564 // These bits cannot contribute to the result of the 'xor'.
565 if ((KnownZero & NewMask) == NewMask)
566 return TLO.CombineTo(Op, Op.getOperand(0));
567 if ((KnownZero2 & NewMask) == NewMask)
568 return TLO.CombineTo(Op, Op.getOperand(1));
569 // If the operation can be done in a smaller type, do so.
570 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
573 // If all of the unknown bits are known to be zero on one side or the other
574 // (but not both) turn this into an *inclusive* or.
575 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
576 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
577 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
581 // Output known-0 bits are known if clear or set in both the LHS & RHS.
582 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
583 // Output known-1 are known to be set if set in only one of the LHS, RHS.
584 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
586 // If all of the demanded bits on one side are known, and all of the set
587 // bits on that side are also known to be set on the other side, turn this
588 // into an AND, as we know the bits will be cleared.
589 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
590 // NB: it is okay if more bits are known than are requested
591 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
592 if (KnownOne == KnownOne2) { // set bits are the same on both sides
593 EVT VT = Op.getValueType();
594 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
595 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
596 Op.getOperand(0), ANDC));
600 // If the RHS is a constant, see if we can simplify it.
601 // for XOR, we prefer to force bits to 1 if they will make a -1.
602 // if we can't force bits, try to shrink constant
603 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
604 APInt Expanded = C->getAPIntValue() | (~NewMask);
605 // if we can expand it to have all bits set, do it
606 if (Expanded.isAllOnesValue()) {
607 if (Expanded != C->getAPIntValue()) {
608 EVT VT = Op.getValueType();
609 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
610 TLO.DAG.getConstant(Expanded, dl, VT));
611 return TLO.CombineTo(Op, New);
613 // if it already has all the bits set, nothing to change
614 // but don't shrink either!
615 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
620 KnownZero = KnownZeroOut;
621 KnownOne = KnownOneOut;
624 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
625 KnownOne, TLO, Depth+1))
627 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
628 KnownOne2, TLO, Depth+1))
630 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
631 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
633 // If the operands are constants, see if we can simplify them.
634 if (TLO.ShrinkDemandedConstant(Op, NewMask))
637 // Only known if known in both the LHS and RHS.
638 KnownOne &= KnownOne2;
639 KnownZero &= KnownZero2;
642 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
643 KnownOne, TLO, Depth+1))
645 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
646 KnownOne2, TLO, Depth+1))
648 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
649 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
651 // If the operands are constants, see if we can simplify them.
652 if (TLO.ShrinkDemandedConstant(Op, NewMask))
655 // Only known if known in both the LHS and RHS.
656 KnownOne &= KnownOne2;
657 KnownZero &= KnownZero2;
660 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
661 unsigned ShAmt = SA->getZExtValue();
662 SDValue InOp = Op.getOperand(0);
664 // If the shift count is an invalid immediate, don't do anything.
665 if (ShAmt >= BitWidth)
668 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
669 // single shift. We can do this if the bottom bits (which are shifted
670 // out) are never demanded.
671 if (InOp.getOpcode() == ISD::SRL &&
672 isa<ConstantSDNode>(InOp.getOperand(1))) {
673 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
674 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
675 unsigned Opc = ISD::SHL;
683 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
684 EVT VT = Op.getValueType();
685 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
686 InOp.getOperand(0), NewSA));
690 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
691 KnownZero, KnownOne, TLO, Depth+1))
694 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
695 // are not demanded. This will likely allow the anyext to be folded away.
696 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
697 SDValue InnerOp = InOp.getNode()->getOperand(0);
698 EVT InnerVT = InnerOp.getValueType();
699 unsigned InnerBits = InnerVT.getSizeInBits();
700 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
701 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
702 EVT ShTy = getShiftAmountTy(InnerVT, DL);
703 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
706 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
707 TLO.DAG.getConstant(ShAmt, dl, ShTy));
710 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
713 // Repeat the SHL optimization above in cases where an extension
714 // intervenes: (shl (anyext (shr x, c1)), c2) to
715 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
716 // aren't demanded (as above) and that the shifted upper c1 bits of
717 // x aren't demanded.
718 if (InOp.hasOneUse() &&
719 InnerOp.getOpcode() == ISD::SRL &&
720 InnerOp.hasOneUse() &&
721 isa<ConstantSDNode>(InnerOp.getOperand(1))) {
722 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
724 if (InnerShAmt < ShAmt &&
725 InnerShAmt < InnerBits &&
726 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
727 NewMask.trunc(ShAmt) == 0) {
729 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
730 Op.getOperand(1).getValueType());
731 EVT VT = Op.getValueType();
732 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
733 InnerOp.getOperand(0));
734 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
740 KnownZero <<= SA->getZExtValue();
741 KnownOne <<= SA->getZExtValue();
742 // low bits known zero.
743 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
747 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
748 EVT VT = Op.getValueType();
749 unsigned ShAmt = SA->getZExtValue();
750 unsigned VTSize = VT.getSizeInBits();
751 SDValue InOp = Op.getOperand(0);
753 // If the shift count is an invalid immediate, don't do anything.
754 if (ShAmt >= BitWidth)
757 APInt InDemandedMask = (NewMask << ShAmt);
759 // If the shift is exact, then it does demand the low bits (and knows that
761 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
762 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
764 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
765 // single shift. We can do this if the top bits (which are shifted out)
766 // are never demanded.
767 if (InOp.getOpcode() == ISD::SHL &&
768 isa<ConstantSDNode>(InOp.getOperand(1))) {
769 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
770 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
771 unsigned Opc = ISD::SRL;
779 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
780 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
781 InOp.getOperand(0), NewSA));
785 // Compute the new bits that are at the top now.
786 if (SimplifyDemandedBits(InOp, InDemandedMask,
787 KnownZero, KnownOne, TLO, Depth+1))
789 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
790 KnownZero = KnownZero.lshr(ShAmt);
791 KnownOne = KnownOne.lshr(ShAmt);
793 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
794 KnownZero |= HighBits; // High bits known zero.
798 // If this is an arithmetic shift right and only the low-bit is set, we can
799 // always convert this into a logical shr, even if the shift amount is
800 // variable. The low bit of the shift cannot be an input sign bit unless
801 // the shift amount is >= the size of the datatype, which is undefined.
803 return TLO.CombineTo(Op,
804 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
805 Op.getOperand(0), Op.getOperand(1)));
807 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
808 EVT VT = Op.getValueType();
809 unsigned ShAmt = SA->getZExtValue();
811 // If the shift count is an invalid immediate, don't do anything.
812 if (ShAmt >= BitWidth)
815 APInt InDemandedMask = (NewMask << ShAmt);
817 // If the shift is exact, then it does demand the low bits (and knows that
819 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
820 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt);
822 // If any of the demanded bits are produced by the sign extension, we also
823 // demand the input sign bit.
824 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
825 if (HighBits.intersects(NewMask))
826 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
828 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
829 KnownZero, KnownOne, TLO, Depth+1))
831 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
832 KnownZero = KnownZero.lshr(ShAmt);
833 KnownOne = KnownOne.lshr(ShAmt);
835 // Handle the sign bit, adjusted to where it is now in the mask.
836 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
838 // If the input sign bit is known to be zero, or if none of the top bits
839 // are demanded, turn this into an unsigned shift right.
840 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
842 Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
843 return TLO.CombineTo(Op,
844 TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
845 Op.getOperand(1), &Flags));
848 int Log2 = NewMask.exactLogBase2();
850 // The bit must come from the sign.
852 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
853 Op.getOperand(1).getValueType());
854 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
855 Op.getOperand(0), NewSA));
858 if (KnownOne.intersects(SignBit))
859 // New bits are known one.
860 KnownOne |= HighBits;
863 case ISD::SIGN_EXTEND_INREG: {
864 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
866 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
867 // If we only care about the highest bit, don't bother shifting right.
868 if (MsbMask == NewMask) {
869 unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
870 SDValue InOp = Op.getOperand(0);
871 unsigned VTBits = Op->getValueType(0).getScalarType().getSizeInBits();
872 bool AlreadySignExtended =
873 TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
874 // However if the input is already sign extended we expect the sign
875 // extension to be dropped altogether later and do not simplify.
876 if (!AlreadySignExtended) {
877 // Compute the correct shift amount type, which must be getShiftAmountTy
878 // for scalar types after legalization.
879 EVT ShiftAmtTy = Op.getValueType();
880 if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
881 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
883 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
885 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
886 Op.getValueType(), InOp,
891 // Sign extension. Compute the demanded bits in the result that are not
892 // present in the input.
894 APInt::getHighBitsSet(BitWidth,
895 BitWidth - ExVT.getScalarType().getSizeInBits());
897 // If none of the extended bits are demanded, eliminate the sextinreg.
898 if ((NewBits & NewMask) == 0)
899 return TLO.CombineTo(Op, Op.getOperand(0));
902 APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
903 APInt InputDemandedBits =
904 APInt::getLowBitsSet(BitWidth,
905 ExVT.getScalarType().getSizeInBits()) &
908 // Since the sign extended bits are demanded, we know that the sign
910 InputDemandedBits |= InSignBit;
912 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
913 KnownZero, KnownOne, TLO, Depth+1))
915 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
917 // If the sign bit of the input is known set or clear, then we know the
918 // top bits of the result.
920 // If the input sign bit is known zero, convert this into a zero extension.
921 if (KnownZero.intersects(InSignBit))
922 return TLO.CombineTo(Op,
923 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
925 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
927 KnownZero &= ~NewBits;
928 } else { // Input sign bit unknown
929 KnownZero &= ~NewBits;
930 KnownOne &= ~NewBits;
934 case ISD::BUILD_PAIR: {
935 EVT HalfVT = Op.getOperand(0).getValueType();
936 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
938 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
939 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
941 APInt KnownZeroLo, KnownOneLo;
942 APInt KnownZeroHi, KnownOneHi;
944 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
945 KnownOneLo, TLO, Depth + 1))
948 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
949 KnownOneHi, TLO, Depth + 1))
952 KnownZero = KnownZeroLo.zext(BitWidth) |
953 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
955 KnownOne = KnownOneLo.zext(BitWidth) |
956 KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
959 case ISD::ZERO_EXTEND: {
960 unsigned OperandBitWidth =
961 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
962 APInt InMask = NewMask.trunc(OperandBitWidth);
964 // If none of the top bits are demanded, convert this into an any_extend.
966 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
967 if (!NewBits.intersects(NewMask))
968 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
972 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
973 KnownZero, KnownOne, TLO, Depth+1))
975 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
976 KnownZero = KnownZero.zext(BitWidth);
977 KnownOne = KnownOne.zext(BitWidth);
978 KnownZero |= NewBits;
981 case ISD::SIGN_EXTEND: {
982 EVT InVT = Op.getOperand(0).getValueType();
983 unsigned InBits = InVT.getScalarType().getSizeInBits();
984 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
985 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
986 APInt NewBits = ~InMask & NewMask;
988 // If none of the top bits are demanded, convert this into an any_extend.
990 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
994 // Since some of the sign extended bits are demanded, we know that the sign
996 APInt InDemandedBits = InMask & NewMask;
997 InDemandedBits |= InSignBit;
998 InDemandedBits = InDemandedBits.trunc(InBits);
1000 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1001 KnownOne, TLO, Depth+1))
1003 KnownZero = KnownZero.zext(BitWidth);
1004 KnownOne = KnownOne.zext(BitWidth);
1006 // If the sign bit is known zero, convert this to a zero extend.
1007 if (KnownZero.intersects(InSignBit))
1008 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
1012 // If the sign bit is known one, the top bits match.
1013 if (KnownOne.intersects(InSignBit)) {
1014 KnownOne |= NewBits;
1015 assert((KnownZero & NewBits) == 0);
1016 } else { // Otherwise, top bits aren't known.
1017 assert((KnownOne & NewBits) == 0);
1018 assert((KnownZero & NewBits) == 0);
1022 case ISD::ANY_EXTEND: {
1023 unsigned OperandBitWidth =
1024 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1025 APInt InMask = NewMask.trunc(OperandBitWidth);
1026 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1027 KnownZero, KnownOne, TLO, Depth+1))
1029 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1030 KnownZero = KnownZero.zext(BitWidth);
1031 KnownOne = KnownOne.zext(BitWidth);
1034 case ISD::TRUNCATE: {
1035 // Simplify the input, using demanded bit information, and compute the known
1036 // zero/one bits live out.
1037 unsigned OperandBitWidth =
1038 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
1039 APInt TruncMask = NewMask.zext(OperandBitWidth);
1040 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
1041 KnownZero, KnownOne, TLO, Depth+1))
1043 KnownZero = KnownZero.trunc(BitWidth);
1044 KnownOne = KnownOne.trunc(BitWidth);
1046 // If the input is only used by this truncate, see if we can shrink it based
1047 // on the known demanded bits.
1048 if (Op.getOperand(0).getNode()->hasOneUse()) {
1049 SDValue In = Op.getOperand(0);
1050 switch (In.getOpcode()) {
1053 // Shrink SRL by a constant if none of the high bits shifted in are
1055 if (TLO.LegalTypes() &&
1056 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1057 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1060 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1063 SDValue Shift = In.getOperand(1);
1064 if (TLO.LegalTypes()) {
1065 uint64_t ShVal = ShAmt->getZExtValue();
1066 Shift = TLO.DAG.getConstant(ShVal, dl,
1067 getShiftAmountTy(Op.getValueType(), DL));
1070 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1071 OperandBitWidth - BitWidth);
1072 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
1074 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1075 // None of the shifted in bits are needed. Add a truncate of the
1076 // shift input, then shift it.
1077 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1080 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1089 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1092 case ISD::AssertZext: {
1093 // AssertZext demands all of the high bits, plus any of the low bits
1094 // demanded by its users.
1095 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1096 APInt InMask = APInt::getLowBitsSet(BitWidth,
1097 VT.getSizeInBits());
1098 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
1099 KnownZero, KnownOne, TLO, Depth+1))
1101 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1103 KnownZero |= ~InMask & NewMask;
1107 // If this is an FP->Int bitcast and if the sign bit is the only
1108 // thing demanded, turn this into a FGETSIGN.
1109 if (!TLO.LegalOperations() &&
1110 !Op.getValueType().isVector() &&
1111 !Op.getOperand(0).getValueType().isVector() &&
1112 NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1113 Op.getOperand(0).getValueType().isFloatingPoint()) {
1114 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1115 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1116 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
1117 Op.getOperand(0).getValueType() != MVT::f128) {
1118 // Cannot eliminate/lower SHL for f128 yet.
1119 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1120 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1121 // place. We expect the SHL to be eliminated by other optimizations.
1122 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1123 unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1124 if (!OpVTLegal && OpVTSizeInBits > 32)
1125 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1126 unsigned ShVal = Op.getValueType().getSizeInBits()-1;
1127 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
1128 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1137 // Add, Sub, and Mul don't demand any bits in positions beyond that
1138 // of the highest bit demanded of them.
1139 APInt LoMask = APInt::getLowBitsSet(BitWidth,
1140 BitWidth - NewMask.countLeadingZeros());
1141 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1142 KnownOne2, TLO, Depth+1))
1144 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1145 KnownOne2, TLO, Depth+1))
1147 // See if the operation should be performed at a smaller bit width.
1148 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1153 // Just use computeKnownBits to compute output bits.
1154 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
1158 // If we know the value of all of the demanded bits, return this as a
1160 if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1161 // Avoid folding to a constant if any OpaqueConstant is involved.
1162 const SDNode *N = Op.getNode();
1163 for (SDNodeIterator I = SDNodeIterator::begin(N),
1164 E = SDNodeIterator::end(N); I != E; ++I) {
1166 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1170 return TLO.CombineTo(Op,
1171 TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
1177 /// Determine which of the bits specified in Mask are known to be either zero or
1178 /// one and return them in the KnownZero/KnownOne bitsets.
1179 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1182 const SelectionDAG &DAG,
1183 unsigned Depth) const {
1184 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1185 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1186 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1187 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1188 "Should use MaskedValueIsZero if you don't know whether Op"
1189 " is a target node!");
1190 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1193 /// This method can be implemented by targets that want to expose additional
1194 /// information about sign bits to the DAG Combiner.
1195 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1196 const SelectionDAG &,
1197 unsigned Depth) const {
1198 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1199 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1200 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1201 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1202 "Should use ComputeNumSignBits if you don't know whether Op"
1203 " is a target node!");
1207 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1211 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1213 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1217 BitVector UndefElements;
1218 CN = BV->getConstantSplatNode(&UndefElements);
1219 // Only interested in constant splats, and we don't try to handle undef
1220 // elements in identifying boolean constants.
1221 if (!CN || UndefElements.none())
1225 switch (getBooleanContents(N->getValueType(0))) {
1226 case UndefinedBooleanContent:
1227 return CN->getAPIntValue()[0];
1228 case ZeroOrOneBooleanContent:
1230 case ZeroOrNegativeOneBooleanContent:
1231 return CN->isAllOnesValue();
1234 llvm_unreachable("Invalid boolean contents");
1237 SDValue TargetLowering::getConstTrueVal(SelectionDAG &DAG, EVT VT,
1238 const SDLoc &DL) const {
1239 unsigned ElementWidth = VT.getScalarSizeInBits();
1241 getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent
1242 ? APInt(ElementWidth, 1)
1243 : APInt::getAllOnesValue(ElementWidth);
1244 return DAG.getConstant(TrueInt, DL, VT);
1247 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1251 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1253 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1257 BitVector UndefElements;
1258 CN = BV->getConstantSplatNode(&UndefElements);
1259 // Only interested in constant splats, and we don't try to handle undef
1260 // elements in identifying boolean constants.
1261 if (!CN || UndefElements.none())
1265 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
1266 return !CN->getAPIntValue()[0];
1268 return CN->isNullValue();
1271 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
1276 TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
1278 case TargetLowering::ZeroOrOneBooleanContent:
1279 // An extended value of 1 is always true, unless its original type is i1,
1280 // in which case it will be sign extended to -1.
1281 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
1282 case TargetLowering::UndefinedBooleanContent:
1283 case TargetLowering::ZeroOrNegativeOneBooleanContent:
1284 return N->isAllOnesValue() && SExt;
1286 llvm_unreachable("Unexpected enumeration.");
1289 /// This helper function of SimplifySetCC tries to optimize the comparison when
1290 /// either operand of the SetCC node is a bitwise-and instruction.
1291 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
1293 DAGCombinerInfo &DCI,
1294 const SDLoc &DL) const {
1295 // Match these patterns in any of their permutations:
1298 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
1301 EVT OpVT = N0.getValueType();
1302 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
1303 (Cond != ISD::SETEQ && Cond != ISD::SETNE))
1307 if (N0.getOperand(0) == N1) {
1308 X = N0.getOperand(1);
1309 Y = N0.getOperand(0);
1310 } else if (N0.getOperand(1) == N1) {
1311 X = N0.getOperand(0);
1312 Y = N0.getOperand(1);
1317 SelectionDAG &DAG = DCI.DAG;
1318 SDValue Zero = DAG.getConstant(0, DL, OpVT);
1319 if (DAG.isKnownToBeAPowerOfTwo(Y)) {
1320 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
1321 // Note that where Y is variable and is known to have at most one bit set
1322 // (for example, if it is Z & 1) we cannot do this; the expressions are not
1323 // equivalent when Y == 0.
1324 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1325 if (DCI.isBeforeLegalizeOps() ||
1326 isCondCodeLegal(Cond, N0.getSimpleValueType()))
1327 return DAG.getSetCC(DL, VT, N0, Zero, Cond);
1328 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
1329 // If the target supports an 'and-not' or 'and-complement' logic operation,
1330 // try to use that to make a comparison operation more efficient.
1331 // But don't do this transform if the mask is a single bit because there are
1332 // more efficient ways to deal with that case (for example, 'bt' on x86 or
1333 // 'rlwinm' on PPC).
1335 // Bail out if the compare operand that we want to turn into a zero is
1336 // already a zero (otherwise, infinite loop).
1337 auto *YConst = dyn_cast<ConstantSDNode>(Y);
1338 if (YConst && YConst->isNullValue())
1341 // Transform this into: ~X & Y == 0.
1342 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
1343 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
1344 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
1350 /// Try to simplify a setcc built with the specified operands and cc. If it is
1351 /// unable to simplify it, return a null SDValue.
1352 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1353 ISD::CondCode Cond, bool foldBooleans,
1354 DAGCombinerInfo &DCI,
1355 const SDLoc &dl) const {
1356 SelectionDAG &DAG = DCI.DAG;
1358 // These setcc operations always fold.
1362 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
1364 case ISD::SETTRUE2: {
1365 TargetLowering::BooleanContent Cnt =
1366 getBooleanContents(N0->getValueType(0));
1367 return DAG.getConstant(
1368 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1373 // Ensure that the constant occurs on the RHS, and fold constant
1375 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1376 if (isa<ConstantSDNode>(N0.getNode()) &&
1377 (DCI.isBeforeLegalizeOps() ||
1378 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1379 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
1381 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1382 const APInt &C1 = N1C->getAPIntValue();
1384 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1385 // equality comparison, then we're just comparing whether X itself is
1387 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1388 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1389 N0.getOperand(1).getOpcode() == ISD::Constant) {
1391 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1392 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1393 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1394 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1395 // (srl (ctlz x), 5) == 0 -> X != 0
1396 // (srl (ctlz x), 5) != 1 -> X != 0
1399 // (srl (ctlz x), 5) != 0 -> X == 0
1400 // (srl (ctlz x), 5) == 1 -> X == 0
1403 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
1404 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1410 // Look through truncs that don't change the value of a ctpop.
1411 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1412 CTPOP = N0.getOperand(0);
1414 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1415 (N0 == CTPOP || N0.getValueType().getSizeInBits() >
1416 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1417 EVT CTVT = CTPOP.getValueType();
1418 SDValue CTOp = CTPOP.getOperand(0);
1420 // (ctpop x) u< 2 -> (x & x-1) == 0
1421 // (ctpop x) u> 1 -> (x & x-1) != 0
1422 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1423 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1424 DAG.getConstant(1, dl, CTVT));
1425 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1426 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1427 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
1430 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1433 // (zext x) == C --> x == (trunc C)
1434 // (sext x) == C --> x == (trunc C)
1435 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1436 DCI.isBeforeLegalize() && N0->hasOneUse()) {
1437 unsigned MinBits = N0.getValueSizeInBits();
1439 bool Signed = false;
1440 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1442 MinBits = N0->getOperand(0).getValueSizeInBits();
1443 PreExt = N0->getOperand(0);
1444 } else if (N0->getOpcode() == ISD::AND) {
1445 // DAGCombine turns costly ZExts into ANDs
1446 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1447 if ((C->getAPIntValue()+1).isPowerOf2()) {
1448 MinBits = C->getAPIntValue().countTrailingOnes();
1449 PreExt = N0->getOperand(0);
1451 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1453 MinBits = N0->getOperand(0).getValueSizeInBits();
1454 PreExt = N0->getOperand(0);
1456 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
1457 // ZEXTLOAD / SEXTLOAD
1458 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1459 MinBits = LN0->getMemoryVT().getSizeInBits();
1461 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1463 MinBits = LN0->getMemoryVT().getSizeInBits();
1468 // Figure out how many bits we need to preserve this constant.
1469 unsigned ReqdBits = Signed ?
1470 C1.getBitWidth() - C1.getNumSignBits() + 1 :
1473 // Make sure we're not losing bits from the constant.
1475 MinBits < C1.getBitWidth() &&
1476 MinBits >= ReqdBits) {
1477 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1478 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1479 // Will get folded away.
1480 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
1481 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
1482 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1485 // If truncating the setcc operands is not desirable, we can still
1486 // simplify the expression in some cases:
1487 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
1488 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
1489 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
1490 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
1491 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
1492 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
1493 SDValue TopSetCC = N0->getOperand(0);
1494 unsigned N0Opc = N0->getOpcode();
1495 bool SExt = (N0Opc == ISD::SIGN_EXTEND);
1496 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
1497 TopSetCC.getOpcode() == ISD::SETCC &&
1498 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
1499 (isConstFalseVal(N1C) ||
1500 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
1502 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
1503 (!N1C->isNullValue() && Cond == ISD::SETNE);
1508 ISD::CondCode InvCond = ISD::getSetCCInverse(
1509 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
1510 TopSetCC.getOperand(0).getValueType().isInteger());
1511 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
1512 TopSetCC.getOperand(1),
1519 // If the LHS is '(and load, const)', the RHS is 0,
1520 // the test is for equality or unsigned, and all 1 bits of the const are
1521 // in the same partial word, see if we can shorten the load.
1522 if (DCI.isBeforeLegalize() &&
1523 !ISD::isSignedIntSetCC(Cond) &&
1524 N0.getOpcode() == ISD::AND && C1 == 0 &&
1525 N0.getNode()->hasOneUse() &&
1526 isa<LoadSDNode>(N0.getOperand(0)) &&
1527 N0.getOperand(0).getNode()->hasOneUse() &&
1528 isa<ConstantSDNode>(N0.getOperand(1))) {
1529 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1531 unsigned bestWidth = 0, bestOffset = 0;
1532 if (!Lod->isVolatile() && Lod->isUnindexed()) {
1533 unsigned origWidth = N0.getValueType().getSizeInBits();
1534 unsigned maskWidth = origWidth;
1535 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1536 // 8 bits, but have to be careful...
1537 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1538 origWidth = Lod->getMemoryVT().getSizeInBits();
1540 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1541 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1542 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1543 for (unsigned offset=0; offset<origWidth/width; offset++) {
1544 if ((newMask & Mask) == Mask) {
1545 if (!DAG.getDataLayout().isLittleEndian())
1546 bestOffset = (origWidth/width - offset - 1) * (width/8);
1548 bestOffset = (uint64_t)offset * (width/8);
1549 bestMask = Mask.lshr(offset * (width/8) * 8);
1553 newMask = newMask << width;
1558 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1559 if (newVT.isRound()) {
1560 EVT PtrType = Lod->getOperand(1).getValueType();
1561 SDValue Ptr = Lod->getBasePtr();
1562 if (bestOffset != 0)
1563 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1564 DAG.getConstant(bestOffset, dl, PtrType));
1565 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1566 SDValue NewLoad = DAG.getLoad(
1567 newVT, dl, Lod->getChain(), Ptr,
1568 Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
1569 return DAG.getSetCC(dl, VT,
1570 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1571 DAG.getConstant(bestMask.trunc(bestWidth),
1573 DAG.getConstant(0LL, dl, newVT), Cond);
1578 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1579 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1580 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1582 // If the comparison constant has bits in the upper part, the
1583 // zero-extended value could never match.
1584 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1585 C1.getBitWidth() - InSize))) {
1589 case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
1592 case ISD::SETNE: return DAG.getConstant(1, dl, VT);
1595 // True if the sign bit of C1 is set.
1596 return DAG.getConstant(C1.isNegative(), dl, VT);
1599 // True if the sign bit of C1 isn't set.
1600 return DAG.getConstant(C1.isNonNegative(), dl, VT);
1606 // Otherwise, we can perform the comparison with the low bits.
1614 EVT newVT = N0.getOperand(0).getValueType();
1615 if (DCI.isBeforeLegalizeOps() ||
1616 (isOperationLegal(ISD::SETCC, newVT) &&
1617 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
1619 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
1620 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
1622 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1624 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
1629 break; // todo, be more careful with signed comparisons
1631 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1632 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1633 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1634 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1635 EVT ExtDstTy = N0.getValueType();
1636 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1638 // If the constant doesn't fit into the number of bits for the source of
1639 // the sign extension, it is impossible for both sides to be equal.
1640 if (C1.getMinSignedBits() > ExtSrcTyBits)
1641 return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
1644 EVT Op0Ty = N0.getOperand(0).getValueType();
1645 if (Op0Ty == ExtSrcTy) {
1646 ZextOp = N0.getOperand(0);
1648 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1649 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1650 DAG.getConstant(Imm, dl, Op0Ty));
1652 if (!DCI.isCalledByLegalizer())
1653 DCI.AddToWorklist(ZextOp.getNode());
1654 // Otherwise, make this a use of a zext.
1655 return DAG.getSetCC(dl, VT, ZextOp,
1656 DAG.getConstant(C1 & APInt::getLowBitsSet(
1661 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1662 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1663 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
1664 if (N0.getOpcode() == ISD::SETCC &&
1665 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
1666 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1668 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
1669 // Invert the condition.
1670 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1671 CC = ISD::getSetCCInverse(CC,
1672 N0.getOperand(0).getValueType().isInteger());
1673 if (DCI.isBeforeLegalizeOps() ||
1674 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1675 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1678 if ((N0.getOpcode() == ISD::XOR ||
1679 (N0.getOpcode() == ISD::AND &&
1680 N0.getOperand(0).getOpcode() == ISD::XOR &&
1681 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1682 isa<ConstantSDNode>(N0.getOperand(1)) &&
1683 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1684 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1685 // can only do this if the top bits are known zero.
1686 unsigned BitWidth = N0.getValueSizeInBits();
1687 if (DAG.MaskedValueIsZero(N0,
1688 APInt::getHighBitsSet(BitWidth,
1690 // Okay, get the un-inverted input value.
1692 if (N0.getOpcode() == ISD::XOR)
1693 Val = N0.getOperand(0);
1695 assert(N0.getOpcode() == ISD::AND &&
1696 N0.getOperand(0).getOpcode() == ISD::XOR);
1697 // ((X^1)&1)^1 -> X & 1
1698 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1699 N0.getOperand(0).getOperand(0),
1703 return DAG.getSetCC(dl, VT, Val, N1,
1704 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1706 } else if (N1C->getAPIntValue() == 1 &&
1708 getBooleanContents(N0->getValueType(0)) ==
1709 ZeroOrOneBooleanContent)) {
1711 if (Op0.getOpcode() == ISD::TRUNCATE)
1712 Op0 = Op0.getOperand(0);
1714 if ((Op0.getOpcode() == ISD::XOR) &&
1715 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1716 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1717 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1718 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1719 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1722 if (Op0.getOpcode() == ISD::AND &&
1723 isa<ConstantSDNode>(Op0.getOperand(1)) &&
1724 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1725 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1726 if (Op0.getValueType().bitsGT(VT))
1727 Op0 = DAG.getNode(ISD::AND, dl, VT,
1728 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1729 DAG.getConstant(1, dl, VT));
1730 else if (Op0.getValueType().bitsLT(VT))
1731 Op0 = DAG.getNode(ISD::AND, dl, VT,
1732 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
1733 DAG.getConstant(1, dl, VT));
1735 return DAG.getSetCC(dl, VT, Op0,
1736 DAG.getConstant(0, dl, Op0.getValueType()),
1737 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1739 if (Op0.getOpcode() == ISD::AssertZext &&
1740 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1741 return DAG.getSetCC(dl, VT, Op0,
1742 DAG.getConstant(0, dl, Op0.getValueType()),
1743 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1747 APInt MinVal, MaxVal;
1748 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1749 if (ISD::isSignedIntSetCC(Cond)) {
1750 MinVal = APInt::getSignedMinValue(OperandBitSize);
1751 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1753 MinVal = APInt::getMinValue(OperandBitSize);
1754 MaxVal = APInt::getMaxValue(OperandBitSize);
1757 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1758 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1759 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true
1760 // X >= C0 --> X > (C0 - 1)
1762 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1763 if ((DCI.isBeforeLegalizeOps() ||
1764 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1765 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1766 isLegalICmpImmediate(C.getSExtValue())))) {
1767 return DAG.getSetCC(dl, VT, N0,
1768 DAG.getConstant(C, dl, N1.getValueType()),
1773 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1774 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true
1775 // X <= C0 --> X < (C0 + 1)
1777 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1778 if ((DCI.isBeforeLegalizeOps() ||
1779 isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1780 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1781 isLegalICmpImmediate(C.getSExtValue())))) {
1782 return DAG.getSetCC(dl, VT, N0,
1783 DAG.getConstant(C, dl, N1.getValueType()),
1788 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1789 return DAG.getConstant(0, dl, VT); // X < MIN --> false
1790 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1791 return DAG.getConstant(1, dl, VT); // X >= MIN --> true
1792 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1793 return DAG.getConstant(0, dl, VT); // X > MAX --> false
1794 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1795 return DAG.getConstant(1, dl, VT); // X <= MAX --> true
1797 // Canonicalize setgt X, Min --> setne X, Min
1798 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1799 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1800 // Canonicalize setlt X, Max --> setne X, Max
1801 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1802 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1804 // If we have setult X, 1, turn it into seteq X, 0
1805 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1806 return DAG.getSetCC(dl, VT, N0,
1807 DAG.getConstant(MinVal, dl, N0.getValueType()),
1809 // If we have setugt X, Max-1, turn it into seteq X, Max
1810 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1811 return DAG.getSetCC(dl, VT, N0,
1812 DAG.getConstant(MaxVal, dl, N0.getValueType()),
1815 // If we have "setcc X, C0", check to see if we can shrink the immediate
1818 // SETUGT X, SINTMAX -> SETLT X, 0
1819 if (Cond == ISD::SETUGT &&
1820 C1 == APInt::getSignedMaxValue(OperandBitSize))
1821 return DAG.getSetCC(dl, VT, N0,
1822 DAG.getConstant(0, dl, N1.getValueType()),
1825 // SETULT X, SINTMIN -> SETGT X, -1
1826 if (Cond == ISD::SETULT &&
1827 C1 == APInt::getSignedMinValue(OperandBitSize)) {
1828 SDValue ConstMinusOne =
1829 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
1831 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1834 // Fold bit comparisons when we can.
1835 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1836 (VT == N0.getValueType() ||
1837 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1838 N0.getOpcode() == ISD::AND) {
1839 auto &DL = DAG.getDataLayout();
1840 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1841 EVT ShiftTy = DCI.isBeforeLegalize()
1843 : getShiftAmountTy(N0.getValueType(), DL);
1844 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1845 // Perform the xform if the AND RHS is a single bit.
1846 if (AndRHS->getAPIntValue().isPowerOf2()) {
1847 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1848 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1849 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
1852 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
1853 // (X & 8) == 8 --> (X & 8) >> 3
1854 // Perform the xform if C1 is a single bit.
1855 if (C1.isPowerOf2()) {
1856 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1857 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1858 DAG.getConstant(C1.logBase2(), dl,
1865 if (C1.getMinSignedBits() <= 64 &&
1866 !isLegalICmpImmediate(C1.getSExtValue())) {
1867 // (X & -256) == 256 -> (X >> 8) == 1
1868 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1869 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
1870 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1871 const APInt &AndRHSC = AndRHS->getAPIntValue();
1872 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
1873 unsigned ShiftBits = AndRHSC.countTrailingZeros();
1874 auto &DL = DAG.getDataLayout();
1875 EVT ShiftTy = DCI.isBeforeLegalize()
1877 : getShiftAmountTy(N0.getValueType(), DL);
1878 EVT CmpTy = N0.getValueType();
1879 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
1880 DAG.getConstant(ShiftBits, dl,
1882 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
1883 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
1886 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
1887 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
1888 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
1889 // X < 0x100000000 -> (X >> 32) < 1
1890 // X >= 0x100000000 -> (X >> 32) >= 1
1891 // X <= 0x0ffffffff -> (X >> 32) < 1
1892 // X > 0x0ffffffff -> (X >> 32) >= 1
1895 ISD::CondCode NewCond = Cond;
1897 ShiftBits = C1.countTrailingOnes();
1899 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1901 ShiftBits = C1.countTrailingZeros();
1903 NewC = NewC.lshr(ShiftBits);
1904 if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
1905 isLegalICmpImmediate(NewC.getSExtValue())) {
1906 auto &DL = DAG.getDataLayout();
1907 EVT ShiftTy = DCI.isBeforeLegalize()
1909 : getShiftAmountTy(N0.getValueType(), DL);
1910 EVT CmpTy = N0.getValueType();
1911 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
1912 DAG.getConstant(ShiftBits, dl, ShiftTy));
1913 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
1914 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
1920 if (isa<ConstantFPSDNode>(N0.getNode())) {
1921 // Constant fold or commute setcc.
1922 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
1923 if (O.getNode()) return O;
1924 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1925 // If the RHS of an FP comparison is a constant, simplify it away in
1927 if (CFP->getValueAPF().isNaN()) {
1928 // If an operand is known to be a nan, we can fold it.
1929 switch (ISD::getUnorderedFlavor(Cond)) {
1930 default: llvm_unreachable("Unknown flavor!");
1931 case 0: // Known false.
1932 return DAG.getConstant(0, dl, VT);
1933 case 1: // Known true.
1934 return DAG.getConstant(1, dl, VT);
1935 case 2: // Undefined.
1936 return DAG.getUNDEF(VT);
1940 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
1941 // constant if knowing that the operand is non-nan is enough. We prefer to
1942 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1944 if (Cond == ISD::SETO || Cond == ISD::SETUO)
1945 return DAG.getSetCC(dl, VT, N0, N0, Cond);
1947 // If the condition is not legal, see if we can find an equivalent one
1949 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
1950 // If the comparison was an awkward floating-point == or != and one of
1951 // the comparison operands is infinity or negative infinity, convert the
1952 // condition to a less-awkward <= or >=.
1953 if (CFP->getValueAPF().isInfinity()) {
1954 if (CFP->getValueAPF().isNegative()) {
1955 if (Cond == ISD::SETOEQ &&
1956 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1957 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1958 if (Cond == ISD::SETUEQ &&
1959 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1960 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1961 if (Cond == ISD::SETUNE &&
1962 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1963 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1964 if (Cond == ISD::SETONE &&
1965 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1966 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1968 if (Cond == ISD::SETOEQ &&
1969 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1970 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
1971 if (Cond == ISD::SETUEQ &&
1972 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1973 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
1974 if (Cond == ISD::SETUNE &&
1975 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1976 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
1977 if (Cond == ISD::SETONE &&
1978 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1979 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
1986 // The sext(setcc()) => setcc() optimization relies on the appropriate
1987 // constant being emitted.
1989 switch (getBooleanContents(N0.getValueType())) {
1990 case UndefinedBooleanContent:
1991 case ZeroOrOneBooleanContent:
1992 EqVal = ISD::isTrueWhenEqual(Cond);
1994 case ZeroOrNegativeOneBooleanContent:
1995 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
1999 // We can always fold X == X for integer setcc's.
2000 if (N0.getValueType().isInteger()) {
2001 return DAG.getConstant(EqVal, dl, VT);
2003 unsigned UOF = ISD::getUnorderedFlavor(Cond);
2004 if (UOF == 2) // FP operators that are undefined on NaNs.
2005 return DAG.getConstant(EqVal, dl, VT);
2006 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2007 return DAG.getConstant(EqVal, dl, VT);
2008 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
2009 // if it is not already.
2010 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2011 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
2012 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
2013 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2016 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2017 N0.getValueType().isInteger()) {
2018 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2019 N0.getOpcode() == ISD::XOR) {
2020 // Simplify (X+Y) == (X+Z) --> Y == Z
2021 if (N0.getOpcode() == N1.getOpcode()) {
2022 if (N0.getOperand(0) == N1.getOperand(0))
2023 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2024 if (N0.getOperand(1) == N1.getOperand(1))
2025 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2026 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2027 // If X op Y == Y op X, try other combinations.
2028 if (N0.getOperand(0) == N1.getOperand(1))
2029 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2031 if (N0.getOperand(1) == N1.getOperand(0))
2032 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2037 // If RHS is a legal immediate value for a compare instruction, we need
2038 // to be careful about increasing register pressure needlessly.
2039 bool LegalRHSImm = false;
2041 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2042 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2043 // Turn (X+C1) == C2 --> X == C2-C1
2044 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2045 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2046 DAG.getConstant(RHSC->getAPIntValue()-
2047 LHSR->getAPIntValue(),
2048 dl, N0.getValueType()), Cond);
2051 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2052 if (N0.getOpcode() == ISD::XOR)
2053 // If we know that all of the inverted bits are zero, don't bother
2054 // performing the inversion.
2055 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2057 DAG.getSetCC(dl, VT, N0.getOperand(0),
2058 DAG.getConstant(LHSR->getAPIntValue() ^
2059 RHSC->getAPIntValue(),
2060 dl, N0.getValueType()),
2064 // Turn (C1-X) == C2 --> X == C1-C2
2065 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2066 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2068 DAG.getSetCC(dl, VT, N0.getOperand(1),
2069 DAG.getConstant(SUBC->getAPIntValue() -
2070 RHSC->getAPIntValue(),
2071 dl, N0.getValueType()),
2076 // Could RHSC fold directly into a compare?
2077 if (RHSC->getValueType(0).getSizeInBits() <= 64)
2078 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
2081 // Simplify (X+Z) == X --> Z == 0
2082 // Don't do this if X is an immediate that can fold into a cmp
2083 // instruction and X+Z has other uses. It could be an induction variable
2084 // chain, and the transform would increase register pressure.
2085 if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2086 if (N0.getOperand(0) == N1)
2087 return DAG.getSetCC(dl, VT, N0.getOperand(1),
2088 DAG.getConstant(0, dl, N0.getValueType()), Cond);
2089 if (N0.getOperand(1) == N1) {
2090 if (DAG.isCommutativeBinOp(N0.getOpcode()))
2091 return DAG.getSetCC(dl, VT, N0.getOperand(0),
2092 DAG.getConstant(0, dl, N0.getValueType()),
2094 if (N0.getNode()->hasOneUse()) {
2095 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2096 auto &DL = DAG.getDataLayout();
2097 // (Z-X) == X --> Z == X<<1
2098 SDValue SH = DAG.getNode(
2099 ISD::SHL, dl, N1.getValueType(), N1,
2100 DAG.getConstant(1, dl,
2101 getShiftAmountTy(N1.getValueType(), DL)));
2102 if (!DCI.isCalledByLegalizer())
2103 DCI.AddToWorklist(SH.getNode());
2104 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2110 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2111 N1.getOpcode() == ISD::XOR) {
2112 // Simplify X == (X+Z) --> Z == 0
2113 if (N1.getOperand(0) == N0)
2114 return DAG.getSetCC(dl, VT, N1.getOperand(1),
2115 DAG.getConstant(0, dl, N1.getValueType()), Cond);
2116 if (N1.getOperand(1) == N0) {
2117 if (DAG.isCommutativeBinOp(N1.getOpcode()))
2118 return DAG.getSetCC(dl, VT, N1.getOperand(0),
2119 DAG.getConstant(0, dl, N1.getValueType()), Cond);
2120 if (N1.getNode()->hasOneUse()) {
2121 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2122 auto &DL = DAG.getDataLayout();
2123 // X == (Z-X) --> X<<1 == Z
2124 SDValue SH = DAG.getNode(
2125 ISD::SHL, dl, N1.getValueType(), N0,
2126 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
2127 if (!DCI.isCalledByLegalizer())
2128 DCI.AddToWorklist(SH.getNode());
2129 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2134 if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
2138 // Fold away ALL boolean setcc's.
2140 if (N0.getValueType() == MVT::i1 && foldBooleans) {
2142 default: llvm_unreachable("Unknown integer setcc!");
2143 case ISD::SETEQ: // X == Y -> ~(X^Y)
2144 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2145 N0 = DAG.getNOT(dl, Temp, MVT::i1);
2146 if (!DCI.isCalledByLegalizer())
2147 DCI.AddToWorklist(Temp.getNode());
2149 case ISD::SETNE: // X != Y --> (X^Y)
2150 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2152 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
2153 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
2154 Temp = DAG.getNOT(dl, N0, MVT::i1);
2155 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2156 if (!DCI.isCalledByLegalizer())
2157 DCI.AddToWorklist(Temp.getNode());
2159 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
2160 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
2161 Temp = DAG.getNOT(dl, N1, MVT::i1);
2162 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2163 if (!DCI.isCalledByLegalizer())
2164 DCI.AddToWorklist(Temp.getNode());
2166 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
2167 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
2168 Temp = DAG.getNOT(dl, N0, MVT::i1);
2169 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2170 if (!DCI.isCalledByLegalizer())
2171 DCI.AddToWorklist(Temp.getNode());
2173 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
2174 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
2175 Temp = DAG.getNOT(dl, N1, MVT::i1);
2176 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2179 if (VT != MVT::i1) {
2180 if (!DCI.isCalledByLegalizer())
2181 DCI.AddToWorklist(N0.getNode());
2182 // FIXME: If running after legalize, we probably can't do this.
2183 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2188 // Could not fold it.
2192 /// Returns true (and the GlobalValue and the offset) if the node is a
2193 /// GlobalAddress + offset.
2194 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
2195 int64_t &Offset) const {
2196 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
2197 GA = GASD->getGlobal();
2198 Offset += GASD->getOffset();
2202 if (N->getOpcode() == ISD::ADD) {
2203 SDValue N1 = N->getOperand(0);
2204 SDValue N2 = N->getOperand(1);
2205 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2206 if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
2207 Offset += V->getSExtValue();
2210 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2211 if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
2212 Offset += V->getSExtValue();
2221 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2222 DAGCombinerInfo &DCI) const {
2223 // Default implementation: no optimization.
2227 //===----------------------------------------------------------------------===//
2228 // Inline Assembler Implementation Methods
2229 //===----------------------------------------------------------------------===//
2231 TargetLowering::ConstraintType
2232 TargetLowering::getConstraintType(StringRef Constraint) const {
2233 unsigned S = Constraint.size();
2236 switch (Constraint[0]) {
2238 case 'r': return C_RegisterClass;
2240 case 'o': // offsetable
2241 case 'V': // not offsetable
2243 case 'i': // Simple Integer or Relocatable Constant
2244 case 'n': // Simple Integer
2245 case 'E': // Floating Point Constant
2246 case 'F': // Floating Point Constant
2247 case 's': // Relocatable Constant
2248 case 'p': // Address.
2249 case 'X': // Allow ANY value.
2250 case 'I': // Target registers.
2264 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
2265 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
2272 /// Try to replace an X constraint, which matches anything, with another that
2273 /// has more specific requirements based on the type of the corresponding
2275 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2276 if (ConstraintVT.isInteger())
2278 if (ConstraintVT.isFloatingPoint())
2279 return "f"; // works for many targets
2283 /// Lower the specified operand into the Ops vector.
2284 /// If it is invalid, don't add anything to Ops.
2285 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2286 std::string &Constraint,
2287 std::vector<SDValue> &Ops,
2288 SelectionDAG &DAG) const {
2290 if (Constraint.length() > 1) return;
2292 char ConstraintLetter = Constraint[0];
2293 switch (ConstraintLetter) {
2295 case 'X': // Allows any operand; labels (basic block) use this.
2296 if (Op.getOpcode() == ISD::BasicBlock) {
2301 case 'i': // Simple Integer or Relocatable Constant
2302 case 'n': // Simple Integer
2303 case 's': { // Relocatable Constant
2304 // These operands are interested in values of the form (GV+C), where C may
2305 // be folded in as an offset of GV, or it may be explicitly added. Also, it
2306 // is possible and fine if either GV or C are missing.
2307 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2308 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2310 // If we have "(add GV, C)", pull out GV/C
2311 if (Op.getOpcode() == ISD::ADD) {
2312 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2313 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2315 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2316 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2324 // If we find a valid operand, map to the TargetXXX version so that the
2325 // value itself doesn't get selected.
2326 if (GA) { // Either &GV or &GV+C
2327 if (ConstraintLetter != 'n') {
2328 int64_t Offs = GA->getOffset();
2329 if (C) Offs += C->getZExtValue();
2330 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2331 C ? SDLoc(C) : SDLoc(),
2332 Op.getValueType(), Offs));
2336 if (C) { // just C, no GV.
2337 // Simple constants are not allowed for 's'.
2338 if (ConstraintLetter != 's') {
2339 // gcc prints these as sign extended. Sign extend value to 64 bits
2340 // now; without this it would get ZExt'd later in
2341 // ScheduleDAGSDNodes::EmitNode, which is very generic.
2342 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2343 SDLoc(C), MVT::i64));
2352 std::pair<unsigned, const TargetRegisterClass *>
2353 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
2354 StringRef Constraint,
2356 if (Constraint.empty() || Constraint[0] != '{')
2357 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
2358 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2360 // Remove the braces from around the name.
2361 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2363 std::pair<unsigned, const TargetRegisterClass*> R =
2364 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
2366 // Figure out which register class contains this reg.
2367 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
2368 E = RI->regclass_end(); RCI != E; ++RCI) {
2369 const TargetRegisterClass *RC = *RCI;
2371 // If none of the value types for this register class are valid, we
2372 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2376 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2378 if (RegName.equals_lower(RI->getRegAsmName(*I))) {
2379 std::pair<unsigned, const TargetRegisterClass*> S =
2380 std::make_pair(*I, RC);
2382 // If this register class has the requested value type, return it,
2383 // otherwise keep searching and return the first class found
2384 // if no other is found which explicitly has the requested type.
2385 if (RC->hasType(VT))
2396 //===----------------------------------------------------------------------===//
2397 // Constraint Selection.
2399 /// Return true of this is an input operand that is a matching constraint like
2401 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2402 assert(!ConstraintCode.empty() && "No known constraint!");
2403 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2406 /// If this is an input matching constraint, this method returns the output
2407 /// operand it matches.
2408 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2409 assert(!ConstraintCode.empty() && "No known constraint!");
2410 return atoi(ConstraintCode.c_str());
2413 /// Split up the constraint string from the inline assembly value into the
2414 /// specific constraints and their prefixes, and also tie in the associated
2416 /// If this returns an empty vector, and if the constraint string itself
2417 /// isn't empty, there was an error parsing.
2418 TargetLowering::AsmOperandInfoVector
2419 TargetLowering::ParseConstraints(const DataLayout &DL,
2420 const TargetRegisterInfo *TRI,
2421 ImmutableCallSite CS) const {
2422 /// Information about all of the constraints.
2423 AsmOperandInfoVector ConstraintOperands;
2424 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2425 unsigned maCount = 0; // Largest number of multiple alternative constraints.
2427 // Do a prepass over the constraints, canonicalizing them, and building up the
2428 // ConstraintOperands list.
2429 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
2430 unsigned ResNo = 0; // ResNo - The result number of the next output.
2432 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2433 ConstraintOperands.emplace_back(std::move(CI));
2434 AsmOperandInfo &OpInfo = ConstraintOperands.back();
2436 // Update multiple alternative constraint count.
2437 if (OpInfo.multipleAlternatives.size() > maCount)
2438 maCount = OpInfo.multipleAlternatives.size();
2440 OpInfo.ConstraintVT = MVT::Other;
2442 // Compute the value type for each operand.
2443 switch (OpInfo.Type) {
2444 case InlineAsm::isOutput:
2445 // Indirect outputs just consume an argument.
2446 if (OpInfo.isIndirect) {
2447 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2451 // The return value of the call is this value. As such, there is no
2452 // corresponding argument.
2453 assert(!CS.getType()->isVoidTy() &&
2455 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2456 OpInfo.ConstraintVT =
2457 getSimpleValueType(DL, STy->getElementType(ResNo));
2459 assert(ResNo == 0 && "Asm only has one result!");
2460 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
2464 case InlineAsm::isInput:
2465 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2467 case InlineAsm::isClobber:
2472 if (OpInfo.CallOperandVal) {
2473 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2474 if (OpInfo.isIndirect) {
2475 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2477 report_fatal_error("Indirect operand for inline asm not a pointer!");
2478 OpTy = PtrTy->getElementType();
2481 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2482 if (StructType *STy = dyn_cast<StructType>(OpTy))
2483 if (STy->getNumElements() == 1)
2484 OpTy = STy->getElementType(0);
2486 // If OpTy is not a single value, it may be a struct/union that we
2487 // can tile with integers.
2488 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2489 unsigned BitSize = DL.getTypeSizeInBits(OpTy);
2498 OpInfo.ConstraintVT =
2499 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2502 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2503 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
2504 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
2506 OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2511 // If we have multiple alternative constraints, select the best alternative.
2512 if (!ConstraintOperands.empty()) {
2514 unsigned bestMAIndex = 0;
2515 int bestWeight = -1;
2516 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
2519 // Compute the sums of the weights for each alternative, keeping track
2520 // of the best (highest weight) one so far.
2521 for (maIndex = 0; maIndex < maCount; ++maIndex) {
2523 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2524 cIndex != eIndex; ++cIndex) {
2525 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2526 if (OpInfo.Type == InlineAsm::isClobber)
2529 // If this is an output operand with a matching input operand,
2530 // look up the matching input. If their types mismatch, e.g. one
2531 // is an integer, the other is floating point, or their sizes are
2532 // different, flag it as an maCantMatch.
2533 if (OpInfo.hasMatchingInput()) {
2534 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2535 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2536 if ((OpInfo.ConstraintVT.isInteger() !=
2537 Input.ConstraintVT.isInteger()) ||
2538 (OpInfo.ConstraintVT.getSizeInBits() !=
2539 Input.ConstraintVT.getSizeInBits())) {
2540 weightSum = -1; // Can't match.
2545 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2550 weightSum += weight;
2553 if (weightSum > bestWeight) {
2554 bestWeight = weightSum;
2555 bestMAIndex = maIndex;
2559 // Now select chosen alternative in each constraint.
2560 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2561 cIndex != eIndex; ++cIndex) {
2562 AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2563 if (cInfo.Type == InlineAsm::isClobber)
2565 cInfo.selectAlternative(bestMAIndex);
2570 // Check and hook up tied operands, choose constraint code to use.
2571 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2572 cIndex != eIndex; ++cIndex) {
2573 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2575 // If this is an output operand with a matching input operand, look up the
2576 // matching input. If their types mismatch, e.g. one is an integer, the
2577 // other is floating point, or their sizes are different, flag it as an
2579 if (OpInfo.hasMatchingInput()) {
2580 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2582 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2583 std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2584 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2585 OpInfo.ConstraintVT);
2586 std::pair<unsigned, const TargetRegisterClass *> InputRC =
2587 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2588 Input.ConstraintVT);
2589 if ((OpInfo.ConstraintVT.isInteger() !=
2590 Input.ConstraintVT.isInteger()) ||
2591 (MatchRC.second != InputRC.second)) {
2592 report_fatal_error("Unsupported asm: input constraint"
2593 " with a matching output constraint of"
2594 " incompatible type!");
2600 return ConstraintOperands;
2603 /// Return an integer indicating how general CT is.
2604 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2606 case TargetLowering::C_Other:
2607 case TargetLowering::C_Unknown:
2609 case TargetLowering::C_Register:
2611 case TargetLowering::C_RegisterClass:
2613 case TargetLowering::C_Memory:
2616 llvm_unreachable("Invalid constraint type");
2619 /// Examine constraint type and operand type and determine a weight value.
2620 /// This object must already have been set up with the operand type
2621 /// and the current alternative constraint selected.
2622 TargetLowering::ConstraintWeight
2623 TargetLowering::getMultipleConstraintMatchWeight(
2624 AsmOperandInfo &info, int maIndex) const {
2625 InlineAsm::ConstraintCodeVector *rCodes;
2626 if (maIndex >= (int)info.multipleAlternatives.size())
2627 rCodes = &info.Codes;
2629 rCodes = &info.multipleAlternatives[maIndex].Codes;
2630 ConstraintWeight BestWeight = CW_Invalid;
2632 // Loop over the options, keeping track of the most general one.
2633 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
2634 ConstraintWeight weight =
2635 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
2636 if (weight > BestWeight)
2637 BestWeight = weight;
2643 /// Examine constraint type and operand type and determine a weight value.
2644 /// This object must already have been set up with the operand type
2645 /// and the current alternative constraint selected.
2646 TargetLowering::ConstraintWeight
2647 TargetLowering::getSingleConstraintMatchWeight(
2648 AsmOperandInfo &info, const char *constraint) const {
2649 ConstraintWeight weight = CW_Invalid;
2650 Value *CallOperandVal = info.CallOperandVal;
2651 // If we don't have a value, we can't do a match,
2652 // but allow it at the lowest weight.
2653 if (!CallOperandVal)
2655 // Look at the constraint type.
2656 switch (*constraint) {
2657 case 'i': // immediate integer.
2658 case 'n': // immediate integer with a known value.
2659 if (isa<ConstantInt>(CallOperandVal))
2660 weight = CW_Constant;
2662 case 's': // non-explicit intregal immediate.
2663 if (isa<GlobalValue>(CallOperandVal))
2664 weight = CW_Constant;
2666 case 'E': // immediate float if host format.
2667 case 'F': // immediate float.
2668 if (isa<ConstantFP>(CallOperandVal))
2669 weight = CW_Constant;
2671 case '<': // memory operand with autodecrement.
2672 case '>': // memory operand with autoincrement.
2673 case 'm': // memory operand.
2674 case 'o': // offsettable memory operand
2675 case 'V': // non-offsettable memory operand
2678 case 'r': // general register.
2679 case 'g': // general register, memory operand or immediate integer.
2680 // note: Clang converts "g" to "imr".
2681 if (CallOperandVal->getType()->isIntegerTy())
2682 weight = CW_Register;
2684 case 'X': // any operand.
2686 weight = CW_Default;
2692 /// If there are multiple different constraints that we could pick for this
2693 /// operand (e.g. "imr") try to pick the 'best' one.
2694 /// This is somewhat tricky: constraints fall into four classes:
2695 /// Other -> immediates and magic values
2696 /// Register -> one specific register
2697 /// RegisterClass -> a group of regs
2698 /// Memory -> memory
2699 /// Ideally, we would pick the most specific constraint possible: if we have
2700 /// something that fits into a register, we would pick it. The problem here
2701 /// is that if we have something that could either be in a register or in
2702 /// memory that use of the register could cause selection of *other*
2703 /// operands to fail: they might only succeed if we pick memory. Because of
2704 /// this the heuristic we use is:
2706 /// 1) If there is an 'other' constraint, and if the operand is valid for
2707 /// that constraint, use it. This makes us take advantage of 'i'
2708 /// constraints when available.
2709 /// 2) Otherwise, pick the most general constraint present. This prefers
2710 /// 'm' over 'r', for example.
2712 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2713 const TargetLowering &TLI,
2714 SDValue Op, SelectionDAG *DAG) {
2715 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2716 unsigned BestIdx = 0;
2717 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2718 int BestGenerality = -1;
2720 // Loop over the options, keeping track of the most general one.
2721 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2722 TargetLowering::ConstraintType CType =
2723 TLI.getConstraintType(OpInfo.Codes[i]);
2725 // If this is an 'other' constraint, see if the operand is valid for it.
2726 // For example, on X86 we might have an 'rI' constraint. If the operand
2727 // is an integer in the range [0..31] we want to use I (saving a load
2728 // of a register), otherwise we must use 'r'.
2729 if (CType == TargetLowering::C_Other && Op.getNode()) {
2730 assert(OpInfo.Codes[i].size() == 1 &&
2731 "Unhandled multi-letter 'other' constraint");
2732 std::vector<SDValue> ResultOps;
2733 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
2735 if (!ResultOps.empty()) {
2742 // Things with matching constraints can only be registers, per gcc
2743 // documentation. This mainly affects "g" constraints.
2744 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2747 // This constraint letter is more general than the previous one, use it.
2748 int Generality = getConstraintGenerality(CType);
2749 if (Generality > BestGenerality) {
2752 BestGenerality = Generality;
2756 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2757 OpInfo.ConstraintType = BestType;
2760 /// Determines the constraint code and constraint type to use for the specific
2761 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2762 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2764 SelectionDAG *DAG) const {
2765 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2767 // Single-letter constraints ('r') are very common.
2768 if (OpInfo.Codes.size() == 1) {
2769 OpInfo.ConstraintCode = OpInfo.Codes[0];
2770 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2772 ChooseConstraint(OpInfo, *this, Op, DAG);
2775 // 'X' matches anything.
2776 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2777 // Labels and constants are handled elsewhere ('X' is the only thing
2778 // that matches labels). For Functions, the type here is the type of
2779 // the result, which is not what we want to look at; leave them alone.
2780 Value *v = OpInfo.CallOperandVal;
2781 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2782 OpInfo.CallOperandVal = v;
2786 // Otherwise, try to resolve it to something we know about by looking at
2787 // the actual operand type.
2788 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2789 OpInfo.ConstraintCode = Repl;
2790 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2795 /// \brief Given an exact SDIV by a constant, create a multiplication
2796 /// with the multiplicative inverse of the constant.
2797 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
2798 const SDLoc &dl, SelectionDAG &DAG,
2799 std::vector<SDNode *> &Created) {
2800 assert(d != 0 && "Division by zero!");
2802 // Shift the value upfront if it is even, so the LSB is one.
2803 unsigned ShAmt = d.countTrailingZeros();
2805 // TODO: For UDIV use SRL instead of SRA.
2807 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
2808 DAG.getDataLayout()));
2810 Flags.setExact(true);
2811 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
2812 Created.push_back(Op1.getNode());
2816 // Calculate the multiplicative inverse, using Newton's method.
2818 while ((t = d*xn) != 1)
2819 xn *= APInt(d.getBitWidth(), 2) - t;
2821 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
2822 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2823 Created.push_back(Mul.getNode());
2827 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
2829 std::vector<SDNode *> *Created) const {
2830 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2831 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2832 if (TLI.isIntDivCheap(N->getValueType(0), Attr))
2833 return SDValue(N,0); // Lower SDIV as SDIV
2837 /// \brief Given an ISD::SDIV node expressing a divide by constant,
2838 /// return a DAG expression to select that will generate the same value by
2839 /// multiplying by a magic number.
2840 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
2841 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
2842 SelectionDAG &DAG, bool IsAfterLegalization,
2843 std::vector<SDNode *> *Created) const {
2844 assert(Created && "No vector to hold sdiv ops.");
2846 EVT VT = N->getValueType(0);
2849 // Check to see if we can do this.
2850 // FIXME: We should be more aggressive here.
2851 if (!isTypeLegal(VT))
2854 // If the sdiv has an 'exact' bit we can use a simpler lowering.
2855 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
2856 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
2858 APInt::ms magics = Divisor.magic();
2860 // Multiply the numerator (operand 0) by the magic value
2861 // FIXME: We should support doing a MUL in a wider type
2863 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
2864 isOperationLegalOrCustom(ISD::MULHS, VT))
2865 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
2866 DAG.getConstant(magics.m, dl, VT));
2867 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
2868 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
2869 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
2871 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
2873 return SDValue(); // No mulhs or equvialent
2874 // If d > 0 and m < 0, add the numerator
2875 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
2876 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
2877 Created->push_back(Q.getNode());
2879 // If d < 0 and m > 0, subtract the numerator.
2880 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
2881 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
2882 Created->push_back(Q.getNode());
2884 auto &DL = DAG.getDataLayout();
2885 // Shift right algebraic if shift value is nonzero
2888 ISD::SRA, dl, VT, Q,
2889 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
2890 Created->push_back(Q.getNode());
2892 // Extract the sign bit and add it to the quotient
2894 DAG.getNode(ISD::SRL, dl, VT, Q,
2895 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
2896 getShiftAmountTy(Q.getValueType(), DL)));
2897 Created->push_back(T.getNode());
2898 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
2901 /// \brief Given an ISD::UDIV node expressing a divide by constant,
2902 /// return a DAG expression to select that will generate the same value by
2903 /// multiplying by a magic number.
2904 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
2905 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
2906 SelectionDAG &DAG, bool IsAfterLegalization,
2907 std::vector<SDNode *> *Created) const {
2908 assert(Created && "No vector to hold udiv ops.");
2910 EVT VT = N->getValueType(0);
2912 auto &DL = DAG.getDataLayout();
2914 // Check to see if we can do this.
2915 // FIXME: We should be more aggressive here.
2916 if (!isTypeLegal(VT))
2919 // FIXME: We should use a narrower constant when the upper
2920 // bits are known to be zero.
2921 APInt::mu magics = Divisor.magicu();
2923 SDValue Q = N->getOperand(0);
2925 // If the divisor is even, we can avoid using the expensive fixup by shifting
2926 // the divided value upfront.
2927 if (magics.a != 0 && !Divisor[0]) {
2928 unsigned Shift = Divisor.countTrailingZeros();
2930 ISD::SRL, dl, VT, Q,
2931 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
2932 Created->push_back(Q.getNode());
2934 // Get magic number for the shifted divisor.
2935 magics = Divisor.lshr(Shift).magicu(Shift);
2936 assert(magics.a == 0 && "Should use cheap fixup now");
2939 // Multiply the numerator (operand 0) by the magic value
2940 // FIXME: We should support doing a MUL in a wider type
2941 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
2942 isOperationLegalOrCustom(ISD::MULHU, VT))
2943 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
2944 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
2945 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
2946 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
2947 DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
2949 return SDValue(); // No mulhu or equvialent
2951 Created->push_back(Q.getNode());
2953 if (magics.a == 0) {
2954 assert(magics.s < Divisor.getBitWidth() &&
2955 "We shouldn't generate an undefined shift!");
2957 ISD::SRL, dl, VT, Q,
2958 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
2960 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
2961 Created->push_back(NPQ.getNode());
2963 ISD::SRL, dl, VT, NPQ,
2964 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
2965 Created->push_back(NPQ.getNode());
2966 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
2967 Created->push_back(NPQ.getNode());
2969 ISD::SRL, dl, VT, NPQ,
2970 DAG.getConstant(magics.s - 1, dl,
2971 getShiftAmountTy(NPQ.getValueType(), DL)));
2975 bool TargetLowering::
2976 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
2977 if (!isa<ConstantSDNode>(Op.getOperand(0))) {
2978 DAG.getContext()->emitError("argument to '__builtin_return_address' must "
2979 "be a constant integer");
2986 //===----------------------------------------------------------------------===//
2987 // Legalization Utilities
2988 //===----------------------------------------------------------------------===//
2990 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
2991 SelectionDAG &DAG, SDValue LL, SDValue LH,
2992 SDValue RL, SDValue RH) const {
2993 EVT VT = N->getValueType(0);
2996 bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
2997 bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
2998 bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
2999 bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
3000 if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
3001 unsigned OuterBitSize = VT.getSizeInBits();
3002 unsigned InnerBitSize = HiLoVT.getSizeInBits();
3003 unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
3004 unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
3006 // LL, LH, RL, and RH must be either all NULL or all set to a value.
3007 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
3008 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
3010 if (!LL.getNode() && !RL.getNode() &&
3011 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3012 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0));
3013 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1));
3019 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
3020 if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
3021 DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
3022 // The inputs are both zero-extended.
3024 // We can emit a umul_lohi.
3025 Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
3027 Hi = SDValue(Lo.getNode(), 1);
3031 // We can emit a mulhu+mul.
3032 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3033 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
3037 if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
3038 // The input values are both sign-extended.
3040 // We can emit a smul_lohi.
3041 Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL,
3043 Hi = SDValue(Lo.getNode(), 1);
3047 // We can emit a mulhs+mul.
3048 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3049 Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL);
3054 if (!LH.getNode() && !RH.getNode() &&
3055 isOperationLegalOrCustom(ISD::SRL, VT) &&
3056 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3057 auto &DL = DAG.getDataLayout();
3058 unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits();
3059 SDValue Shift = DAG.getConstant(ShiftAmt, dl, getShiftAmountTy(VT, DL));
3060 LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift);
3061 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
3062 RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift);
3063 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
3070 // Lo,Hi = umul LHS, RHS.
3071 SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
3072 DAG.getVTList(HiLoVT, HiLoVT), LL, RL);
3074 Hi = UMulLOHI.getValue(1);
3075 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3076 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3077 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3078 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3082 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL);
3083 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL);
3084 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3085 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3086 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3087 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3094 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
3095 SelectionDAG &DAG) const {
3096 EVT VT = Node->getOperand(0).getValueType();
3097 EVT NVT = Node->getValueType(0);
3098 SDLoc dl(SDValue(Node, 0));
3100 // FIXME: Only f32 to i64 conversions are supported.
3101 if (VT != MVT::f32 || NVT != MVT::i64)
3104 // Expand f32 -> i64 conversion
3105 // This algorithm comes from compiler-rt's implementation of fixsfdi:
3106 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
3107 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
3108 VT.getSizeInBits());
3109 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
3110 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
3111 SDValue Bias = DAG.getConstant(127, dl, IntVT);
3112 SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl,
3114 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3115 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
3117 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3119 auto &DL = DAG.getDataLayout();
3120 SDValue ExponentBits = DAG.getNode(
3121 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3122 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
3123 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3125 SDValue Sign = DAG.getNode(
3126 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3127 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
3128 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3130 SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3131 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
3132 DAG.getConstant(0x00800000, dl, IntVT));
3134 R = DAG.getZExtOrTrunc(R, dl, NVT);
3136 R = DAG.getSelectCC(
3137 dl, Exponent, ExponentLoBit,
3138 DAG.getNode(ISD::SHL, dl, NVT, R,
3140 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3141 dl, getShiftAmountTy(IntVT, DL))),
3142 DAG.getNode(ISD::SRL, dl, NVT, R,
3144 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3145 dl, getShiftAmountTy(IntVT, DL))),
3148 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3149 DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3152 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3153 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
3157 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
3158 SelectionDAG &DAG) const {
3160 SDValue Chain = LD->getChain();
3161 SDValue BasePTR = LD->getBasePtr();
3162 EVT SrcVT = LD->getMemoryVT();
3163 ISD::LoadExtType ExtType = LD->getExtensionType();
3165 unsigned NumElem = SrcVT.getVectorNumElements();
3167 EVT SrcEltVT = SrcVT.getScalarType();
3168 EVT DstEltVT = LD->getValueType(0).getScalarType();
3170 unsigned Stride = SrcEltVT.getSizeInBits() / 8;
3171 assert(SrcEltVT.isByteSized());
3173 EVT PtrVT = BasePTR.getValueType();
3175 SmallVector<SDValue, 8> Vals;
3176 SmallVector<SDValue, 8> LoadChains;
3178 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3179 SDValue ScalarLoad =
3180 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
3181 LD->getPointerInfo().getWithOffset(Idx * Stride),
3182 SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
3183 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3185 BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
3186 DAG.getConstant(Stride, SL, PtrVT));
3188 Vals.push_back(ScalarLoad.getValue(0));
3189 LoadChains.push_back(ScalarLoad.getValue(1));
3192 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
3193 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, SL, LD->getValueType(0), Vals);
3195 return DAG.getMergeValues({ Value, NewChain }, SL);
3198 // FIXME: This relies on each element having a byte size, otherwise the stride
3199 // is 0 and just overwrites the same location. ExpandStore currently expects
3200 // this broken behavior.
3201 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
3202 SelectionDAG &DAG) const {
3205 SDValue Chain = ST->getChain();
3206 SDValue BasePtr = ST->getBasePtr();
3207 SDValue Value = ST->getValue();
3208 EVT StVT = ST->getMemoryVT();
3210 // The type of the data we want to save
3211 EVT RegVT = Value.getValueType();
3212 EVT RegSclVT = RegVT.getScalarType();
3214 // The type of data as saved in memory.
3215 EVT MemSclVT = StVT.getScalarType();
3217 EVT PtrVT = BasePtr.getValueType();
3219 // Store Stride in bytes
3220 unsigned Stride = MemSclVT.getSizeInBits() / 8;
3221 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
3222 unsigned NumElem = StVT.getVectorNumElements();
3224 // Extract each of the elements from the original vector and save them into
3225 // memory individually.
3226 SmallVector<SDValue, 8> Stores;
3227 for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3228 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3229 DAG.getConstant(Idx, SL, IdxVT));
3231 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
3232 DAG.getConstant(Idx * Stride, SL, PtrVT));
3234 // This scalar TruncStore may be illegal, but we legalize it later.
3235 SDValue Store = DAG.getTruncStore(
3236 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
3237 MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
3238 ST->getMemOperand()->getFlags(), ST->getAAInfo());
3240 Stores.push_back(Store);
3243 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
3246 std::pair<SDValue, SDValue>
3247 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
3248 assert(LD->getAddressingMode() == ISD::UNINDEXED &&
3249 "unaligned indexed loads not implemented!");
3250 SDValue Chain = LD->getChain();
3251 SDValue Ptr = LD->getBasePtr();
3252 EVT VT = LD->getValueType(0);
3253 EVT LoadedVT = LD->getMemoryVT();
3255 if (VT.isFloatingPoint() || VT.isVector()) {
3256 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
3257 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
3258 if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
3259 // Scalarize the load and let the individual components be handled.
3260 SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
3261 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
3264 // Expand to a (misaligned) integer load of the same size,
3265 // then bitconvert to floating point or vector.
3266 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
3267 LD->getMemOperand());
3268 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
3270 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
3271 ISD::ANY_EXTEND, dl, VT, Result);
3273 return std::make_pair(Result, newLoad.getValue(1));
3276 // Copy the value to a (aligned) stack slot using (unaligned) integer
3277 // loads and stores, then do a (aligned) load from the stack slot.
3278 MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
3279 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
3280 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3281 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
3283 // Make sure the stack slot is also aligned for the register type.
3284 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
3286 SmallVector<SDValue, 8> Stores;
3287 SDValue StackPtr = StackBase;
3288 unsigned Offset = 0;
3290 EVT PtrVT = Ptr.getValueType();
3291 EVT StackPtrVT = StackPtr.getValueType();
3293 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3294 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3296 // Do all but one copies using the full register width.
3297 for (unsigned i = 1; i < NumRegs; i++) {
3298 // Load one integer register's worth from the original location.
3299 SDValue Load = DAG.getLoad(
3300 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
3301 MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
3303 // Follow the load with a store to the stack slot. Remember the store.
3304 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
3305 MachinePointerInfo()));
3306 // Increment the pointers.
3308 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3309 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr,
3313 // The last copy may be partial. Do an extending load.
3314 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3315 8 * (LoadedBytes - Offset));
3317 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
3318 LD->getPointerInfo().getWithOffset(Offset), MemVT,
3319 MinAlign(LD->getAlignment(), Offset),
3320 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3321 // Follow the load with a store to the stack slot. Remember the store.
3322 // On big-endian machines this requires a truncating store to ensure
3323 // that the bits end up in the right place.
3324 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
3325 MachinePointerInfo(), MemVT));
3327 // The order of the stores doesn't matter - say it with a TokenFactor.
3328 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3330 // Finally, perform the original load only redirected to the stack slot.
3331 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
3332 MachinePointerInfo(), LoadedVT);
3334 // Callers expect a MERGE_VALUES node.
3335 return std::make_pair(Load, TF);
3338 assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
3339 "Unaligned load of unsupported type.");
3341 // Compute the new VT that is half the size of the old one. This is an
3343 unsigned NumBits = LoadedVT.getSizeInBits();
3345 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
3348 unsigned Alignment = LD->getAlignment();
3349 unsigned IncrementSize = NumBits / 8;
3350 ISD::LoadExtType HiExtType = LD->getExtensionType();
3352 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
3353 if (HiExtType == ISD::NON_EXTLOAD)
3354 HiExtType = ISD::ZEXTLOAD;
3356 // Load the value in two parts
3358 if (DAG.getDataLayout().isLittleEndian()) {
3359 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3360 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3362 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3363 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3364 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
3365 LD->getPointerInfo().getWithOffset(IncrementSize),
3366 NewLoadedVT, MinAlign(Alignment, IncrementSize),
3367 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3369 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3370 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3372 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3373 DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3374 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
3375 LD->getPointerInfo().getWithOffset(IncrementSize),
3376 NewLoadedVT, MinAlign(Alignment, IncrementSize),
3377 LD->getMemOperand()->getFlags(), LD->getAAInfo());
3380 // aggregate the two parts
3381 SDValue ShiftAmount =
3382 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
3383 DAG.getDataLayout()));
3384 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
3385 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
3387 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3390 return std::make_pair(Result, TF);
3393 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
3394 SelectionDAG &DAG) const {
3395 assert(ST->getAddressingMode() == ISD::UNINDEXED &&
3396 "unaligned indexed stores not implemented!");
3397 SDValue Chain = ST->getChain();
3398 SDValue Ptr = ST->getBasePtr();
3399 SDValue Val = ST->getValue();
3400 EVT VT = Val.getValueType();
3401 int Alignment = ST->getAlignment();
3404 if (ST->getMemoryVT().isFloatingPoint() ||
3405 ST->getMemoryVT().isVector()) {
3406 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
3407 if (isTypeLegal(intVT)) {
3408 if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
3409 // Scalarize the store and let the individual components be handled.
3410 SDValue Result = scalarizeVectorStore(ST, DAG);
3414 // Expand to a bitconvert of the value to the integer type of the
3415 // same size, then a (misaligned) int store.
3416 // FIXME: Does not handle truncating floating point stores!
3417 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3418 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
3419 Alignment, ST->getMemOperand()->getFlags());
3422 // Do a (aligned) store to a stack slot, then copy from the stack slot
3423 // to the final destination using (unaligned) integer loads and stores.
3424 EVT StoredVT = ST->getMemoryVT();
3426 getRegisterType(*DAG.getContext(),
3427 EVT::getIntegerVT(*DAG.getContext(),
3428 StoredVT.getSizeInBits()));
3429 EVT PtrVT = Ptr.getValueType();
3430 unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
3431 unsigned RegBytes = RegVT.getSizeInBits() / 8;
3432 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3434 // Make sure the stack slot is also aligned for the register type.
3435 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
3437 // Perform the original store, only redirected to the stack slot.
3438 SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr,
3439 MachinePointerInfo(), StoredVT);
3441 EVT StackPtrVT = StackPtr.getValueType();
3443 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3444 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3445 SmallVector<SDValue, 8> Stores;
3446 unsigned Offset = 0;
3448 // Do all but one copies using the full register width.
3449 for (unsigned i = 1; i < NumRegs; i++) {
3450 // Load one integer register's worth from the stack slot.
3452 DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo());
3453 // Store it to the final location. Remember the store.
3454 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
3455 ST->getPointerInfo().getWithOffset(Offset),
3456 MinAlign(ST->getAlignment(), Offset),
3457 ST->getMemOperand()->getFlags()));
3458 // Increment the pointers.
3460 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT,
3461 StackPtr, StackPtrIncrement);
3462 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3465 // The last store may be partial. Do a truncating store. On big-endian
3466 // machines this requires an extending load from the stack slot to ensure
3467 // that the bits are in the right place.
3468 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3469 8 * (StoredBytes - Offset));
3471 // Load from the stack slot.
3472 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
3473 MachinePointerInfo(), MemVT);
3476 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
3477 ST->getPointerInfo().getWithOffset(Offset), MemVT,
3478 MinAlign(ST->getAlignment(), Offset),
3479 ST->getMemOperand()->getFlags(), ST->getAAInfo()));
3480 // The order of the stores doesn't matter - say it with a TokenFactor.
3481 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3485 assert(ST->getMemoryVT().isInteger() &&
3486 !ST->getMemoryVT().isVector() &&
3487 "Unaligned store of unknown type.");
3488 // Get the half-size VT
3489 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
3490 int NumBits = NewStoredVT.getSizeInBits();
3491 int IncrementSize = NumBits / 8;
3493 // Divide the stored value in two parts.
3494 SDValue ShiftAmount =
3495 DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
3496 DAG.getDataLayout()));
3498 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
3500 // Store the two parts
3501 SDValue Store1, Store2;
3502 Store1 = DAG.getTruncStore(Chain, dl,
3503 DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
3504 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
3505 ST->getMemOperand()->getFlags());
3507 EVT PtrVT = Ptr.getValueType();
3508 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3509 DAG.getConstant(IncrementSize, dl, PtrVT));
3510 Alignment = MinAlign(Alignment, IncrementSize);
3511 Store2 = DAG.getTruncStore(
3512 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
3513 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
3514 ST->getMemOperand()->getFlags(), ST->getAAInfo());
3517 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
3521 //===----------------------------------------------------------------------===//
3522 // Implementation of Emulated TLS Model
3523 //===----------------------------------------------------------------------===//
3525 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3526 SelectionDAG &DAG) const {
3527 // Access to address of TLS varialbe xyz is lowered to a function call:
3528 // __emutls_get_address( address of global variable named "__emutls_v.xyz" )
3529 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3530 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
3535 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
3536 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
3537 StringRef EmuTlsVarName(NameString);
3538 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
3539 assert(EmuTlsVar && "Cannot find EmuTlsVar ");
3540 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
3541 Entry.Ty = VoidPtrType;
3542 Args.push_back(Entry);
3544 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
3546 TargetLowering::CallLoweringInfo CLI(DAG);
3547 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
3548 CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
3549 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3551 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
3552 // At last for X86 targets, maybe good for other targets too?
3553 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3554 MFI->setAdjustsStack(true); // Is this only for X86 target?
3555 MFI->setHasCalls(true);
3557 assert((GA->getOffset() == 0) &&
3558 "Emulated TLS must have zero offset in GlobalAddressSDNode");
3559 return CallResult.first;