1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements the TargetLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 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/IR/LLVMContext.h" 26 #include "llvm/MC/MCAsmInfo.h" 27 #include "llvm/MC/MCExpr.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/MathExtras.h" 31 #include "llvm/Target/TargetLoweringObjectFile.h" 32 #include "llvm/Target/TargetMachine.h" 33 #include "llvm/Target/TargetRegisterInfo.h" 34 #include <cctype> 35 using namespace llvm; 36 37 /// NOTE: The constructor takes ownership of TLOF. 38 TargetLowering::TargetLowering(const TargetMachine &tm, 39 const TargetLoweringObjectFile *tlof) 40 : TargetLoweringBase(tm, tlof) {} 41 42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { 43 return NULL; 44 } 45 46 /// Check whether a given call node is in tail position within its function. If 47 /// so, it sets Chain to the input chain of the tail call. 48 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, 49 SDValue &Chain) const { 50 const Function *F = DAG.getMachineFunction().getFunction(); 51 52 // Conservatively require the attributes of the call to match those of 53 // the return. Ignore noalias because it doesn't affect the call sequence. 54 AttributeSet CallerAttrs = F->getAttributes(); 55 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex) 56 .removeAttribute(Attribute::NoAlias).hasAttributes()) 57 return false; 58 59 // It's not safe to eliminate the sign / zero extension of the return value. 60 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || 61 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) 62 return false; 63 64 // Check if the only use is a function return node. 65 return isUsedByReturnOnly(Node, Chain); 66 } 67 68 /// \brief Set CallLoweringInfo attribute flags based on a call instruction 69 /// and called function attributes. 70 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS, 71 unsigned AttrIdx) { 72 isSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt); 73 isZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt); 74 isInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg); 75 isSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet); 76 isNest = CS->paramHasAttr(AttrIdx, Attribute::Nest); 77 isByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal); 78 isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned); 79 Alignment = CS->getParamAlignment(AttrIdx); 80 } 81 82 /// Generate a libcall taking the given operands as arguments and returning a 83 /// result of type RetVT. 84 std::pair<SDValue, SDValue> 85 TargetLowering::makeLibCall(SelectionDAG &DAG, 86 RTLIB::Libcall LC, EVT RetVT, 87 const SDValue *Ops, unsigned NumOps, 88 bool isSigned, SDLoc dl, 89 bool doesNotReturn, 90 bool isReturnValueUsed) const { 91 TargetLowering::ArgListTy Args; 92 Args.reserve(NumOps); 93 94 TargetLowering::ArgListEntry Entry; 95 for (unsigned i = 0; i != NumOps; ++i) { 96 Entry.Node = Ops[i]; 97 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 98 Entry.isSExt = isSigned; 99 Entry.isZExt = !isSigned; 100 Args.push_back(Entry); 101 } 102 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), getPointerTy()); 103 104 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 105 TargetLowering:: 106 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false, 107 false, 0, getLibcallCallingConv(LC), 108 /*isTailCall=*/false, 109 doesNotReturn, isReturnValueUsed, Callee, Args, 110 DAG, dl); 111 return LowerCallTo(CLI); 112 } 113 114 115 /// SoftenSetCCOperands - Soften the operands of a comparison. This code is 116 /// shared among BR_CC, SELECT_CC, and SETCC handlers. 117 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 118 SDValue &NewLHS, SDValue &NewRHS, 119 ISD::CondCode &CCCode, 120 SDLoc dl) const { 121 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128) 122 && "Unsupported setcc type!"); 123 124 // Expand into one or more soft-fp libcall(s). 125 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 126 switch (CCCode) { 127 case ISD::SETEQ: 128 case ISD::SETOEQ: 129 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 130 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128; 131 break; 132 case ISD::SETNE: 133 case ISD::SETUNE: 134 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 135 (VT == MVT::f64) ? RTLIB::UNE_F64 : RTLIB::UNE_F128; 136 break; 137 case ISD::SETGE: 138 case ISD::SETOGE: 139 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 140 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128; 141 break; 142 case ISD::SETLT: 143 case ISD::SETOLT: 144 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 145 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128; 146 break; 147 case ISD::SETLE: 148 case ISD::SETOLE: 149 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 150 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128; 151 break; 152 case ISD::SETGT: 153 case ISD::SETOGT: 154 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 155 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128; 156 break; 157 case ISD::SETUO: 158 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 159 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128; 160 break; 161 case ISD::SETO: 162 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : 163 (VT == MVT::f64) ? RTLIB::O_F64 : RTLIB::O_F128; 164 break; 165 default: 166 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 167 (VT == MVT::f64) ? RTLIB::UO_F64 : RTLIB::UO_F128; 168 switch (CCCode) { 169 case ISD::SETONE: 170 // SETONE = SETOLT | SETOGT 171 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 172 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128; 173 // Fallthrough 174 case ISD::SETUGT: 175 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 176 (VT == MVT::f64) ? RTLIB::OGT_F64 : RTLIB::OGT_F128; 177 break; 178 case ISD::SETUGE: 179 LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 180 (VT == MVT::f64) ? RTLIB::OGE_F64 : RTLIB::OGE_F128; 181 break; 182 case ISD::SETULT: 183 LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 184 (VT == MVT::f64) ? RTLIB::OLT_F64 : RTLIB::OLT_F128; 185 break; 186 case ISD::SETULE: 187 LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 188 (VT == MVT::f64) ? RTLIB::OLE_F64 : RTLIB::OLE_F128; 189 break; 190 case ISD::SETUEQ: 191 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 192 (VT == MVT::f64) ? RTLIB::OEQ_F64 : RTLIB::OEQ_F128; 193 break; 194 default: llvm_unreachable("Do not know how to soften this setcc!"); 195 } 196 } 197 198 // Use the target specific return value for comparions lib calls. 199 EVT RetVT = getCmpLibcallReturnType(); 200 SDValue Ops[2] = { NewLHS, NewRHS }; 201 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, 2, false/*sign irrelevant*/, 202 dl).first; 203 NewRHS = DAG.getConstant(0, RetVT); 204 CCCode = getCmpLibcallCC(LC1); 205 if (LC2 != RTLIB::UNKNOWN_LIBCALL) { 206 SDValue Tmp = DAG.getNode(ISD::SETCC, dl, 207 getSetCCResultType(*DAG.getContext(), RetVT), 208 NewLHS, NewRHS, DAG.getCondCode(CCCode)); 209 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, 2, false/*sign irrelevant*/, 210 dl).first; 211 NewLHS = DAG.getNode(ISD::SETCC, dl, 212 getSetCCResultType(*DAG.getContext(), RetVT), NewLHS, 213 NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2))); 214 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS); 215 NewRHS = SDValue(); 216 } 217 } 218 219 /// getJumpTableEncoding - Return the entry encoding for a jump table in the 220 /// current function. The returned value is a member of the 221 /// MachineJumpTableInfo::JTEntryKind enum. 222 unsigned TargetLowering::getJumpTableEncoding() const { 223 // In non-pic modes, just use the address of a block. 224 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) 225 return MachineJumpTableInfo::EK_BlockAddress; 226 227 // In PIC mode, if the target supports a GPRel32 directive, use it. 228 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != 0) 229 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 230 231 // Otherwise, use a label difference. 232 return MachineJumpTableInfo::EK_LabelDifference32; 233 } 234 235 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 236 SelectionDAG &DAG) const { 237 // If our PIC model is GP relative, use the global offset table as the base. 238 unsigned JTEncoding = getJumpTableEncoding(); 239 240 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 241 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 242 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(0)); 243 244 return Table; 245 } 246 247 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the 248 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an 249 /// MCExpr. 250 const MCExpr * 251 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 252 unsigned JTI,MCContext &Ctx) const{ 253 // The normal PIC reloc base is the label at the start of the jump table. 254 return MCSymbolRefExpr::Create(MF->getJTISymbol(JTI, Ctx), Ctx); 255 } 256 257 bool 258 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 259 // Assume that everything is safe in static mode. 260 if (getTargetMachine().getRelocationModel() == Reloc::Static) 261 return true; 262 263 // In dynamic-no-pic mode, assume that known defined values are safe. 264 if (getTargetMachine().getRelocationModel() == Reloc::DynamicNoPIC && 265 GA && 266 !GA->getGlobal()->isDeclaration() && 267 !GA->getGlobal()->isWeakForLinker()) 268 return true; 269 270 // Otherwise assume nothing is safe. 271 return false; 272 } 273 274 //===----------------------------------------------------------------------===// 275 // Optimization Methods 276 //===----------------------------------------------------------------------===// 277 278 /// ShrinkDemandedConstant - Check to see if the specified operand of the 279 /// specified instruction is a constant integer. If so, check to see if there 280 /// are any bits set in the constant that are not demanded. If so, shrink the 281 /// constant and return true. 282 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(SDValue Op, 283 const APInt &Demanded) { 284 SDLoc dl(Op); 285 286 // FIXME: ISD::SELECT, ISD::SELECT_CC 287 switch (Op.getOpcode()) { 288 default: break; 289 case ISD::XOR: 290 case ISD::AND: 291 case ISD::OR: { 292 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 293 if (!C) return false; 294 295 if (Op.getOpcode() == ISD::XOR && 296 (C->getAPIntValue() | (~Demanded)).isAllOnesValue()) 297 return false; 298 299 // if we can expand it to have all bits set, do it 300 if (C->getAPIntValue().intersects(~Demanded)) { 301 EVT VT = Op.getValueType(); 302 SDValue New = DAG.getNode(Op.getOpcode(), dl, VT, Op.getOperand(0), 303 DAG.getConstant(Demanded & 304 C->getAPIntValue(), 305 VT)); 306 return CombineTo(Op, New); 307 } 308 309 break; 310 } 311 } 312 313 return false; 314 } 315 316 /// ShrinkDemandedOp - Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the 317 /// casts are free. This uses isZExtFree and ZERO_EXTEND for the widening 318 /// cast, but it could be generalized for targets with other types of 319 /// implicit widening casts. 320 bool 321 TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op, 322 unsigned BitWidth, 323 const APInt &Demanded, 324 SDLoc dl) { 325 assert(Op.getNumOperands() == 2 && 326 "ShrinkDemandedOp only supports binary operators!"); 327 assert(Op.getNode()->getNumValues() == 1 && 328 "ShrinkDemandedOp only supports nodes with one result!"); 329 330 // Don't do this if the node has another user, which may require the 331 // full value. 332 if (!Op.getNode()->hasOneUse()) 333 return false; 334 335 // Search for the smallest integer type with free casts to and from 336 // Op's type. For expedience, just check power-of-2 integer types. 337 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 338 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros(); 339 unsigned SmallVTBits = DemandedSize; 340 if (!isPowerOf2_32(SmallVTBits)) 341 SmallVTBits = NextPowerOf2(SmallVTBits); 342 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 343 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 344 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 345 TLI.isZExtFree(SmallVT, Op.getValueType())) { 346 // We found a type with free casts. 347 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT, 348 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, 349 Op.getNode()->getOperand(0)), 350 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, 351 Op.getNode()->getOperand(1))); 352 bool NeedZext = DemandedSize > SmallVTBits; 353 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, 354 dl, Op.getValueType(), X); 355 return CombineTo(Op, Z); 356 } 357 } 358 return false; 359 } 360 361 /// SimplifyDemandedBits - Look at Op. At this point, we know that only the 362 /// DemandedMask bits of the result of Op are ever used downstream. If we can 363 /// use this information to simplify Op, create a new simplified DAG node and 364 /// return true, returning the original and new nodes in Old and New. Otherwise, 365 /// analyze the expression and return a mask of KnownOne and KnownZero bits for 366 /// the expression (used to simplify the caller). The KnownZero/One bits may 367 /// only be accurate for those bits in the DemandedMask. 368 bool TargetLowering::SimplifyDemandedBits(SDValue Op, 369 const APInt &DemandedMask, 370 APInt &KnownZero, 371 APInt &KnownOne, 372 TargetLoweringOpt &TLO, 373 unsigned Depth) const { 374 unsigned BitWidth = DemandedMask.getBitWidth(); 375 assert(Op.getValueType().getScalarType().getSizeInBits() == BitWidth && 376 "Mask size mismatches value type size!"); 377 APInt NewMask = DemandedMask; 378 SDLoc dl(Op); 379 380 // Don't know anything. 381 KnownZero = KnownOne = APInt(BitWidth, 0); 382 383 // Other users may use these bits. 384 if (!Op.getNode()->hasOneUse()) { 385 if (Depth != 0) { 386 // If not at the root, Just compute the KnownZero/KnownOne bits to 387 // simplify things downstream. 388 TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth); 389 return false; 390 } 391 // If this is the root being simplified, allow it to have multiple uses, 392 // just set the NewMask to all bits. 393 NewMask = APInt::getAllOnesValue(BitWidth); 394 } else if (DemandedMask == 0) { 395 // Not demanding any bits from Op. 396 if (Op.getOpcode() != ISD::UNDEF) 397 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType())); 398 return false; 399 } else if (Depth == 6) { // Limit search depth. 400 return false; 401 } 402 403 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut; 404 switch (Op.getOpcode()) { 405 case ISD::Constant: 406 // We know all of the bits for a constant! 407 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue(); 408 KnownZero = ~KnownOne; 409 return false; // Don't fall through, will infinitely loop. 410 case ISD::AND: 411 // If the RHS is a constant, check to see if the LHS would be zero without 412 // using the bits from the RHS. Below, we use knowledge about the RHS to 413 // simplify the LHS, here we're using information from the LHS to simplify 414 // the RHS. 415 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 416 APInt LHSZero, LHSOne; 417 // Do not increment Depth here; that can cause an infinite loop. 418 TLO.DAG.ComputeMaskedBits(Op.getOperand(0), LHSZero, LHSOne, Depth); 419 // If the LHS already has zeros where RHSC does, this and is dead. 420 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask)) 421 return TLO.CombineTo(Op, Op.getOperand(0)); 422 // If any of the set bits in the RHS are known zero on the LHS, shrink 423 // the constant. 424 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask)) 425 return true; 426 } 427 428 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 429 KnownOne, TLO, Depth+1)) 430 return true; 431 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 432 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask, 433 KnownZero2, KnownOne2, TLO, Depth+1)) 434 return true; 435 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 436 437 // If all of the demanded bits are known one on one side, return the other. 438 // These bits cannot contribute to the result of the 'and'. 439 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask)) 440 return TLO.CombineTo(Op, Op.getOperand(0)); 441 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask)) 442 return TLO.CombineTo(Op, Op.getOperand(1)); 443 // If all of the demanded bits in the inputs are known zeros, return zero. 444 if ((NewMask & (KnownZero|KnownZero2)) == NewMask) 445 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, Op.getValueType())); 446 // If the RHS is a constant, see if we can simplify it. 447 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask)) 448 return true; 449 // If the operation can be done in a smaller type, do so. 450 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 451 return true; 452 453 // Output known-1 bits are only known if set in both the LHS & RHS. 454 KnownOne &= KnownOne2; 455 // Output known-0 are known to be clear if zero in either the LHS | RHS. 456 KnownZero |= KnownZero2; 457 break; 458 case ISD::OR: 459 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 460 KnownOne, TLO, Depth+1)) 461 return true; 462 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 463 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask, 464 KnownZero2, KnownOne2, TLO, Depth+1)) 465 return true; 466 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 467 468 // If all of the demanded bits are known zero on one side, return the other. 469 // These bits cannot contribute to the result of the 'or'. 470 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask)) 471 return TLO.CombineTo(Op, Op.getOperand(0)); 472 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask)) 473 return TLO.CombineTo(Op, Op.getOperand(1)); 474 // If all of the potentially set bits on one side are known to be set on 475 // the other side, just use the 'other' side. 476 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask)) 477 return TLO.CombineTo(Op, Op.getOperand(0)); 478 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask)) 479 return TLO.CombineTo(Op, Op.getOperand(1)); 480 // If the RHS is a constant, see if we can simplify it. 481 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 482 return true; 483 // If the operation can be done in a smaller type, do so. 484 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 485 return true; 486 487 // Output known-0 bits are only known if clear in both the LHS & RHS. 488 KnownZero &= KnownZero2; 489 // Output known-1 are known to be set if set in either the LHS | RHS. 490 KnownOne |= KnownOne2; 491 break; 492 case ISD::XOR: 493 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 494 KnownOne, TLO, Depth+1)) 495 return true; 496 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 497 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2, 498 KnownOne2, TLO, Depth+1)) 499 return true; 500 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 501 502 // If all of the demanded bits are known zero on one side, return the other. 503 // These bits cannot contribute to the result of the 'xor'. 504 if ((KnownZero & NewMask) == NewMask) 505 return TLO.CombineTo(Op, Op.getOperand(0)); 506 if ((KnownZero2 & NewMask) == NewMask) 507 return TLO.CombineTo(Op, Op.getOperand(1)); 508 // If the operation can be done in a smaller type, do so. 509 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 510 return true; 511 512 // If all of the unknown bits are known to be zero on one side or the other 513 // (but not both) turn this into an *inclusive* or. 514 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 515 if ((NewMask & ~KnownZero & ~KnownZero2) == 0) 516 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(), 517 Op.getOperand(0), 518 Op.getOperand(1))); 519 520 // Output known-0 bits are known if clear or set in both the LHS & RHS. 521 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 522 // Output known-1 are known to be set if set in only one of the LHS, RHS. 523 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 524 525 // If all of the demanded bits on one side are known, and all of the set 526 // bits on that side are also known to be set on the other side, turn this 527 // into an AND, as we know the bits will be cleared. 528 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 529 // NB: it is okay if more bits are known than are requested 530 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side 531 if (KnownOne == KnownOne2) { // set bits are the same on both sides 532 EVT VT = Op.getValueType(); 533 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, VT); 534 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, 535 Op.getOperand(0), ANDC)); 536 } 537 } 538 539 // If the RHS is a constant, see if we can simplify it. 540 // for XOR, we prefer to force bits to 1 if they will make a -1. 541 // if we can't force bits, try to shrink constant 542 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 543 APInt Expanded = C->getAPIntValue() | (~NewMask); 544 // if we can expand it to have all bits set, do it 545 if (Expanded.isAllOnesValue()) { 546 if (Expanded != C->getAPIntValue()) { 547 EVT VT = Op.getValueType(); 548 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0), 549 TLO.DAG.getConstant(Expanded, VT)); 550 return TLO.CombineTo(Op, New); 551 } 552 // if it already has all the bits set, nothing to change 553 // but don't shrink either! 554 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) { 555 return true; 556 } 557 } 558 559 KnownZero = KnownZeroOut; 560 KnownOne = KnownOneOut; 561 break; 562 case ISD::SELECT: 563 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero, 564 KnownOne, TLO, Depth+1)) 565 return true; 566 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2, 567 KnownOne2, TLO, Depth+1)) 568 return true; 569 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 570 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 571 572 // If the operands are constants, see if we can simplify them. 573 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 574 return true; 575 576 // Only known if known in both the LHS and RHS. 577 KnownOne &= KnownOne2; 578 KnownZero &= KnownZero2; 579 break; 580 case ISD::SELECT_CC: 581 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero, 582 KnownOne, TLO, Depth+1)) 583 return true; 584 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2, 585 KnownOne2, TLO, Depth+1)) 586 return true; 587 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 588 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 589 590 // If the operands are constants, see if we can simplify them. 591 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 592 return true; 593 594 // Only known if known in both the LHS and RHS. 595 KnownOne &= KnownOne2; 596 KnownZero &= KnownZero2; 597 break; 598 case ISD::SHL: 599 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 600 unsigned ShAmt = SA->getZExtValue(); 601 SDValue InOp = Op.getOperand(0); 602 603 // If the shift count is an invalid immediate, don't do anything. 604 if (ShAmt >= BitWidth) 605 break; 606 607 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 608 // single shift. We can do this if the bottom bits (which are shifted 609 // out) are never demanded. 610 if (InOp.getOpcode() == ISD::SRL && 611 isa<ConstantSDNode>(InOp.getOperand(1))) { 612 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) { 613 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue(); 614 unsigned Opc = ISD::SHL; 615 int Diff = ShAmt-C1; 616 if (Diff < 0) { 617 Diff = -Diff; 618 Opc = ISD::SRL; 619 } 620 621 SDValue NewSA = 622 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType()); 623 EVT VT = Op.getValueType(); 624 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, 625 InOp.getOperand(0), NewSA)); 626 } 627 } 628 629 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt), 630 KnownZero, KnownOne, TLO, Depth+1)) 631 return true; 632 633 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 634 // are not demanded. This will likely allow the anyext to be folded away. 635 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) { 636 SDValue InnerOp = InOp.getNode()->getOperand(0); 637 EVT InnerVT = InnerOp.getValueType(); 638 unsigned InnerBits = InnerVT.getSizeInBits(); 639 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 && 640 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 641 EVT ShTy = getShiftAmountTy(InnerVT); 642 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 643 ShTy = InnerVT; 644 SDValue NarrowShl = 645 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 646 TLO.DAG.getConstant(ShAmt, ShTy)); 647 return 648 TLO.CombineTo(Op, 649 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), 650 NarrowShl)); 651 } 652 // Repeat the SHL optimization above in cases where an extension 653 // intervenes: (shl (anyext (shr x, c1)), c2) to 654 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 655 // aren't demanded (as above) and that the shifted upper c1 bits of 656 // x aren't demanded. 657 if (InOp.hasOneUse() && 658 InnerOp.getOpcode() == ISD::SRL && 659 InnerOp.hasOneUse() && 660 isa<ConstantSDNode>(InnerOp.getOperand(1))) { 661 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1)) 662 ->getZExtValue(); 663 if (InnerShAmt < ShAmt && 664 InnerShAmt < InnerBits && 665 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 && 666 NewMask.trunc(ShAmt) == 0) { 667 SDValue NewSA = 668 TLO.DAG.getConstant(ShAmt - InnerShAmt, 669 Op.getOperand(1).getValueType()); 670 EVT VT = Op.getValueType(); 671 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 672 InnerOp.getOperand(0)); 673 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, 674 NewExt, NewSA)); 675 } 676 } 677 } 678 679 KnownZero <<= SA->getZExtValue(); 680 KnownOne <<= SA->getZExtValue(); 681 // low bits known zero. 682 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue()); 683 } 684 break; 685 case ISD::SRL: 686 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 687 EVT VT = Op.getValueType(); 688 unsigned ShAmt = SA->getZExtValue(); 689 unsigned VTSize = VT.getSizeInBits(); 690 SDValue InOp = Op.getOperand(0); 691 692 // If the shift count is an invalid immediate, don't do anything. 693 if (ShAmt >= BitWidth) 694 break; 695 696 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 697 // single shift. We can do this if the top bits (which are shifted out) 698 // are never demanded. 699 if (InOp.getOpcode() == ISD::SHL && 700 isa<ConstantSDNode>(InOp.getOperand(1))) { 701 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) { 702 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue(); 703 unsigned Opc = ISD::SRL; 704 int Diff = ShAmt-C1; 705 if (Diff < 0) { 706 Diff = -Diff; 707 Opc = ISD::SHL; 708 } 709 710 SDValue NewSA = 711 TLO.DAG.getConstant(Diff, Op.getOperand(1).getValueType()); 712 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, 713 InOp.getOperand(0), NewSA)); 714 } 715 } 716 717 // Compute the new bits that are at the top now. 718 if (SimplifyDemandedBits(InOp, (NewMask << ShAmt), 719 KnownZero, KnownOne, TLO, Depth+1)) 720 return true; 721 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 722 KnownZero = KnownZero.lshr(ShAmt); 723 KnownOne = KnownOne.lshr(ShAmt); 724 725 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 726 KnownZero |= HighBits; // High bits known zero. 727 } 728 break; 729 case ISD::SRA: 730 // If this is an arithmetic shift right and only the low-bit is set, we can 731 // always convert this into a logical shr, even if the shift amount is 732 // variable. The low bit of the shift cannot be an input sign bit unless 733 // the shift amount is >= the size of the datatype, which is undefined. 734 if (NewMask == 1) 735 return TLO.CombineTo(Op, 736 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(), 737 Op.getOperand(0), Op.getOperand(1))); 738 739 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 740 EVT VT = Op.getValueType(); 741 unsigned ShAmt = SA->getZExtValue(); 742 743 // If the shift count is an invalid immediate, don't do anything. 744 if (ShAmt >= BitWidth) 745 break; 746 747 APInt InDemandedMask = (NewMask << ShAmt); 748 749 // If any of the demanded bits are produced by the sign extension, we also 750 // demand the input sign bit. 751 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 752 if (HighBits.intersects(NewMask)) 753 InDemandedMask |= APInt::getSignBit(VT.getScalarType().getSizeInBits()); 754 755 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask, 756 KnownZero, KnownOne, TLO, Depth+1)) 757 return true; 758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 759 KnownZero = KnownZero.lshr(ShAmt); 760 KnownOne = KnownOne.lshr(ShAmt); 761 762 // Handle the sign bit, adjusted to where it is now in the mask. 763 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt); 764 765 // If the input sign bit is known to be zero, or if none of the top bits 766 // are demanded, turn this into an unsigned shift right. 767 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) 768 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, 769 Op.getOperand(0), 770 Op.getOperand(1))); 771 772 int Log2 = NewMask.exactLogBase2(); 773 if (Log2 >= 0) { 774 // The bit must come from the sign. 775 SDValue NewSA = 776 TLO.DAG.getConstant(BitWidth - 1 - Log2, 777 Op.getOperand(1).getValueType()); 778 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, 779 Op.getOperand(0), NewSA)); 780 } 781 782 if (KnownOne.intersects(SignBit)) 783 // New bits are known one. 784 KnownOne |= HighBits; 785 } 786 break; 787 case ISD::SIGN_EXTEND_INREG: { 788 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 789 790 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1); 791 // If we only care about the highest bit, don't bother shifting right. 792 if (MsbMask == DemandedMask) { 793 unsigned ShAmt = ExVT.getScalarType().getSizeInBits(); 794 SDValue InOp = Op.getOperand(0); 795 796 // Compute the correct shift amount type, which must be getShiftAmountTy 797 // for scalar types after legalization. 798 EVT ShiftAmtTy = Op.getValueType(); 799 if (TLO.LegalTypes() && !ShiftAmtTy.isVector()) 800 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy); 801 802 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, ShiftAmtTy); 803 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, 804 Op.getValueType(), InOp, ShiftAmt)); 805 } 806 807 // Sign extension. Compute the demanded bits in the result that are not 808 // present in the input. 809 APInt NewBits = 810 APInt::getHighBitsSet(BitWidth, 811 BitWidth - ExVT.getScalarType().getSizeInBits()); 812 813 // If none of the extended bits are demanded, eliminate the sextinreg. 814 if ((NewBits & NewMask) == 0) 815 return TLO.CombineTo(Op, Op.getOperand(0)); 816 817 APInt InSignBit = 818 APInt::getSignBit(ExVT.getScalarType().getSizeInBits()).zext(BitWidth); 819 APInt InputDemandedBits = 820 APInt::getLowBitsSet(BitWidth, 821 ExVT.getScalarType().getSizeInBits()) & 822 NewMask; 823 824 // Since the sign extended bits are demanded, we know that the sign 825 // bit is demanded. 826 InputDemandedBits |= InSignBit; 827 828 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits, 829 KnownZero, KnownOne, TLO, Depth+1)) 830 return true; 831 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 832 833 // If the sign bit of the input is known set or clear, then we know the 834 // top bits of the result. 835 836 // If the input sign bit is known zero, convert this into a zero extension. 837 if (KnownZero.intersects(InSignBit)) 838 return TLO.CombineTo(Op, 839 TLO.DAG.getZeroExtendInReg(Op.getOperand(0),dl,ExVT)); 840 841 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 842 KnownOne |= NewBits; 843 KnownZero &= ~NewBits; 844 } else { // Input sign bit unknown 845 KnownZero &= ~NewBits; 846 KnownOne &= ~NewBits; 847 } 848 break; 849 } 850 case ISD::ZERO_EXTEND: { 851 unsigned OperandBitWidth = 852 Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 853 APInt InMask = NewMask.trunc(OperandBitWidth); 854 855 // If none of the top bits are demanded, convert this into an any_extend. 856 APInt NewBits = 857 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask; 858 if (!NewBits.intersects(NewMask)) 859 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, 860 Op.getValueType(), 861 Op.getOperand(0))); 862 863 if (SimplifyDemandedBits(Op.getOperand(0), InMask, 864 KnownZero, KnownOne, TLO, Depth+1)) 865 return true; 866 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 867 KnownZero = KnownZero.zext(BitWidth); 868 KnownOne = KnownOne.zext(BitWidth); 869 KnownZero |= NewBits; 870 break; 871 } 872 case ISD::SIGN_EXTEND: { 873 EVT InVT = Op.getOperand(0).getValueType(); 874 unsigned InBits = InVT.getScalarType().getSizeInBits(); 875 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits); 876 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits); 877 APInt NewBits = ~InMask & NewMask; 878 879 // If none of the top bits are demanded, convert this into an any_extend. 880 if (NewBits == 0) 881 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl, 882 Op.getValueType(), 883 Op.getOperand(0))); 884 885 // Since some of the sign extended bits are demanded, we know that the sign 886 // bit is demanded. 887 APInt InDemandedBits = InMask & NewMask; 888 InDemandedBits |= InSignBit; 889 InDemandedBits = InDemandedBits.trunc(InBits); 890 891 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero, 892 KnownOne, TLO, Depth+1)) 893 return true; 894 KnownZero = KnownZero.zext(BitWidth); 895 KnownOne = KnownOne.zext(BitWidth); 896 897 // If the sign bit is known zero, convert this to a zero extend. 898 if (KnownZero.intersects(InSignBit)) 899 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, 900 Op.getValueType(), 901 Op.getOperand(0))); 902 903 // If the sign bit is known one, the top bits match. 904 if (KnownOne.intersects(InSignBit)) { 905 KnownOne |= NewBits; 906 assert((KnownZero & NewBits) == 0); 907 } else { // Otherwise, top bits aren't known. 908 assert((KnownOne & NewBits) == 0); 909 assert((KnownZero & NewBits) == 0); 910 } 911 break; 912 } 913 case ISD::ANY_EXTEND: { 914 unsigned OperandBitWidth = 915 Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 916 APInt InMask = NewMask.trunc(OperandBitWidth); 917 if (SimplifyDemandedBits(Op.getOperand(0), InMask, 918 KnownZero, KnownOne, TLO, Depth+1)) 919 return true; 920 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 921 KnownZero = KnownZero.zext(BitWidth); 922 KnownOne = KnownOne.zext(BitWidth); 923 break; 924 } 925 case ISD::TRUNCATE: { 926 // Simplify the input, using demanded bit information, and compute the known 927 // zero/one bits live out. 928 unsigned OperandBitWidth = 929 Op.getOperand(0).getValueType().getScalarType().getSizeInBits(); 930 APInt TruncMask = NewMask.zext(OperandBitWidth); 931 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask, 932 KnownZero, KnownOne, TLO, Depth+1)) 933 return true; 934 KnownZero = KnownZero.trunc(BitWidth); 935 KnownOne = KnownOne.trunc(BitWidth); 936 937 // If the input is only used by this truncate, see if we can shrink it based 938 // on the known demanded bits. 939 if (Op.getOperand(0).getNode()->hasOneUse()) { 940 SDValue In = Op.getOperand(0); 941 switch (In.getOpcode()) { 942 default: break; 943 case ISD::SRL: 944 // Shrink SRL by a constant if none of the high bits shifted in are 945 // demanded. 946 if (TLO.LegalTypes() && 947 !isTypeDesirableForOp(ISD::SRL, Op.getValueType())) 948 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 949 // undesirable. 950 break; 951 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1)); 952 if (!ShAmt) 953 break; 954 SDValue Shift = In.getOperand(1); 955 if (TLO.LegalTypes()) { 956 uint64_t ShVal = ShAmt->getZExtValue(); 957 Shift = 958 TLO.DAG.getConstant(ShVal, getShiftAmountTy(Op.getValueType())); 959 } 960 961 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth, 962 OperandBitWidth - BitWidth); 963 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth); 964 965 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) { 966 // None of the shifted in bits are needed. Add a truncate of the 967 // shift input, then shift it. 968 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl, 969 Op.getValueType(), 970 In.getOperand(0)); 971 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, 972 Op.getValueType(), 973 NewTrunc, 974 Shift)); 975 } 976 break; 977 } 978 } 979 980 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 981 break; 982 } 983 case ISD::AssertZext: { 984 // AssertZext demands all of the high bits, plus any of the low bits 985 // demanded by its users. 986 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 987 APInt InMask = APInt::getLowBitsSet(BitWidth, 988 VT.getSizeInBits()); 989 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask, 990 KnownZero, KnownOne, TLO, Depth+1)) 991 return true; 992 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 993 994 KnownZero |= ~InMask & NewMask; 995 break; 996 } 997 case ISD::BITCAST: 998 // If this is an FP->Int bitcast and if the sign bit is the only 999 // thing demanded, turn this into a FGETSIGN. 1000 if (!TLO.LegalOperations() && 1001 !Op.getValueType().isVector() && 1002 !Op.getOperand(0).getValueType().isVector() && 1003 NewMask == APInt::getSignBit(Op.getValueType().getSizeInBits()) && 1004 Op.getOperand(0).getValueType().isFloatingPoint()) { 1005 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType()); 1006 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 1007 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple()) { 1008 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32; 1009 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 1010 // place. We expect the SHL to be eliminated by other optimizations. 1011 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0)); 1012 unsigned OpVTSizeInBits = Op.getValueType().getSizeInBits(); 1013 if (!OpVTLegal && OpVTSizeInBits > 32) 1014 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign); 1015 unsigned ShVal = Op.getValueType().getSizeInBits()-1; 1016 SDValue ShAmt = TLO.DAG.getConstant(ShVal, Op.getValueType()); 1017 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, 1018 Op.getValueType(), 1019 Sign, ShAmt)); 1020 } 1021 } 1022 break; 1023 case ISD::ADD: 1024 case ISD::MUL: 1025 case ISD::SUB: { 1026 // Add, Sub, and Mul don't demand any bits in positions beyond that 1027 // of the highest bit demanded of them. 1028 APInt LoMask = APInt::getLowBitsSet(BitWidth, 1029 BitWidth - NewMask.countLeadingZeros()); 1030 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2, 1031 KnownOne2, TLO, Depth+1)) 1032 return true; 1033 if (SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2, 1034 KnownOne2, TLO, Depth+1)) 1035 return true; 1036 // See if the operation should be performed at a smaller bit width. 1037 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 1038 return true; 1039 } 1040 // FALL THROUGH 1041 default: 1042 // Just use ComputeMaskedBits to compute output bits. 1043 TLO.DAG.ComputeMaskedBits(Op, KnownZero, KnownOne, Depth); 1044 break; 1045 } 1046 1047 // If we know the value of all of the demanded bits, return this as a 1048 // constant. 1049 if ((NewMask & (KnownZero|KnownOne)) == NewMask) 1050 return TLO.CombineTo(Op, TLO.DAG.getConstant(KnownOne, Op.getValueType())); 1051 1052 return false; 1053 } 1054 1055 /// computeMaskedBitsForTargetNode - Determine which of the bits specified 1056 /// in Mask are known to be either zero or one and return them in the 1057 /// KnownZero/KnownOne bitsets. 1058 void TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op, 1059 APInt &KnownZero, 1060 APInt &KnownOne, 1061 const SelectionDAG &DAG, 1062 unsigned Depth) const { 1063 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1064 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1065 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1066 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1067 "Should use MaskedValueIsZero if you don't know whether Op" 1068 " is a target node!"); 1069 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); 1070 } 1071 1072 /// ComputeNumSignBitsForTargetNode - This method can be implemented by 1073 /// targets that want to expose additional information about sign bits to the 1074 /// DAG Combiner. 1075 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 1076 unsigned Depth) const { 1077 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1078 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1079 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1080 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1081 "Should use ComputeNumSignBits if you don't know whether Op" 1082 " is a target node!"); 1083 return 1; 1084 } 1085 1086 /// ValueHasExactlyOneBitSet - Test if the given value is known to have exactly 1087 /// one bit set. This differs from ComputeMaskedBits in that it doesn't need to 1088 /// determine which bit is set. 1089 /// 1090 static bool ValueHasExactlyOneBitSet(SDValue Val, const SelectionDAG &DAG) { 1091 // A left-shift of a constant one will have exactly one bit set, because 1092 // shifting the bit off the end is undefined. 1093 if (Val.getOpcode() == ISD::SHL) 1094 if (ConstantSDNode *C = 1095 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0))) 1096 if (C->getAPIntValue() == 1) 1097 return true; 1098 1099 // Similarly, a right-shift of a constant sign-bit will have exactly 1100 // one bit set. 1101 if (Val.getOpcode() == ISD::SRL) 1102 if (ConstantSDNode *C = 1103 dyn_cast<ConstantSDNode>(Val.getNode()->getOperand(0))) 1104 if (C->getAPIntValue().isSignBit()) 1105 return true; 1106 1107 // More could be done here, though the above checks are enough 1108 // to handle some common cases. 1109 1110 // Fall back to ComputeMaskedBits to catch other known cases. 1111 EVT OpVT = Val.getValueType(); 1112 unsigned BitWidth = OpVT.getScalarType().getSizeInBits(); 1113 APInt KnownZero, KnownOne; 1114 DAG.ComputeMaskedBits(Val, KnownZero, KnownOne); 1115 return (KnownZero.countPopulation() == BitWidth - 1) && 1116 (KnownOne.countPopulation() == 1); 1117 } 1118 1119 /// SimplifySetCC - Try to simplify a setcc built with the specified operands 1120 /// and cc. If it is unable to simplify it, return a null SDValue. 1121 SDValue 1122 TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 1123 ISD::CondCode Cond, bool foldBooleans, 1124 DAGCombinerInfo &DCI, SDLoc dl) const { 1125 SelectionDAG &DAG = DCI.DAG; 1126 1127 // These setcc operations always fold. 1128 switch (Cond) { 1129 default: break; 1130 case ISD::SETFALSE: 1131 case ISD::SETFALSE2: return DAG.getConstant(0, VT); 1132 case ISD::SETTRUE: 1133 case ISD::SETTRUE2: { 1134 TargetLowering::BooleanContent Cnt = getBooleanContents(VT.isVector()); 1135 return DAG.getConstant( 1136 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, VT); 1137 } 1138 } 1139 1140 // Ensure that the constant occurs on the RHS, and fold constant 1141 // comparisons. 1142 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 1143 if (isa<ConstantSDNode>(N0.getNode()) && 1144 (DCI.isBeforeLegalizeOps() || 1145 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 1146 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 1147 1148 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 1149 const APInt &C1 = N1C->getAPIntValue(); 1150 1151 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 1152 // equality comparison, then we're just comparing whether X itself is 1153 // zero. 1154 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) && 1155 N0.getOperand(0).getOpcode() == ISD::CTLZ && 1156 N0.getOperand(1).getOpcode() == ISD::Constant) { 1157 const APInt &ShAmt 1158 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1159 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1160 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) { 1161 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 1162 // (srl (ctlz x), 5) == 0 -> X != 0 1163 // (srl (ctlz x), 5) != 1 -> X != 0 1164 Cond = ISD::SETNE; 1165 } else { 1166 // (srl (ctlz x), 5) != 0 -> X == 0 1167 // (srl (ctlz x), 5) == 1 -> X == 0 1168 Cond = ISD::SETEQ; 1169 } 1170 SDValue Zero = DAG.getConstant(0, N0.getValueType()); 1171 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), 1172 Zero, Cond); 1173 } 1174 } 1175 1176 SDValue CTPOP = N0; 1177 // Look through truncs that don't change the value of a ctpop. 1178 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE) 1179 CTPOP = N0.getOperand(0); 1180 1181 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP && 1182 (N0 == CTPOP || N0.getValueType().getSizeInBits() > 1183 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) { 1184 EVT CTVT = CTPOP.getValueType(); 1185 SDValue CTOp = CTPOP.getOperand(0); 1186 1187 // (ctpop x) u< 2 -> (x & x-1) == 0 1188 // (ctpop x) u> 1 -> (x & x-1) != 0 1189 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){ 1190 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp, 1191 DAG.getConstant(1, CTVT)); 1192 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub); 1193 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 1194 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, CTVT), CC); 1195 } 1196 1197 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal. 1198 } 1199 1200 // (zext x) == C --> x == (trunc C) 1201 if (DCI.isBeforeLegalize() && N0->hasOneUse() && 1202 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1203 unsigned MinBits = N0.getValueSizeInBits(); 1204 SDValue PreZExt; 1205 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 1206 // ZExt 1207 MinBits = N0->getOperand(0).getValueSizeInBits(); 1208 PreZExt = N0->getOperand(0); 1209 } else if (N0->getOpcode() == ISD::AND) { 1210 // DAGCombine turns costly ZExts into ANDs 1211 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 1212 if ((C->getAPIntValue()+1).isPowerOf2()) { 1213 MinBits = C->getAPIntValue().countTrailingOnes(); 1214 PreZExt = N0->getOperand(0); 1215 } 1216 } else if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(N0)) { 1217 // ZEXTLOAD 1218 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 1219 MinBits = LN0->getMemoryVT().getSizeInBits(); 1220 PreZExt = N0; 1221 } 1222 } 1223 1224 // Make sure we're not losing bits from the constant. 1225 if (MinBits > 0 && 1226 MinBits < C1.getBitWidth() && MinBits >= C1.getActiveBits()) { 1227 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 1228 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 1229 // Will get folded away. 1230 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreZExt); 1231 SDValue C = DAG.getConstant(C1.trunc(MinBits), MinVT); 1232 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 1233 } 1234 } 1235 } 1236 1237 // If the LHS is '(and load, const)', the RHS is 0, 1238 // the test is for equality or unsigned, and all 1 bits of the const are 1239 // in the same partial word, see if we can shorten the load. 1240 if (DCI.isBeforeLegalize() && 1241 !ISD::isSignedIntSetCC(Cond) && 1242 N0.getOpcode() == ISD::AND && C1 == 0 && 1243 N0.getNode()->hasOneUse() && 1244 isa<LoadSDNode>(N0.getOperand(0)) && 1245 N0.getOperand(0).getNode()->hasOneUse() && 1246 isa<ConstantSDNode>(N0.getOperand(1))) { 1247 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 1248 APInt bestMask; 1249 unsigned bestWidth = 0, bestOffset = 0; 1250 if (!Lod->isVolatile() && Lod->isUnindexed()) { 1251 unsigned origWidth = N0.getValueType().getSizeInBits(); 1252 unsigned maskWidth = origWidth; 1253 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 1254 // 8 bits, but have to be careful... 1255 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 1256 origWidth = Lod->getMemoryVT().getSizeInBits(); 1257 const APInt &Mask = 1258 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1259 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 1260 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 1261 for (unsigned offset=0; offset<origWidth/width; offset++) { 1262 if ((newMask & Mask) == Mask) { 1263 if (!getDataLayout()->isLittleEndian()) 1264 bestOffset = (origWidth/width - offset - 1) * (width/8); 1265 else 1266 bestOffset = (uint64_t)offset * (width/8); 1267 bestMask = Mask.lshr(offset * (width/8) * 8); 1268 bestWidth = width; 1269 break; 1270 } 1271 newMask = newMask << width; 1272 } 1273 } 1274 } 1275 if (bestWidth) { 1276 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 1277 if (newVT.isRound()) { 1278 EVT PtrType = Lod->getOperand(1).getValueType(); 1279 SDValue Ptr = Lod->getBasePtr(); 1280 if (bestOffset != 0) 1281 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(), 1282 DAG.getConstant(bestOffset, PtrType)); 1283 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset); 1284 SDValue NewLoad = DAG.getLoad(newVT, dl, Lod->getChain(), Ptr, 1285 Lod->getPointerInfo().getWithOffset(bestOffset), 1286 false, false, false, NewAlign); 1287 return DAG.getSetCC(dl, VT, 1288 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 1289 DAG.getConstant(bestMask.trunc(bestWidth), 1290 newVT)), 1291 DAG.getConstant(0LL, newVT), Cond); 1292 } 1293 } 1294 } 1295 1296 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 1297 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 1298 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits(); 1299 1300 // If the comparison constant has bits in the upper part, the 1301 // zero-extended value could never match. 1302 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 1303 C1.getBitWidth() - InSize))) { 1304 switch (Cond) { 1305 case ISD::SETUGT: 1306 case ISD::SETUGE: 1307 case ISD::SETEQ: return DAG.getConstant(0, VT); 1308 case ISD::SETULT: 1309 case ISD::SETULE: 1310 case ISD::SETNE: return DAG.getConstant(1, VT); 1311 case ISD::SETGT: 1312 case ISD::SETGE: 1313 // True if the sign bit of C1 is set. 1314 return DAG.getConstant(C1.isNegative(), VT); 1315 case ISD::SETLT: 1316 case ISD::SETLE: 1317 // True if the sign bit of C1 isn't set. 1318 return DAG.getConstant(C1.isNonNegative(), VT); 1319 default: 1320 break; 1321 } 1322 } 1323 1324 // Otherwise, we can perform the comparison with the low bits. 1325 switch (Cond) { 1326 case ISD::SETEQ: 1327 case ISD::SETNE: 1328 case ISD::SETUGT: 1329 case ISD::SETUGE: 1330 case ISD::SETULT: 1331 case ISD::SETULE: { 1332 EVT newVT = N0.getOperand(0).getValueType(); 1333 if (DCI.isBeforeLegalizeOps() || 1334 (isOperationLegal(ISD::SETCC, newVT) && 1335 getCondCodeAction(Cond, newVT.getSimpleVT())==Legal)) 1336 return DAG.getSetCC(dl, VT, N0.getOperand(0), 1337 DAG.getConstant(C1.trunc(InSize), newVT), 1338 Cond); 1339 break; 1340 } 1341 default: 1342 break; // todo, be more careful with signed comparisons 1343 } 1344 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 1345 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1346 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 1347 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 1348 EVT ExtDstTy = N0.getValueType(); 1349 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 1350 1351 // If the constant doesn't fit into the number of bits for the source of 1352 // the sign extension, it is impossible for both sides to be equal. 1353 if (C1.getMinSignedBits() > ExtSrcTyBits) 1354 return DAG.getConstant(Cond == ISD::SETNE, VT); 1355 1356 SDValue ZextOp; 1357 EVT Op0Ty = N0.getOperand(0).getValueType(); 1358 if (Op0Ty == ExtSrcTy) { 1359 ZextOp = N0.getOperand(0); 1360 } else { 1361 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 1362 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0), 1363 DAG.getConstant(Imm, Op0Ty)); 1364 } 1365 if (!DCI.isCalledByLegalizer()) 1366 DCI.AddToWorklist(ZextOp.getNode()); 1367 // Otherwise, make this a use of a zext. 1368 return DAG.getSetCC(dl, VT, ZextOp, 1369 DAG.getConstant(C1 & APInt::getLowBitsSet( 1370 ExtDstTyBits, 1371 ExtSrcTyBits), 1372 ExtDstTy), 1373 Cond); 1374 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) && 1375 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1376 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 1377 if (N0.getOpcode() == ISD::SETCC && 1378 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) { 1379 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1); 1380 if (TrueWhenTrue) 1381 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 1382 // Invert the condition. 1383 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 1384 CC = ISD::getSetCCInverse(CC, 1385 N0.getOperand(0).getValueType().isInteger()); 1386 if (DCI.isBeforeLegalizeOps() || 1387 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 1388 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 1389 } 1390 1391 if ((N0.getOpcode() == ISD::XOR || 1392 (N0.getOpcode() == ISD::AND && 1393 N0.getOperand(0).getOpcode() == ISD::XOR && 1394 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 1395 isa<ConstantSDNode>(N0.getOperand(1)) && 1396 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) { 1397 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 1398 // can only do this if the top bits are known zero. 1399 unsigned BitWidth = N0.getValueSizeInBits(); 1400 if (DAG.MaskedValueIsZero(N0, 1401 APInt::getHighBitsSet(BitWidth, 1402 BitWidth-1))) { 1403 // Okay, get the un-inverted input value. 1404 SDValue Val; 1405 if (N0.getOpcode() == ISD::XOR) 1406 Val = N0.getOperand(0); 1407 else { 1408 assert(N0.getOpcode() == ISD::AND && 1409 N0.getOperand(0).getOpcode() == ISD::XOR); 1410 // ((X^1)&1)^1 -> X & 1 1411 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 1412 N0.getOperand(0).getOperand(0), 1413 N0.getOperand(1)); 1414 } 1415 1416 return DAG.getSetCC(dl, VT, Val, N1, 1417 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1418 } 1419 } else if (N1C->getAPIntValue() == 1 && 1420 (VT == MVT::i1 || 1421 getBooleanContents(false) == ZeroOrOneBooleanContent)) { 1422 SDValue Op0 = N0; 1423 if (Op0.getOpcode() == ISD::TRUNCATE) 1424 Op0 = Op0.getOperand(0); 1425 1426 if ((Op0.getOpcode() == ISD::XOR) && 1427 Op0.getOperand(0).getOpcode() == ISD::SETCC && 1428 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 1429 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 1430 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 1431 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1), 1432 Cond); 1433 } 1434 if (Op0.getOpcode() == ISD::AND && 1435 isa<ConstantSDNode>(Op0.getOperand(1)) && 1436 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) { 1437 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 1438 if (Op0.getValueType().bitsGT(VT)) 1439 Op0 = DAG.getNode(ISD::AND, dl, VT, 1440 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 1441 DAG.getConstant(1, VT)); 1442 else if (Op0.getValueType().bitsLT(VT)) 1443 Op0 = DAG.getNode(ISD::AND, dl, VT, 1444 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 1445 DAG.getConstant(1, VT)); 1446 1447 return DAG.getSetCC(dl, VT, Op0, 1448 DAG.getConstant(0, Op0.getValueType()), 1449 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1450 } 1451 if (Op0.getOpcode() == ISD::AssertZext && 1452 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 1453 return DAG.getSetCC(dl, VT, Op0, 1454 DAG.getConstant(0, Op0.getValueType()), 1455 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1456 } 1457 } 1458 1459 APInt MinVal, MaxVal; 1460 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits(); 1461 if (ISD::isSignedIntSetCC(Cond)) { 1462 MinVal = APInt::getSignedMinValue(OperandBitSize); 1463 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 1464 } else { 1465 MinVal = APInt::getMinValue(OperandBitSize); 1466 MaxVal = APInt::getMaxValue(OperandBitSize); 1467 } 1468 1469 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 1470 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 1471 if (C1 == MinVal) return DAG.getConstant(1, VT); // X >= MIN --> true 1472 // X >= C0 --> X > (C0-1) 1473 return DAG.getSetCC(dl, VT, N0, 1474 DAG.getConstant(C1-1, N1.getValueType()), 1475 (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT); 1476 } 1477 1478 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 1479 if (C1 == MaxVal) return DAG.getConstant(1, VT); // X <= MAX --> true 1480 // X <= C0 --> X < (C0+1) 1481 return DAG.getSetCC(dl, VT, N0, 1482 DAG.getConstant(C1+1, N1.getValueType()), 1483 (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT); 1484 } 1485 1486 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal) 1487 return DAG.getConstant(0, VT); // X < MIN --> false 1488 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal) 1489 return DAG.getConstant(1, VT); // X >= MIN --> true 1490 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal) 1491 return DAG.getConstant(0, VT); // X > MAX --> false 1492 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal) 1493 return DAG.getConstant(1, VT); // X <= MAX --> true 1494 1495 // Canonicalize setgt X, Min --> setne X, Min 1496 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal) 1497 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1498 // Canonicalize setlt X, Max --> setne X, Max 1499 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal) 1500 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1501 1502 // If we have setult X, 1, turn it into seteq X, 0 1503 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1) 1504 return DAG.getSetCC(dl, VT, N0, 1505 DAG.getConstant(MinVal, N0.getValueType()), 1506 ISD::SETEQ); 1507 // If we have setugt X, Max-1, turn it into seteq X, Max 1508 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1) 1509 return DAG.getSetCC(dl, VT, N0, 1510 DAG.getConstant(MaxVal, N0.getValueType()), 1511 ISD::SETEQ); 1512 1513 // If we have "setcc X, C0", check to see if we can shrink the immediate 1514 // by changing cc. 1515 1516 // SETUGT X, SINTMAX -> SETLT X, 0 1517 if (Cond == ISD::SETUGT && 1518 C1 == APInt::getSignedMaxValue(OperandBitSize)) 1519 return DAG.getSetCC(dl, VT, N0, 1520 DAG.getConstant(0, N1.getValueType()), 1521 ISD::SETLT); 1522 1523 // SETULT X, SINTMIN -> SETGT X, -1 1524 if (Cond == ISD::SETULT && 1525 C1 == APInt::getSignedMinValue(OperandBitSize)) { 1526 SDValue ConstMinusOne = 1527 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), 1528 N1.getValueType()); 1529 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT); 1530 } 1531 1532 // Fold bit comparisons when we can. 1533 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1534 (VT == N0.getValueType() || 1535 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) && 1536 N0.getOpcode() == ISD::AND) 1537 if (ConstantSDNode *AndRHS = 1538 dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1539 EVT ShiftTy = DCI.isBeforeLegalizeOps() ? 1540 getPointerTy() : getShiftAmountTy(N0.getValueType()); 1541 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 1542 // Perform the xform if the AND RHS is a single bit. 1543 if (AndRHS->getAPIntValue().isPowerOf2()) { 1544 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1545 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1546 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), ShiftTy))); 1547 } 1548 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 1549 // (X & 8) == 8 --> (X & 8) >> 3 1550 // Perform the xform if C1 is a single bit. 1551 if (C1.isPowerOf2()) { 1552 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1553 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1554 DAG.getConstant(C1.logBase2(), ShiftTy))); 1555 } 1556 } 1557 } 1558 1559 if (C1.getMinSignedBits() <= 64 && 1560 !isLegalICmpImmediate(C1.getSExtValue())) { 1561 // (X & -256) == 256 -> (X >> 8) == 1 1562 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1563 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 1564 if (ConstantSDNode *AndRHS = 1565 dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1566 const APInt &AndRHSC = AndRHS->getAPIntValue(); 1567 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 1568 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 1569 EVT ShiftTy = DCI.isBeforeLegalizeOps() ? 1570 getPointerTy() : getShiftAmountTy(N0.getValueType()); 1571 EVT CmpTy = N0.getValueType(); 1572 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0), 1573 DAG.getConstant(ShiftBits, ShiftTy)); 1574 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), CmpTy); 1575 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 1576 } 1577 } 1578 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 1579 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 1580 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 1581 // X < 0x100000000 -> (X >> 32) < 1 1582 // X >= 0x100000000 -> (X >> 32) >= 1 1583 // X <= 0x0ffffffff -> (X >> 32) < 1 1584 // X > 0x0ffffffff -> (X >> 32) >= 1 1585 unsigned ShiftBits; 1586 APInt NewC = C1; 1587 ISD::CondCode NewCond = Cond; 1588 if (AdjOne) { 1589 ShiftBits = C1.countTrailingOnes(); 1590 NewC = NewC + 1; 1591 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1592 } else { 1593 ShiftBits = C1.countTrailingZeros(); 1594 } 1595 NewC = NewC.lshr(ShiftBits); 1596 if (ShiftBits && isLegalICmpImmediate(NewC.getSExtValue())) { 1597 EVT ShiftTy = DCI.isBeforeLegalizeOps() ? 1598 getPointerTy() : getShiftAmountTy(N0.getValueType()); 1599 EVT CmpTy = N0.getValueType(); 1600 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0, 1601 DAG.getConstant(ShiftBits, ShiftTy)); 1602 SDValue CmpRHS = DAG.getConstant(NewC, CmpTy); 1603 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 1604 } 1605 } 1606 } 1607 } 1608 1609 if (isa<ConstantFPSDNode>(N0.getNode())) { 1610 // Constant fold or commute setcc. 1611 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl); 1612 if (O.getNode()) return O; 1613 } else if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) { 1614 // If the RHS of an FP comparison is a constant, simplify it away in 1615 // some cases. 1616 if (CFP->getValueAPF().isNaN()) { 1617 // If an operand is known to be a nan, we can fold it. 1618 switch (ISD::getUnorderedFlavor(Cond)) { 1619 default: llvm_unreachable("Unknown flavor!"); 1620 case 0: // Known false. 1621 return DAG.getConstant(0, VT); 1622 case 1: // Known true. 1623 return DAG.getConstant(1, VT); 1624 case 2: // Undefined. 1625 return DAG.getUNDEF(VT); 1626 } 1627 } 1628 1629 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 1630 // constant if knowing that the operand is non-nan is enough. We prefer to 1631 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 1632 // materialize 0.0. 1633 if (Cond == ISD::SETO || Cond == ISD::SETUO) 1634 return DAG.getSetCC(dl, VT, N0, N0, Cond); 1635 1636 // If the condition is not legal, see if we can find an equivalent one 1637 // which is legal. 1638 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 1639 // If the comparison was an awkward floating-point == or != and one of 1640 // the comparison operands is infinity or negative infinity, convert the 1641 // condition to a less-awkward <= or >=. 1642 if (CFP->getValueAPF().isInfinity()) { 1643 if (CFP->getValueAPF().isNegative()) { 1644 if (Cond == ISD::SETOEQ && 1645 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 1646 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE); 1647 if (Cond == ISD::SETUEQ && 1648 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 1649 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE); 1650 if (Cond == ISD::SETUNE && 1651 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 1652 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT); 1653 if (Cond == ISD::SETONE && 1654 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 1655 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT); 1656 } else { 1657 if (Cond == ISD::SETOEQ && 1658 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 1659 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE); 1660 if (Cond == ISD::SETUEQ && 1661 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 1662 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE); 1663 if (Cond == ISD::SETUNE && 1664 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 1665 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT); 1666 if (Cond == ISD::SETONE && 1667 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 1668 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT); 1669 } 1670 } 1671 } 1672 } 1673 1674 if (N0 == N1) { 1675 // The sext(setcc()) => setcc() optimization relies on the appropriate 1676 // constant being emitted. 1677 uint64_t EqVal = 0; 1678 switch (getBooleanContents(N0.getValueType().isVector())) { 1679 case UndefinedBooleanContent: 1680 case ZeroOrOneBooleanContent: 1681 EqVal = ISD::isTrueWhenEqual(Cond); 1682 break; 1683 case ZeroOrNegativeOneBooleanContent: 1684 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0; 1685 break; 1686 } 1687 1688 // We can always fold X == X for integer setcc's. 1689 if (N0.getValueType().isInteger()) { 1690 return DAG.getConstant(EqVal, VT); 1691 } 1692 unsigned UOF = ISD::getUnorderedFlavor(Cond); 1693 if (UOF == 2) // FP operators that are undefined on NaNs. 1694 return DAG.getConstant(EqVal, VT); 1695 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond))) 1696 return DAG.getConstant(EqVal, VT); 1697 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 1698 // if it is not already. 1699 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 1700 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() || 1701 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal)) 1702 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 1703 } 1704 1705 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1706 N0.getValueType().isInteger()) { 1707 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 1708 N0.getOpcode() == ISD::XOR) { 1709 // Simplify (X+Y) == (X+Z) --> Y == Z 1710 if (N0.getOpcode() == N1.getOpcode()) { 1711 if (N0.getOperand(0) == N1.getOperand(0)) 1712 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 1713 if (N0.getOperand(1) == N1.getOperand(1)) 1714 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 1715 if (DAG.isCommutativeBinOp(N0.getOpcode())) { 1716 // If X op Y == Y op X, try other combinations. 1717 if (N0.getOperand(0) == N1.getOperand(1)) 1718 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 1719 Cond); 1720 if (N0.getOperand(1) == N1.getOperand(0)) 1721 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 1722 Cond); 1723 } 1724 } 1725 1726 // If RHS is a legal immediate value for a compare instruction, we need 1727 // to be careful about increasing register pressure needlessly. 1728 bool LegalRHSImm = false; 1729 1730 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(N1)) { 1731 if (ConstantSDNode *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1732 // Turn (X+C1) == C2 --> X == C2-C1 1733 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 1734 return DAG.getSetCC(dl, VT, N0.getOperand(0), 1735 DAG.getConstant(RHSC->getAPIntValue()- 1736 LHSR->getAPIntValue(), 1737 N0.getValueType()), Cond); 1738 } 1739 1740 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 1741 if (N0.getOpcode() == ISD::XOR) 1742 // If we know that all of the inverted bits are zero, don't bother 1743 // performing the inversion. 1744 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 1745 return 1746 DAG.getSetCC(dl, VT, N0.getOperand(0), 1747 DAG.getConstant(LHSR->getAPIntValue() ^ 1748 RHSC->getAPIntValue(), 1749 N0.getValueType()), 1750 Cond); 1751 } 1752 1753 // Turn (C1-X) == C2 --> X == C1-C2 1754 if (ConstantSDNode *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 1755 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 1756 return 1757 DAG.getSetCC(dl, VT, N0.getOperand(1), 1758 DAG.getConstant(SUBC->getAPIntValue() - 1759 RHSC->getAPIntValue(), 1760 N0.getValueType()), 1761 Cond); 1762 } 1763 } 1764 1765 // Could RHSC fold directly into a compare? 1766 if (RHSC->getValueType(0).getSizeInBits() <= 64) 1767 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 1768 } 1769 1770 // Simplify (X+Z) == X --> Z == 0 1771 // Don't do this if X is an immediate that can fold into a cmp 1772 // instruction and X+Z has other uses. It could be an induction variable 1773 // chain, and the transform would increase register pressure. 1774 if (!LegalRHSImm || N0.getNode()->hasOneUse()) { 1775 if (N0.getOperand(0) == N1) 1776 return DAG.getSetCC(dl, VT, N0.getOperand(1), 1777 DAG.getConstant(0, N0.getValueType()), Cond); 1778 if (N0.getOperand(1) == N1) { 1779 if (DAG.isCommutativeBinOp(N0.getOpcode())) 1780 return DAG.getSetCC(dl, VT, N0.getOperand(0), 1781 DAG.getConstant(0, N0.getValueType()), Cond); 1782 if (N0.getNode()->hasOneUse()) { 1783 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!"); 1784 // (Z-X) == X --> Z == X<<1 1785 SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N1, 1786 DAG.getConstant(1, getShiftAmountTy(N1.getValueType()))); 1787 if (!DCI.isCalledByLegalizer()) 1788 DCI.AddToWorklist(SH.getNode()); 1789 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond); 1790 } 1791 } 1792 } 1793 } 1794 1795 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 1796 N1.getOpcode() == ISD::XOR) { 1797 // Simplify X == (X+Z) --> Z == 0 1798 if (N1.getOperand(0) == N0) 1799 return DAG.getSetCC(dl, VT, N1.getOperand(1), 1800 DAG.getConstant(0, N1.getValueType()), Cond); 1801 if (N1.getOperand(1) == N0) { 1802 if (DAG.isCommutativeBinOp(N1.getOpcode())) 1803 return DAG.getSetCC(dl, VT, N1.getOperand(0), 1804 DAG.getConstant(0, N1.getValueType()), Cond); 1805 if (N1.getNode()->hasOneUse()) { 1806 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!"); 1807 // X == (Z-X) --> X<<1 == Z 1808 SDValue SH = DAG.getNode(ISD::SHL, dl, N1.getValueType(), N0, 1809 DAG.getConstant(1, getShiftAmountTy(N0.getValueType()))); 1810 if (!DCI.isCalledByLegalizer()) 1811 DCI.AddToWorklist(SH.getNode()); 1812 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond); 1813 } 1814 } 1815 } 1816 1817 // Simplify x&y == y to x&y != 0 if y has exactly one bit set. 1818 // Note that where y is variable and is known to have at most 1819 // one bit set (for example, if it is z&1) we cannot do this; 1820 // the expressions are not equivalent when y==0. 1821 if (N0.getOpcode() == ISD::AND) 1822 if (N0.getOperand(0) == N1 || N0.getOperand(1) == N1) { 1823 if (ValueHasExactlyOneBitSet(N1, DAG)) { 1824 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 1825 if (DCI.isBeforeLegalizeOps() || 1826 isCondCodeLegal(Cond, N0.getSimpleValueType())) { 1827 SDValue Zero = DAG.getConstant(0, N1.getValueType()); 1828 return DAG.getSetCC(dl, VT, N0, Zero, Cond); 1829 } 1830 } 1831 } 1832 if (N1.getOpcode() == ISD::AND) 1833 if (N1.getOperand(0) == N0 || N1.getOperand(1) == N0) { 1834 if (ValueHasExactlyOneBitSet(N0, DAG)) { 1835 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 1836 if (DCI.isBeforeLegalizeOps() || 1837 isCondCodeLegal(Cond, N1.getSimpleValueType())) { 1838 SDValue Zero = DAG.getConstant(0, N0.getValueType()); 1839 return DAG.getSetCC(dl, VT, N1, Zero, Cond); 1840 } 1841 } 1842 } 1843 } 1844 1845 // Fold away ALL boolean setcc's. 1846 SDValue Temp; 1847 if (N0.getValueType() == MVT::i1 && foldBooleans) { 1848 switch (Cond) { 1849 default: llvm_unreachable("Unknown integer setcc!"); 1850 case ISD::SETEQ: // X == Y -> ~(X^Y) 1851 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 1852 N0 = DAG.getNOT(dl, Temp, MVT::i1); 1853 if (!DCI.isCalledByLegalizer()) 1854 DCI.AddToWorklist(Temp.getNode()); 1855 break; 1856 case ISD::SETNE: // X != Y --> (X^Y) 1857 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 1858 break; 1859 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 1860 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 1861 Temp = DAG.getNOT(dl, N0, MVT::i1); 1862 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp); 1863 if (!DCI.isCalledByLegalizer()) 1864 DCI.AddToWorklist(Temp.getNode()); 1865 break; 1866 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 1867 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 1868 Temp = DAG.getNOT(dl, N1, MVT::i1); 1869 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp); 1870 if (!DCI.isCalledByLegalizer()) 1871 DCI.AddToWorklist(Temp.getNode()); 1872 break; 1873 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 1874 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 1875 Temp = DAG.getNOT(dl, N0, MVT::i1); 1876 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp); 1877 if (!DCI.isCalledByLegalizer()) 1878 DCI.AddToWorklist(Temp.getNode()); 1879 break; 1880 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 1881 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 1882 Temp = DAG.getNOT(dl, N1, MVT::i1); 1883 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp); 1884 break; 1885 } 1886 if (VT != MVT::i1) { 1887 if (!DCI.isCalledByLegalizer()) 1888 DCI.AddToWorklist(N0.getNode()); 1889 // FIXME: If running after legalize, we probably can't do this. 1890 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0); 1891 } 1892 return N0; 1893 } 1894 1895 // Could not fold it. 1896 return SDValue(); 1897 } 1898 1899 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the 1900 /// node is a GlobalAddress + offset. 1901 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA, 1902 int64_t &Offset) const { 1903 if (isa<GlobalAddressSDNode>(N)) { 1904 GlobalAddressSDNode *GASD = cast<GlobalAddressSDNode>(N); 1905 GA = GASD->getGlobal(); 1906 Offset += GASD->getOffset(); 1907 return true; 1908 } 1909 1910 if (N->getOpcode() == ISD::ADD) { 1911 SDValue N1 = N->getOperand(0); 1912 SDValue N2 = N->getOperand(1); 1913 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 1914 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2); 1915 if (V) { 1916 Offset += V->getSExtValue(); 1917 return true; 1918 } 1919 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 1920 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1); 1921 if (V) { 1922 Offset += V->getSExtValue(); 1923 return true; 1924 } 1925 } 1926 } 1927 1928 return false; 1929 } 1930 1931 1932 SDValue TargetLowering:: 1933 PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const { 1934 // Default implementation: no optimization. 1935 return SDValue(); 1936 } 1937 1938 //===----------------------------------------------------------------------===// 1939 // Inline Assembler Implementation Methods 1940 //===----------------------------------------------------------------------===// 1941 1942 1943 TargetLowering::ConstraintType 1944 TargetLowering::getConstraintType(const std::string &Constraint) const { 1945 unsigned S = Constraint.size(); 1946 1947 if (S == 1) { 1948 switch (Constraint[0]) { 1949 default: break; 1950 case 'r': return C_RegisterClass; 1951 case 'm': // memory 1952 case 'o': // offsetable 1953 case 'V': // not offsetable 1954 return C_Memory; 1955 case 'i': // Simple Integer or Relocatable Constant 1956 case 'n': // Simple Integer 1957 case 'E': // Floating Point Constant 1958 case 'F': // Floating Point Constant 1959 case 's': // Relocatable Constant 1960 case 'p': // Address. 1961 case 'X': // Allow ANY value. 1962 case 'I': // Target registers. 1963 case 'J': 1964 case 'K': 1965 case 'L': 1966 case 'M': 1967 case 'N': 1968 case 'O': 1969 case 'P': 1970 case '<': 1971 case '>': 1972 return C_Other; 1973 } 1974 } 1975 1976 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') { 1977 if (S == 8 && !Constraint.compare(1, 6, "memory", 6)) // "{memory}" 1978 return C_Memory; 1979 return C_Register; 1980 } 1981 return C_Unknown; 1982 } 1983 1984 /// LowerXConstraint - try to replace an X constraint, which matches anything, 1985 /// with another that has more specific requirements based on the type of the 1986 /// corresponding operand. 1987 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{ 1988 if (ConstraintVT.isInteger()) 1989 return "r"; 1990 if (ConstraintVT.isFloatingPoint()) 1991 return "f"; // works for many targets 1992 return 0; 1993 } 1994 1995 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 1996 /// vector. If it is invalid, don't add anything to Ops. 1997 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 1998 std::string &Constraint, 1999 std::vector<SDValue> &Ops, 2000 SelectionDAG &DAG) const { 2001 2002 if (Constraint.length() > 1) return; 2003 2004 char ConstraintLetter = Constraint[0]; 2005 switch (ConstraintLetter) { 2006 default: break; 2007 case 'X': // Allows any operand; labels (basic block) use this. 2008 if (Op.getOpcode() == ISD::BasicBlock) { 2009 Ops.push_back(Op); 2010 return; 2011 } 2012 // fall through 2013 case 'i': // Simple Integer or Relocatable Constant 2014 case 'n': // Simple Integer 2015 case 's': { // Relocatable Constant 2016 // These operands are interested in values of the form (GV+C), where C may 2017 // be folded in as an offset of GV, or it may be explicitly added. Also, it 2018 // is possible and fine if either GV or C are missing. 2019 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 2020 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op); 2021 2022 // If we have "(add GV, C)", pull out GV/C 2023 if (Op.getOpcode() == ISD::ADD) { 2024 C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 2025 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0)); 2026 if (C == 0 || GA == 0) { 2027 C = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 2028 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1)); 2029 } 2030 if (C == 0 || GA == 0) 2031 C = 0, GA = 0; 2032 } 2033 2034 // If we find a valid operand, map to the TargetXXX version so that the 2035 // value itself doesn't get selected. 2036 if (GA) { // Either &GV or &GV+C 2037 if (ConstraintLetter != 'n') { 2038 int64_t Offs = GA->getOffset(); 2039 if (C) Offs += C->getZExtValue(); 2040 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), 2041 C ? SDLoc(C) : SDLoc(), 2042 Op.getValueType(), Offs)); 2043 return; 2044 } 2045 } 2046 if (C) { // just C, no GV. 2047 // Simple constants are not allowed for 's'. 2048 if (ConstraintLetter != 's') { 2049 // gcc prints these as sign extended. Sign extend value to 64 bits 2050 // now; without this it would get ZExt'd later in 2051 // ScheduleDAGSDNodes::EmitNode, which is very generic. 2052 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(), 2053 MVT::i64)); 2054 return; 2055 } 2056 } 2057 break; 2058 } 2059 } 2060 } 2061 2062 std::pair<unsigned, const TargetRegisterClass*> TargetLowering:: 2063 getRegForInlineAsmConstraint(const std::string &Constraint, 2064 MVT VT) const { 2065 if (Constraint.empty() || Constraint[0] != '{') 2066 return std::make_pair(0u, static_cast<TargetRegisterClass*>(0)); 2067 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?"); 2068 2069 // Remove the braces from around the name. 2070 StringRef RegName(Constraint.data()+1, Constraint.size()-2); 2071 2072 std::pair<unsigned, const TargetRegisterClass*> R = 2073 std::make_pair(0u, static_cast<const TargetRegisterClass*>(0)); 2074 2075 // Figure out which register class contains this reg. 2076 const TargetRegisterInfo *RI = getTargetMachine().getRegisterInfo(); 2077 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(), 2078 E = RI->regclass_end(); RCI != E; ++RCI) { 2079 const TargetRegisterClass *RC = *RCI; 2080 2081 // If none of the value types for this register class are valid, we 2082 // can't use it. For example, 64-bit reg classes on 32-bit targets. 2083 if (!isLegalRC(RC)) 2084 continue; 2085 2086 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 2087 I != E; ++I) { 2088 if (RegName.equals_lower(RI->getName(*I))) { 2089 std::pair<unsigned, const TargetRegisterClass*> S = 2090 std::make_pair(*I, RC); 2091 2092 // If this register class has the requested value type, return it, 2093 // otherwise keep searching and return the first class found 2094 // if no other is found which explicitly has the requested type. 2095 if (RC->hasType(VT)) 2096 return S; 2097 else if (!R.second) 2098 R = S; 2099 } 2100 } 2101 } 2102 2103 return R; 2104 } 2105 2106 //===----------------------------------------------------------------------===// 2107 // Constraint Selection. 2108 2109 /// isMatchingInputConstraint - Return true of this is an input operand that is 2110 /// a matching constraint like "4". 2111 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 2112 assert(!ConstraintCode.empty() && "No known constraint!"); 2113 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 2114 } 2115 2116 /// getMatchedOperand - If this is an input matching constraint, this method 2117 /// returns the output operand it matches. 2118 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 2119 assert(!ConstraintCode.empty() && "No known constraint!"); 2120 return atoi(ConstraintCode.c_str()); 2121 } 2122 2123 2124 /// ParseConstraints - Split up the constraint string from the inline 2125 /// assembly value into the specific constraints and their prefixes, 2126 /// and also tie in the associated operand values. 2127 /// If this returns an empty vector, and if the constraint string itself 2128 /// isn't empty, there was an error parsing. 2129 TargetLowering::AsmOperandInfoVector TargetLowering::ParseConstraints( 2130 ImmutableCallSite CS) const { 2131 /// ConstraintOperands - Information about all of the constraints. 2132 AsmOperandInfoVector ConstraintOperands; 2133 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 2134 unsigned maCount = 0; // Largest number of multiple alternative constraints. 2135 2136 // Do a prepass over the constraints, canonicalizing them, and building up the 2137 // ConstraintOperands list. 2138 InlineAsm::ConstraintInfoVector 2139 ConstraintInfos = IA->ParseConstraints(); 2140 2141 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 2142 unsigned ResNo = 0; // ResNo - The result number of the next output. 2143 2144 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) { 2145 ConstraintOperands.push_back(AsmOperandInfo(ConstraintInfos[i])); 2146 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 2147 2148 // Update multiple alternative constraint count. 2149 if (OpInfo.multipleAlternatives.size() > maCount) 2150 maCount = OpInfo.multipleAlternatives.size(); 2151 2152 OpInfo.ConstraintVT = MVT::Other; 2153 2154 // Compute the value type for each operand. 2155 switch (OpInfo.Type) { 2156 case InlineAsm::isOutput: 2157 // Indirect outputs just consume an argument. 2158 if (OpInfo.isIndirect) { 2159 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2160 break; 2161 } 2162 2163 // The return value of the call is this value. As such, there is no 2164 // corresponding argument. 2165 assert(!CS.getType()->isVoidTy() && 2166 "Bad inline asm!"); 2167 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 2168 OpInfo.ConstraintVT = getSimpleValueType(STy->getElementType(ResNo)); 2169 } else { 2170 assert(ResNo == 0 && "Asm only has one result!"); 2171 OpInfo.ConstraintVT = getSimpleValueType(CS.getType()); 2172 } 2173 ++ResNo; 2174 break; 2175 case InlineAsm::isInput: 2176 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2177 break; 2178 case InlineAsm::isClobber: 2179 // Nothing to do. 2180 break; 2181 } 2182 2183 if (OpInfo.CallOperandVal) { 2184 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 2185 if (OpInfo.isIndirect) { 2186 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 2187 if (!PtrTy) 2188 report_fatal_error("Indirect operand for inline asm not a pointer!"); 2189 OpTy = PtrTy->getElementType(); 2190 } 2191 2192 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 2193 if (StructType *STy = dyn_cast<StructType>(OpTy)) 2194 if (STy->getNumElements() == 1) 2195 OpTy = STy->getElementType(0); 2196 2197 // If OpTy is not a single value, it may be a struct/union that we 2198 // can tile with integers. 2199 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 2200 unsigned BitSize = getDataLayout()->getTypeSizeInBits(OpTy); 2201 switch (BitSize) { 2202 default: break; 2203 case 1: 2204 case 8: 2205 case 16: 2206 case 32: 2207 case 64: 2208 case 128: 2209 OpInfo.ConstraintVT = 2210 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 2211 break; 2212 } 2213 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 2214 unsigned PtrSize 2215 = getDataLayout()->getPointerSizeInBits(PT->getAddressSpace()); 2216 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 2217 } else { 2218 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 2219 } 2220 } 2221 } 2222 2223 // If we have multiple alternative constraints, select the best alternative. 2224 if (ConstraintInfos.size()) { 2225 if (maCount) { 2226 unsigned bestMAIndex = 0; 2227 int bestWeight = -1; 2228 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 2229 int weight = -1; 2230 unsigned maIndex; 2231 // Compute the sums of the weights for each alternative, keeping track 2232 // of the best (highest weight) one so far. 2233 for (maIndex = 0; maIndex < maCount; ++maIndex) { 2234 int weightSum = 0; 2235 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2236 cIndex != eIndex; ++cIndex) { 2237 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2238 if (OpInfo.Type == InlineAsm::isClobber) 2239 continue; 2240 2241 // If this is an output operand with a matching input operand, 2242 // look up the matching input. If their types mismatch, e.g. one 2243 // is an integer, the other is floating point, or their sizes are 2244 // different, flag it as an maCantMatch. 2245 if (OpInfo.hasMatchingInput()) { 2246 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2247 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2248 if ((OpInfo.ConstraintVT.isInteger() != 2249 Input.ConstraintVT.isInteger()) || 2250 (OpInfo.ConstraintVT.getSizeInBits() != 2251 Input.ConstraintVT.getSizeInBits())) { 2252 weightSum = -1; // Can't match. 2253 break; 2254 } 2255 } 2256 } 2257 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 2258 if (weight == -1) { 2259 weightSum = -1; 2260 break; 2261 } 2262 weightSum += weight; 2263 } 2264 // Update best. 2265 if (weightSum > bestWeight) { 2266 bestWeight = weightSum; 2267 bestMAIndex = maIndex; 2268 } 2269 } 2270 2271 // Now select chosen alternative in each constraint. 2272 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2273 cIndex != eIndex; ++cIndex) { 2274 AsmOperandInfo& cInfo = ConstraintOperands[cIndex]; 2275 if (cInfo.Type == InlineAsm::isClobber) 2276 continue; 2277 cInfo.selectAlternative(bestMAIndex); 2278 } 2279 } 2280 } 2281 2282 // Check and hook up tied operands, choose constraint code to use. 2283 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2284 cIndex != eIndex; ++cIndex) { 2285 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2286 2287 // If this is an output operand with a matching input operand, look up the 2288 // matching input. If their types mismatch, e.g. one is an integer, the 2289 // other is floating point, or their sizes are different, flag it as an 2290 // error. 2291 if (OpInfo.hasMatchingInput()) { 2292 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2293 2294 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2295 std::pair<unsigned, const TargetRegisterClass*> MatchRC = 2296 getRegForInlineAsmConstraint(OpInfo.ConstraintCode, 2297 OpInfo.ConstraintVT); 2298 std::pair<unsigned, const TargetRegisterClass*> InputRC = 2299 getRegForInlineAsmConstraint(Input.ConstraintCode, 2300 Input.ConstraintVT); 2301 if ((OpInfo.ConstraintVT.isInteger() != 2302 Input.ConstraintVT.isInteger()) || 2303 (MatchRC.second != InputRC.second)) { 2304 report_fatal_error("Unsupported asm: input constraint" 2305 " with a matching output constraint of" 2306 " incompatible type!"); 2307 } 2308 } 2309 2310 } 2311 } 2312 2313 return ConstraintOperands; 2314 } 2315 2316 2317 /// getConstraintGenerality - Return an integer indicating how general CT 2318 /// is. 2319 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 2320 switch (CT) { 2321 case TargetLowering::C_Other: 2322 case TargetLowering::C_Unknown: 2323 return 0; 2324 case TargetLowering::C_Register: 2325 return 1; 2326 case TargetLowering::C_RegisterClass: 2327 return 2; 2328 case TargetLowering::C_Memory: 2329 return 3; 2330 } 2331 llvm_unreachable("Invalid constraint type"); 2332 } 2333 2334 /// Examine constraint type and operand type and determine a weight value. 2335 /// This object must already have been set up with the operand type 2336 /// and the current alternative constraint selected. 2337 TargetLowering::ConstraintWeight 2338 TargetLowering::getMultipleConstraintMatchWeight( 2339 AsmOperandInfo &info, int maIndex) const { 2340 InlineAsm::ConstraintCodeVector *rCodes; 2341 if (maIndex >= (int)info.multipleAlternatives.size()) 2342 rCodes = &info.Codes; 2343 else 2344 rCodes = &info.multipleAlternatives[maIndex].Codes; 2345 ConstraintWeight BestWeight = CW_Invalid; 2346 2347 // Loop over the options, keeping track of the most general one. 2348 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 2349 ConstraintWeight weight = 2350 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 2351 if (weight > BestWeight) 2352 BestWeight = weight; 2353 } 2354 2355 return BestWeight; 2356 } 2357 2358 /// Examine constraint type and operand type and determine a weight value. 2359 /// This object must already have been set up with the operand type 2360 /// and the current alternative constraint selected. 2361 TargetLowering::ConstraintWeight 2362 TargetLowering::getSingleConstraintMatchWeight( 2363 AsmOperandInfo &info, const char *constraint) const { 2364 ConstraintWeight weight = CW_Invalid; 2365 Value *CallOperandVal = info.CallOperandVal; 2366 // If we don't have a value, we can't do a match, 2367 // but allow it at the lowest weight. 2368 if (CallOperandVal == NULL) 2369 return CW_Default; 2370 // Look at the constraint type. 2371 switch (*constraint) { 2372 case 'i': // immediate integer. 2373 case 'n': // immediate integer with a known value. 2374 if (isa<ConstantInt>(CallOperandVal)) 2375 weight = CW_Constant; 2376 break; 2377 case 's': // non-explicit intregal immediate. 2378 if (isa<GlobalValue>(CallOperandVal)) 2379 weight = CW_Constant; 2380 break; 2381 case 'E': // immediate float if host format. 2382 case 'F': // immediate float. 2383 if (isa<ConstantFP>(CallOperandVal)) 2384 weight = CW_Constant; 2385 break; 2386 case '<': // memory operand with autodecrement. 2387 case '>': // memory operand with autoincrement. 2388 case 'm': // memory operand. 2389 case 'o': // offsettable memory operand 2390 case 'V': // non-offsettable memory operand 2391 weight = CW_Memory; 2392 break; 2393 case 'r': // general register. 2394 case 'g': // general register, memory operand or immediate integer. 2395 // note: Clang converts "g" to "imr". 2396 if (CallOperandVal->getType()->isIntegerTy()) 2397 weight = CW_Register; 2398 break; 2399 case 'X': // any operand. 2400 default: 2401 weight = CW_Default; 2402 break; 2403 } 2404 return weight; 2405 } 2406 2407 /// ChooseConstraint - If there are multiple different constraints that we 2408 /// could pick for this operand (e.g. "imr") try to pick the 'best' one. 2409 /// This is somewhat tricky: constraints fall into four classes: 2410 /// Other -> immediates and magic values 2411 /// Register -> one specific register 2412 /// RegisterClass -> a group of regs 2413 /// Memory -> memory 2414 /// Ideally, we would pick the most specific constraint possible: if we have 2415 /// something that fits into a register, we would pick it. The problem here 2416 /// is that if we have something that could either be in a register or in 2417 /// memory that use of the register could cause selection of *other* 2418 /// operands to fail: they might only succeed if we pick memory. Because of 2419 /// this the heuristic we use is: 2420 /// 2421 /// 1) If there is an 'other' constraint, and if the operand is valid for 2422 /// that constraint, use it. This makes us take advantage of 'i' 2423 /// constraints when available. 2424 /// 2) Otherwise, pick the most general constraint present. This prefers 2425 /// 'm' over 'r', for example. 2426 /// 2427 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 2428 const TargetLowering &TLI, 2429 SDValue Op, SelectionDAG *DAG) { 2430 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 2431 unsigned BestIdx = 0; 2432 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 2433 int BestGenerality = -1; 2434 2435 // Loop over the options, keeping track of the most general one. 2436 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 2437 TargetLowering::ConstraintType CType = 2438 TLI.getConstraintType(OpInfo.Codes[i]); 2439 2440 // If this is an 'other' constraint, see if the operand is valid for it. 2441 // For example, on X86 we might have an 'rI' constraint. If the operand 2442 // is an integer in the range [0..31] we want to use I (saving a load 2443 // of a register), otherwise we must use 'r'. 2444 if (CType == TargetLowering::C_Other && Op.getNode()) { 2445 assert(OpInfo.Codes[i].size() == 1 && 2446 "Unhandled multi-letter 'other' constraint"); 2447 std::vector<SDValue> ResultOps; 2448 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 2449 ResultOps, *DAG); 2450 if (!ResultOps.empty()) { 2451 BestType = CType; 2452 BestIdx = i; 2453 break; 2454 } 2455 } 2456 2457 // Things with matching constraints can only be registers, per gcc 2458 // documentation. This mainly affects "g" constraints. 2459 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 2460 continue; 2461 2462 // This constraint letter is more general than the previous one, use it. 2463 int Generality = getConstraintGenerality(CType); 2464 if (Generality > BestGenerality) { 2465 BestType = CType; 2466 BestIdx = i; 2467 BestGenerality = Generality; 2468 } 2469 } 2470 2471 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 2472 OpInfo.ConstraintType = BestType; 2473 } 2474 2475 /// ComputeConstraintToUse - Determines the constraint code and constraint 2476 /// type to use for the specific AsmOperandInfo, setting 2477 /// OpInfo.ConstraintCode and OpInfo.ConstraintType. 2478 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 2479 SDValue Op, 2480 SelectionDAG *DAG) const { 2481 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 2482 2483 // Single-letter constraints ('r') are very common. 2484 if (OpInfo.Codes.size() == 1) { 2485 OpInfo.ConstraintCode = OpInfo.Codes[0]; 2486 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2487 } else { 2488 ChooseConstraint(OpInfo, *this, Op, DAG); 2489 } 2490 2491 // 'X' matches anything. 2492 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 2493 // Labels and constants are handled elsewhere ('X' is the only thing 2494 // that matches labels). For Functions, the type here is the type of 2495 // the result, which is not what we want to look at; leave them alone. 2496 Value *v = OpInfo.CallOperandVal; 2497 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 2498 OpInfo.CallOperandVal = v; 2499 return; 2500 } 2501 2502 // Otherwise, try to resolve it to something we know about by looking at 2503 // the actual operand type. 2504 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 2505 OpInfo.ConstraintCode = Repl; 2506 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2507 } 2508 } 2509 } 2510 2511 /// \brief Given an exact SDIV by a constant, create a multiplication 2512 /// with the multiplicative inverse of the constant. 2513 SDValue TargetLowering::BuildExactSDIV(SDValue Op1, SDValue Op2, SDLoc dl, 2514 SelectionDAG &DAG) const { 2515 ConstantSDNode *C = cast<ConstantSDNode>(Op2); 2516 APInt d = C->getAPIntValue(); 2517 assert(d != 0 && "Division by zero!"); 2518 2519 // Shift the value upfront if it is even, so the LSB is one. 2520 unsigned ShAmt = d.countTrailingZeros(); 2521 if (ShAmt) { 2522 // TODO: For UDIV use SRL instead of SRA. 2523 SDValue Amt = DAG.getConstant(ShAmt, getShiftAmountTy(Op1.getValueType())); 2524 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt); 2525 d = d.ashr(ShAmt); 2526 } 2527 2528 // Calculate the multiplicative inverse, using Newton's method. 2529 APInt t, xn = d; 2530 while ((t = d*xn) != 1) 2531 xn *= APInt(d.getBitWidth(), 2) - t; 2532 2533 Op2 = DAG.getConstant(xn, Op1.getValueType()); 2534 return DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2); 2535 } 2536 2537 /// \brief Given an ISD::SDIV node expressing a divide by constant, 2538 /// return a DAG expression to select that will generate the same value by 2539 /// multiplying by a magic number. See: 2540 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 2541 SDValue TargetLowering:: 2542 BuildSDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization, 2543 std::vector<SDNode*> *Created) const { 2544 EVT VT = N->getValueType(0); 2545 SDLoc dl(N); 2546 2547 // Check to see if we can do this. 2548 // FIXME: We should be more aggressive here. 2549 if (!isTypeLegal(VT)) 2550 return SDValue(); 2551 2552 APInt d = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue(); 2553 APInt::ms magics = d.magic(); 2554 2555 // Multiply the numerator (operand 0) by the magic value 2556 // FIXME: We should support doing a MUL in a wider type 2557 SDValue Q; 2558 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) : 2559 isOperationLegalOrCustom(ISD::MULHS, VT)) 2560 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0), 2561 DAG.getConstant(magics.m, VT)); 2562 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) : 2563 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) 2564 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), 2565 N->getOperand(0), 2566 DAG.getConstant(magics.m, VT)).getNode(), 1); 2567 else 2568 return SDValue(); // No mulhs or equvialent 2569 // If d > 0 and m < 0, add the numerator 2570 if (d.isStrictlyPositive() && magics.m.isNegative()) { 2571 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0)); 2572 if (Created) 2573 Created->push_back(Q.getNode()); 2574 } 2575 // If d < 0 and m > 0, subtract the numerator. 2576 if (d.isNegative() && magics.m.isStrictlyPositive()) { 2577 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0)); 2578 if (Created) 2579 Created->push_back(Q.getNode()); 2580 } 2581 // Shift right algebraic if shift value is nonzero 2582 if (magics.s > 0) { 2583 Q = DAG.getNode(ISD::SRA, dl, VT, Q, 2584 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType()))); 2585 if (Created) 2586 Created->push_back(Q.getNode()); 2587 } 2588 // Extract the sign bit and add it to the quotient 2589 SDValue T = 2590 DAG.getNode(ISD::SRL, dl, VT, Q, DAG.getConstant(VT.getSizeInBits()-1, 2591 getShiftAmountTy(Q.getValueType()))); 2592 if (Created) 2593 Created->push_back(T.getNode()); 2594 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 2595 } 2596 2597 /// \brief Given an ISD::UDIV node expressing a divide by constant, 2598 /// return a DAG expression to select that will generate the same value by 2599 /// multiplying by a magic number. See: 2600 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html> 2601 SDValue TargetLowering:: 2602 BuildUDIV(SDNode *N, SelectionDAG &DAG, bool IsAfterLegalization, 2603 std::vector<SDNode*> *Created) const { 2604 EVT VT = N->getValueType(0); 2605 SDLoc dl(N); 2606 2607 // Check to see if we can do this. 2608 // FIXME: We should be more aggressive here. 2609 if (!isTypeLegal(VT)) 2610 return SDValue(); 2611 2612 // FIXME: We should use a narrower constant when the upper 2613 // bits are known to be zero. 2614 const APInt &N1C = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue(); 2615 APInt::mu magics = N1C.magicu(); 2616 2617 SDValue Q = N->getOperand(0); 2618 2619 // If the divisor is even, we can avoid using the expensive fixup by shifting 2620 // the divided value upfront. 2621 if (magics.a != 0 && !N1C[0]) { 2622 unsigned Shift = N1C.countTrailingZeros(); 2623 Q = DAG.getNode(ISD::SRL, dl, VT, Q, 2624 DAG.getConstant(Shift, getShiftAmountTy(Q.getValueType()))); 2625 if (Created) 2626 Created->push_back(Q.getNode()); 2627 2628 // Get magic number for the shifted divisor. 2629 magics = N1C.lshr(Shift).magicu(Shift); 2630 assert(magics.a == 0 && "Should use cheap fixup now"); 2631 } 2632 2633 // Multiply the numerator (operand 0) by the magic value 2634 // FIXME: We should support doing a MUL in a wider type 2635 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) : 2636 isOperationLegalOrCustom(ISD::MULHU, VT)) 2637 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, VT)); 2638 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) : 2639 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) 2640 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q, 2641 DAG.getConstant(magics.m, VT)).getNode(), 1); 2642 else 2643 return SDValue(); // No mulhu or equvialent 2644 if (Created) 2645 Created->push_back(Q.getNode()); 2646 2647 if (magics.a == 0) { 2648 assert(magics.s < N1C.getBitWidth() && 2649 "We shouldn't generate an undefined shift!"); 2650 return DAG.getNode(ISD::SRL, dl, VT, Q, 2651 DAG.getConstant(magics.s, getShiftAmountTy(Q.getValueType()))); 2652 } else { 2653 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q); 2654 if (Created) 2655 Created->push_back(NPQ.getNode()); 2656 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, 2657 DAG.getConstant(1, getShiftAmountTy(NPQ.getValueType()))); 2658 if (Created) 2659 Created->push_back(NPQ.getNode()); 2660 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 2661 if (Created) 2662 Created->push_back(NPQ.getNode()); 2663 return DAG.getNode(ISD::SRL, dl, VT, NPQ, 2664 DAG.getConstant(magics.s-1, getShiftAmountTy(NPQ.getValueType()))); 2665 } 2666 } 2667 2668 bool TargetLowering:: 2669 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 2670 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 2671 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 2672 "be a constant integer"); 2673 return true; 2674 } 2675 2676 return false; 2677 } 2678