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/Analysis.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
36 /// NOTE: The constructor takes ownership of TLOF.
37 TargetLowering::TargetLowering(const TargetMachine &tm,
38 const TargetLoweringObjectFile *tlof)
39 : TargetLoweringBase(tm, tlof) {}
41 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
45 /// Check whether a given call node is in tail position within its function. If
46 /// so, it sets Chain to the input chain of the tail call.
47 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
48 SDValue &Chain) const {
49 const Function *F = DAG.getMachineFunction().getFunction();
51 // Conservatively require the attributes of the call to match those of
52 // the return. Ignore noalias because it doesn't affect the call sequence.
53 AttributeSet CallerAttrs = F->getAttributes();
54 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex)
55 .removeAttribute(Attribute::NoAlias).hasAttributes())
58 // It's not safe to eliminate the sign / zero extension of the return value.
59 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
60 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
63 // Check if the only use is a function return node.
64 return isUsedByReturnOnly(Node, Chain);
67 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
68 /// and called function attributes.
69 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS,
71 isSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt);
72 isZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
73 isInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg);
74 isSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
75 isNest = CS->paramHasAttr(AttrIdx, Attribute::Nest);
76 isByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
77 isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
78 Alignment = CS->getParamAlignment(AttrIdx);
81 /// Generate a libcall taking the given operands as arguments and returning a
82 /// result of type RetVT.
83 std::pair<SDValue, SDValue>
84 TargetLowering::makeLibCall(SelectionDAG &DAG,
85 RTLIB::Libcall LC, EVT RetVT,
86 const SDValue *Ops, unsigned NumOps,
87 bool isSigned, SDLoc dl,
89 bool isReturnValueUsed) const {
90 TargetLowering::ArgListTy Args;
93 TargetLowering::ArgListEntry Entry;
94 for (unsigned i = 0; i != NumOps; ++i) {
96 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
97 Entry.isSExt = isSigned;
98 Entry.isZExt = !isSigned;
99 Args.push_back(Entry);
101 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), getPointerTy());
103 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
105 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
106 false, 0, getLibcallCallingConv(LC),
107 /*isTailCall=*/false,
108 doesNotReturn, isReturnValueUsed, Callee, Args,
110 return LowerCallTo(CLI);
114 /// SoftenSetCCOperands - Soften the operands of a comparison. This code is
115 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
116 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
117 SDValue &NewLHS, SDValue &NewRHS,
118 ISD::CondCode &CCCode,
120 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
121 && "Unsupported setcc type!");
123 // Expand into one or more soft-fp libcall(s).
124 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
128 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
129 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
133 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
134 (VT == MVT::f64) ? RTLIB::UNE_F64 : RTLIB::UNE_F128;
138 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
139 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
143 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
144 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
148 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
149 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
153 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
154 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
157 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
158 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
161 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
162 (VT == MVT::f64) ? RTLIB::O_F64 : RTLIB::O_F128;
165 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
166 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128;
169 // SETONE = SETOLT | SETOGT
170 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
171 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
174 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
175 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128;
178 LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
179 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128;
182 LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
183 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128;
186 LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
187 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128;
190 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
191 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128;
193 default: llvm_unreachable("Do not know how to soften this setcc!");
197 // Use the target specific return value for comparions lib calls.
198 EVT RetVT = getCmpLibcallReturnType();
199 SDValue Ops[2] = { NewLHS, NewRHS };
200 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, 2, false/*sign irrelevant*/,
202 NewRHS = DAG.getConstant(0, RetVT);
203 CCCode = getCmpLibcallCC(LC1);
204 if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
205 SDValue Tmp = DAG.getNode(ISD::SETCC, dl,
206 getSetCCResultType(*DAG.getContext(), RetVT),
207 NewLHS, NewRHS, DAG.getCondCode(CCCode));
208 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, 2, false/*sign irrelevant*/,
210 NewLHS = DAG.getNode(ISD::SETCC, dl,
211 getSetCCResultType(*DAG.getContext(), RetVT), NewLHS,
212 NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
213 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
218 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
219 /// current function. The returned value is a member of the
220 /// MachineJumpTableInfo::JTEntryKind enum.
221 unsigned TargetLowering::getJumpTableEncoding() const {
222 // In non-pic modes, just use the address of a block.
223 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
224 return MachineJumpTableInfo::EK_BlockAddress;
226 // In PIC mode, if the target supports a GPRel32 directive, use it.
227 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != 0)
228 return MachineJumpTableInfo::EK_GPRel32BlockAddress;
230 // Otherwise, use a label difference.
231 return MachineJumpTableInfo::EK_LabelDifference32;
234 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
235 SelectionDAG &DAG) const {
236 // If our PIC model is GP relative, use the global offset table as the base.
237 unsigned JTEncoding = getJumpTableEncoding();
239 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
240 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
241 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(0));
246 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
247 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
250 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
251 unsigned JTI,MCContext &Ctx) const{
252 // The normal PIC reloc base is the label at the start of the jump table.
253 return MCSymbolRefExpr::Create(MF->getJTISymbol(JTI, Ctx), Ctx);
257 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
258 // Assume that everything is safe in static mode.
259 if (getTargetMachine().getRelocationModel() == Reloc::Static)
262 // In dynamic-no-pic mode, assume that known defined values are safe.
263 if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC &&
265 !GA->getGlobal()->isDeclaration() &&
266 !GA->getGlobal()->isWeakForLinker())
269 // Otherwise assume nothing is safe.
273 //===----------------------------------------------------------------------===//
274 // Optimization Methods
275 //===----------------------------------------------------------------------===//
277 /// ShrinkDemandedConstant - Check to see if the specified operand of the
278 /// specified instruction is a constant integer. If so, check to see if there
279 /// are any bits set in the constant that are not demanded. If so, shrink the
280 /// constant and return true.
281 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op,
282 const APInt &Demanded) {
285 // FIXME: ISD::SELECT, ISD::SELECT_CC
286 switch (Op.getOpcode()) {
291 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
292 if (!C) return false;
294 if (Op.getOpcode() == ISD::XOR &&
295 (C->getAPIntValue() | (~Demanded)).isAllOnesValue())
298 // if we can expand it to have all bits set, do it
299 if (C->getAPIntValue().intersects(~Demanded)) {
300 EVT VT = Op.getValueType();
301 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0),
302 DAG.getConstant(Demanded &
305 return CombineTo(Op, New);
315 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the
316 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening
317 /// cast, but it could be generalized for targets with other types of
318 /// implicit widening casts.
320 TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
322 const APInt &Demanded,
324 assert(Op.getNumOperands() == 2 &&
325 "ShrinkDemandedOp only supports binary operators!");
326 assert(Op.getNode()->getNumValues() == 1 &&
327 "ShrinkDemandedOp only supports nodes with one result!");
329 // Don't do this if the node has another user, which may require the
331 if (!Op.getNode()->hasOneUse())
334 // Search for the smallest integer type with free casts to and from
335 // Op's type. For expedience, just check power-of-2 integer types.
336 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
337 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
338 unsigned SmallVTBits = DemandedSize;
339 if (!isPowerOf2_32(SmallVTBits))
340 SmallVTBits = NextPowerOf2(SmallVTBits);
341 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
342 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
343 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
344 TLI.isZExtFree(SmallVT, Op.getValueType())) {
345 // We found a type with free casts.
346 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
347 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
348 Op.getNode()->getOperand(0)),
349 DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
350 Op.getNode()->getOperand(1)));
351 bool NeedZext = DemandedSize > SmallVTBits;
352 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
353 dl, Op.getValueType(), X);
354 return CombineTo(Op, Z);
360 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the
361 /// DemandedMask bits of the result of Op are ever used downstream. If we can
362 /// use this information to simplify Op, create a new simplified DAG node and
363 /// return true, returning the original and new nodes in Old and New. Otherwise,
364 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
365 /// the expression (used to simplify the caller). The KnownZero/One bits may
366 /// only be accurate for those bits in the DemandedMask.
367 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
368 const APInt &DemandedMask,
371 TargetLoweringOpt &TLO,
372 unsigned Depth) const {
373 unsigned BitWidth = DemandedMask.getBitWidth();
374 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth &&
375 "Mask size mismatches value type size!");
376 APInt NewMask = DemandedMask;
379 // Don't know anything.
380 KnownZero = KnownOne = APInt(BitWidth, 0);
382 // Other users may use these bits.
383 if (!Op.getNode()->hasOneUse()) {
385 // If not at the root, Just compute the KnownZero/KnownOne bits to
386 // simplify things downstream.
387 TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
390 // If this is the root being simplified, allow it to have multiple uses,
391 // just set the NewMask to all bits.
392 NewMask = APInt::getAllOnesValue(BitWidth);
393 } else if (DemandedMask == 0) {
394 // Not demanding any bits from Op.
395 if (Op.getOpcode() != ISD::UNDEF)
396 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
398 } else if (Depth == 6) { // Limit search depth.
402 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
403 switch (Op.getOpcode()) {
405 // We know all of the bits for a constant!
406 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
407 KnownZero = ~KnownOne;
408 return false; // Don't fall through, will infinitely loop.
410 // If the RHS is a constant, check to see if the LHS would be zero without
411 // using the bits from the RHS. Below, we use knowledge about the RHS to
412 // simplify the LHS, here we're using information from the LHS to simplify
414 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
415 APInt LHSZero, LHSOne;
416 // Do not increment Depth here; that can cause an infinite loop.
417 TLO.DAG.ComputeMaskedBits(Op.getOperand(0), LHSZero, LHSOne, Depth);
418 // If the LHS already has zeros where RHSC does, this and is dead.
419 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
420 return TLO.CombineTo(Op, Op.getOperand(0));
421 // If any of the set bits in the RHS are known zero on the LHS, shrink
423 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
427 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
428 KnownOne, TLO, Depth+1))
430 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
431 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
432 KnownZero2, KnownOne2, TLO, Depth+1))
434 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
436 // If all of the demanded bits are known one on one side, return the other.
437 // These bits cannot contribute to the result of the 'and'.
438 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
439 return TLO.CombineTo(Op, Op.getOperand(0));
440 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
441 return TLO.CombineTo(Op, Op.getOperand(1));
442 // If all of the demanded bits in the inputs are known zeros, return zero.
443 if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
444 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType()));
445 // If the RHS is a constant, see if we can simplify it.
446 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
448 // If the operation can be done in a smaller type, do so.
449 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
452 // Output known-1 bits are only known if set in both the LHS & RHS.
453 KnownOne &= KnownOne2;
454 // Output known-0 are known to be clear if zero in either the LHS | RHS.
455 KnownZero |= KnownZero2;
458 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
459 KnownOne, TLO, Depth+1))
461 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
462 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
463 KnownZero2, KnownOne2, TLO, Depth+1))
465 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
467 // If all of the demanded bits are known zero on one side, return the other.
468 // These bits cannot contribute to the result of the 'or'.
469 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
470 return TLO.CombineTo(Op, Op.getOperand(0));
471 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
472 return TLO.CombineTo(Op, Op.getOperand(1));
473 // If all of the potentially set bits on one side are known to be set on
474 // the other side, just use the 'other' side.
475 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
476 return TLO.CombineTo(Op, Op.getOperand(0));
477 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
478 return TLO.CombineTo(Op, Op.getOperand(1));
479 // If the RHS is a constant, see if we can simplify it.
480 if (TLO.ShrinkDemandedConstant(Op, NewMask))
482 // If the operation can be done in a smaller type, do so.
483 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
486 // Output known-0 bits are only known if clear in both the LHS & RHS.
487 KnownZero &= KnownZero2;
488 // Output known-1 are known to be set if set in either the LHS | RHS.
489 KnownOne |= KnownOne2;
492 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
493 KnownOne, TLO, Depth+1))
495 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
496 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
497 KnownOne2, TLO, Depth+1))
499 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
501 // If all of the demanded bits are known zero on one side, return the other.
502 // These bits cannot contribute to the result of the 'xor'.
503 if ((KnownZero & NewMask) == NewMask)
504 return TLO.CombineTo(Op, Op.getOperand(0));
505 if ((KnownZero2 & NewMask) == NewMask)
506 return TLO.CombineTo(Op, Op.getOperand(1));
507 // If the operation can be done in a smaller type, do so.
508 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
511 // If all of the unknown bits are known to be zero on one side or the other
512 // (but not both) turn this into an *inclusive* or.
513 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
514 if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
515 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
519 // Output known-0 bits are known if clear or set in both the LHS & RHS.
520 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
521 // Output known-1 are known to be set if set in only one of the LHS, RHS.
522 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
524 // If all of the demanded bits on one side are known, and all of the set
525 // bits on that side are also known to be set on the other side, turn this
526 // into an AND, as we know the bits will be cleared.
527 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
528 // NB: it is okay if more bits are known than are requested
529 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
530 if (KnownOne == KnownOne2) { // set bits are the same on both sides
531 EVT VT = Op.getValueType();
532 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT);
533 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
534 Op.getOperand(0), ANDC));
538 // If the RHS is a constant, see if we can simplify it.
539 // for XOR, we prefer to force bits to 1 if they will make a -1.
540 // if we can't force bits, try to shrink constant
541 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
542 APInt Expanded = C->getAPIntValue() | (~NewMask);
543 // if we can expand it to have all bits set, do it
544 if (Expanded.isAllOnesValue()) {
545 if (Expanded != C->getAPIntValue()) {
546 EVT VT = Op.getValueType();
547 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
548 TLO.DAG.getConstant(Expanded, VT));
549 return TLO.CombineTo(Op, New);
551 // if it already has all the bits set, nothing to change
552 // but don't shrink either!
553 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
558 KnownZero = KnownZeroOut;
559 KnownOne = KnownOneOut;
562 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
563 KnownOne, TLO, Depth+1))
565 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
566 KnownOne2, TLO, Depth+1))
568 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
569 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
571 // If the operands are constants, see if we can simplify them.
572 if (TLO.ShrinkDemandedConstant(Op, NewMask))
575 // Only known if known in both the LHS and RHS.
576 KnownOne &= KnownOne2;
577 KnownZero &= KnownZero2;
580 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
581 KnownOne, TLO, Depth+1))
583 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
584 KnownOne2, TLO, Depth+1))
586 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
587 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
589 // If the operands are constants, see if we can simplify them.
590 if (TLO.ShrinkDemandedConstant(Op, NewMask))
593 // Only known if known in both the LHS and RHS.
594 KnownOne &= KnownOne2;
595 KnownZero &= KnownZero2;
598 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
599 unsigned ShAmt = SA->getZExtValue();
600 SDValue InOp = Op.getOperand(0);
602 // If the shift count is an invalid immediate, don't do anything.
603 if (ShAmt >= BitWidth)
606 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
607 // single shift. We can do this if the bottom bits (which are shifted
608 // out) are never demanded.
609 if (InOp.getOpcode() == ISD::SRL &&
610 isa<ConstantSDNode>(InOp.getOperand(1))) {
611 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
612 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
613 unsigned Opc = ISD::SHL;
621 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
622 EVT VT = Op.getValueType();
623 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
624 InOp.getOperand(0), NewSA));
628 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
629 KnownZero, KnownOne, TLO, Depth+1))
632 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
633 // are not demanded. This will likely allow the anyext to be folded away.
634 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
635 SDValue InnerOp = InOp.getNode()->getOperand(0);
636 EVT InnerVT = InnerOp.getValueType();
637 unsigned InnerBits = InnerVT.getSizeInBits();
638 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
639 isTypeDesirableForOp(ISD::SHL, InnerVT)) {
640 EVT ShTy = getShiftAmountTy(InnerVT);
641 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
644 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
645 TLO.DAG.getConstant(ShAmt, ShTy));
648 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
651 // Repeat the SHL optimization above in cases where an extension
652 // intervenes: (shl (anyext (shr x, c1)), c2) to
653 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits
654 // aren't demanded (as above) and that the shifted upper c1 bits of
655 // x aren't demanded.
656 if (InOp.hasOneUse() &&
657 InnerOp.getOpcode() == ISD::SRL &&
658 InnerOp.hasOneUse() &&
659 isa<ConstantSDNode>(InnerOp.getOperand(1))) {
660 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
662 if (InnerShAmt < ShAmt &&
663 InnerShAmt < InnerBits &&
664 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
665 NewMask.trunc(ShAmt) == 0) {
667 TLO.DAG.getConstant(ShAmt - InnerShAmt,
668 Op.getOperand(1).getValueType());
669 EVT VT = Op.getValueType();
670 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
671 InnerOp.getOperand(0));
672 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
678 KnownZero <<= SA->getZExtValue();
679 KnownOne <<= SA->getZExtValue();
680 // low bits known zero.
681 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue());
685 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
686 EVT VT = Op.getValueType();
687 unsigned ShAmt = SA->getZExtValue();
688 unsigned VTSize = VT.getSizeInBits();
689 SDValue InOp = Op.getOperand(0);
691 // If the shift count is an invalid immediate, don't do anything.
692 if (ShAmt >= BitWidth)
695 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
696 // single shift. We can do this if the top bits (which are shifted out)
697 // are never demanded.
698 if (InOp.getOpcode() == ISD::SHL &&
699 isa<ConstantSDNode>(InOp.getOperand(1))) {
700 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
701 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
702 unsigned Opc = ISD::SRL;
710 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType());
711 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
712 InOp.getOperand(0), NewSA));
716 // Compute the new bits that are at the top now.
717 if (SimplifyDemandedBits(InOp, (NewMask << ShAmt),
718 KnownZero, KnownOne, TLO, Depth+1))
720 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
721 KnownZero = KnownZero.lshr(ShAmt);
722 KnownOne = KnownOne.lshr(ShAmt);
724 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
725 KnownZero |= HighBits; // High bits known zero.
729 // If this is an arithmetic shift right and only the low-bit is set, we can
730 // always convert this into a logical shr, even if the shift amount is
731 // variable. The low bit of the shift cannot be an input sign bit unless
732 // the shift amount is >= the size of the datatype, which is undefined.
734 return TLO.CombineTo(Op,
735 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
736 Op.getOperand(0), Op.getOperand(1)));
738 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
739 EVT VT = Op.getValueType();
740 unsigned ShAmt = SA->getZExtValue();
742 // If the shift count is an invalid immediate, don't do anything.
743 if (ShAmt >= BitWidth)
746 APInt InDemandedMask = (NewMask << ShAmt);
748 // If any of the demanded bits are produced by the sign extension, we also
749 // demand the input sign bit.
750 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
751 if (HighBits.intersects(NewMask))
752 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits());
754 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
755 KnownZero, KnownOne, TLO, Depth+1))
757 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
758 KnownZero = KnownZero.lshr(ShAmt);
759 KnownOne = KnownOne.lshr(ShAmt);
761 // Handle the sign bit, adjusted to where it is now in the mask.
762 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
764 // If the input sign bit is known to be zero, or if none of the top bits
765 // are demanded, turn this into an unsigned shift right.
766 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits)
767 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
771 int Log2 = NewMask.exactLogBase2();
773 // The bit must come from the sign.
775 TLO.DAG.getConstant(BitWidth - 1 - Log2,
776 Op.getOperand(1).getValueType());
777 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
778 Op.getOperand(0), NewSA));
781 if (KnownOne.intersects(SignBit))
782 // New bits are known one.
783 KnownOne |= HighBits;
786 case ISD::SIGN_EXTEND_INREG: {
787 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
789 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
790 // If we only care about the highest bit, don't bother shifting right.
791 if (MsbMask == DemandedMask) {
792 unsigned ShAmt = ExVT.getScalarType().getSizeInBits();
793 SDValue InOp = Op.getOperand(0);
795 // Compute the correct shift amount type, which must be getShiftAmountTy
796 // for scalar types after legalization.
797 EVT ShiftAmtTy = Op.getValueType();
798 if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
799 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy);
801 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, ShiftAmtTy);
802 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
803 Op.getValueType(), InOp, ShiftAmt));
806 // Sign extension. Compute the demanded bits in the result that are not
807 // present in the input.
809 APInt::getHighBitsSet(BitWidth,
810 BitWidth - ExVT.getScalarType().getSizeInBits());
812 // If none of the extended bits are demanded, eliminate the sextinreg.
813 if ((NewBits & NewMask) == 0)
814 return TLO.CombineTo(Op, Op.getOperand(0));
817 APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth);
818 APInt InputDemandedBits =
819 APInt::getLowBitsSet(BitWidth,
820 ExVT.getScalarType().getSizeInBits()) &
823 // Since the sign extended bits are demanded, we know that the sign
825 InputDemandedBits |= InSignBit;
827 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
828 KnownZero, KnownOne, TLO, Depth+1))
830 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
832 // If the sign bit of the input is known set or clear, then we know the
833 // top bits of the result.
835 // If the input sign bit is known zero, convert this into a zero extension.
836 if (KnownZero.intersects(InSignBit))
837 return TLO.CombineTo(Op,
838 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT));
840 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
842 KnownZero &= ~NewBits;
843 } else { // Input sign bit unknown
844 KnownZero &= ~NewBits;
845 KnownOne &= ~NewBits;
849 case ISD::ZERO_EXTEND: {
850 unsigned OperandBitWidth =
851 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
852 APInt InMask = NewMask.trunc(OperandBitWidth);
854 // If none of the top bits are demanded, convert this into an any_extend.
856 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
857 if (!NewBits.intersects(NewMask))
858 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
862 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
863 KnownZero, KnownOne, TLO, Depth+1))
865 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
866 KnownZero = KnownZero.zext(BitWidth);
867 KnownOne = KnownOne.zext(BitWidth);
868 KnownZero |= NewBits;
871 case ISD::SIGN_EXTEND: {
872 EVT InVT = Op.getOperand(0).getValueType();
873 unsigned InBits = InVT.getScalarType().getSizeInBits();
874 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits);
875 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits);
876 APInt NewBits = ~InMask & NewMask;
878 // If none of the top bits are demanded, convert this into an any_extend.
880 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
884 // Since some of the sign extended bits are demanded, we know that the sign
886 APInt InDemandedBits = InMask & NewMask;
887 InDemandedBits |= InSignBit;
888 InDemandedBits = InDemandedBits.trunc(InBits);
890 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
891 KnownOne, TLO, Depth+1))
893 KnownZero = KnownZero.zext(BitWidth);
894 KnownOne = KnownOne.zext(BitWidth);
896 // If the sign bit is known zero, convert this to a zero extend.
897 if (KnownZero.intersects(InSignBit))
898 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
902 // If the sign bit is known one, the top bits match.
903 if (KnownOne.intersects(InSignBit)) {
905 assert((KnownZero & NewBits) == 0);
906 } else { // Otherwise, top bits aren't known.
907 assert((KnownOne & NewBits) == 0);
908 assert((KnownZero & NewBits) == 0);
912 case ISD::ANY_EXTEND: {
913 unsigned OperandBitWidth =
914 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
915 APInt InMask = NewMask.trunc(OperandBitWidth);
916 if (SimplifyDemandedBits(Op.getOperand(0), InMask,
917 KnownZero, KnownOne, TLO, Depth+1))
919 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
920 KnownZero = KnownZero.zext(BitWidth);
921 KnownOne = KnownOne.zext(BitWidth);
924 case ISD::TRUNCATE: {
925 // Simplify the input, using demanded bit information, and compute the known
926 // zero/one bits live out.
927 unsigned OperandBitWidth =
928 Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
929 APInt TruncMask = NewMask.zext(OperandBitWidth);
930 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
931 KnownZero, KnownOne, TLO, Depth+1))
933 KnownZero = KnownZero.trunc(BitWidth);
934 KnownOne = KnownOne.trunc(BitWidth);
936 // If the input is only used by this truncate, see if we can shrink it based
937 // on the known demanded bits.
938 if (Op.getOperand(0).getNode()->hasOneUse()) {
939 SDValue In = Op.getOperand(0);
940 switch (In.getOpcode()) {
943 // Shrink SRL by a constant if none of the high bits shifted in are
945 if (TLO.LegalTypes() &&
946 !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
947 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
950 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
953 SDValue Shift = In.getOperand(1);
954 if (TLO.LegalTypes()) {
955 uint64_t ShVal = ShAmt->getZExtValue();
957 TLO.DAG.getConstant(ShVal, getShiftAmountTy(Op.getValueType()));
960 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
961 OperandBitWidth - BitWidth);
962 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
964 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
965 // None of the shifted in bits are needed. Add a truncate of the
966 // shift input, then shift it.
967 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
970 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
979 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
982 case ISD::AssertZext: {
983 // AssertZext demands all of the high bits, plus any of the low bits
984 // demanded by its users.
985 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
986 APInt InMask = APInt::getLowBitsSet(BitWidth,
988 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
989 KnownZero, KnownOne, TLO, Depth+1))
991 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
993 KnownZero |= ~InMask & NewMask;
997 // If this is an FP->Int bitcast and if the sign bit is the only
998 // thing demanded, turn this into a FGETSIGN.
999 if (!TLO.LegalOperations() &&
1000 !Op.getValueType().isVector() &&
1001 !Op.getOperand(0).getValueType().isVector() &&
1002 NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) &&
1003 Op.getOperand(0).getValueType().isFloatingPoint()) {
1004 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1005 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1006 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) {
1007 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1008 // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1009 // place. We expect the SHL to be eliminated by other optimizations.
1010 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1011 unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits();
1012 if (!OpVTLegal && OpVTSizeInBits > 32)
1013 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1014 unsigned ShVal = Op.getValueType().getSizeInBits()-1;
1015 SDValue ShAmt = TLO.DAG.getConstant(ShVal, Op.getValueType());
1016 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1025 // Add, Sub, and Mul don't demand any bits in positions beyond that
1026 // of the highest bit demanded of them.
1027 APInt LoMask = APInt::getLowBitsSet(BitWidth,
1028 BitWidth - NewMask.countLeadingZeros());
1029 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1030 KnownOne2, TLO, Depth+1))
1032 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1033 KnownOne2, TLO, Depth+1))
1035 // See if the operation should be performed at a smaller bit width.
1036 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
1041 // Just use ComputeMaskedBits to compute output bits.
1042 TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth);
1046 // If we know the value of all of the demanded bits, return this as a
1048 if ((NewMask & (KnownZero|KnownOne)) == NewMask)
1049 return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType()));
1054 /// computeMaskedBitsForTargetNode - Determine which of the bits specified
1055 /// in Mask are known to be either zero or one and return them in the
1056 /// KnownZero/KnownOne bitsets.
1057 void TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1060 const SelectionDAG &DAG,
1061 unsigned Depth) const {
1062 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1063 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1064 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1065 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1066 "Should use MaskedValueIsZero if you don't know whether Op"
1067 " is a target node!");
1068 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1071 /// ComputeNumSignBitsForTargetNode - This method can be implemented by
1072 /// targets that want to expose additional information about sign bits to the
1074 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1075 unsigned Depth) const {
1076 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1077 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1078 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1079 Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1080 "Should use ComputeNumSignBits if you don't know whether Op"
1081 " is a target node!");
1085 /// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly
1086 /// one bit set. This differs from ComputeMaskedBits in that it doesn't need to
1087 /// determine which bit is set.
1089 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) {
1090 // A left-shift of a constant one will have exactly one bit set, because
1091 // shifting the bit off the end is undefined.
1092 if (Val.getOpcode() == ISD::SHL)
1093 if (ConstantSDNode *C =
1094 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1095 if (C->getAPIntValue() == 1)
1098 // Similarly, a right-shift of a constant sign-bit will have exactly
1100 if (Val.getOpcode() == ISD::SRL)
1101 if (ConstantSDNode *C =
1102 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0)))
1103 if (C->getAPIntValue().isSignBit())
1106 // More could be done here, though the above checks are enough
1107 // to handle some common cases.
1109 // Fall back to ComputeMaskedBits to catch other known cases.
1110 EVT OpVT = Val.getValueType();
1111 unsigned BitWidth = OpVT.getScalarType().getSizeInBits();
1112 APInt KnownZero, KnownOne;
1113 DAG.ComputeMaskedBits(Val, KnownZero, KnownOne);
1114 return (KnownZero.countPopulation() == BitWidth - 1) &&
1115 (KnownOne.countPopulation() == 1);
1118 /// SimplifySetCC - Try to simplify a setcc built with the specified operands
1119 /// and cc. If it is unable to simplify it, return a null SDValue.
1121 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1122 ISD::CondCode Cond, bool foldBooleans,
1123 DAGCombinerInfo &DCI, SDLoc dl) const {
1124 SelectionDAG &DAG = DCI.DAG;
1126 // These setcc operations always fold.
1130 case ISD::SETFALSE2: return DAG.getConstant(0, VT);
1132 case ISD::SETTRUE2: {
1133 TargetLowering::BooleanContent Cnt = getBooleanContents(VT.isVector());
1134 return DAG.getConstant(
1135 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, VT);
1139 // Ensure that the constant occurs on the RHS, and fold constant
1141 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1142 if (isa<ConstantSDNode>(N0.getNode()) &&
1143 (DCI.isBeforeLegalizeOps() ||
1144 isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1145 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
1147 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1148 const APInt &C1 = N1C->getAPIntValue();
1150 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1151 // equality comparison, then we're just comparing whether X itself is
1153 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1154 N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1155 N0.getOperand(1).getOpcode() == ISD::Constant) {
1157 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1158 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1159 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) {
1160 if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1161 // (srl (ctlz x), 5) == 0 -> X != 0
1162 // (srl (ctlz x), 5) != 1 -> X != 0
1165 // (srl (ctlz x), 5) != 0 -> X == 0
1166 // (srl (ctlz x), 5) == 1 -> X == 0
1169 SDValue Zero = DAG.getConstant(0, N0.getValueType());
1170 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1176 // Look through truncs that don't change the value of a ctpop.
1177 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1178 CTPOP = N0.getOperand(0);
1180 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1181 (N0 == CTPOP || N0.getValueType().getSizeInBits() >
1182 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) {
1183 EVT CTVT = CTPOP.getValueType();
1184 SDValue CTOp = CTPOP.getOperand(0);
1186 // (ctpop x) u< 2 -> (x & x-1) == 0
1187 // (ctpop x) u> 1 -> (x & x-1) != 0
1188 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1189 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1190 DAG.getConstant(1, CTVT));
1191 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1192 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1193 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, CTVT), CC);
1196 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1199 // (zext x) == C --> x == (trunc C)
1200 if (DCI.isBeforeLegalize() && N0->hasOneUse() &&
1201 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1202 unsigned MinBits = N0.getValueSizeInBits();
1204 if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1206 MinBits = N0->getOperand(0).getValueSizeInBits();
1207 PreZExt = N0->getOperand(0);
1208 } else if (N0->getOpcode() == ISD::AND) {
1209 // DAGCombine turns costly ZExts into ANDs
1210 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1211 if ((C->getAPIntValue()+1).isPowerOf2()) {
1212 MinBits = C->getAPIntValue().countTrailingOnes();
1213 PreZExt = N0->getOperand(0);
1215 } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) {
1217 if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1218 MinBits = LN0->getMemoryVT().getSizeInBits();
1223 // Make sure we're not losing bits from the constant.
1225 MinBits < C1.getBitWidth() && MinBits >= C1.getActiveBits()) {
1226 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1227 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1228 // Will get folded away.
1229 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreZExt);
1230 SDValue C = DAG.getConstant(C1.trunc(MinBits), MinVT);
1231 return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1236 // If the LHS is '(and load, const)', the RHS is 0,
1237 // the test is for equality or unsigned, and all 1 bits of the const are
1238 // in the same partial word, see if we can shorten the load.
1239 if (DCI.isBeforeLegalize() &&
1240 !ISD::isSignedIntSetCC(Cond) &&
1241 N0.getOpcode() == ISD::AND && C1 == 0 &&
1242 N0.getNode()->hasOneUse() &&
1243 isa<LoadSDNode>(N0.getOperand(0)) &&
1244 N0.getOperand(0).getNode()->hasOneUse() &&
1245 isa<ConstantSDNode>(N0.getOperand(1))) {
1246 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1248 unsigned bestWidth = 0, bestOffset = 0;
1249 if (!Lod->isVolatile() && Lod->isUnindexed()) {
1250 unsigned origWidth = N0.getValueType().getSizeInBits();
1251 unsigned maskWidth = origWidth;
1252 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1253 // 8 bits, but have to be careful...
1254 if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1255 origWidth = Lod->getMemoryVT().getSizeInBits();
1257 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1258 for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1259 APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1260 for (unsigned offset=0; offset<origWidth/width; offset++) {
1261 if ((newMask & Mask) == Mask) {
1262 if (!getDataLayout()->isLittleEndian())
1263 bestOffset = (origWidth/width - offset - 1) * (width/8);
1265 bestOffset = (uint64_t)offset * (width/8);
1266 bestMask = Mask.lshr(offset * (width/8) * 8);
1270 newMask = newMask << width;
1275 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1276 if (newVT.isRound()) {
1277 EVT PtrType = Lod->getOperand(1).getValueType();
1278 SDValue Ptr = Lod->getBasePtr();
1279 if (bestOffset != 0)
1280 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1281 DAG.getConstant(bestOffset, PtrType));
1282 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1283 SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
1284 Lod->getPointerInfo().getWithOffset(bestOffset),
1285 false, false, false, NewAlign);
1286 return DAG.getSetCC(dl, VT,
1287 DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1288 DAG.getConstant(bestMask.trunc(bestWidth),
1290 DAG.getConstant(0LL, newVT), Cond);
1295 // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1296 if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1297 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits();
1299 // If the comparison constant has bits in the upper part, the
1300 // zero-extended value could never match.
1301 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1302 C1.getBitWidth() - InSize))) {
1306 case ISD::SETEQ: return DAG.getConstant(0, VT);
1309 case ISD::SETNE: return DAG.getConstant(1, VT);
1312 // True if the sign bit of C1 is set.
1313 return DAG.getConstant(C1.isNegative(), VT);
1316 // True if the sign bit of C1 isn't set.
1317 return DAG.getConstant(C1.isNonNegative(), VT);
1323 // Otherwise, we can perform the comparison with the low bits.
1331 EVT newVT = N0.getOperand(0).getValueType();
1332 if (DCI.isBeforeLegalizeOps() ||
1333 (isOperationLegal(ISD::SETCC, newVT) &&
1334 getCondCodeAction(Cond, newVT.getSimpleVT())==Legal))
1335 return DAG.getSetCC(dl, VT, N0.getOperand(0),
1336 DAG.getConstant(C1.trunc(InSize), newVT),
1341 break; // todo, be more careful with signed comparisons
1343 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1344 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1345 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1346 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1347 EVT ExtDstTy = N0.getValueType();
1348 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1350 // If the constant doesn't fit into the number of bits for the source of
1351 // the sign extension, it is impossible for both sides to be equal.
1352 if (C1.getMinSignedBits() > ExtSrcTyBits)
1353 return DAG.getConstant(Cond == ISD::SETNE, VT);
1356 EVT Op0Ty = N0.getOperand(0).getValueType();
1357 if (Op0Ty == ExtSrcTy) {
1358 ZextOp = N0.getOperand(0);
1360 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1361 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1362 DAG.getConstant(Imm, Op0Ty));
1364 if (!DCI.isCalledByLegalizer())
1365 DCI.AddToWorklist(ZextOp.getNode());
1366 // Otherwise, make this a use of a zext.
1367 return DAG.getSetCC(dl, VT, ZextOp,
1368 DAG.getConstant(C1 & APInt::getLowBitsSet(
1373 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1374 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1375 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC
1376 if (N0.getOpcode() == ISD::SETCC &&
1377 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
1378 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1380 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
1381 // Invert the condition.
1382 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1383 CC = ISD::getSetCCInverse(CC,
1384 N0.getOperand(0).getValueType().isInteger());
1385 if (DCI.isBeforeLegalizeOps() ||
1386 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1387 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1390 if ((N0.getOpcode() == ISD::XOR ||
1391 (N0.getOpcode() == ISD::AND &&
1392 N0.getOperand(0).getOpcode() == ISD::XOR &&
1393 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1394 isa<ConstantSDNode>(N0.getOperand(1)) &&
1395 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1396 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We
1397 // can only do this if the top bits are known zero.
1398 unsigned BitWidth = N0.getValueSizeInBits();
1399 if (DAG.MaskedValueIsZero(N0,
1400 APInt::getHighBitsSet(BitWidth,
1402 // Okay, get the un-inverted input value.
1404 if (N0.getOpcode() == ISD::XOR)
1405 Val = N0.getOperand(0);
1407 assert(N0.getOpcode() == ISD::AND &&
1408 N0.getOperand(0).getOpcode() == ISD::XOR);
1409 // ((X^1)&1)^1 -> X & 1
1410 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1411 N0.getOperand(0).getOperand(0),
1415 return DAG.getSetCC(dl, VT, Val, N1,
1416 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1418 } else if (N1C->getAPIntValue() == 1 &&
1420 getBooleanContents(false) == ZeroOrOneBooleanContent)) {
1422 if (Op0.getOpcode() == ISD::TRUNCATE)
1423 Op0 = Op0.getOperand(0);
1425 if ((Op0.getOpcode() == ISD::XOR) &&
1426 Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1427 Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1428 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1429 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1430 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1433 if (Op0.getOpcode() == ISD::AND &&
1434 isa<ConstantSDNode>(Op0.getOperand(1)) &&
1435 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1436 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1437 if (Op0.getValueType().bitsGT(VT))
1438 Op0 = DAG.getNode(ISD::AND, dl, VT,
1439 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1440 DAG.getConstant(1, VT));
1441 else if (Op0.getValueType().bitsLT(VT))
1442 Op0 = DAG.getNode(ISD::AND, dl, VT,
1443 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
1444 DAG.getConstant(1, VT));
1446 return DAG.getSetCC(dl, VT, Op0,
1447 DAG.getConstant(0, Op0.getValueType()),
1448 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1450 if (Op0.getOpcode() == ISD::AssertZext &&
1451 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1452 return DAG.getSetCC(dl, VT, Op0,
1453 DAG.getConstant(0, Op0.getValueType()),
1454 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1458 APInt MinVal, MaxVal;
1459 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1460 if (ISD::isSignedIntSetCC(Cond)) {
1461 MinVal = APInt::getSignedMinValue(OperandBitSize);
1462 MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1464 MinVal = APInt::getMinValue(OperandBitSize);
1465 MaxVal = APInt::getMaxValue(OperandBitSize);
1468 // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1469 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1470 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true
1471 // X >= C0 --> X > (C0-1)
1472 return DAG.getSetCC(dl, VT, N0,
1473 DAG.getConstant(C1-1, N1.getValueType()),
1474 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
1477 if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1478 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true
1479 // X <= C0 --> X < (C0+1)
1480 return DAG.getSetCC(dl, VT, N0,
1481 DAG.getConstant(C1+1, N1.getValueType()),
1482 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
1485 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1486 return DAG.getConstant(0, VT); // X < MIN --> false
1487 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1488 return DAG.getConstant(1, VT); // X >= MIN --> true
1489 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1490 return DAG.getConstant(0, VT); // X > MAX --> false
1491 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1492 return DAG.getConstant(1, VT); // X <= MAX --> true
1494 // Canonicalize setgt X, Min --> setne X, Min
1495 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1496 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1497 // Canonicalize setlt X, Max --> setne X, Max
1498 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1499 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1501 // If we have setult X, 1, turn it into seteq X, 0
1502 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1503 return DAG.getSetCC(dl, VT, N0,
1504 DAG.getConstant(MinVal, N0.getValueType()),
1506 // If we have setugt X, Max-1, turn it into seteq X, Max
1507 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1508 return DAG.getSetCC(dl, VT, N0,
1509 DAG.getConstant(MaxVal, N0.getValueType()),
1512 // If we have "setcc X, C0", check to see if we can shrink the immediate
1515 // SETUGT X, SINTMAX -> SETLT X, 0
1516 if (Cond == ISD::SETUGT &&
1517 C1 == APInt::getSignedMaxValue(OperandBitSize))
1518 return DAG.getSetCC(dl, VT, N0,
1519 DAG.getConstant(0, N1.getValueType()),
1522 // SETULT X, SINTMIN -> SETGT X, -1
1523 if (Cond == ISD::SETULT &&
1524 C1 == APInt::getSignedMinValue(OperandBitSize)) {
1525 SDValue ConstMinusOne =
1526 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize),
1528 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1531 // Fold bit comparisons when we can.
1532 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1533 (VT == N0.getValueType() ||
1534 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1535 N0.getOpcode() == ISD::AND)
1536 if (ConstantSDNode *AndRHS =
1537 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1538 EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
1539 getPointerTy() : getShiftAmountTy(N0.getValueType());
1540 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3
1541 // Perform the xform if the AND RHS is a single bit.
1542 if (AndRHS->getAPIntValue().isPowerOf2()) {
1543 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1544 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1545 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy)));
1547 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
1548 // (X & 8) == 8 --> (X & 8) >> 3
1549 // Perform the xform if C1 is a single bit.
1550 if (C1.isPowerOf2()) {
1551 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1552 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
1553 DAG.getConstant(C1.logBase2(), ShiftTy)));
1558 if (C1.getMinSignedBits() <= 64 &&
1559 !isLegalICmpImmediate(C1.getSExtValue())) {
1560 // (X & -256) == 256 -> (X >> 8) == 1
1561 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1562 N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
1563 if (ConstantSDNode *AndRHS =
1564 dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1565 const APInt &AndRHSC = AndRHS->getAPIntValue();
1566 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
1567 unsigned ShiftBits = AndRHSC.countTrailingZeros();
1568 EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
1569 getPointerTy() : getShiftAmountTy(N0.getValueType());
1570 EVT CmpTy = N0.getValueType();
1571 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
1572 DAG.getConstant(ShiftBits, ShiftTy));
1573 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), CmpTy);
1574 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
1577 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
1578 Cond == ISD::SETULE || Cond == ISD::SETUGT) {
1579 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
1580 // X < 0x100000000 -> (X >> 32) < 1
1581 // X >= 0x100000000 -> (X >> 32) >= 1
1582 // X <= 0x0ffffffff -> (X >> 32) < 1
1583 // X > 0x0ffffffff -> (X >> 32) >= 1
1586 ISD::CondCode NewCond = Cond;
1588 ShiftBits = C1.countTrailingOnes();
1590 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1592 ShiftBits = C1.countTrailingZeros();
1594 NewC = NewC.lshr(ShiftBits);
1595 if (ShiftBits && isLegalICmpImmediate(NewC.getSExtValue())) {
1596 EVT ShiftTy = DCI.isBeforeLegalizeOps() ?
1597 getPointerTy() : getShiftAmountTy(N0.getValueType());
1598 EVT CmpTy = N0.getValueType();
1599 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
1600 DAG.getConstant(ShiftBits, ShiftTy));
1601 SDValue CmpRHS = DAG.getConstant(NewC, CmpTy);
1602 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
1608 if (isa<ConstantFPSDNode>(N0.getNode())) {
1609 // Constant fold or commute setcc.
1610 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
1611 if (O.getNode()) return O;
1612 } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
1613 // If the RHS of an FP comparison is a constant, simplify it away in
1615 if (CFP->getValueAPF().isNaN()) {
1616 // If an operand is known to be a nan, we can fold it.
1617 switch (ISD::getUnorderedFlavor(Cond)) {
1618 default: llvm_unreachable("Unknown flavor!");
1619 case 0: // Known false.
1620 return DAG.getConstant(0, VT);
1621 case 1: // Known true.
1622 return DAG.getConstant(1, VT);
1623 case 2: // Undefined.
1624 return DAG.getUNDEF(VT);
1628 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the
1629 // constant if knowing that the operand is non-nan is enough. We prefer to
1630 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
1632 if (Cond == ISD::SETO || Cond == ISD::SETUO)
1633 return DAG.getSetCC(dl, VT, N0, N0, Cond);
1635 // If the condition is not legal, see if we can find an equivalent one
1637 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
1638 // If the comparison was an awkward floating-point == or != and one of
1639 // the comparison operands is infinity or negative infinity, convert the
1640 // condition to a less-awkward <= or >=.
1641 if (CFP->getValueAPF().isInfinity()) {
1642 if (CFP->getValueAPF().isNegative()) {
1643 if (Cond == ISD::SETOEQ &&
1644 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1645 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
1646 if (Cond == ISD::SETUEQ &&
1647 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
1648 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
1649 if (Cond == ISD::SETUNE &&
1650 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1651 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
1652 if (Cond == ISD::SETONE &&
1653 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
1654 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
1656 if (Cond == ISD::SETOEQ &&
1657 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1658 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
1659 if (Cond == ISD::SETUEQ &&
1660 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
1661 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
1662 if (Cond == ISD::SETUNE &&
1663 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1664 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
1665 if (Cond == ISD::SETONE &&
1666 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
1667 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
1674 // The sext(setcc()) => setcc() optimization relies on the appropriate
1675 // constant being emitted.
1677 switch (getBooleanContents(N0.getValueType().isVector())) {
1678 case UndefinedBooleanContent:
1679 case ZeroOrOneBooleanContent:
1680 EqVal = ISD::isTrueWhenEqual(Cond);
1682 case ZeroOrNegativeOneBooleanContent:
1683 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
1687 // We can always fold X == X for integer setcc's.
1688 if (N0.getValueType().isInteger()) {
1689 return DAG.getConstant(EqVal, VT);
1691 unsigned UOF = ISD::getUnorderedFlavor(Cond);
1692 if (UOF == 2) // FP operators that are undefined on NaNs.
1693 return DAG.getConstant(EqVal, VT);
1694 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
1695 return DAG.getConstant(EqVal, VT);
1696 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO
1697 // if it is not already.
1698 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
1699 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
1700 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
1701 return DAG.getSetCC(dl, VT, N0, N1, NewCond);
1704 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1705 N0.getValueType().isInteger()) {
1706 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
1707 N0.getOpcode() == ISD::XOR) {
1708 // Simplify (X+Y) == (X+Z) --> Y == Z
1709 if (N0.getOpcode() == N1.getOpcode()) {
1710 if (N0.getOperand(0) == N1.getOperand(0))
1711 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
1712 if (N0.getOperand(1) == N1.getOperand(1))
1713 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
1714 if (DAG.isCommutativeBinOp(N0.getOpcode())) {
1715 // If X op Y == Y op X, try other combinations.
1716 if (N0.getOperand(0) == N1.getOperand(1))
1717 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
1719 if (N0.getOperand(1) == N1.getOperand(0))
1720 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
1725 // If RHS is a legal immediate value for a compare instruction, we need
1726 // to be careful about increasing register pressure needlessly.
1727 bool LegalRHSImm = false;
1729 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) {
1730 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1731 // Turn (X+C1) == C2 --> X == C2-C1
1732 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
1733 return DAG.getSetCC(dl, VT, N0.getOperand(0),
1734 DAG.getConstant(RHSC->getAPIntValue()-
1735 LHSR->getAPIntValue(),
1736 N0.getValueType()), Cond);
1739 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
1740 if (N0.getOpcode() == ISD::XOR)
1741 // If we know that all of the inverted bits are zero, don't bother
1742 // performing the inversion.
1743 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
1745 DAG.getSetCC(dl, VT, N0.getOperand(0),
1746 DAG.getConstant(LHSR->getAPIntValue() ^
1747 RHSC->getAPIntValue(),
1752 // Turn (C1-X) == C2 --> X == C1-C2
1753 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1754 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
1756 DAG.getSetCC(dl, VT, N0.getOperand(1),
1757 DAG.getConstant(SUBC->getAPIntValue() -
1758 RHSC->getAPIntValue(),
1764 // Could RHSC fold directly into a compare?
1765 if (RHSC->getValueType(0).getSizeInBits() <= 64)
1766 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
1769 // Simplify (X+Z) == X --> Z == 0
1770 // Don't do this if X is an immediate that can fold into a cmp
1771 // instruction and X+Z has other uses. It could be an induction variable
1772 // chain, and the transform would increase register pressure.
1773 if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
1774 if (N0.getOperand(0) == N1)
1775 return DAG.getSetCC(dl, VT, N0.getOperand(1),
1776 DAG.getConstant(0, N0.getValueType()), Cond);
1777 if (N0.getOperand(1) == N1) {
1778 if (DAG.isCommutativeBinOp(N0.getOpcode()))
1779 return DAG.getSetCC(dl, VT, N0.getOperand(0),
1780 DAG.getConstant(0, N0.getValueType()), Cond);
1781 if (N0.getNode()->hasOneUse()) {
1782 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
1783 // (Z-X) == X --> Z == X<<1
1784 SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1,
1785 DAG.getConstant(1, getShiftAmountTy(N1.getValueType())));
1786 if (!DCI.isCalledByLegalizer())
1787 DCI.AddToWorklist(SH.getNode());
1788 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
1794 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
1795 N1.getOpcode() == ISD::XOR) {
1796 // Simplify X == (X+Z) --> Z == 0
1797 if (N1.getOperand(0) == N0)
1798 return DAG.getSetCC(dl, VT, N1.getOperand(1),
1799 DAG.getConstant(0, N1.getValueType()), Cond);
1800 if (N1.getOperand(1) == N0) {
1801 if (DAG.isCommutativeBinOp(N1.getOpcode()))
1802 return DAG.getSetCC(dl, VT, N1.getOperand(0),
1803 DAG.getConstant(0, N1.getValueType()), Cond);
1804 if (N1.getNode()->hasOneUse()) {
1805 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
1806 // X == (Z-X) --> X<<1 == Z
1807 SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0,
1808 DAG.getConstant(1, getShiftAmountTy(N0.getValueType())));
1809 if (!DCI.isCalledByLegalizer())
1810 DCI.AddToWorklist(SH.getNode());
1811 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
1816 // Simplify x&y == y to x&y != 0 if y has exactly one bit set.
1817 // Note that where y is variable and is known to have at most
1818 // one bit set (for example, if it is z&1) we cannot do this;
1819 // the expressions are not equivalent when y==0.
1820 if (N0.getOpcode() == ISD::AND)
1821 if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) {
1822 if (ValueHasExactlyOneBitSet(N1, DAG)) {
1823 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1824 if (DCI.isBeforeLegalizeOps() ||
1825 isCondCodeLegal(Cond, N0.getSimpleValueType())) {
1826 SDValue Zero = DAG.getConstant(0, N1.getValueType());
1827 return DAG.getSetCC(dl, VT, N0, Zero, Cond);
1831 if (N1.getOpcode() == ISD::AND)
1832 if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) {
1833 if (ValueHasExactlyOneBitSet(N0, DAG)) {
1834 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1835 if (DCI.isBeforeLegalizeOps() ||
1836 isCondCodeLegal(Cond, N1.getSimpleValueType())) {
1837 SDValue Zero = DAG.getConstant(0, N0.getValueType());
1838 return DAG.getSetCC(dl, VT, N1, Zero, Cond);
1844 // Fold away ALL boolean setcc's.
1846 if (N0.getValueType() == MVT::i1 && foldBooleans) {
1848 default: llvm_unreachable("Unknown integer setcc!");
1849 case ISD::SETEQ: // X == Y -> ~(X^Y)
1850 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
1851 N0 = DAG.getNOT(dl, Temp, MVT::i1);
1852 if (!DCI.isCalledByLegalizer())
1853 DCI.AddToWorklist(Temp.getNode());
1855 case ISD::SETNE: // X != Y --> (X^Y)
1856 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
1858 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y
1859 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y
1860 Temp = DAG.getNOT(dl, N0, MVT::i1);
1861 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
1862 if (!DCI.isCalledByLegalizer())
1863 DCI.AddToWorklist(Temp.getNode());
1865 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X
1866 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X
1867 Temp = DAG.getNOT(dl, N1, MVT::i1);
1868 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
1869 if (!DCI.isCalledByLegalizer())
1870 DCI.AddToWorklist(Temp.getNode());
1872 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
1873 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
1874 Temp = DAG.getNOT(dl, N0, MVT::i1);
1875 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
1876 if (!DCI.isCalledByLegalizer())
1877 DCI.AddToWorklist(Temp.getNode());
1879 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
1880 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
1881 Temp = DAG.getNOT(dl, N1, MVT::i1);
1882 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
1885 if (VT != MVT::i1) {
1886 if (!DCI.isCalledByLegalizer())
1887 DCI.AddToWorklist(N0.getNode());
1888 // FIXME: If running after legalize, we probably can't do this.
1889 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
1894 // Could not fold it.
1898 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
1899 /// node is a GlobalAddress + offset.
1900 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
1901 int64_t &Offset) const {
1902 if (isa<GlobalAddressSDNode>(N)) {
1903 GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N);
1904 GA = GASD->getGlobal();
1905 Offset += GASD->getOffset();
1909 if (N->getOpcode() == ISD::ADD) {
1910 SDValue N1 = N->getOperand(0);
1911 SDValue N2 = N->getOperand(1);
1912 if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
1913 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
1915 Offset += V->getSExtValue();
1918 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
1919 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
1921 Offset += V->getSExtValue();
1931 SDValue TargetLowering::
1932 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const {
1933 // Default implementation: no optimization.
1937 //===----------------------------------------------------------------------===//
1938 // Inline Assembler Implementation Methods
1939 //===----------------------------------------------------------------------===//
1942 TargetLowering::ConstraintType
1943 TargetLowering::getConstraintType(const std::string &Constraint) const {
1944 unsigned S = Constraint.size();
1947 switch (Constraint[0]) {
1949 case 'r': return C_RegisterClass;
1951 case 'o': // offsetable
1952 case 'V': // not offsetable
1954 case 'i': // Simple Integer or Relocatable Constant
1955 case 'n': // Simple Integer
1956 case 'E': // Floating Point Constant
1957 case 'F': // Floating Point Constant
1958 case 's': // Relocatable Constant
1959 case 'p': // Address.
1960 case 'X': // Allow ANY value.
1961 case 'I': // Target registers.
1975 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
1976 if (S == 8 && !Constraint.compare(1, 6, "memory", 6)) // "{memory}"
1983 /// LowerXConstraint - try to replace an X constraint, which matches anything,
1984 /// with another that has more specific requirements based on the type of the
1985 /// corresponding operand.
1986 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
1987 if (ConstraintVT.isInteger())
1989 if (ConstraintVT.isFloatingPoint())
1990 return "f"; // works for many targets
1994 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
1995 /// vector. If it is invalid, don't add anything to Ops.
1996 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
1997 std::string &Constraint,
1998 std::vector<SDValue> &Ops,
1999 SelectionDAG &DAG) const {
2001 if (Constraint.length() > 1) return;
2003 char ConstraintLetter = Constraint[0];
2004 switch (ConstraintLetter) {
2006 case 'X': // Allows any operand; labels (basic block) use this.
2007 if (Op.getOpcode() == ISD::BasicBlock) {
2012 case 'i': // Simple Integer or Relocatable Constant
2013 case 'n': // Simple Integer
2014 case 's': { // Relocatable Constant
2015 // These operands are interested in values of the form (GV+C), where C may
2016 // be folded in as an offset of GV, or it may be explicitly added. Also, it
2017 // is possible and fine if either GV or C are missing.
2018 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2019 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2021 // If we have "(add GV, C)", pull out GV/C
2022 if (Op.getOpcode() == ISD::ADD) {
2023 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2024 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2025 if (C == 0 || GA == 0) {
2026 C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2027 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2029 if (C == 0 || GA == 0)
2033 // If we find a valid operand, map to the TargetXXX version so that the
2034 // value itself doesn't get selected.
2035 if (GA) { // Either &GV or &GV+C
2036 if (ConstraintLetter != 'n') {
2037 int64_t Offs = GA->getOffset();
2038 if (C) Offs += C->getZExtValue();
2039 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2040 C ? SDLoc(C) : SDLoc(),
2041 Op.getValueType(), Offs));
2045 if (C) { // just C, no GV.
2046 // Simple constants are not allowed for 's'.
2047 if (ConstraintLetter != 's') {
2048 // gcc prints these as sign extended. Sign extend value to 64 bits
2049 // now; without this it would get ZExt'd later in
2050 // ScheduleDAGSDNodes::EmitNode, which is very generic.
2051 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2061 std::pair<unsigned, const TargetRegisterClass*> TargetLowering::
2062 getRegForInlineAsmConstraint(const std::string &Constraint,
2064 if (Constraint.empty() || Constraint[0] != '{')
2065 return std::make_pair(0u, static_cast<TargetRegisterClass*>(0));
2066 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2068 // Remove the braces from around the name.
2069 StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2071 std::pair<unsigned, const TargetRegisterClass*> R =
2072 std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2074 // Figure out which register class contains this reg.
2075 const TargetRegisterInfo *RI = getTargetMachine().getRegisterInfo();
2076 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(),
2077 E = RI->regclass_end(); RCI != E; ++RCI) {
2078 const TargetRegisterClass *RC = *RCI;
2080 // If none of the value types for this register class are valid, we
2081 // can't use it. For example, 64-bit reg classes on 32-bit targets.
2085 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2087 if (RegName.equals_lower(RI->getName(*I))) {
2088 std::pair<unsigned, const TargetRegisterClass*> S =
2089 std::make_pair(*I, RC);
2091 // If this register class has the requested value type, return it,
2092 // otherwise keep searching and return the first class found
2093 // if no other is found which explicitly has the requested type.
2094 if (RC->hasType(VT))
2105 //===----------------------------------------------------------------------===//
2106 // Constraint Selection.
2108 /// isMatchingInputConstraint - Return true of this is an input operand that is
2109 /// a matching constraint like "4".
2110 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2111 assert(!ConstraintCode.empty() && "No known constraint!");
2112 return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2115 /// getMatchedOperand - If this is an input matching constraint, this method
2116 /// returns the output operand it matches.
2117 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2118 assert(!ConstraintCode.empty() && "No known constraint!");
2119 return atoi(ConstraintCode.c_str());
2123 /// ParseConstraints - Split up the constraint string from the inline
2124 /// assembly value into the specific constraints and their prefixes,
2125 /// and also tie in the associated operand values.
2126 /// If this returns an empty vector, and if the constraint string itself
2127 /// isn't empty, there was an error parsing.
2128 TargetLowering::AsmOperandInfoVector TargetLowering::ParseConstraints(
2129 ImmutableCallSite CS) const {
2130 /// ConstraintOperands - Information about all of the constraints.
2131 AsmOperandInfoVector ConstraintOperands;
2132 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2133 unsigned maCount = 0; // Largest number of multiple alternative constraints.
2135 // Do a prepass over the constraints, canonicalizing them, and building up the
2136 // ConstraintOperands list.
2137 InlineAsm::ConstraintInfoVector
2138 ConstraintInfos = IA->ParseConstraints();
2140 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
2141 unsigned ResNo = 0; // ResNo - The result number of the next output.
2143 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
2144 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i]));
2145 AsmOperandInfo &OpInfo = ConstraintOperands.back();
2147 // Update multiple alternative constraint count.
2148 if (OpInfo.multipleAlternatives.size() > maCount)
2149 maCount = OpInfo.multipleAlternatives.size();
2151 OpInfo.ConstraintVT = MVT::Other;
2153 // Compute the value type for each operand.
2154 switch (OpInfo.Type) {
2155 case InlineAsm::isOutput:
2156 // Indirect outputs just consume an argument.
2157 if (OpInfo.isIndirect) {
2158 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2162 // The return value of the call is this value. As such, there is no
2163 // corresponding argument.
2164 assert(!CS.getType()->isVoidTy() &&
2166 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2167 OpInfo.ConstraintVT = getSimpleValueType(STy->getElementType(ResNo));
2169 assert(ResNo == 0 && "Asm only has one result!");
2170 OpInfo.ConstraintVT = getSimpleValueType(CS.getType());
2174 case InlineAsm::isInput:
2175 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2177 case InlineAsm::isClobber:
2182 if (OpInfo.CallOperandVal) {
2183 llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2184 if (OpInfo.isIndirect) {
2185 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2187 report_fatal_error("Indirect operand for inline asm not a pointer!");
2188 OpTy = PtrTy->getElementType();
2191 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2192 if (StructType *STy = dyn_cast<StructType>(OpTy))
2193 if (STy->getNumElements() == 1)
2194 OpTy = STy->getElementType(0);
2196 // If OpTy is not a single value, it may be a struct/union that we
2197 // can tile with integers.
2198 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2199 unsigned BitSize = getDataLayout()->getTypeSizeInBits(OpTy);
2208 OpInfo.ConstraintVT =
2209 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2212 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2214 = getDataLayout()->getPointerSizeInBits(PT->getAddressSpace());
2215 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
2217 OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2222 // If we have multiple alternative constraints, select the best alternative.
2223 if (ConstraintInfos.size()) {
2225 unsigned bestMAIndex = 0;
2226 int bestWeight = -1;
2227 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match.
2230 // Compute the sums of the weights for each alternative, keeping track
2231 // of the best (highest weight) one so far.
2232 for (maIndex = 0; maIndex < maCount; ++maIndex) {
2234 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2235 cIndex != eIndex; ++cIndex) {
2236 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2237 if (OpInfo.Type == InlineAsm::isClobber)
2240 // If this is an output operand with a matching input operand,
2241 // look up the matching input. If their types mismatch, e.g. one
2242 // is an integer, the other is floating point, or their sizes are
2243 // different, flag it as an maCantMatch.
2244 if (OpInfo.hasMatchingInput()) {
2245 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2246 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2247 if ((OpInfo.ConstraintVT.isInteger() !=
2248 Input.ConstraintVT.isInteger()) ||
2249 (OpInfo.ConstraintVT.getSizeInBits() !=
2250 Input.ConstraintVT.getSizeInBits())) {
2251 weightSum = -1; // Can't match.
2256 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2261 weightSum += weight;
2264 if (weightSum > bestWeight) {
2265 bestWeight = weightSum;
2266 bestMAIndex = maIndex;
2270 // Now select chosen alternative in each constraint.
2271 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2272 cIndex != eIndex; ++cIndex) {
2273 AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2274 if (cInfo.Type == InlineAsm::isClobber)
2276 cInfo.selectAlternative(bestMAIndex);
2281 // Check and hook up tied operands, choose constraint code to use.
2282 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2283 cIndex != eIndex; ++cIndex) {
2284 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2286 // If this is an output operand with a matching input operand, look up the
2287 // matching input. If their types mismatch, e.g. one is an integer, the
2288 // other is floating point, or their sizes are different, flag it as an
2290 if (OpInfo.hasMatchingInput()) {
2291 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2293 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2294 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
2295 getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
2296 OpInfo.ConstraintVT);
2297 std::pair<unsigned, const TargetRegisterClass*> InputRC =
2298 getRegForInlineAsmConstraint(Input.ConstraintCode,
2299 Input.ConstraintVT);
2300 if ((OpInfo.ConstraintVT.isInteger() !=
2301 Input.ConstraintVT.isInteger()) ||
2302 (MatchRC.second != InputRC.second)) {
2303 report_fatal_error("Unsupported asm: input constraint"
2304 " with a matching output constraint of"
2305 " incompatible type!");
2312 return ConstraintOperands;
2316 /// getConstraintGenerality - Return an integer indicating how general CT
2318 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2320 case TargetLowering::C_Other:
2321 case TargetLowering::C_Unknown:
2323 case TargetLowering::C_Register:
2325 case TargetLowering::C_RegisterClass:
2327 case TargetLowering::C_Memory:
2330 llvm_unreachable("Invalid constraint type");
2333 /// Examine constraint type and operand type and determine a weight value.
2334 /// This object must already have been set up with the operand type
2335 /// and the current alternative constraint selected.
2336 TargetLowering::ConstraintWeight
2337 TargetLowering::getMultipleConstraintMatchWeight(
2338 AsmOperandInfo &info, int maIndex) const {
2339 InlineAsm::ConstraintCodeVector *rCodes;
2340 if (maIndex >= (int)info.multipleAlternatives.size())
2341 rCodes = &info.Codes;
2343 rCodes = &info.multipleAlternatives[maIndex].Codes;
2344 ConstraintWeight BestWeight = CW_Invalid;
2346 // Loop over the options, keeping track of the most general one.
2347 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
2348 ConstraintWeight weight =
2349 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
2350 if (weight > BestWeight)
2351 BestWeight = weight;
2357 /// Examine constraint type and operand type and determine a weight value.
2358 /// This object must already have been set up with the operand type
2359 /// and the current alternative constraint selected.
2360 TargetLowering::ConstraintWeight
2361 TargetLowering::getSingleConstraintMatchWeight(
2362 AsmOperandInfo &info, const char *constraint) const {
2363 ConstraintWeight weight = CW_Invalid;
2364 Value *CallOperandVal = info.CallOperandVal;
2365 // If we don't have a value, we can't do a match,
2366 // but allow it at the lowest weight.
2367 if (CallOperandVal == NULL)
2369 // Look at the constraint type.
2370 switch (*constraint) {
2371 case 'i': // immediate integer.
2372 case 'n': // immediate integer with a known value.
2373 if (isa<ConstantInt>(CallOperandVal))
2374 weight = CW_Constant;
2376 case 's': // non-explicit intregal immediate.
2377 if (isa<GlobalValue>(CallOperandVal))
2378 weight = CW_Constant;
2380 case 'E': // immediate float if host format.
2381 case 'F': // immediate float.
2382 if (isa<ConstantFP>(CallOperandVal))
2383 weight = CW_Constant;
2385 case '<': // memory operand with autodecrement.
2386 case '>': // memory operand with autoincrement.
2387 case 'm': // memory operand.
2388 case 'o': // offsettable memory operand
2389 case 'V': // non-offsettable memory operand
2392 case 'r': // general register.
2393 case 'g': // general register, memory operand or immediate integer.
2394 // note: Clang converts "g" to "imr".
2395 if (CallOperandVal->getType()->isIntegerTy())
2396 weight = CW_Register;
2398 case 'X': // any operand.
2400 weight = CW_Default;
2406 /// ChooseConstraint - If there are multiple different constraints that we
2407 /// could pick for this operand (e.g. "imr") try to pick the 'best' one.
2408 /// This is somewhat tricky: constraints fall into four classes:
2409 /// Other -> immediates and magic values
2410 /// Register -> one specific register
2411 /// RegisterClass -> a group of regs
2412 /// Memory -> memory
2413 /// Ideally, we would pick the most specific constraint possible: if we have
2414 /// something that fits into a register, we would pick it. The problem here
2415 /// is that if we have something that could either be in a register or in
2416 /// memory that use of the register could cause selection of *other*
2417 /// operands to fail: they might only succeed if we pick memory. Because of
2418 /// this the heuristic we use is:
2420 /// 1) If there is an 'other' constraint, and if the operand is valid for
2421 /// that constraint, use it. This makes us take advantage of 'i'
2422 /// constraints when available.
2423 /// 2) Otherwise, pick the most general constraint present. This prefers
2424 /// 'm' over 'r', for example.
2426 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2427 const TargetLowering &TLI,
2428 SDValue Op, SelectionDAG *DAG) {
2429 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2430 unsigned BestIdx = 0;
2431 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2432 int BestGenerality = -1;
2434 // Loop over the options, keeping track of the most general one.
2435 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2436 TargetLowering::ConstraintType CType =
2437 TLI.getConstraintType(OpInfo.Codes[i]);
2439 // If this is an 'other' constraint, see if the operand is valid for it.
2440 // For example, on X86 we might have an 'rI' constraint. If the operand
2441 // is an integer in the range [0..31] we want to use I (saving a load
2442 // of a register), otherwise we must use 'r'.
2443 if (CType == TargetLowering::C_Other && Op.getNode()) {
2444 assert(OpInfo.Codes[i].size() == 1 &&
2445 "Unhandled multi-letter 'other' constraint");
2446 std::vector<SDValue> ResultOps;
2447 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
2449 if (!ResultOps.empty()) {
2456 // Things with matching constraints can only be registers, per gcc
2457 // documentation. This mainly affects "g" constraints.
2458 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2461 // This constraint letter is more general than the previous one, use it.
2462 int Generality = getConstraintGenerality(CType);
2463 if (Generality > BestGenerality) {
2466 BestGenerality = Generality;
2470 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2471 OpInfo.ConstraintType = BestType;
2474 /// ComputeConstraintToUse - Determines the constraint code and constraint
2475 /// type to use for the specific AsmOperandInfo, setting
2476 /// OpInfo.ConstraintCode and OpInfo.ConstraintType.
2477 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2479 SelectionDAG *DAG) const {
2480 assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2482 // Single-letter constraints ('r') are very common.
2483 if (OpInfo.Codes.size() == 1) {
2484 OpInfo.ConstraintCode = OpInfo.Codes[0];
2485 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2487 ChooseConstraint(OpInfo, *this, Op, DAG);
2490 // 'X' matches anything.
2491 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2492 // Labels and constants are handled elsewhere ('X' is the only thing
2493 // that matches labels). For Functions, the type here is the type of
2494 // the result, which is not what we want to look at; leave them alone.
2495 Value *v = OpInfo.CallOperandVal;
2496 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2497 OpInfo.CallOperandVal = v;
2501 // Otherwise, try to resolve it to something we know about by looking at
2502 // the actual operand type.
2503 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2504 OpInfo.ConstraintCode = Repl;
2505 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2510 /// \brief Given an exact SDIV by a constant, create a multiplication
2511 /// with the multiplicative inverse of the constant.
2512 SDValue TargetLowering::BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl,
2513 SelectionDAG &DAG) const {
2514 ConstantSDNode *C = cast<ConstantSDNode>(Op2);
2515 APInt d = C->getAPIntValue();
2516 assert(d != 0 && "Division by zero!");
2518 // Shift the value upfront if it is even, so the LSB is one.
2519 unsigned ShAmt = d.countTrailingZeros();
2521 // TODO: For UDIV use SRL instead of SRA.
2522 SDValue Amt = DAG.getConstant(ShAmt, getShiftAmountTy(Op1.getValueType()));
2523 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt);
2527 // Calculate the multiplicative inverse, using Newton's method.
2529 while ((t = d*xn) != 1)
2530 xn *= APInt(d.getBitWidth(), 2) - t;
2532 Op2 = DAG.getConstant(xn, Op1.getValueType());
2533 return DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2536 /// \brief Given an ISD::SDIV node expressing a divide by constant,
2537 /// return a DAG expression to select that will generate the same value by
2538 /// multiplying by a magic number. See:
2539 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2540 SDValue TargetLowering::
2541 BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2542 std::vector<SDNode*> *Created) const {
2543 EVT VT = N->getValueType(0);
2546 // Check to see if we can do this.
2547 // FIXME: We should be more aggressive here.
2548 if (!isTypeLegal(VT))
2551 APInt d = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
2552 APInt::ms magics = d.magic();
2554 // Multiply the numerator (operand 0) by the magic value
2555 // FIXME: We should support doing a MUL in a wider type
2557 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
2558 isOperationLegalOrCustom(ISD::MULHS, VT))
2559 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
2560 DAG.getConstant(magics.m, VT));
2561 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
2562 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
2563 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
2565 DAG.getConstant(magics.m, VT)).getNode(), 1);
2567 return SDValue(); // No mulhs or equvialent
2568 // If d > 0 and m < 0, add the numerator
2569 if (d.isStrictlyPositive() && magics.m.isNegative()) {
2570 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
2572 Created->push_back(Q.getNode());
2574 // If d < 0 and m > 0, subtract the numerator.
2575 if (d.isNegative() && magics.m.isStrictlyPositive()) {
2576 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
2578 Created->push_back(Q.getNode());
2580 // Shift right algebraic if shift value is nonzero
2582 Q = DAG.getNode(ISD::SRA, dl, VT, Q,
2583 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
2585 Created->push_back(Q.getNode());
2587 // Extract the sign bit and add it to the quotient
2589 DAG.getNode(ISD::SRL, dl, VT, Q, DAG.getConstant(VT.getSizeInBits()-1,
2590 getShiftAmountTy(Q.getValueType())));
2592 Created->push_back(T.getNode());
2593 return DAG.getNode(ISD::ADD, dl, VT, Q, T);
2596 /// \brief Given an ISD::UDIV node expressing a divide by constant,
2597 /// return a DAG expression to select that will generate the same value by
2598 /// multiplying by a magic number. See:
2599 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
2600 SDValue TargetLowering::
2601 BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization,
2602 std::vector<SDNode*> *Created) const {
2603 EVT VT = N->getValueType(0);
2606 // Check to see if we can do this.
2607 // FIXME: We should be more aggressive here.
2608 if (!isTypeLegal(VT))
2611 // FIXME: We should use a narrower constant when the upper
2612 // bits are known to be zero.
2613 const APInt &N1C = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
2614 APInt::mu magics = N1C.magicu();
2616 SDValue Q = N->getOperand(0);
2618 // If the divisor is even, we can avoid using the expensive fixup by shifting
2619 // the divided value upfront.
2620 if (magics.a != 0 && !N1C[0]) {
2621 unsigned Shift = N1C.countTrailingZeros();
2622 Q = DAG.getNode(ISD::SRL, dl, VT, Q,
2623 DAG.getConstant(Shift, getShiftAmountTy(Q.getValueType())));
2625 Created->push_back(Q.getNode());
2627 // Get magic number for the shifted divisor.
2628 magics = N1C.lshr(Shift).magicu(Shift);
2629 assert(magics.a == 0 && "Should use cheap fixup now");
2632 // Multiply the numerator (operand 0) by the magic value
2633 // FIXME: We should support doing a MUL in a wider type
2634 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
2635 isOperationLegalOrCustom(ISD::MULHU, VT))
2636 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT));
2637 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
2638 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
2639 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
2640 DAG.getConstant(magics.m, VT)).getNode(), 1);
2642 return SDValue(); // No mulhu or equvialent
2644 Created->push_back(Q.getNode());
2646 if (magics.a == 0) {
2647 assert(magics.s < N1C.getBitWidth() &&
2648 "We shouldn't generate an undefined shift!");
2649 return DAG.getNode(ISD::SRL, dl, VT, Q,
2650 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType())));
2652 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
2654 Created->push_back(NPQ.getNode());
2655 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ,
2656 DAG.getConstant(1, getShiftAmountTy(NPQ.getValueType())));
2658 Created->push_back(NPQ.getNode());
2659 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
2661 Created->push_back(NPQ.getNode());
2662 return DAG.getNode(ISD::SRL, dl, VT, NPQ,
2663 DAG.getConstant(magics.s-1, getShiftAmountTy(NPQ.getValueType())));