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/CallingConvLower.h" 18 #include "llvm/CodeGen/MachineFrameInfo.h" 19 #include "llvm/CodeGen/MachineFunction.h" 20 #include "llvm/CodeGen/MachineJumpTableInfo.h" 21 #include "llvm/CodeGen/MachineRegisterInfo.h" 22 #include "llvm/CodeGen/SelectionDAG.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/GlobalVariable.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/MC/MCAsmInfo.h" 28 #include "llvm/MC/MCExpr.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/MathExtras.h" 31 #include "llvm/Target/TargetLoweringObjectFile.h" 32 #include "llvm/Target/TargetMachine.h" 33 #include "llvm/Target/TargetRegisterInfo.h" 34 #include "llvm/Target/TargetSubtargetInfo.h" 35 #include <cctype> 36 using namespace llvm; 37 38 /// NOTE: The TargetMachine owns TLOF. 39 TargetLowering::TargetLowering(const TargetMachine &tm) 40 : TargetLoweringBase(tm) {} 41 42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const { 43 return nullptr; 44 } 45 46 bool TargetLowering::isPositionIndependent() const { 47 return getTargetMachine().isPositionIndependent(); 48 } 49 50 /// Check whether a given call node is in tail position within its function. If 51 /// so, it sets Chain to the input chain of the tail call. 52 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, 53 SDValue &Chain) const { 54 const Function *F = DAG.getMachineFunction().getFunction(); 55 56 // Conservatively require the attributes of the call to match those of 57 // the return. Ignore noalias because it doesn't affect the call sequence. 58 AttributeSet CallerAttrs = F->getAttributes(); 59 if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex) 60 .removeAttribute(Attribute::NoAlias).hasAttributes()) 61 return false; 62 63 // It's not safe to eliminate the sign / zero extension of the return value. 64 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || 65 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) 66 return false; 67 68 // Check if the only use is a function return node. 69 return isUsedByReturnOnly(Node, Chain); 70 } 71 72 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 73 const uint32_t *CallerPreservedMask, 74 const SmallVectorImpl<CCValAssign> &ArgLocs, 75 const SmallVectorImpl<SDValue> &OutVals) const { 76 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 77 const CCValAssign &ArgLoc = ArgLocs[I]; 78 if (!ArgLoc.isRegLoc()) 79 continue; 80 unsigned Reg = ArgLoc.getLocReg(); 81 // Only look at callee saved registers. 82 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 83 continue; 84 // Check that we pass the value used for the caller. 85 // (We look for a CopyFromReg reading a virtual register that is used 86 // for the function live-in value of register Reg) 87 SDValue Value = OutVals[I]; 88 if (Value->getOpcode() != ISD::CopyFromReg) 89 return false; 90 unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 91 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 92 return false; 93 } 94 return true; 95 } 96 97 /// \brief Set CallLoweringInfo attribute flags based on a call instruction 98 /// and called function attributes. 99 void TargetLowering::ArgListEntry::setAttributes(ImmutableCallSite *CS, 100 unsigned AttrIdx) { 101 isSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt); 102 isZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt); 103 isInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg); 104 isSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet); 105 isNest = CS->paramHasAttr(AttrIdx, Attribute::Nest); 106 isByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal); 107 isInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca); 108 isReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned); 109 isSwiftSelf = CS->paramHasAttr(AttrIdx, Attribute::SwiftSelf); 110 isSwiftError = CS->paramHasAttr(AttrIdx, Attribute::SwiftError); 111 Alignment = CS->getParamAlignment(AttrIdx); 112 } 113 114 /// Generate a libcall taking the given operands as arguments and returning a 115 /// result of type RetVT. 116 std::pair<SDValue, SDValue> 117 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 118 ArrayRef<SDValue> Ops, bool isSigned, 119 const SDLoc &dl, bool doesNotReturn, 120 bool isReturnValueUsed) const { 121 TargetLowering::ArgListTy Args; 122 Args.reserve(Ops.size()); 123 124 TargetLowering::ArgListEntry Entry; 125 for (SDValue Op : Ops) { 126 Entry.Node = Op; 127 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 128 Entry.isSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned); 129 Entry.isZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned); 130 Args.push_back(Entry); 131 } 132 133 if (LC == RTLIB::UNKNOWN_LIBCALL) 134 report_fatal_error("Unsupported library call operation!"); 135 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 136 getPointerTy(DAG.getDataLayout())); 137 138 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 139 TargetLowering::CallLoweringInfo CLI(DAG); 140 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned); 141 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()) 142 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 143 .setNoReturn(doesNotReturn).setDiscardResult(!isReturnValueUsed) 144 .setSExtResult(signExtend).setZExtResult(!signExtend); 145 return LowerCallTo(CLI); 146 } 147 148 /// Soften the operands of a comparison. This code is shared among BR_CC, 149 /// SELECT_CC, and SETCC handlers. 150 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 151 SDValue &NewLHS, SDValue &NewRHS, 152 ISD::CondCode &CCCode, 153 const SDLoc &dl) const { 154 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 155 && "Unsupported setcc type!"); 156 157 // Expand into one or more soft-fp libcall(s). 158 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 159 bool ShouldInvertCC = false; 160 switch (CCCode) { 161 case ISD::SETEQ: 162 case ISD::SETOEQ: 163 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 164 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 165 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 166 break; 167 case ISD::SETNE: 168 case ISD::SETUNE: 169 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 170 (VT == MVT::f64) ? RTLIB::UNE_F64 : 171 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 172 break; 173 case ISD::SETGE: 174 case ISD::SETOGE: 175 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 176 (VT == MVT::f64) ? RTLIB::OGE_F64 : 177 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 178 break; 179 case ISD::SETLT: 180 case ISD::SETOLT: 181 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 182 (VT == MVT::f64) ? RTLIB::OLT_F64 : 183 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 184 break; 185 case ISD::SETLE: 186 case ISD::SETOLE: 187 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 188 (VT == MVT::f64) ? RTLIB::OLE_F64 : 189 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 190 break; 191 case ISD::SETGT: 192 case ISD::SETOGT: 193 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 194 (VT == MVT::f64) ? RTLIB::OGT_F64 : 195 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 196 break; 197 case ISD::SETUO: 198 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 199 (VT == MVT::f64) ? RTLIB::UO_F64 : 200 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 201 break; 202 case ISD::SETO: 203 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : 204 (VT == MVT::f64) ? RTLIB::O_F64 : 205 (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128; 206 break; 207 case ISD::SETONE: 208 // SETONE = SETOLT | SETOGT 209 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 210 (VT == MVT::f64) ? RTLIB::OLT_F64 : 211 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 212 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 213 (VT == MVT::f64) ? RTLIB::OGT_F64 : 214 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 215 break; 216 case ISD::SETUEQ: 217 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 218 (VT == MVT::f64) ? RTLIB::UO_F64 : 219 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 220 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 221 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 222 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 223 break; 224 default: 225 // Invert CC for unordered comparisons 226 ShouldInvertCC = true; 227 switch (CCCode) { 228 case ISD::SETULT: 229 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 230 (VT == MVT::f64) ? RTLIB::OGE_F64 : 231 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 232 break; 233 case ISD::SETULE: 234 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 235 (VT == MVT::f64) ? RTLIB::OGT_F64 : 236 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 237 break; 238 case ISD::SETUGT: 239 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 240 (VT == MVT::f64) ? RTLIB::OLE_F64 : 241 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 242 break; 243 case ISD::SETUGE: 244 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 245 (VT == MVT::f64) ? RTLIB::OLT_F64 : 246 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 247 break; 248 default: llvm_unreachable("Do not know how to soften this setcc!"); 249 } 250 } 251 252 // Use the target specific return value for comparions lib calls. 253 EVT RetVT = getCmpLibcallReturnType(); 254 SDValue Ops[2] = {NewLHS, NewRHS}; 255 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/, 256 dl).first; 257 NewRHS = DAG.getConstant(0, dl, RetVT); 258 259 CCCode = getCmpLibcallCC(LC1); 260 if (ShouldInvertCC) 261 CCCode = getSetCCInverse(CCCode, /*isInteger=*/true); 262 263 if (LC2 != RTLIB::UNKNOWN_LIBCALL) { 264 SDValue Tmp = DAG.getNode( 265 ISD::SETCC, dl, 266 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT), 267 NewLHS, NewRHS, DAG.getCondCode(CCCode)); 268 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/, 269 dl).first; 270 NewLHS = DAG.getNode( 271 ISD::SETCC, dl, 272 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT), 273 NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2))); 274 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS); 275 NewRHS = SDValue(); 276 } 277 } 278 279 /// Return the entry encoding for a jump table in the current function. The 280 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 281 unsigned TargetLowering::getJumpTableEncoding() const { 282 // In non-pic modes, just use the address of a block. 283 if (!isPositionIndependent()) 284 return MachineJumpTableInfo::EK_BlockAddress; 285 286 // In PIC mode, if the target supports a GPRel32 directive, use it. 287 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 288 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 289 290 // Otherwise, use a label difference. 291 return MachineJumpTableInfo::EK_LabelDifference32; 292 } 293 294 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 295 SelectionDAG &DAG) const { 296 // If our PIC model is GP relative, use the global offset table as the base. 297 unsigned JTEncoding = getJumpTableEncoding(); 298 299 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 300 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 301 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 302 303 return Table; 304 } 305 306 /// This returns the relocation base for the given PIC jumptable, the same as 307 /// getPICJumpTableRelocBase, but as an MCExpr. 308 const MCExpr * 309 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 310 unsigned JTI,MCContext &Ctx) const{ 311 // The normal PIC reloc base is the label at the start of the jump table. 312 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 313 } 314 315 bool 316 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 317 const TargetMachine &TM = getTargetMachine(); 318 const GlobalValue *GV = GA->getGlobal(); 319 320 // If the address is not even local to this DSO we will have to load it from 321 // a got and then add the offset. 322 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 323 return false; 324 325 // If the code is position independent we will have to add a base register. 326 if (isPositionIndependent()) 327 return false; 328 329 // Otherwise we can do it. 330 return true; 331 } 332 333 //===----------------------------------------------------------------------===// 334 // Optimization Methods 335 //===----------------------------------------------------------------------===// 336 337 /// If the specified instruction has a constant integer operand and there are 338 /// bits set in that constant that are not demanded, then clear those bits and 339 /// return true. 340 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant( 341 SDValue Op, const APInt &Demanded) { 342 SDLoc DL(Op); 343 unsigned Opcode = Op.getOpcode(); 344 345 // FIXME: ISD::SELECT, ISD::SELECT_CC 346 switch (Opcode) { 347 default: 348 break; 349 case ISD::XOR: 350 case ISD::AND: 351 case ISD::OR: { 352 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 353 if (!Op1C) 354 return false; 355 356 // If this is a 'not' op, don't touch it because that's a canonical form. 357 const APInt &C = Op1C->getAPIntValue(); 358 if (Opcode == ISD::XOR && (C | ~Demanded).isAllOnesValue()) 359 return false; 360 361 if (C.intersects(~Demanded)) { 362 EVT VT = Op.getValueType(); 363 SDValue NewC = DAG.getConstant(Demanded & C, DL, VT); 364 SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 365 return CombineTo(Op, NewOp); 366 } 367 368 break; 369 } 370 } 371 372 return false; 373 } 374 375 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 376 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 377 /// generalized for targets with other types of implicit widening casts. 378 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op, 379 unsigned BitWidth, 380 const APInt &Demanded, 381 const SDLoc &dl) { 382 assert(Op.getNumOperands() == 2 && 383 "ShrinkDemandedOp only supports binary operators!"); 384 assert(Op.getNode()->getNumValues() == 1 && 385 "ShrinkDemandedOp only supports nodes with one result!"); 386 387 // Early return, as this function cannot handle vector types. 388 if (Op.getValueType().isVector()) 389 return false; 390 391 // Don't do this if the node has another user, which may require the 392 // full value. 393 if (!Op.getNode()->hasOneUse()) 394 return false; 395 396 // Search for the smallest integer type with free casts to and from 397 // Op's type. For expedience, just check power-of-2 integer types. 398 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 399 unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros(); 400 unsigned SmallVTBits = DemandedSize; 401 if (!isPowerOf2_32(SmallVTBits)) 402 SmallVTBits = NextPowerOf2(SmallVTBits); 403 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 404 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 405 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 406 TLI.isZExtFree(SmallVT, Op.getValueType())) { 407 // We found a type with free casts. 408 SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT, 409 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, 410 Op.getNode()->getOperand(0)), 411 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, 412 Op.getNode()->getOperand(1))); 413 bool NeedZext = DemandedSize > SmallVTBits; 414 SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, 415 dl, Op.getValueType(), X); 416 return CombineTo(Op, Z); 417 } 418 } 419 return false; 420 } 421 422 bool 423 TargetLowering::TargetLoweringOpt::SimplifyDemandedBits(SDNode *User, 424 unsigned OpIdx, 425 const APInt &Demanded, 426 DAGCombinerInfo &DCI) { 427 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 428 SDValue Op = User->getOperand(OpIdx); 429 APInt KnownZero, KnownOne; 430 431 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, 432 *this, 0, true)) 433 return false; 434 435 436 // Old will not always be the same as Op. For example: 437 // 438 // Demanded = 0xffffff 439 // Op = i64 truncate (i32 and x, 0xffffff) 440 // In this case simplify demand bits will want to replace the 'and' node 441 // with the value 'x', which will give us: 442 // Old = i32 and x, 0xffffff 443 // New = x 444 if (Old.hasOneUse()) { 445 // For the one use case, we just commit the change. 446 DCI.CommitTargetLoweringOpt(*this); 447 return true; 448 } 449 450 // If Old has more than one use then it must be Op, because the 451 // AssumeSingleUse flag is not propogated to recursive calls of 452 // SimplifyDemanded bits, so the only node with multiple use that 453 // it will attempt to combine will be opt. 454 assert(Old == Op); 455 456 SmallVector <SDValue, 4> NewOps; 457 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 458 if (i == OpIdx) { 459 NewOps.push_back(New); 460 continue; 461 } 462 NewOps.push_back(User->getOperand(i)); 463 } 464 DAG.UpdateNodeOperands(User, NewOps); 465 // Op has less users now, so we may be able to perform additional combines 466 // with it. 467 DCI.AddToWorklist(Op.getNode()); 468 // User's operands have been updated, so we may be able to do new combines 469 // with it. 470 DCI.AddToWorklist(User); 471 return true; 472 } 473 474 /// Look at Op. At this point, we know that only the DemandedMask bits of the 475 /// result of Op are ever used downstream. If we can use this information to 476 /// simplify Op, create a new simplified DAG node and return true, returning the 477 /// original and new nodes in Old and New. Otherwise, analyze the expression and 478 /// return a mask of KnownOne and KnownZero bits for the expression (used to 479 /// simplify the caller). The KnownZero/One bits may only be accurate for those 480 /// bits in the DemandedMask. 481 bool TargetLowering::SimplifyDemandedBits(SDValue Op, 482 const APInt &DemandedMask, 483 APInt &KnownZero, 484 APInt &KnownOne, 485 TargetLoweringOpt &TLO, 486 unsigned Depth, 487 bool AssumeSingleUse) const { 488 unsigned BitWidth = DemandedMask.getBitWidth(); 489 assert(Op.getScalarValueSizeInBits() == BitWidth && 490 "Mask size mismatches value type size!"); 491 APInt NewMask = DemandedMask; 492 SDLoc dl(Op); 493 auto &DL = TLO.DAG.getDataLayout(); 494 495 // Don't know anything. 496 KnownZero = KnownOne = APInt(BitWidth, 0); 497 498 // Other users may use these bits. 499 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 500 if (Depth != 0) { 501 // If not at the root, Just compute the KnownZero/KnownOne bits to 502 // simplify things downstream. 503 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth); 504 return false; 505 } 506 // If this is the root being simplified, allow it to have multiple uses, 507 // just set the NewMask to all bits. 508 NewMask = APInt::getAllOnesValue(BitWidth); 509 } else if (DemandedMask == 0) { 510 // Not demanding any bits from Op. 511 if (!Op.isUndef()) 512 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType())); 513 return false; 514 } else if (Depth == 6) { // Limit search depth. 515 return false; 516 } 517 518 APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut; 519 switch (Op.getOpcode()) { 520 case ISD::Constant: 521 // We know all of the bits for a constant! 522 KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue(); 523 KnownZero = ~KnownOne; 524 return false; // Don't fall through, will infinitely loop. 525 case ISD::BUILD_VECTOR: 526 // Collect the known bits that are shared by every constant vector element. 527 KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth); 528 for (SDValue SrcOp : Op->ops()) { 529 if (!isa<ConstantSDNode>(SrcOp)) { 530 // We can only handle all constant values - bail out with no known bits. 531 KnownZero = KnownOne = APInt(BitWidth, 0); 532 return false; 533 } 534 KnownOne2 = cast<ConstantSDNode>(SrcOp)->getAPIntValue(); 535 KnownZero2 = ~KnownOne2; 536 537 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 538 if (KnownOne2.getBitWidth() != BitWidth) { 539 assert(KnownOne2.getBitWidth() > BitWidth && 540 KnownZero2.getBitWidth() > BitWidth && 541 "Expected BUILD_VECTOR implicit truncation"); 542 KnownOne2 = KnownOne2.trunc(BitWidth); 543 KnownZero2 = KnownZero2.trunc(BitWidth); 544 } 545 546 // Known bits are the values that are shared by every element. 547 // TODO: support per-element known bits. 548 KnownOne &= KnownOne2; 549 KnownZero &= KnownZero2; 550 } 551 return false; // Don't fall through, will infinitely loop. 552 case ISD::AND: 553 // If the RHS is a constant, check to see if the LHS would be zero without 554 // using the bits from the RHS. Below, we use knowledge about the RHS to 555 // simplify the LHS, here we're using information from the LHS to simplify 556 // the RHS. 557 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 558 SDValue Op0 = Op.getOperand(0); 559 APInt LHSZero, LHSOne; 560 // Do not increment Depth here; that can cause an infinite loop. 561 TLO.DAG.computeKnownBits(Op0, LHSZero, LHSOne, Depth); 562 // If the LHS already has zeros where RHSC does, this and is dead. 563 if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask)) 564 return TLO.CombineTo(Op, Op0); 565 566 // If any of the set bits in the RHS are known zero on the LHS, shrink 567 // the constant. 568 if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask)) 569 return true; 570 571 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 572 // constant, but if this 'and' is only clearing bits that were just set by 573 // the xor, then this 'and' can be eliminated by shrinking the mask of 574 // the xor. For example, for a 32-bit X: 575 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 576 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 577 LHSOne == ~RHSC->getAPIntValue()) { 578 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, Op.getValueType(), 579 Op0.getOperand(0), Op.getOperand(1)); 580 return TLO.CombineTo(Op, Xor); 581 } 582 } 583 584 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 585 KnownOne, TLO, Depth+1)) 586 return true; 587 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 588 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask, 589 KnownZero2, KnownOne2, TLO, Depth+1)) 590 return true; 591 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 592 593 // If all of the demanded bits are known one on one side, return the other. 594 // These bits cannot contribute to the result of the 'and'. 595 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask)) 596 return TLO.CombineTo(Op, Op.getOperand(0)); 597 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask)) 598 return TLO.CombineTo(Op, Op.getOperand(1)); 599 // If all of the demanded bits in the inputs are known zeros, return zero. 600 if ((NewMask & (KnownZero|KnownZero2)) == NewMask) 601 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType())); 602 // If the RHS is a constant, see if we can simplify it. 603 if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask)) 604 return true; 605 // If the operation can be done in a smaller type, do so. 606 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 607 return true; 608 609 // Output known-1 bits are only known if set in both the LHS & RHS. 610 KnownOne &= KnownOne2; 611 // Output known-0 are known to be clear if zero in either the LHS | RHS. 612 KnownZero |= KnownZero2; 613 break; 614 case ISD::OR: 615 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 616 KnownOne, TLO, Depth+1)) 617 return true; 618 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 619 if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask, 620 KnownZero2, KnownOne2, TLO, Depth+1)) 621 return true; 622 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 623 624 // If all of the demanded bits are known zero on one side, return the other. 625 // These bits cannot contribute to the result of the 'or'. 626 if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask)) 627 return TLO.CombineTo(Op, Op.getOperand(0)); 628 if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask)) 629 return TLO.CombineTo(Op, Op.getOperand(1)); 630 // If all of the potentially set bits on one side are known to be set on 631 // the other side, just use the 'other' side. 632 if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask)) 633 return TLO.CombineTo(Op, Op.getOperand(0)); 634 if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask)) 635 return TLO.CombineTo(Op, Op.getOperand(1)); 636 // If the RHS is a constant, see if we can simplify it. 637 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 638 return true; 639 // If the operation can be done in a smaller type, do so. 640 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 641 return true; 642 643 // Output known-0 bits are only known if clear in both the LHS & RHS. 644 KnownZero &= KnownZero2; 645 // Output known-1 are known to be set if set in either the LHS | RHS. 646 KnownOne |= KnownOne2; 647 break; 648 case ISD::XOR: 649 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero, 650 KnownOne, TLO, Depth+1)) 651 return true; 652 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 653 if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2, 654 KnownOne2, TLO, Depth+1)) 655 return true; 656 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 657 658 // If all of the demanded bits are known zero on one side, return the other. 659 // These bits cannot contribute to the result of the 'xor'. 660 if ((KnownZero & NewMask) == NewMask) 661 return TLO.CombineTo(Op, Op.getOperand(0)); 662 if ((KnownZero2 & NewMask) == NewMask) 663 return TLO.CombineTo(Op, Op.getOperand(1)); 664 // If the operation can be done in a smaller type, do so. 665 if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) 666 return true; 667 668 // If all of the unknown bits are known to be zero on one side or the other 669 // (but not both) turn this into an *inclusive* or. 670 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 671 if ((NewMask & ~KnownZero & ~KnownZero2) == 0) 672 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(), 673 Op.getOperand(0), 674 Op.getOperand(1))); 675 676 // Output known-0 bits are known if clear or set in both the LHS & RHS. 677 KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2); 678 // Output known-1 are known to be set if set in only one of the LHS, RHS. 679 KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2); 680 681 // If all of the demanded bits on one side are known, and all of the set 682 // bits on that side are also known to be set on the other side, turn this 683 // into an AND, as we know the bits will be cleared. 684 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 685 // NB: it is okay if more bits are known than are requested 686 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side 687 if (KnownOne == KnownOne2) { // set bits are the same on both sides 688 EVT VT = Op.getValueType(); 689 SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT); 690 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, 691 Op.getOperand(0), ANDC)); 692 } 693 } 694 695 // If the RHS is a constant, see if we can simplify it. 696 // for XOR, we prefer to force bits to 1 if they will make a -1. 697 // If we can't force bits, try to shrink the constant. 698 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 699 APInt Expanded = C->getAPIntValue() | (~NewMask); 700 // If we can expand it to have all bits set, do it. 701 if (Expanded.isAllOnesValue()) { 702 if (Expanded != C->getAPIntValue()) { 703 EVT VT = Op.getValueType(); 704 SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0), 705 TLO.DAG.getConstant(Expanded, dl, VT)); 706 return TLO.CombineTo(Op, New); 707 } 708 // If it already has all the bits set, nothing to change 709 // but don't shrink either! 710 } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) { 711 return true; 712 } 713 } 714 715 KnownZero = KnownZeroOut; 716 KnownOne = KnownOneOut; 717 break; 718 case ISD::SELECT: 719 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero, 720 KnownOne, TLO, Depth+1)) 721 return true; 722 if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2, 723 KnownOne2, TLO, Depth+1)) 724 return true; 725 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 726 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 727 728 // If the operands are constants, see if we can simplify them. 729 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 730 return true; 731 732 // Only known if known in both the LHS and RHS. 733 KnownOne &= KnownOne2; 734 KnownZero &= KnownZero2; 735 break; 736 case ISD::SELECT_CC: 737 if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero, 738 KnownOne, TLO, Depth+1)) 739 return true; 740 if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2, 741 KnownOne2, TLO, Depth+1)) 742 return true; 743 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 744 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 745 746 // If the operands are constants, see if we can simplify them. 747 if (TLO.ShrinkDemandedConstant(Op, NewMask)) 748 return true; 749 750 // Only known if known in both the LHS and RHS. 751 KnownOne &= KnownOne2; 752 KnownZero &= KnownZero2; 753 break; 754 case ISD::SETCC: { 755 SDValue Op0 = Op.getOperand(0); 756 SDValue Op1 = Op.getOperand(1); 757 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 758 // If (1) we only need the sign-bit, (2) the setcc operands are the same 759 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 760 // -1, we may be able to bypass the setcc. 761 if (NewMask.isSignBit() && Op0.getScalarValueSizeInBits() == BitWidth && 762 getBooleanContents(Op.getValueType()) == 763 BooleanContent::ZeroOrNegativeOneBooleanContent) { 764 // If we're testing X < 0, then this compare isn't needed - just use X! 765 // FIXME: We're limiting to integer types here, but this should also work 766 // if we don't care about FP signed-zero. The use of SETLT with FP means 767 // that we don't care about NaNs. 768 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 769 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 770 return TLO.CombineTo(Op, Op0); 771 772 // TODO: Should we check for other forms of sign-bit comparisons? 773 // Examples: X <= -1, X >= 0 774 } 775 break; 776 } 777 case ISD::SHL: 778 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 779 unsigned ShAmt = SA->getZExtValue(); 780 SDValue InOp = Op.getOperand(0); 781 782 // If the shift count is an invalid immediate, don't do anything. 783 if (ShAmt >= BitWidth) 784 break; 785 786 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 787 // single shift. We can do this if the bottom bits (which are shifted 788 // out) are never demanded. 789 if (InOp.getOpcode() == ISD::SRL && 790 isa<ConstantSDNode>(InOp.getOperand(1))) { 791 if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) { 792 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue(); 793 unsigned Opc = ISD::SHL; 794 int Diff = ShAmt-C1; 795 if (Diff < 0) { 796 Diff = -Diff; 797 Opc = ISD::SRL; 798 } 799 800 SDValue NewSA = 801 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType()); 802 EVT VT = Op.getValueType(); 803 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, 804 InOp.getOperand(0), NewSA)); 805 } 806 } 807 808 if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt), 809 KnownZero, KnownOne, TLO, Depth+1)) 810 return true; 811 812 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 813 // are not demanded. This will likely allow the anyext to be folded away. 814 if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) { 815 SDValue InnerOp = InOp.getNode()->getOperand(0); 816 EVT InnerVT = InnerOp.getValueType(); 817 unsigned InnerBits = InnerVT.getSizeInBits(); 818 if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 && 819 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 820 EVT ShTy = getShiftAmountTy(InnerVT, DL); 821 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 822 ShTy = InnerVT; 823 SDValue NarrowShl = 824 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 825 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 826 return 827 TLO.CombineTo(Op, 828 TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), 829 NarrowShl)); 830 } 831 // Repeat the SHL optimization above in cases where an extension 832 // intervenes: (shl (anyext (shr x, c1)), c2) to 833 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 834 // aren't demanded (as above) and that the shifted upper c1 bits of 835 // x aren't demanded. 836 if (InOp.hasOneUse() && 837 InnerOp.getOpcode() == ISD::SRL && 838 InnerOp.hasOneUse() && 839 isa<ConstantSDNode>(InnerOp.getOperand(1))) { 840 uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1)) 841 ->getZExtValue(); 842 if (InnerShAmt < ShAmt && 843 InnerShAmt < InnerBits && 844 NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 && 845 NewMask.trunc(ShAmt) == 0) { 846 SDValue NewSA = 847 TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, 848 Op.getOperand(1).getValueType()); 849 EVT VT = Op.getValueType(); 850 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 851 InnerOp.getOperand(0)); 852 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, 853 NewExt, NewSA)); 854 } 855 } 856 } 857 858 KnownZero <<= SA->getZExtValue(); 859 KnownOne <<= SA->getZExtValue(); 860 // low bits known zero. 861 KnownZero |= APInt::getLowBitsSet(BitWidth, SA->getZExtValue()); 862 } 863 break; 864 case ISD::SRL: 865 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 866 EVT VT = Op.getValueType(); 867 unsigned ShAmt = SA->getZExtValue(); 868 unsigned VTSize = VT.getSizeInBits(); 869 SDValue InOp = Op.getOperand(0); 870 871 // If the shift count is an invalid immediate, don't do anything. 872 if (ShAmt >= BitWidth) 873 break; 874 875 APInt InDemandedMask = (NewMask << ShAmt); 876 877 // If the shift is exact, then it does demand the low bits (and knows that 878 // they are zero). 879 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact()) 880 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt); 881 882 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 883 // single shift. We can do this if the top bits (which are shifted out) 884 // are never demanded. 885 if (InOp.getOpcode() == ISD::SHL && 886 isa<ConstantSDNode>(InOp.getOperand(1))) { 887 if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) { 888 unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue(); 889 unsigned Opc = ISD::SRL; 890 int Diff = ShAmt-C1; 891 if (Diff < 0) { 892 Diff = -Diff; 893 Opc = ISD::SHL; 894 } 895 896 SDValue NewSA = 897 TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType()); 898 return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, 899 InOp.getOperand(0), NewSA)); 900 } 901 } 902 903 // Compute the new bits that are at the top now. 904 if (SimplifyDemandedBits(InOp, InDemandedMask, 905 KnownZero, KnownOne, TLO, Depth+1)) 906 return true; 907 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 908 KnownZero = KnownZero.lshr(ShAmt); 909 KnownOne = KnownOne.lshr(ShAmt); 910 911 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 912 KnownZero |= HighBits; // High bits known zero. 913 } 914 break; 915 case ISD::SRA: 916 // If this is an arithmetic shift right and only the low-bit is set, we can 917 // always convert this into a logical shr, even if the shift amount is 918 // variable. The low bit of the shift cannot be an input sign bit unless 919 // the shift amount is >= the size of the datatype, which is undefined. 920 if (NewMask == 1) 921 return TLO.CombineTo(Op, 922 TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(), 923 Op.getOperand(0), Op.getOperand(1))); 924 925 if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 926 EVT VT = Op.getValueType(); 927 unsigned ShAmt = SA->getZExtValue(); 928 929 // If the shift count is an invalid immediate, don't do anything. 930 if (ShAmt >= BitWidth) 931 break; 932 933 APInt InDemandedMask = (NewMask << ShAmt); 934 935 // If the shift is exact, then it does demand the low bits (and knows that 936 // they are zero). 937 if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact()) 938 InDemandedMask |= APInt::getLowBitsSet(BitWidth, ShAmt); 939 940 // If any of the demanded bits are produced by the sign extension, we also 941 // demand the input sign bit. 942 APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt); 943 if (HighBits.intersects(NewMask)) 944 InDemandedMask |= APInt::getSignBit(VT.getScalarSizeInBits()); 945 946 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask, 947 KnownZero, KnownOne, TLO, Depth+1)) 948 return true; 949 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 950 KnownZero = KnownZero.lshr(ShAmt); 951 KnownOne = KnownOne.lshr(ShAmt); 952 953 // Handle the sign bit, adjusted to where it is now in the mask. 954 APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt); 955 956 // If the input sign bit is known to be zero, or if none of the top bits 957 // are demanded, turn this into an unsigned shift right. 958 if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) { 959 SDNodeFlags Flags; 960 Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact()); 961 return TLO.CombineTo(Op, 962 TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0), 963 Op.getOperand(1), &Flags)); 964 } 965 966 int Log2 = NewMask.exactLogBase2(); 967 if (Log2 >= 0) { 968 // The bit must come from the sign. 969 SDValue NewSA = 970 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, 971 Op.getOperand(1).getValueType()); 972 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, 973 Op.getOperand(0), NewSA)); 974 } 975 976 if (KnownOne.intersects(SignBit)) 977 // New bits are known one. 978 KnownOne |= HighBits; 979 } 980 break; 981 case ISD::SIGN_EXTEND_INREG: { 982 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 983 984 APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1); 985 // If we only care about the highest bit, don't bother shifting right. 986 if (MsbMask == NewMask) { 987 unsigned ShAmt = ExVT.getScalarSizeInBits(); 988 SDValue InOp = Op.getOperand(0); 989 unsigned VTBits = Op->getValueType(0).getScalarSizeInBits(); 990 bool AlreadySignExtended = 991 TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1; 992 // However if the input is already sign extended we expect the sign 993 // extension to be dropped altogether later and do not simplify. 994 if (!AlreadySignExtended) { 995 // Compute the correct shift amount type, which must be getShiftAmountTy 996 // for scalar types after legalization. 997 EVT ShiftAmtTy = Op.getValueType(); 998 if (TLO.LegalTypes() && !ShiftAmtTy.isVector()) 999 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL); 1000 1001 SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl, 1002 ShiftAmtTy); 1003 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, 1004 Op.getValueType(), InOp, 1005 ShiftAmt)); 1006 } 1007 } 1008 1009 // Sign extension. Compute the demanded bits in the result that are not 1010 // present in the input. 1011 APInt NewBits = 1012 APInt::getHighBitsSet(BitWidth, 1013 BitWidth - ExVT.getScalarSizeInBits()); 1014 1015 // If none of the extended bits are demanded, eliminate the sextinreg. 1016 if ((NewBits & NewMask) == 0) 1017 return TLO.CombineTo(Op, Op.getOperand(0)); 1018 1019 APInt InSignBit = 1020 APInt::getSignBit(ExVT.getScalarSizeInBits()).zext(BitWidth); 1021 APInt InputDemandedBits = 1022 APInt::getLowBitsSet(BitWidth, 1023 ExVT.getScalarSizeInBits()) & 1024 NewMask; 1025 1026 // Since the sign extended bits are demanded, we know that the sign 1027 // bit is demanded. 1028 InputDemandedBits |= InSignBit; 1029 1030 if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits, 1031 KnownZero, KnownOne, TLO, Depth+1)) 1032 return true; 1033 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1034 1035 // If the sign bit of the input is known set or clear, then we know the 1036 // top bits of the result. 1037 1038 // If the input sign bit is known zero, convert this into a zero extension. 1039 if (KnownZero.intersects(InSignBit)) 1040 return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg( 1041 Op.getOperand(0), dl, ExVT.getScalarType())); 1042 1043 if (KnownOne.intersects(InSignBit)) { // Input sign bit known set 1044 KnownOne |= NewBits; 1045 KnownZero &= ~NewBits; 1046 } else { // Input sign bit unknown 1047 KnownZero &= ~NewBits; 1048 KnownOne &= ~NewBits; 1049 } 1050 break; 1051 } 1052 case ISD::BUILD_PAIR: { 1053 EVT HalfVT = Op.getOperand(0).getValueType(); 1054 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 1055 1056 APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 1057 APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 1058 1059 APInt KnownZeroLo, KnownOneLo; 1060 APInt KnownZeroHi, KnownOneHi; 1061 1062 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo, 1063 KnownOneLo, TLO, Depth + 1)) 1064 return true; 1065 1066 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi, 1067 KnownOneHi, TLO, Depth + 1)) 1068 return true; 1069 1070 KnownZero = KnownZeroLo.zext(BitWidth) | 1071 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth); 1072 1073 KnownOne = KnownOneLo.zext(BitWidth) | 1074 KnownOneHi.zext(BitWidth).shl(HalfBitWidth); 1075 break; 1076 } 1077 case ISD::ZERO_EXTEND: { 1078 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 1079 APInt InMask = NewMask.trunc(OperandBitWidth); 1080 1081 // If none of the top bits are demanded, convert this into an any_extend. 1082 APInt NewBits = 1083 APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask; 1084 if (!NewBits.intersects(NewMask)) 1085 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, 1086 Op.getValueType(), 1087 Op.getOperand(0))); 1088 1089 if (SimplifyDemandedBits(Op.getOperand(0), InMask, 1090 KnownZero, KnownOne, TLO, Depth+1)) 1091 return true; 1092 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1093 KnownZero = KnownZero.zext(BitWidth); 1094 KnownOne = KnownOne.zext(BitWidth); 1095 KnownZero |= NewBits; 1096 break; 1097 } 1098 case ISD::SIGN_EXTEND: { 1099 EVT InVT = Op.getOperand(0).getValueType(); 1100 unsigned InBits = InVT.getScalarSizeInBits(); 1101 APInt InMask = APInt::getLowBitsSet(BitWidth, InBits); 1102 APInt InSignBit = APInt::getBitsSet(BitWidth, InBits - 1, InBits); 1103 APInt NewBits = ~InMask & NewMask; 1104 1105 // If none of the top bits are demanded, convert this into an any_extend. 1106 if (NewBits == 0) 1107 return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl, 1108 Op.getValueType(), 1109 Op.getOperand(0))); 1110 1111 // Since some of the sign extended bits are demanded, we know that the sign 1112 // bit is demanded. 1113 APInt InDemandedBits = InMask & NewMask; 1114 InDemandedBits |= InSignBit; 1115 InDemandedBits = InDemandedBits.trunc(InBits); 1116 1117 if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero, 1118 KnownOne, TLO, Depth+1)) 1119 return true; 1120 KnownZero = KnownZero.zext(BitWidth); 1121 KnownOne = KnownOne.zext(BitWidth); 1122 1123 // If the sign bit is known zero, convert this to a zero extend. 1124 if (KnownZero.intersects(InSignBit)) 1125 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, 1126 Op.getValueType(), 1127 Op.getOperand(0))); 1128 1129 // If the sign bit is known one, the top bits match. 1130 if (KnownOne.intersects(InSignBit)) { 1131 KnownOne |= NewBits; 1132 assert((KnownZero & NewBits) == 0); 1133 } else { // Otherwise, top bits aren't known. 1134 assert((KnownOne & NewBits) == 0); 1135 assert((KnownZero & NewBits) == 0); 1136 } 1137 break; 1138 } 1139 case ISD::ANY_EXTEND: { 1140 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 1141 APInt InMask = NewMask.trunc(OperandBitWidth); 1142 if (SimplifyDemandedBits(Op.getOperand(0), InMask, 1143 KnownZero, KnownOne, TLO, Depth+1)) 1144 return true; 1145 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1146 KnownZero = KnownZero.zext(BitWidth); 1147 KnownOne = KnownOne.zext(BitWidth); 1148 break; 1149 } 1150 case ISD::TRUNCATE: { 1151 // Simplify the input, using demanded bit information, and compute the known 1152 // zero/one bits live out. 1153 unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits(); 1154 APInt TruncMask = NewMask.zext(OperandBitWidth); 1155 if (SimplifyDemandedBits(Op.getOperand(0), TruncMask, 1156 KnownZero, KnownOne, TLO, Depth+1)) 1157 return true; 1158 KnownZero = KnownZero.trunc(BitWidth); 1159 KnownOne = KnownOne.trunc(BitWidth); 1160 1161 // If the input is only used by this truncate, see if we can shrink it based 1162 // on the known demanded bits. 1163 if (Op.getOperand(0).getNode()->hasOneUse()) { 1164 SDValue In = Op.getOperand(0); 1165 switch (In.getOpcode()) { 1166 default: break; 1167 case ISD::SRL: 1168 // Shrink SRL by a constant if none of the high bits shifted in are 1169 // demanded. 1170 if (TLO.LegalTypes() && 1171 !isTypeDesirableForOp(ISD::SRL, Op.getValueType())) 1172 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 1173 // undesirable. 1174 break; 1175 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1)); 1176 if (!ShAmt) 1177 break; 1178 SDValue Shift = In.getOperand(1); 1179 if (TLO.LegalTypes()) { 1180 uint64_t ShVal = ShAmt->getZExtValue(); 1181 Shift = TLO.DAG.getConstant(ShVal, dl, 1182 getShiftAmountTy(Op.getValueType(), DL)); 1183 } 1184 1185 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth, 1186 OperandBitWidth - BitWidth); 1187 HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth); 1188 1189 if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) { 1190 // None of the shifted in bits are needed. Add a truncate of the 1191 // shift input, then shift it. 1192 SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl, 1193 Op.getValueType(), 1194 In.getOperand(0)); 1195 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, 1196 Op.getValueType(), 1197 NewTrunc, 1198 Shift)); 1199 } 1200 break; 1201 } 1202 } 1203 1204 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1205 break; 1206 } 1207 case ISD::AssertZext: { 1208 // AssertZext demands all of the high bits, plus any of the low bits 1209 // demanded by its users. 1210 EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1211 APInt InMask = APInt::getLowBitsSet(BitWidth, 1212 VT.getSizeInBits()); 1213 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask, 1214 KnownZero, KnownOne, TLO, Depth+1)) 1215 return true; 1216 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 1217 1218 KnownZero |= ~InMask & NewMask; 1219 break; 1220 } 1221 case ISD::BITCAST: 1222 // If this is an FP->Int bitcast and if the sign bit is the only 1223 // thing demanded, turn this into a FGETSIGN. 1224 if (!TLO.LegalOperations() && 1225 !Op.getValueType().isVector() && 1226 !Op.getOperand(0).getValueType().isVector() && 1227 NewMask == APInt::getSignBit(Op.getValueSizeInBits()) && 1228 Op.getOperand(0).getValueType().isFloatingPoint()) { 1229 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType()); 1230 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 1231 if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() && 1232 Op.getOperand(0).getValueType() != MVT::f128) { 1233 // Cannot eliminate/lower SHL for f128 yet. 1234 EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32; 1235 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 1236 // place. We expect the SHL to be eliminated by other optimizations. 1237 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0)); 1238 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 1239 if (!OpVTLegal && OpVTSizeInBits > 32) 1240 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign); 1241 unsigned ShVal = Op.getValueSizeInBits() - 1; 1242 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType()); 1243 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, 1244 Op.getValueType(), 1245 Sign, ShAmt)); 1246 } 1247 } 1248 break; 1249 case ISD::ADD: 1250 case ISD::MUL: 1251 case ISD::SUB: { 1252 // Add, Sub, and Mul don't demand any bits in positions beyond that 1253 // of the highest bit demanded of them. 1254 APInt LoMask = APInt::getLowBitsSet(BitWidth, 1255 BitWidth - NewMask.countLeadingZeros()); 1256 if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2, 1257 KnownOne2, TLO, Depth+1) || 1258 SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2, 1259 KnownOne2, TLO, Depth+1) || 1260 // See if the operation should be performed at a smaller bit width. 1261 TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) { 1262 const SDNodeFlags *Flags = Op.getNode()->getFlags(); 1263 if (Flags->hasNoSignedWrap() || Flags->hasNoUnsignedWrap()) { 1264 // Disable the nsw and nuw flags. We can no longer guarantee that we 1265 // won't wrap after simplification. 1266 SDNodeFlags NewFlags = *Flags; 1267 NewFlags.setNoSignedWrap(false); 1268 NewFlags.setNoUnsignedWrap(false); 1269 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), 1270 Op.getOperand(0), Op.getOperand(1), 1271 &NewFlags); 1272 return TLO.CombineTo(Op, NewOp); 1273 } 1274 return true; 1275 } 1276 LLVM_FALLTHROUGH; 1277 } 1278 default: 1279 // Just use computeKnownBits to compute output bits. 1280 TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth); 1281 break; 1282 } 1283 1284 // If we know the value of all of the demanded bits, return this as a 1285 // constant. 1286 if ((NewMask & (KnownZero|KnownOne)) == NewMask) { 1287 // Avoid folding to a constant if any OpaqueConstant is involved. 1288 const SDNode *N = Op.getNode(); 1289 for (SDNodeIterator I = SDNodeIterator::begin(N), 1290 E = SDNodeIterator::end(N); I != E; ++I) { 1291 SDNode *Op = *I; 1292 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 1293 if (C->isOpaque()) 1294 return false; 1295 } 1296 return TLO.CombineTo(Op, 1297 TLO.DAG.getConstant(KnownOne, dl, Op.getValueType())); 1298 } 1299 1300 return false; 1301 } 1302 1303 /// Determine which of the bits specified in Mask are known to be either zero or 1304 /// one and return them in the KnownZero/KnownOne bitsets. 1305 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 1306 APInt &KnownZero, 1307 APInt &KnownOne, 1308 const SelectionDAG &DAG, 1309 unsigned Depth) const { 1310 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1311 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1312 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1313 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1314 "Should use MaskedValueIsZero if you don't know whether Op" 1315 " is a target node!"); 1316 KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0); 1317 } 1318 1319 /// This method can be implemented by targets that want to expose additional 1320 /// information about sign bits to the DAG Combiner. 1321 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 1322 const SelectionDAG &, 1323 unsigned Depth) const { 1324 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1325 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1326 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1327 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1328 "Should use ComputeNumSignBits if you don't know whether Op" 1329 " is a target node!"); 1330 return 1; 1331 } 1332 1333 bool TargetLowering::isConstTrueVal(const SDNode *N) const { 1334 if (!N) 1335 return false; 1336 1337 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 1338 if (!CN) { 1339 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 1340 if (!BV) 1341 return false; 1342 1343 // Only interested in constant splats, we don't care about undef 1344 // elements in identifying boolean constants and getConstantSplatNode 1345 // returns NULL if all ops are undef; 1346 CN = BV->getConstantSplatNode(); 1347 if (!CN) 1348 return false; 1349 } 1350 1351 switch (getBooleanContents(N->getValueType(0))) { 1352 case UndefinedBooleanContent: 1353 return CN->getAPIntValue()[0]; 1354 case ZeroOrOneBooleanContent: 1355 return CN->isOne(); 1356 case ZeroOrNegativeOneBooleanContent: 1357 return CN->isAllOnesValue(); 1358 } 1359 1360 llvm_unreachable("Invalid boolean contents"); 1361 } 1362 1363 SDValue TargetLowering::getConstTrueVal(SelectionDAG &DAG, EVT VT, 1364 const SDLoc &DL) const { 1365 unsigned ElementWidth = VT.getScalarSizeInBits(); 1366 APInt TrueInt = 1367 getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent 1368 ? APInt(ElementWidth, 1) 1369 : APInt::getAllOnesValue(ElementWidth); 1370 return DAG.getConstant(TrueInt, DL, VT); 1371 } 1372 1373 bool TargetLowering::isConstFalseVal(const SDNode *N) const { 1374 if (!N) 1375 return false; 1376 1377 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 1378 if (!CN) { 1379 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 1380 if (!BV) 1381 return false; 1382 1383 // Only interested in constant splats, we don't care about undef 1384 // elements in identifying boolean constants and getConstantSplatNode 1385 // returns NULL if all ops are undef; 1386 CN = BV->getConstantSplatNode(); 1387 if (!CN) 1388 return false; 1389 } 1390 1391 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 1392 return !CN->getAPIntValue()[0]; 1393 1394 return CN->isNullValue(); 1395 } 1396 1397 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 1398 bool SExt) const { 1399 if (VT == MVT::i1) 1400 return N->isOne(); 1401 1402 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 1403 switch (Cnt) { 1404 case TargetLowering::ZeroOrOneBooleanContent: 1405 // An extended value of 1 is always true, unless its original type is i1, 1406 // in which case it will be sign extended to -1. 1407 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 1408 case TargetLowering::UndefinedBooleanContent: 1409 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1410 return N->isAllOnesValue() && SExt; 1411 } 1412 llvm_unreachable("Unexpected enumeration."); 1413 } 1414 1415 /// This helper function of SimplifySetCC tries to optimize the comparison when 1416 /// either operand of the SetCC node is a bitwise-and instruction. 1417 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 1418 ISD::CondCode Cond, 1419 DAGCombinerInfo &DCI, 1420 const SDLoc &DL) const { 1421 // Match these patterns in any of their permutations: 1422 // (X & Y) == Y 1423 // (X & Y) != Y 1424 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 1425 std::swap(N0, N1); 1426 1427 EVT OpVT = N0.getValueType(); 1428 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 1429 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 1430 return SDValue(); 1431 1432 SDValue X, Y; 1433 if (N0.getOperand(0) == N1) { 1434 X = N0.getOperand(1); 1435 Y = N0.getOperand(0); 1436 } else if (N0.getOperand(1) == N1) { 1437 X = N0.getOperand(0); 1438 Y = N0.getOperand(1); 1439 } else { 1440 return SDValue(); 1441 } 1442 1443 SelectionDAG &DAG = DCI.DAG; 1444 SDValue Zero = DAG.getConstant(0, DL, OpVT); 1445 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 1446 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 1447 // Note that where Y is variable and is known to have at most one bit set 1448 // (for example, if it is Z & 1) we cannot do this; the expressions are not 1449 // equivalent when Y == 0. 1450 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 1451 if (DCI.isBeforeLegalizeOps() || 1452 isCondCodeLegal(Cond, N0.getSimpleValueType())) 1453 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 1454 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 1455 // If the target supports an 'and-not' or 'and-complement' logic operation, 1456 // try to use that to make a comparison operation more efficient. 1457 // But don't do this transform if the mask is a single bit because there are 1458 // more efficient ways to deal with that case (for example, 'bt' on x86 or 1459 // 'rlwinm' on PPC). 1460 1461 // Bail out if the compare operand that we want to turn into a zero is 1462 // already a zero (otherwise, infinite loop). 1463 auto *YConst = dyn_cast<ConstantSDNode>(Y); 1464 if (YConst && YConst->isNullValue()) 1465 return SDValue(); 1466 1467 // Transform this into: ~X & Y == 0. 1468 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 1469 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 1470 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 1471 } 1472 1473 return SDValue(); 1474 } 1475 1476 /// Try to simplify a setcc built with the specified operands and cc. If it is 1477 /// unable to simplify it, return a null SDValue. 1478 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 1479 ISD::CondCode Cond, bool foldBooleans, 1480 DAGCombinerInfo &DCI, 1481 const SDLoc &dl) const { 1482 SelectionDAG &DAG = DCI.DAG; 1483 1484 // These setcc operations always fold. 1485 switch (Cond) { 1486 default: break; 1487 case ISD::SETFALSE: 1488 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT); 1489 case ISD::SETTRUE: 1490 case ISD::SETTRUE2: { 1491 TargetLowering::BooleanContent Cnt = 1492 getBooleanContents(N0->getValueType(0)); 1493 return DAG.getConstant( 1494 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl, 1495 VT); 1496 } 1497 } 1498 1499 // Ensure that the constant occurs on the RHS, and fold constant 1500 // comparisons. 1501 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 1502 if (isa<ConstantSDNode>(N0.getNode()) && 1503 (DCI.isBeforeLegalizeOps() || 1504 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 1505 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 1506 1507 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 1508 const APInt &C1 = N1C->getAPIntValue(); 1509 1510 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 1511 // equality comparison, then we're just comparing whether X itself is 1512 // zero. 1513 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) && 1514 N0.getOperand(0).getOpcode() == ISD::CTLZ && 1515 N0.getOperand(1).getOpcode() == ISD::Constant) { 1516 const APInt &ShAmt 1517 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1518 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1519 ShAmt == Log2_32(N0.getValueSizeInBits())) { 1520 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 1521 // (srl (ctlz x), 5) == 0 -> X != 0 1522 // (srl (ctlz x), 5) != 1 -> X != 0 1523 Cond = ISD::SETNE; 1524 } else { 1525 // (srl (ctlz x), 5) != 0 -> X == 0 1526 // (srl (ctlz x), 5) == 1 -> X == 0 1527 Cond = ISD::SETEQ; 1528 } 1529 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 1530 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), 1531 Zero, Cond); 1532 } 1533 } 1534 1535 SDValue CTPOP = N0; 1536 // Look through truncs that don't change the value of a ctpop. 1537 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE) 1538 CTPOP = N0.getOperand(0); 1539 1540 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP && 1541 (N0 == CTPOP || 1542 N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) { 1543 EVT CTVT = CTPOP.getValueType(); 1544 SDValue CTOp = CTPOP.getOperand(0); 1545 1546 // (ctpop x) u< 2 -> (x & x-1) == 0 1547 // (ctpop x) u> 1 -> (x & x-1) != 0 1548 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){ 1549 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp, 1550 DAG.getConstant(1, dl, CTVT)); 1551 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub); 1552 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 1553 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC); 1554 } 1555 1556 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal. 1557 } 1558 1559 // (zext x) == C --> x == (trunc C) 1560 // (sext x) == C --> x == (trunc C) 1561 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1562 DCI.isBeforeLegalize() && N0->hasOneUse()) { 1563 unsigned MinBits = N0.getValueSizeInBits(); 1564 SDValue PreExt; 1565 bool Signed = false; 1566 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 1567 // ZExt 1568 MinBits = N0->getOperand(0).getValueSizeInBits(); 1569 PreExt = N0->getOperand(0); 1570 } else if (N0->getOpcode() == ISD::AND) { 1571 // DAGCombine turns costly ZExts into ANDs 1572 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 1573 if ((C->getAPIntValue()+1).isPowerOf2()) { 1574 MinBits = C->getAPIntValue().countTrailingOnes(); 1575 PreExt = N0->getOperand(0); 1576 } 1577 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 1578 // SExt 1579 MinBits = N0->getOperand(0).getValueSizeInBits(); 1580 PreExt = N0->getOperand(0); 1581 Signed = true; 1582 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 1583 // ZEXTLOAD / SEXTLOAD 1584 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 1585 MinBits = LN0->getMemoryVT().getSizeInBits(); 1586 PreExt = N0; 1587 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 1588 Signed = true; 1589 MinBits = LN0->getMemoryVT().getSizeInBits(); 1590 PreExt = N0; 1591 } 1592 } 1593 1594 // Figure out how many bits we need to preserve this constant. 1595 unsigned ReqdBits = Signed ? 1596 C1.getBitWidth() - C1.getNumSignBits() + 1 : 1597 C1.getActiveBits(); 1598 1599 // Make sure we're not losing bits from the constant. 1600 if (MinBits > 0 && 1601 MinBits < C1.getBitWidth() && 1602 MinBits >= ReqdBits) { 1603 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 1604 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 1605 // Will get folded away. 1606 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 1607 if (MinBits == 1 && C1 == 1) 1608 // Invert the condition. 1609 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 1610 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1611 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 1612 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 1613 } 1614 1615 // If truncating the setcc operands is not desirable, we can still 1616 // simplify the expression in some cases: 1617 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 1618 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 1619 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 1620 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 1621 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 1622 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 1623 SDValue TopSetCC = N0->getOperand(0); 1624 unsigned N0Opc = N0->getOpcode(); 1625 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 1626 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 1627 TopSetCC.getOpcode() == ISD::SETCC && 1628 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 1629 (isConstFalseVal(N1C) || 1630 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 1631 1632 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) || 1633 (!N1C->isNullValue() && Cond == ISD::SETNE); 1634 1635 if (!Inverse) 1636 return TopSetCC; 1637 1638 ISD::CondCode InvCond = ISD::getSetCCInverse( 1639 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 1640 TopSetCC.getOperand(0).getValueType().isInteger()); 1641 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 1642 TopSetCC.getOperand(1), 1643 InvCond); 1644 1645 } 1646 } 1647 } 1648 1649 // If the LHS is '(and load, const)', the RHS is 0, 1650 // the test is for equality or unsigned, and all 1 bits of the const are 1651 // in the same partial word, see if we can shorten the load. 1652 if (DCI.isBeforeLegalize() && 1653 !ISD::isSignedIntSetCC(Cond) && 1654 N0.getOpcode() == ISD::AND && C1 == 0 && 1655 N0.getNode()->hasOneUse() && 1656 isa<LoadSDNode>(N0.getOperand(0)) && 1657 N0.getOperand(0).getNode()->hasOneUse() && 1658 isa<ConstantSDNode>(N0.getOperand(1))) { 1659 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 1660 APInt bestMask; 1661 unsigned bestWidth = 0, bestOffset = 0; 1662 if (!Lod->isVolatile() && Lod->isUnindexed()) { 1663 unsigned origWidth = N0.getValueSizeInBits(); 1664 unsigned maskWidth = origWidth; 1665 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 1666 // 8 bits, but have to be careful... 1667 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 1668 origWidth = Lod->getMemoryVT().getSizeInBits(); 1669 const APInt &Mask = 1670 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1671 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 1672 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 1673 for (unsigned offset=0; offset<origWidth/width; offset++) { 1674 if ((newMask & Mask) == Mask) { 1675 if (!DAG.getDataLayout().isLittleEndian()) 1676 bestOffset = (origWidth/width - offset - 1) * (width/8); 1677 else 1678 bestOffset = (uint64_t)offset * (width/8); 1679 bestMask = Mask.lshr(offset * (width/8) * 8); 1680 bestWidth = width; 1681 break; 1682 } 1683 newMask = newMask << width; 1684 } 1685 } 1686 } 1687 if (bestWidth) { 1688 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 1689 if (newVT.isRound()) { 1690 EVT PtrType = Lod->getOperand(1).getValueType(); 1691 SDValue Ptr = Lod->getBasePtr(); 1692 if (bestOffset != 0) 1693 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(), 1694 DAG.getConstant(bestOffset, dl, PtrType)); 1695 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset); 1696 SDValue NewLoad = DAG.getLoad( 1697 newVT, dl, Lod->getChain(), Ptr, 1698 Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign); 1699 return DAG.getSetCC(dl, VT, 1700 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 1701 DAG.getConstant(bestMask.trunc(bestWidth), 1702 dl, newVT)), 1703 DAG.getConstant(0LL, dl, newVT), Cond); 1704 } 1705 } 1706 } 1707 1708 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 1709 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 1710 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 1711 1712 // If the comparison constant has bits in the upper part, the 1713 // zero-extended value could never match. 1714 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 1715 C1.getBitWidth() - InSize))) { 1716 switch (Cond) { 1717 case ISD::SETUGT: 1718 case ISD::SETUGE: 1719 case ISD::SETEQ: return DAG.getConstant(0, dl, VT); 1720 case ISD::SETULT: 1721 case ISD::SETULE: 1722 case ISD::SETNE: return DAG.getConstant(1, dl, VT); 1723 case ISD::SETGT: 1724 case ISD::SETGE: 1725 // True if the sign bit of C1 is set. 1726 return DAG.getConstant(C1.isNegative(), dl, VT); 1727 case ISD::SETLT: 1728 case ISD::SETLE: 1729 // True if the sign bit of C1 isn't set. 1730 return DAG.getConstant(C1.isNonNegative(), dl, VT); 1731 default: 1732 break; 1733 } 1734 } 1735 1736 // Otherwise, we can perform the comparison with the low bits. 1737 switch (Cond) { 1738 case ISD::SETEQ: 1739 case ISD::SETNE: 1740 case ISD::SETUGT: 1741 case ISD::SETUGE: 1742 case ISD::SETULT: 1743 case ISD::SETULE: { 1744 EVT newVT = N0.getOperand(0).getValueType(); 1745 if (DCI.isBeforeLegalizeOps() || 1746 (isOperationLegal(ISD::SETCC, newVT) && 1747 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) { 1748 EVT NewSetCCVT = 1749 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT); 1750 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 1751 1752 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 1753 NewConst, Cond); 1754 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 1755 } 1756 break; 1757 } 1758 default: 1759 break; // todo, be more careful with signed comparisons 1760 } 1761 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 1762 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1763 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 1764 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 1765 EVT ExtDstTy = N0.getValueType(); 1766 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 1767 1768 // If the constant doesn't fit into the number of bits for the source of 1769 // the sign extension, it is impossible for both sides to be equal. 1770 if (C1.getMinSignedBits() > ExtSrcTyBits) 1771 return DAG.getConstant(Cond == ISD::SETNE, dl, VT); 1772 1773 SDValue ZextOp; 1774 EVT Op0Ty = N0.getOperand(0).getValueType(); 1775 if (Op0Ty == ExtSrcTy) { 1776 ZextOp = N0.getOperand(0); 1777 } else { 1778 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 1779 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0), 1780 DAG.getConstant(Imm, dl, Op0Ty)); 1781 } 1782 if (!DCI.isCalledByLegalizer()) 1783 DCI.AddToWorklist(ZextOp.getNode()); 1784 // Otherwise, make this a use of a zext. 1785 return DAG.getSetCC(dl, VT, ZextOp, 1786 DAG.getConstant(C1 & APInt::getLowBitsSet( 1787 ExtDstTyBits, 1788 ExtSrcTyBits), 1789 dl, ExtDstTy), 1790 Cond); 1791 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) && 1792 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1793 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 1794 if (N0.getOpcode() == ISD::SETCC && 1795 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) { 1796 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1); 1797 if (TrueWhenTrue) 1798 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 1799 // Invert the condition. 1800 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 1801 CC = ISD::getSetCCInverse(CC, 1802 N0.getOperand(0).getValueType().isInteger()); 1803 if (DCI.isBeforeLegalizeOps() || 1804 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 1805 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 1806 } 1807 1808 if ((N0.getOpcode() == ISD::XOR || 1809 (N0.getOpcode() == ISD::AND && 1810 N0.getOperand(0).getOpcode() == ISD::XOR && 1811 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 1812 isa<ConstantSDNode>(N0.getOperand(1)) && 1813 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) { 1814 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 1815 // can only do this if the top bits are known zero. 1816 unsigned BitWidth = N0.getValueSizeInBits(); 1817 if (DAG.MaskedValueIsZero(N0, 1818 APInt::getHighBitsSet(BitWidth, 1819 BitWidth-1))) { 1820 // Okay, get the un-inverted input value. 1821 SDValue Val; 1822 if (N0.getOpcode() == ISD::XOR) 1823 Val = N0.getOperand(0); 1824 else { 1825 assert(N0.getOpcode() == ISD::AND && 1826 N0.getOperand(0).getOpcode() == ISD::XOR); 1827 // ((X^1)&1)^1 -> X & 1 1828 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 1829 N0.getOperand(0).getOperand(0), 1830 N0.getOperand(1)); 1831 } 1832 1833 return DAG.getSetCC(dl, VT, Val, N1, 1834 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1835 } 1836 } else if (N1C->getAPIntValue() == 1 && 1837 (VT == MVT::i1 || 1838 getBooleanContents(N0->getValueType(0)) == 1839 ZeroOrOneBooleanContent)) { 1840 SDValue Op0 = N0; 1841 if (Op0.getOpcode() == ISD::TRUNCATE) 1842 Op0 = Op0.getOperand(0); 1843 1844 if ((Op0.getOpcode() == ISD::XOR) && 1845 Op0.getOperand(0).getOpcode() == ISD::SETCC && 1846 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 1847 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 1848 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 1849 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1), 1850 Cond); 1851 } 1852 if (Op0.getOpcode() == ISD::AND && 1853 isa<ConstantSDNode>(Op0.getOperand(1)) && 1854 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) { 1855 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 1856 if (Op0.getValueType().bitsGT(VT)) 1857 Op0 = DAG.getNode(ISD::AND, dl, VT, 1858 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 1859 DAG.getConstant(1, dl, VT)); 1860 else if (Op0.getValueType().bitsLT(VT)) 1861 Op0 = DAG.getNode(ISD::AND, dl, VT, 1862 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 1863 DAG.getConstant(1, dl, VT)); 1864 1865 return DAG.getSetCC(dl, VT, Op0, 1866 DAG.getConstant(0, dl, Op0.getValueType()), 1867 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1868 } 1869 if (Op0.getOpcode() == ISD::AssertZext && 1870 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 1871 return DAG.getSetCC(dl, VT, Op0, 1872 DAG.getConstant(0, dl, Op0.getValueType()), 1873 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1874 } 1875 } 1876 1877 APInt MinVal, MaxVal; 1878 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits(); 1879 if (ISD::isSignedIntSetCC(Cond)) { 1880 MinVal = APInt::getSignedMinValue(OperandBitSize); 1881 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 1882 } else { 1883 MinVal = APInt::getMinValue(OperandBitSize); 1884 MaxVal = APInt::getMaxValue(OperandBitSize); 1885 } 1886 1887 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 1888 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 1889 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true 1890 // X >= C0 --> X > (C0 - 1) 1891 APInt C = C1 - 1; 1892 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 1893 if ((DCI.isBeforeLegalizeOps() || 1894 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 1895 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 && 1896 isLegalICmpImmediate(C.getSExtValue())))) { 1897 return DAG.getSetCC(dl, VT, N0, 1898 DAG.getConstant(C, dl, N1.getValueType()), 1899 NewCC); 1900 } 1901 } 1902 1903 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 1904 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true 1905 // X <= C0 --> X < (C0 + 1) 1906 APInt C = C1 + 1; 1907 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 1908 if ((DCI.isBeforeLegalizeOps() || 1909 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 1910 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 && 1911 isLegalICmpImmediate(C.getSExtValue())))) { 1912 return DAG.getSetCC(dl, VT, N0, 1913 DAG.getConstant(C, dl, N1.getValueType()), 1914 NewCC); 1915 } 1916 } 1917 1918 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal) 1919 return DAG.getConstant(0, dl, VT); // X < MIN --> false 1920 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal) 1921 return DAG.getConstant(1, dl, VT); // X >= MIN --> true 1922 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal) 1923 return DAG.getConstant(0, dl, VT); // X > MAX --> false 1924 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal) 1925 return DAG.getConstant(1, dl, VT); // X <= MAX --> true 1926 1927 // Canonicalize setgt X, Min --> setne X, Min 1928 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal) 1929 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1930 // Canonicalize setlt X, Max --> setne X, Max 1931 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal) 1932 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1933 1934 // If we have setult X, 1, turn it into seteq X, 0 1935 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1) 1936 return DAG.getSetCC(dl, VT, N0, 1937 DAG.getConstant(MinVal, dl, N0.getValueType()), 1938 ISD::SETEQ); 1939 // If we have setugt X, Max-1, turn it into seteq X, Max 1940 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1) 1941 return DAG.getSetCC(dl, VT, N0, 1942 DAG.getConstant(MaxVal, dl, N0.getValueType()), 1943 ISD::SETEQ); 1944 1945 // If we have "setcc X, C0", check to see if we can shrink the immediate 1946 // by changing cc. 1947 1948 // SETUGT X, SINTMAX -> SETLT X, 0 1949 if (Cond == ISD::SETUGT && 1950 C1 == APInt::getSignedMaxValue(OperandBitSize)) 1951 return DAG.getSetCC(dl, VT, N0, 1952 DAG.getConstant(0, dl, N1.getValueType()), 1953 ISD::SETLT); 1954 1955 // SETULT X, SINTMIN -> SETGT X, -1 1956 if (Cond == ISD::SETULT && 1957 C1 == APInt::getSignedMinValue(OperandBitSize)) { 1958 SDValue ConstMinusOne = 1959 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl, 1960 N1.getValueType()); 1961 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT); 1962 } 1963 1964 // Fold bit comparisons when we can. 1965 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1966 (VT == N0.getValueType() || 1967 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) && 1968 N0.getOpcode() == ISD::AND) { 1969 auto &DL = DAG.getDataLayout(); 1970 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1971 EVT ShiftTy = DCI.isBeforeLegalize() 1972 ? getPointerTy(DL) 1973 : getShiftAmountTy(N0.getValueType(), DL); 1974 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 1975 // Perform the xform if the AND RHS is a single bit. 1976 if (AndRHS->getAPIntValue().isPowerOf2()) { 1977 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1978 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1979 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl, 1980 ShiftTy))); 1981 } 1982 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 1983 // (X & 8) == 8 --> (X & 8) >> 3 1984 // Perform the xform if C1 is a single bit. 1985 if (C1.isPowerOf2()) { 1986 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1987 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1988 DAG.getConstant(C1.logBase2(), dl, 1989 ShiftTy))); 1990 } 1991 } 1992 } 1993 } 1994 1995 if (C1.getMinSignedBits() <= 64 && 1996 !isLegalICmpImmediate(C1.getSExtValue())) { 1997 // (X & -256) == 256 -> (X >> 8) == 1 1998 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1999 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 2000 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2001 const APInt &AndRHSC = AndRHS->getAPIntValue(); 2002 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 2003 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 2004 auto &DL = DAG.getDataLayout(); 2005 EVT ShiftTy = DCI.isBeforeLegalize() 2006 ? getPointerTy(DL) 2007 : getShiftAmountTy(N0.getValueType(), DL); 2008 EVT CmpTy = N0.getValueType(); 2009 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0), 2010 DAG.getConstant(ShiftBits, dl, 2011 ShiftTy)); 2012 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy); 2013 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 2014 } 2015 } 2016 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 2017 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 2018 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 2019 // X < 0x100000000 -> (X >> 32) < 1 2020 // X >= 0x100000000 -> (X >> 32) >= 1 2021 // X <= 0x0ffffffff -> (X >> 32) < 1 2022 // X > 0x0ffffffff -> (X >> 32) >= 1 2023 unsigned ShiftBits; 2024 APInt NewC = C1; 2025 ISD::CondCode NewCond = Cond; 2026 if (AdjOne) { 2027 ShiftBits = C1.countTrailingOnes(); 2028 NewC = NewC + 1; 2029 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 2030 } else { 2031 ShiftBits = C1.countTrailingZeros(); 2032 } 2033 NewC = NewC.lshr(ShiftBits); 2034 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 2035 isLegalICmpImmediate(NewC.getSExtValue())) { 2036 auto &DL = DAG.getDataLayout(); 2037 EVT ShiftTy = DCI.isBeforeLegalize() 2038 ? getPointerTy(DL) 2039 : getShiftAmountTy(N0.getValueType(), DL); 2040 EVT CmpTy = N0.getValueType(); 2041 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0, 2042 DAG.getConstant(ShiftBits, dl, ShiftTy)); 2043 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy); 2044 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 2045 } 2046 } 2047 } 2048 } 2049 2050 if (isa<ConstantFPSDNode>(N0.getNode())) { 2051 // Constant fold or commute setcc. 2052 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl); 2053 if (O.getNode()) return O; 2054 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) { 2055 // If the RHS of an FP comparison is a constant, simplify it away in 2056 // some cases. 2057 if (CFP->getValueAPF().isNaN()) { 2058 // If an operand is known to be a nan, we can fold it. 2059 switch (ISD::getUnorderedFlavor(Cond)) { 2060 default: llvm_unreachable("Unknown flavor!"); 2061 case 0: // Known false. 2062 return DAG.getConstant(0, dl, VT); 2063 case 1: // Known true. 2064 return DAG.getConstant(1, dl, VT); 2065 case 2: // Undefined. 2066 return DAG.getUNDEF(VT); 2067 } 2068 } 2069 2070 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 2071 // constant if knowing that the operand is non-nan is enough. We prefer to 2072 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 2073 // materialize 0.0. 2074 if (Cond == ISD::SETO || Cond == ISD::SETUO) 2075 return DAG.getSetCC(dl, VT, N0, N0, Cond); 2076 2077 // setcc (fneg x), C -> setcc swap(pred) x, -C 2078 if (N0.getOpcode() == ISD::FNEG) { 2079 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 2080 if (DCI.isBeforeLegalizeOps() || 2081 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 2082 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 2083 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 2084 } 2085 } 2086 2087 // If the condition is not legal, see if we can find an equivalent one 2088 // which is legal. 2089 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 2090 // If the comparison was an awkward floating-point == or != and one of 2091 // the comparison operands is infinity or negative infinity, convert the 2092 // condition to a less-awkward <= or >=. 2093 if (CFP->getValueAPF().isInfinity()) { 2094 if (CFP->getValueAPF().isNegative()) { 2095 if (Cond == ISD::SETOEQ && 2096 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 2097 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE); 2098 if (Cond == ISD::SETUEQ && 2099 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 2100 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE); 2101 if (Cond == ISD::SETUNE && 2102 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 2103 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT); 2104 if (Cond == ISD::SETONE && 2105 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 2106 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT); 2107 } else { 2108 if (Cond == ISD::SETOEQ && 2109 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 2110 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE); 2111 if (Cond == ISD::SETUEQ && 2112 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 2113 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE); 2114 if (Cond == ISD::SETUNE && 2115 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 2116 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT); 2117 if (Cond == ISD::SETONE && 2118 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 2119 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT); 2120 } 2121 } 2122 } 2123 } 2124 2125 if (N0 == N1) { 2126 // The sext(setcc()) => setcc() optimization relies on the appropriate 2127 // constant being emitted. 2128 uint64_t EqVal = 0; 2129 switch (getBooleanContents(N0.getValueType())) { 2130 case UndefinedBooleanContent: 2131 case ZeroOrOneBooleanContent: 2132 EqVal = ISD::isTrueWhenEqual(Cond); 2133 break; 2134 case ZeroOrNegativeOneBooleanContent: 2135 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0; 2136 break; 2137 } 2138 2139 // We can always fold X == X for integer setcc's. 2140 if (N0.getValueType().isInteger()) { 2141 return DAG.getConstant(EqVal, dl, VT); 2142 } 2143 unsigned UOF = ISD::getUnorderedFlavor(Cond); 2144 if (UOF == 2) // FP operators that are undefined on NaNs. 2145 return DAG.getConstant(EqVal, dl, VT); 2146 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond))) 2147 return DAG.getConstant(EqVal, dl, VT); 2148 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 2149 // if it is not already. 2150 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 2151 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() || 2152 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal)) 2153 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 2154 } 2155 2156 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2157 N0.getValueType().isInteger()) { 2158 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 2159 N0.getOpcode() == ISD::XOR) { 2160 // Simplify (X+Y) == (X+Z) --> Y == Z 2161 if (N0.getOpcode() == N1.getOpcode()) { 2162 if (N0.getOperand(0) == N1.getOperand(0)) 2163 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 2164 if (N0.getOperand(1) == N1.getOperand(1)) 2165 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 2166 if (DAG.isCommutativeBinOp(N0.getOpcode())) { 2167 // If X op Y == Y op X, try other combinations. 2168 if (N0.getOperand(0) == N1.getOperand(1)) 2169 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 2170 Cond); 2171 if (N0.getOperand(1) == N1.getOperand(0)) 2172 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 2173 Cond); 2174 } 2175 } 2176 2177 // If RHS is a legal immediate value for a compare instruction, we need 2178 // to be careful about increasing register pressure needlessly. 2179 bool LegalRHSImm = false; 2180 2181 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 2182 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2183 // Turn (X+C1) == C2 --> X == C2-C1 2184 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 2185 return DAG.getSetCC(dl, VT, N0.getOperand(0), 2186 DAG.getConstant(RHSC->getAPIntValue()- 2187 LHSR->getAPIntValue(), 2188 dl, N0.getValueType()), Cond); 2189 } 2190 2191 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 2192 if (N0.getOpcode() == ISD::XOR) 2193 // If we know that all of the inverted bits are zero, don't bother 2194 // performing the inversion. 2195 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 2196 return 2197 DAG.getSetCC(dl, VT, N0.getOperand(0), 2198 DAG.getConstant(LHSR->getAPIntValue() ^ 2199 RHSC->getAPIntValue(), 2200 dl, N0.getValueType()), 2201 Cond); 2202 } 2203 2204 // Turn (C1-X) == C2 --> X == C1-C2 2205 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 2206 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 2207 return 2208 DAG.getSetCC(dl, VT, N0.getOperand(1), 2209 DAG.getConstant(SUBC->getAPIntValue() - 2210 RHSC->getAPIntValue(), 2211 dl, N0.getValueType()), 2212 Cond); 2213 } 2214 } 2215 2216 // Could RHSC fold directly into a compare? 2217 if (RHSC->getValueType(0).getSizeInBits() <= 64) 2218 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 2219 } 2220 2221 // Simplify (X+Z) == X --> Z == 0 2222 // Don't do this if X is an immediate that can fold into a cmp 2223 // instruction and X+Z has other uses. It could be an induction variable 2224 // chain, and the transform would increase register pressure. 2225 if (!LegalRHSImm || N0.getNode()->hasOneUse()) { 2226 if (N0.getOperand(0) == N1) 2227 return DAG.getSetCC(dl, VT, N0.getOperand(1), 2228 DAG.getConstant(0, dl, N0.getValueType()), Cond); 2229 if (N0.getOperand(1) == N1) { 2230 if (DAG.isCommutativeBinOp(N0.getOpcode())) 2231 return DAG.getSetCC(dl, VT, N0.getOperand(0), 2232 DAG.getConstant(0, dl, N0.getValueType()), 2233 Cond); 2234 if (N0.getNode()->hasOneUse()) { 2235 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!"); 2236 auto &DL = DAG.getDataLayout(); 2237 // (Z-X) == X --> Z == X<<1 2238 SDValue SH = DAG.getNode( 2239 ISD::SHL, dl, N1.getValueType(), N1, 2240 DAG.getConstant(1, dl, 2241 getShiftAmountTy(N1.getValueType(), DL))); 2242 if (!DCI.isCalledByLegalizer()) 2243 DCI.AddToWorklist(SH.getNode()); 2244 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond); 2245 } 2246 } 2247 } 2248 } 2249 2250 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 2251 N1.getOpcode() == ISD::XOR) { 2252 // Simplify X == (X+Z) --> Z == 0 2253 if (N1.getOperand(0) == N0) 2254 return DAG.getSetCC(dl, VT, N1.getOperand(1), 2255 DAG.getConstant(0, dl, N1.getValueType()), Cond); 2256 if (N1.getOperand(1) == N0) { 2257 if (DAG.isCommutativeBinOp(N1.getOpcode())) 2258 return DAG.getSetCC(dl, VT, N1.getOperand(0), 2259 DAG.getConstant(0, dl, N1.getValueType()), Cond); 2260 if (N1.getNode()->hasOneUse()) { 2261 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!"); 2262 auto &DL = DAG.getDataLayout(); 2263 // X == (Z-X) --> X<<1 == Z 2264 SDValue SH = DAG.getNode( 2265 ISD::SHL, dl, N1.getValueType(), N0, 2266 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL))); 2267 if (!DCI.isCalledByLegalizer()) 2268 DCI.AddToWorklist(SH.getNode()); 2269 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond); 2270 } 2271 } 2272 } 2273 2274 if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl)) 2275 return V; 2276 } 2277 2278 // Fold away ALL boolean setcc's. 2279 SDValue Temp; 2280 if (N0.getValueType() == MVT::i1 && foldBooleans) { 2281 switch (Cond) { 2282 default: llvm_unreachable("Unknown integer setcc!"); 2283 case ISD::SETEQ: // X == Y -> ~(X^Y) 2284 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 2285 N0 = DAG.getNOT(dl, Temp, MVT::i1); 2286 if (!DCI.isCalledByLegalizer()) 2287 DCI.AddToWorklist(Temp.getNode()); 2288 break; 2289 case ISD::SETNE: // X != Y --> (X^Y) 2290 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 2291 break; 2292 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 2293 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 2294 Temp = DAG.getNOT(dl, N0, MVT::i1); 2295 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp); 2296 if (!DCI.isCalledByLegalizer()) 2297 DCI.AddToWorklist(Temp.getNode()); 2298 break; 2299 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 2300 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 2301 Temp = DAG.getNOT(dl, N1, MVT::i1); 2302 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp); 2303 if (!DCI.isCalledByLegalizer()) 2304 DCI.AddToWorklist(Temp.getNode()); 2305 break; 2306 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 2307 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 2308 Temp = DAG.getNOT(dl, N0, MVT::i1); 2309 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp); 2310 if (!DCI.isCalledByLegalizer()) 2311 DCI.AddToWorklist(Temp.getNode()); 2312 break; 2313 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 2314 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 2315 Temp = DAG.getNOT(dl, N1, MVT::i1); 2316 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp); 2317 break; 2318 } 2319 if (VT != MVT::i1) { 2320 if (!DCI.isCalledByLegalizer()) 2321 DCI.AddToWorklist(N0.getNode()); 2322 // FIXME: If running after legalize, we probably can't do this. 2323 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0); 2324 } 2325 return N0; 2326 } 2327 2328 // Could not fold it. 2329 return SDValue(); 2330 } 2331 2332 /// Returns true (and the GlobalValue and the offset) if the node is a 2333 /// GlobalAddress + offset. 2334 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA, 2335 int64_t &Offset) const { 2336 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 2337 GA = GASD->getGlobal(); 2338 Offset += GASD->getOffset(); 2339 return true; 2340 } 2341 2342 if (N->getOpcode() == ISD::ADD) { 2343 SDValue N1 = N->getOperand(0); 2344 SDValue N2 = N->getOperand(1); 2345 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 2346 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 2347 Offset += V->getSExtValue(); 2348 return true; 2349 } 2350 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 2351 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 2352 Offset += V->getSExtValue(); 2353 return true; 2354 } 2355 } 2356 } 2357 2358 return false; 2359 } 2360 2361 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 2362 DAGCombinerInfo &DCI) const { 2363 // Default implementation: no optimization. 2364 return SDValue(); 2365 } 2366 2367 //===----------------------------------------------------------------------===// 2368 // Inline Assembler Implementation Methods 2369 //===----------------------------------------------------------------------===// 2370 2371 TargetLowering::ConstraintType 2372 TargetLowering::getConstraintType(StringRef Constraint) const { 2373 unsigned S = Constraint.size(); 2374 2375 if (S == 1) { 2376 switch (Constraint[0]) { 2377 default: break; 2378 case 'r': return C_RegisterClass; 2379 case 'm': // memory 2380 case 'o': // offsetable 2381 case 'V': // not offsetable 2382 return C_Memory; 2383 case 'i': // Simple Integer or Relocatable Constant 2384 case 'n': // Simple Integer 2385 case 'E': // Floating Point Constant 2386 case 'F': // Floating Point Constant 2387 case 's': // Relocatable Constant 2388 case 'p': // Address. 2389 case 'X': // Allow ANY value. 2390 case 'I': // Target registers. 2391 case 'J': 2392 case 'K': 2393 case 'L': 2394 case 'M': 2395 case 'N': 2396 case 'O': 2397 case 'P': 2398 case '<': 2399 case '>': 2400 return C_Other; 2401 } 2402 } 2403 2404 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') { 2405 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 2406 return C_Memory; 2407 return C_Register; 2408 } 2409 return C_Unknown; 2410 } 2411 2412 /// Try to replace an X constraint, which matches anything, with another that 2413 /// has more specific requirements based on the type of the corresponding 2414 /// operand. 2415 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{ 2416 if (ConstraintVT.isInteger()) 2417 return "r"; 2418 if (ConstraintVT.isFloatingPoint()) 2419 return "f"; // works for many targets 2420 return nullptr; 2421 } 2422 2423 /// Lower the specified operand into the Ops vector. 2424 /// If it is invalid, don't add anything to Ops. 2425 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 2426 std::string &Constraint, 2427 std::vector<SDValue> &Ops, 2428 SelectionDAG &DAG) const { 2429 2430 if (Constraint.length() > 1) return; 2431 2432 char ConstraintLetter = Constraint[0]; 2433 switch (ConstraintLetter) { 2434 default: break; 2435 case 'X': // Allows any operand; labels (basic block) use this. 2436 if (Op.getOpcode() == ISD::BasicBlock) { 2437 Ops.push_back(Op); 2438 return; 2439 } 2440 LLVM_FALLTHROUGH; 2441 case 'i': // Simple Integer or Relocatable Constant 2442 case 'n': // Simple Integer 2443 case 's': { // Relocatable Constant 2444 // These operands are interested in values of the form (GV+C), where C may 2445 // be folded in as an offset of GV, or it may be explicitly added. Also, it 2446 // is possible and fine if either GV or C are missing. 2447 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 2448 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op); 2449 2450 // If we have "(add GV, C)", pull out GV/C 2451 if (Op.getOpcode() == ISD::ADD) { 2452 C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 2453 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0)); 2454 if (!C || !GA) { 2455 C = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 2456 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1)); 2457 } 2458 if (!C || !GA) { 2459 C = nullptr; 2460 GA = nullptr; 2461 } 2462 } 2463 2464 // If we find a valid operand, map to the TargetXXX version so that the 2465 // value itself doesn't get selected. 2466 if (GA) { // Either &GV or &GV+C 2467 if (ConstraintLetter != 'n') { 2468 int64_t Offs = GA->getOffset(); 2469 if (C) Offs += C->getZExtValue(); 2470 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), 2471 C ? SDLoc(C) : SDLoc(), 2472 Op.getValueType(), Offs)); 2473 } 2474 return; 2475 } 2476 if (C) { // just C, no GV. 2477 // Simple constants are not allowed for 's'. 2478 if (ConstraintLetter != 's') { 2479 // gcc prints these as sign extended. Sign extend value to 64 bits 2480 // now; without this it would get ZExt'd later in 2481 // ScheduleDAGSDNodes::EmitNode, which is very generic. 2482 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(), 2483 SDLoc(C), MVT::i64)); 2484 } 2485 return; 2486 } 2487 break; 2488 } 2489 } 2490 } 2491 2492 std::pair<unsigned, const TargetRegisterClass *> 2493 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 2494 StringRef Constraint, 2495 MVT VT) const { 2496 if (Constraint.empty() || Constraint[0] != '{') 2497 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr)); 2498 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?"); 2499 2500 // Remove the braces from around the name. 2501 StringRef RegName(Constraint.data()+1, Constraint.size()-2); 2502 2503 std::pair<unsigned, const TargetRegisterClass*> R = 2504 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr)); 2505 2506 // Figure out which register class contains this reg. 2507 for (const TargetRegisterClass *RC : RI->regclasses()) { 2508 // If none of the value types for this register class are valid, we 2509 // can't use it. For example, 64-bit reg classes on 32-bit targets. 2510 if (!isLegalRC(RC)) 2511 continue; 2512 2513 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 2514 I != E; ++I) { 2515 if (RegName.equals_lower(RI->getRegAsmName(*I))) { 2516 std::pair<unsigned, const TargetRegisterClass*> S = 2517 std::make_pair(*I, RC); 2518 2519 // If this register class has the requested value type, return it, 2520 // otherwise keep searching and return the first class found 2521 // if no other is found which explicitly has the requested type. 2522 if (RC->hasType(VT)) 2523 return S; 2524 else if (!R.second) 2525 R = S; 2526 } 2527 } 2528 } 2529 2530 return R; 2531 } 2532 2533 //===----------------------------------------------------------------------===// 2534 // Constraint Selection. 2535 2536 /// Return true of this is an input operand that is a matching constraint like 2537 /// "4". 2538 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 2539 assert(!ConstraintCode.empty() && "No known constraint!"); 2540 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 2541 } 2542 2543 /// If this is an input matching constraint, this method returns the output 2544 /// operand it matches. 2545 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 2546 assert(!ConstraintCode.empty() && "No known constraint!"); 2547 return atoi(ConstraintCode.c_str()); 2548 } 2549 2550 /// Split up the constraint string from the inline assembly value into the 2551 /// specific constraints and their prefixes, and also tie in the associated 2552 /// operand values. 2553 /// If this returns an empty vector, and if the constraint string itself 2554 /// isn't empty, there was an error parsing. 2555 TargetLowering::AsmOperandInfoVector 2556 TargetLowering::ParseConstraints(const DataLayout &DL, 2557 const TargetRegisterInfo *TRI, 2558 ImmutableCallSite CS) const { 2559 /// Information about all of the constraints. 2560 AsmOperandInfoVector ConstraintOperands; 2561 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 2562 unsigned maCount = 0; // Largest number of multiple alternative constraints. 2563 2564 // Do a prepass over the constraints, canonicalizing them, and building up the 2565 // ConstraintOperands list. 2566 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 2567 unsigned ResNo = 0; // ResNo - The result number of the next output. 2568 2569 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 2570 ConstraintOperands.emplace_back(std::move(CI)); 2571 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 2572 2573 // Update multiple alternative constraint count. 2574 if (OpInfo.multipleAlternatives.size() > maCount) 2575 maCount = OpInfo.multipleAlternatives.size(); 2576 2577 OpInfo.ConstraintVT = MVT::Other; 2578 2579 // Compute the value type for each operand. 2580 switch (OpInfo.Type) { 2581 case InlineAsm::isOutput: 2582 // Indirect outputs just consume an argument. 2583 if (OpInfo.isIndirect) { 2584 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2585 break; 2586 } 2587 2588 // The return value of the call is this value. As such, there is no 2589 // corresponding argument. 2590 assert(!CS.getType()->isVoidTy() && 2591 "Bad inline asm!"); 2592 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 2593 OpInfo.ConstraintVT = 2594 getSimpleValueType(DL, STy->getElementType(ResNo)); 2595 } else { 2596 assert(ResNo == 0 && "Asm only has one result!"); 2597 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType()); 2598 } 2599 ++ResNo; 2600 break; 2601 case InlineAsm::isInput: 2602 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2603 break; 2604 case InlineAsm::isClobber: 2605 // Nothing to do. 2606 break; 2607 } 2608 2609 if (OpInfo.CallOperandVal) { 2610 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 2611 if (OpInfo.isIndirect) { 2612 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 2613 if (!PtrTy) 2614 report_fatal_error("Indirect operand for inline asm not a pointer!"); 2615 OpTy = PtrTy->getElementType(); 2616 } 2617 2618 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 2619 if (StructType *STy = dyn_cast<StructType>(OpTy)) 2620 if (STy->getNumElements() == 1) 2621 OpTy = STy->getElementType(0); 2622 2623 // If OpTy is not a single value, it may be a struct/union that we 2624 // can tile with integers. 2625 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 2626 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 2627 switch (BitSize) { 2628 default: break; 2629 case 1: 2630 case 8: 2631 case 16: 2632 case 32: 2633 case 64: 2634 case 128: 2635 OpInfo.ConstraintVT = 2636 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 2637 break; 2638 } 2639 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 2640 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 2641 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 2642 } else { 2643 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 2644 } 2645 } 2646 } 2647 2648 // If we have multiple alternative constraints, select the best alternative. 2649 if (!ConstraintOperands.empty()) { 2650 if (maCount) { 2651 unsigned bestMAIndex = 0; 2652 int bestWeight = -1; 2653 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 2654 int weight = -1; 2655 unsigned maIndex; 2656 // Compute the sums of the weights for each alternative, keeping track 2657 // of the best (highest weight) one so far. 2658 for (maIndex = 0; maIndex < maCount; ++maIndex) { 2659 int weightSum = 0; 2660 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2661 cIndex != eIndex; ++cIndex) { 2662 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2663 if (OpInfo.Type == InlineAsm::isClobber) 2664 continue; 2665 2666 // If this is an output operand with a matching input operand, 2667 // look up the matching input. If their types mismatch, e.g. one 2668 // is an integer, the other is floating point, or their sizes are 2669 // different, flag it as an maCantMatch. 2670 if (OpInfo.hasMatchingInput()) { 2671 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2672 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2673 if ((OpInfo.ConstraintVT.isInteger() != 2674 Input.ConstraintVT.isInteger()) || 2675 (OpInfo.ConstraintVT.getSizeInBits() != 2676 Input.ConstraintVT.getSizeInBits())) { 2677 weightSum = -1; // Can't match. 2678 break; 2679 } 2680 } 2681 } 2682 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 2683 if (weight == -1) { 2684 weightSum = -1; 2685 break; 2686 } 2687 weightSum += weight; 2688 } 2689 // Update best. 2690 if (weightSum > bestWeight) { 2691 bestWeight = weightSum; 2692 bestMAIndex = maIndex; 2693 } 2694 } 2695 2696 // Now select chosen alternative in each constraint. 2697 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2698 cIndex != eIndex; ++cIndex) { 2699 AsmOperandInfo& cInfo = ConstraintOperands[cIndex]; 2700 if (cInfo.Type == InlineAsm::isClobber) 2701 continue; 2702 cInfo.selectAlternative(bestMAIndex); 2703 } 2704 } 2705 } 2706 2707 // Check and hook up tied operands, choose constraint code to use. 2708 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2709 cIndex != eIndex; ++cIndex) { 2710 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2711 2712 // If this is an output operand with a matching input operand, look up the 2713 // matching input. If their types mismatch, e.g. one is an integer, the 2714 // other is floating point, or their sizes are different, flag it as an 2715 // error. 2716 if (OpInfo.hasMatchingInput()) { 2717 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2718 2719 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2720 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 2721 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 2722 OpInfo.ConstraintVT); 2723 std::pair<unsigned, const TargetRegisterClass *> InputRC = 2724 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 2725 Input.ConstraintVT); 2726 if ((OpInfo.ConstraintVT.isInteger() != 2727 Input.ConstraintVT.isInteger()) || 2728 (MatchRC.second != InputRC.second)) { 2729 report_fatal_error("Unsupported asm: input constraint" 2730 " with a matching output constraint of" 2731 " incompatible type!"); 2732 } 2733 } 2734 } 2735 } 2736 2737 return ConstraintOperands; 2738 } 2739 2740 /// Return an integer indicating how general CT is. 2741 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 2742 switch (CT) { 2743 case TargetLowering::C_Other: 2744 case TargetLowering::C_Unknown: 2745 return 0; 2746 case TargetLowering::C_Register: 2747 return 1; 2748 case TargetLowering::C_RegisterClass: 2749 return 2; 2750 case TargetLowering::C_Memory: 2751 return 3; 2752 } 2753 llvm_unreachable("Invalid constraint type"); 2754 } 2755 2756 /// Examine constraint type and operand type and determine a weight value. 2757 /// This object must already have been set up with the operand type 2758 /// and the current alternative constraint selected. 2759 TargetLowering::ConstraintWeight 2760 TargetLowering::getMultipleConstraintMatchWeight( 2761 AsmOperandInfo &info, int maIndex) const { 2762 InlineAsm::ConstraintCodeVector *rCodes; 2763 if (maIndex >= (int)info.multipleAlternatives.size()) 2764 rCodes = &info.Codes; 2765 else 2766 rCodes = &info.multipleAlternatives[maIndex].Codes; 2767 ConstraintWeight BestWeight = CW_Invalid; 2768 2769 // Loop over the options, keeping track of the most general one. 2770 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 2771 ConstraintWeight weight = 2772 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 2773 if (weight > BestWeight) 2774 BestWeight = weight; 2775 } 2776 2777 return BestWeight; 2778 } 2779 2780 /// Examine constraint type and operand type and determine a weight value. 2781 /// This object must already have been set up with the operand type 2782 /// and the current alternative constraint selected. 2783 TargetLowering::ConstraintWeight 2784 TargetLowering::getSingleConstraintMatchWeight( 2785 AsmOperandInfo &info, const char *constraint) const { 2786 ConstraintWeight weight = CW_Invalid; 2787 Value *CallOperandVal = info.CallOperandVal; 2788 // If we don't have a value, we can't do a match, 2789 // but allow it at the lowest weight. 2790 if (!CallOperandVal) 2791 return CW_Default; 2792 // Look at the constraint type. 2793 switch (*constraint) { 2794 case 'i': // immediate integer. 2795 case 'n': // immediate integer with a known value. 2796 if (isa<ConstantInt>(CallOperandVal)) 2797 weight = CW_Constant; 2798 break; 2799 case 's': // non-explicit intregal immediate. 2800 if (isa<GlobalValue>(CallOperandVal)) 2801 weight = CW_Constant; 2802 break; 2803 case 'E': // immediate float if host format. 2804 case 'F': // immediate float. 2805 if (isa<ConstantFP>(CallOperandVal)) 2806 weight = CW_Constant; 2807 break; 2808 case '<': // memory operand with autodecrement. 2809 case '>': // memory operand with autoincrement. 2810 case 'm': // memory operand. 2811 case 'o': // offsettable memory operand 2812 case 'V': // non-offsettable memory operand 2813 weight = CW_Memory; 2814 break; 2815 case 'r': // general register. 2816 case 'g': // general register, memory operand or immediate integer. 2817 // note: Clang converts "g" to "imr". 2818 if (CallOperandVal->getType()->isIntegerTy()) 2819 weight = CW_Register; 2820 break; 2821 case 'X': // any operand. 2822 default: 2823 weight = CW_Default; 2824 break; 2825 } 2826 return weight; 2827 } 2828 2829 /// If there are multiple different constraints that we could pick for this 2830 /// operand (e.g. "imr") try to pick the 'best' one. 2831 /// This is somewhat tricky: constraints fall into four classes: 2832 /// Other -> immediates and magic values 2833 /// Register -> one specific register 2834 /// RegisterClass -> a group of regs 2835 /// Memory -> memory 2836 /// Ideally, we would pick the most specific constraint possible: if we have 2837 /// something that fits into a register, we would pick it. The problem here 2838 /// is that if we have something that could either be in a register or in 2839 /// memory that use of the register could cause selection of *other* 2840 /// operands to fail: they might only succeed if we pick memory. Because of 2841 /// this the heuristic we use is: 2842 /// 2843 /// 1) If there is an 'other' constraint, and if the operand is valid for 2844 /// that constraint, use it. This makes us take advantage of 'i' 2845 /// constraints when available. 2846 /// 2) Otherwise, pick the most general constraint present. This prefers 2847 /// 'm' over 'r', for example. 2848 /// 2849 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 2850 const TargetLowering &TLI, 2851 SDValue Op, SelectionDAG *DAG) { 2852 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 2853 unsigned BestIdx = 0; 2854 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 2855 int BestGenerality = -1; 2856 2857 // Loop over the options, keeping track of the most general one. 2858 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 2859 TargetLowering::ConstraintType CType = 2860 TLI.getConstraintType(OpInfo.Codes[i]); 2861 2862 // If this is an 'other' constraint, see if the operand is valid for it. 2863 // For example, on X86 we might have an 'rI' constraint. If the operand 2864 // is an integer in the range [0..31] we want to use I (saving a load 2865 // of a register), otherwise we must use 'r'. 2866 if (CType == TargetLowering::C_Other && Op.getNode()) { 2867 assert(OpInfo.Codes[i].size() == 1 && 2868 "Unhandled multi-letter 'other' constraint"); 2869 std::vector<SDValue> ResultOps; 2870 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 2871 ResultOps, *DAG); 2872 if (!ResultOps.empty()) { 2873 BestType = CType; 2874 BestIdx = i; 2875 break; 2876 } 2877 } 2878 2879 // Things with matching constraints can only be registers, per gcc 2880 // documentation. This mainly affects "g" constraints. 2881 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 2882 continue; 2883 2884 // This constraint letter is more general than the previous one, use it. 2885 int Generality = getConstraintGenerality(CType); 2886 if (Generality > BestGenerality) { 2887 BestType = CType; 2888 BestIdx = i; 2889 BestGenerality = Generality; 2890 } 2891 } 2892 2893 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 2894 OpInfo.ConstraintType = BestType; 2895 } 2896 2897 /// Determines the constraint code and constraint type to use for the specific 2898 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 2899 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 2900 SDValue Op, 2901 SelectionDAG *DAG) const { 2902 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 2903 2904 // Single-letter constraints ('r') are very common. 2905 if (OpInfo.Codes.size() == 1) { 2906 OpInfo.ConstraintCode = OpInfo.Codes[0]; 2907 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2908 } else { 2909 ChooseConstraint(OpInfo, *this, Op, DAG); 2910 } 2911 2912 // 'X' matches anything. 2913 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 2914 // Labels and constants are handled elsewhere ('X' is the only thing 2915 // that matches labels). For Functions, the type here is the type of 2916 // the result, which is not what we want to look at; leave them alone. 2917 Value *v = OpInfo.CallOperandVal; 2918 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 2919 OpInfo.CallOperandVal = v; 2920 return; 2921 } 2922 2923 // Otherwise, try to resolve it to something we know about by looking at 2924 // the actual operand type. 2925 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 2926 OpInfo.ConstraintCode = Repl; 2927 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2928 } 2929 } 2930 } 2931 2932 /// \brief Given an exact SDIV by a constant, create a multiplication 2933 /// with the multiplicative inverse of the constant. 2934 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d, 2935 const SDLoc &dl, SelectionDAG &DAG, 2936 std::vector<SDNode *> &Created) { 2937 assert(d != 0 && "Division by zero!"); 2938 2939 // Shift the value upfront if it is even, so the LSB is one. 2940 unsigned ShAmt = d.countTrailingZeros(); 2941 if (ShAmt) { 2942 // TODO: For UDIV use SRL instead of SRA. 2943 SDValue Amt = 2944 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(), 2945 DAG.getDataLayout())); 2946 SDNodeFlags Flags; 2947 Flags.setExact(true); 2948 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags); 2949 Created.push_back(Op1.getNode()); 2950 d = d.ashr(ShAmt); 2951 } 2952 2953 // Calculate the multiplicative inverse, using Newton's method. 2954 APInt t, xn = d; 2955 while ((t = d*xn) != 1) 2956 xn *= APInt(d.getBitWidth(), 2) - t; 2957 2958 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType()); 2959 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2); 2960 Created.push_back(Mul.getNode()); 2961 return Mul; 2962 } 2963 2964 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 2965 SelectionDAG &DAG, 2966 std::vector<SDNode *> *Created) const { 2967 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2968 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2969 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 2970 return SDValue(N,0); // Lower SDIV as SDIV 2971 return SDValue(); 2972 } 2973 2974 /// \brief Given an ISD::SDIV node expressing a divide by constant, 2975 /// return a DAG expression to select that will generate the same value by 2976 /// multiplying by a magic number. 2977 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 2978 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor, 2979 SelectionDAG &DAG, bool IsAfterLegalization, 2980 std::vector<SDNode *> *Created) const { 2981 assert(Created && "No vector to hold sdiv ops."); 2982 2983 EVT VT = N->getValueType(0); 2984 SDLoc dl(N); 2985 2986 // Check to see if we can do this. 2987 // FIXME: We should be more aggressive here. 2988 if (!isTypeLegal(VT)) 2989 return SDValue(); 2990 2991 // If the sdiv has an 'exact' bit we can use a simpler lowering. 2992 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact()) 2993 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created); 2994 2995 APInt::ms magics = Divisor.magic(); 2996 2997 // Multiply the numerator (operand 0) by the magic value 2998 // FIXME: We should support doing a MUL in a wider type 2999 SDValue Q; 3000 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) : 3001 isOperationLegalOrCustom(ISD::MULHS, VT)) 3002 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0), 3003 DAG.getConstant(magics.m, dl, VT)); 3004 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) : 3005 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) 3006 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), 3007 N->getOperand(0), 3008 DAG.getConstant(magics.m, dl, VT)).getNode(), 1); 3009 else 3010 return SDValue(); // No mulhs or equvialent 3011 // If d > 0 and m < 0, add the numerator 3012 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 3013 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0)); 3014 Created->push_back(Q.getNode()); 3015 } 3016 // If d < 0 and m > 0, subtract the numerator. 3017 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 3018 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0)); 3019 Created->push_back(Q.getNode()); 3020 } 3021 auto &DL = DAG.getDataLayout(); 3022 // Shift right algebraic if shift value is nonzero 3023 if (magics.s > 0) { 3024 Q = DAG.getNode( 3025 ISD::SRA, dl, VT, Q, 3026 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL))); 3027 Created->push_back(Q.getNode()); 3028 } 3029 // Extract the sign bit and add it to the quotient 3030 SDValue T = 3031 DAG.getNode(ISD::SRL, dl, VT, Q, 3032 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, 3033 getShiftAmountTy(Q.getValueType(), DL))); 3034 Created->push_back(T.getNode()); 3035 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 3036 } 3037 3038 /// \brief Given an ISD::UDIV node expressing a divide by constant, 3039 /// return a DAG expression to select that will generate the same value by 3040 /// multiplying by a magic number. 3041 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 3042 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor, 3043 SelectionDAG &DAG, bool IsAfterLegalization, 3044 std::vector<SDNode *> *Created) const { 3045 assert(Created && "No vector to hold udiv ops."); 3046 3047 EVT VT = N->getValueType(0); 3048 SDLoc dl(N); 3049 auto &DL = DAG.getDataLayout(); 3050 3051 // Check to see if we can do this. 3052 // FIXME: We should be more aggressive here. 3053 if (!isTypeLegal(VT)) 3054 return SDValue(); 3055 3056 // FIXME: We should use a narrower constant when the upper 3057 // bits are known to be zero. 3058 APInt::mu magics = Divisor.magicu(); 3059 3060 SDValue Q = N->getOperand(0); 3061 3062 // If the divisor is even, we can avoid using the expensive fixup by shifting 3063 // the divided value upfront. 3064 if (magics.a != 0 && !Divisor[0]) { 3065 unsigned Shift = Divisor.countTrailingZeros(); 3066 Q = DAG.getNode( 3067 ISD::SRL, dl, VT, Q, 3068 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL))); 3069 Created->push_back(Q.getNode()); 3070 3071 // Get magic number for the shifted divisor. 3072 magics = Divisor.lshr(Shift).magicu(Shift); 3073 assert(magics.a == 0 && "Should use cheap fixup now"); 3074 } 3075 3076 // Multiply the numerator (operand 0) by the magic value 3077 // FIXME: We should support doing a MUL in a wider type 3078 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) : 3079 isOperationLegalOrCustom(ISD::MULHU, VT)) 3080 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT)); 3081 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) : 3082 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) 3083 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q, 3084 DAG.getConstant(magics.m, dl, VT)).getNode(), 1); 3085 else 3086 return SDValue(); // No mulhu or equivalent 3087 3088 Created->push_back(Q.getNode()); 3089 3090 if (magics.a == 0) { 3091 assert(magics.s < Divisor.getBitWidth() && 3092 "We shouldn't generate an undefined shift!"); 3093 return DAG.getNode( 3094 ISD::SRL, dl, VT, Q, 3095 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL))); 3096 } else { 3097 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q); 3098 Created->push_back(NPQ.getNode()); 3099 NPQ = DAG.getNode( 3100 ISD::SRL, dl, VT, NPQ, 3101 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL))); 3102 Created->push_back(NPQ.getNode()); 3103 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 3104 Created->push_back(NPQ.getNode()); 3105 return DAG.getNode( 3106 ISD::SRL, dl, VT, NPQ, 3107 DAG.getConstant(magics.s - 1, dl, 3108 getShiftAmountTy(NPQ.getValueType(), DL))); 3109 } 3110 } 3111 3112 bool TargetLowering:: 3113 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 3114 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 3115 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 3116 "be a constant integer"); 3117 return true; 3118 } 3119 3120 return false; 3121 } 3122 3123 //===----------------------------------------------------------------------===// 3124 // Legalization Utilities 3125 //===----------------------------------------------------------------------===// 3126 3127 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl, 3128 SDValue LHS, SDValue RHS, 3129 SmallVectorImpl<SDValue> &Result, 3130 EVT HiLoVT, SelectionDAG &DAG, 3131 MulExpansionKind Kind, SDValue LL, 3132 SDValue LH, SDValue RL, SDValue RH) const { 3133 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 3134 Opcode == ISD::SMUL_LOHI); 3135 3136 bool HasMULHS = (Kind == MulExpansionKind::Always) || 3137 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 3138 bool HasMULHU = (Kind == MulExpansionKind::Always) || 3139 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 3140 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 3141 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 3142 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 3143 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 3144 3145 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 3146 return false; 3147 3148 unsigned OuterBitSize = VT.getScalarSizeInBits(); 3149 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 3150 unsigned LHSSB = DAG.ComputeNumSignBits(LHS); 3151 unsigned RHSSB = DAG.ComputeNumSignBits(RHS); 3152 3153 // LL, LH, RL, and RH must be either all NULL or all set to a value. 3154 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 3155 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 3156 3157 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 3158 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 3159 bool Signed) -> bool { 3160 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 3161 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 3162 Hi = SDValue(Lo.getNode(), 1); 3163 return true; 3164 } 3165 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 3166 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 3167 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 3168 return true; 3169 } 3170 return false; 3171 }; 3172 3173 SDValue Lo, Hi; 3174 3175 if (!LL.getNode() && !RL.getNode() && 3176 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 3177 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 3178 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 3179 } 3180 3181 if (!LL.getNode()) 3182 return false; 3183 3184 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 3185 if (DAG.MaskedValueIsZero(LHS, HighMask) && 3186 DAG.MaskedValueIsZero(RHS, HighMask)) { 3187 // The inputs are both zero-extended. 3188 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 3189 Result.push_back(Lo); 3190 Result.push_back(Hi); 3191 if (Opcode != ISD::MUL) { 3192 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 3193 Result.push_back(Zero); 3194 Result.push_back(Zero); 3195 } 3196 return true; 3197 } 3198 } 3199 3200 if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize && 3201 RHSSB > InnerBitSize) { 3202 // The input values are both sign-extended. 3203 // TODO non-MUL case? 3204 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 3205 Result.push_back(Lo); 3206 Result.push_back(Hi); 3207 return true; 3208 } 3209 } 3210 3211 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 3212 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 3213 if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) { 3214 // FIXME getShiftAmountTy does not always return a sensible result when VT 3215 // is an illegal type, and so the type may be too small to fit the shift 3216 // amount. Override it with i32. The shift will have to be legalized. 3217 ShiftAmountTy = MVT::i32; 3218 } 3219 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 3220 3221 if (!LH.getNode() && !RH.getNode() && 3222 isOperationLegalOrCustom(ISD::SRL, VT) && 3223 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 3224 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 3225 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 3226 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 3227 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 3228 } 3229 3230 if (!LH.getNode()) 3231 return false; 3232 3233 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 3234 return false; 3235 3236 Result.push_back(Lo); 3237 3238 if (Opcode == ISD::MUL) { 3239 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 3240 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 3241 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 3242 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 3243 Result.push_back(Hi); 3244 return true; 3245 } 3246 3247 // Compute the full width result. 3248 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 3249 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 3250 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 3251 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 3252 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 3253 }; 3254 3255 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 3256 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 3257 return false; 3258 3259 // This is effectively the add part of a multiply-add of half-sized operands, 3260 // so it cannot overflow. 3261 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 3262 3263 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 3264 return false; 3265 3266 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 3267 Merge(Lo, Hi)); 3268 3269 SDValue Carry = Next.getValue(1); 3270 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 3271 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 3272 3273 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 3274 return false; 3275 3276 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 3277 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 3278 Carry); 3279 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 3280 3281 if (Opcode == ISD::SMUL_LOHI) { 3282 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 3283 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 3284 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 3285 3286 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 3287 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 3288 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 3289 } 3290 3291 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 3292 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 3293 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 3294 return true; 3295 } 3296 3297 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 3298 SelectionDAG &DAG, MulExpansionKind Kind, 3299 SDValue LL, SDValue LH, SDValue RL, 3300 SDValue RH) const { 3301 SmallVector<SDValue, 2> Result; 3302 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N, 3303 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 3304 DAG, Kind, LL, LH, RL, RH); 3305 if (Ok) { 3306 assert(Result.size() == 2); 3307 Lo = Result[0]; 3308 Hi = Result[1]; 3309 } 3310 return Ok; 3311 } 3312 3313 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 3314 SelectionDAG &DAG) const { 3315 EVT VT = Node->getOperand(0).getValueType(); 3316 EVT NVT = Node->getValueType(0); 3317 SDLoc dl(SDValue(Node, 0)); 3318 3319 // FIXME: Only f32 to i64 conversions are supported. 3320 if (VT != MVT::f32 || NVT != MVT::i64) 3321 return false; 3322 3323 // Expand f32 -> i64 conversion 3324 // This algorithm comes from compiler-rt's implementation of fixsfdi: 3325 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c 3326 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), 3327 VT.getSizeInBits()); 3328 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 3329 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 3330 SDValue Bias = DAG.getConstant(127, dl, IntVT); 3331 SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl, 3332 IntVT); 3333 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT); 3334 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 3335 3336 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0)); 3337 3338 auto &DL = DAG.getDataLayout(); 3339 SDValue ExponentBits = DAG.getNode( 3340 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 3341 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL))); 3342 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 3343 3344 SDValue Sign = DAG.getNode( 3345 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 3346 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL))); 3347 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT); 3348 3349 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 3350 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 3351 DAG.getConstant(0x00800000, dl, IntVT)); 3352 3353 R = DAG.getZExtOrTrunc(R, dl, NVT); 3354 3355 R = DAG.getSelectCC( 3356 dl, Exponent, ExponentLoBit, 3357 DAG.getNode(ISD::SHL, dl, NVT, R, 3358 DAG.getZExtOrTrunc( 3359 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 3360 dl, getShiftAmountTy(IntVT, DL))), 3361 DAG.getNode(ISD::SRL, dl, NVT, R, 3362 DAG.getZExtOrTrunc( 3363 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 3364 dl, getShiftAmountTy(IntVT, DL))), 3365 ISD::SETGT); 3366 3367 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT, 3368 DAG.getNode(ISD::XOR, dl, NVT, R, Sign), 3369 Sign); 3370 3371 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 3372 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT); 3373 return true; 3374 } 3375 3376 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 3377 SelectionDAG &DAG) const { 3378 SDLoc SL(LD); 3379 SDValue Chain = LD->getChain(); 3380 SDValue BasePTR = LD->getBasePtr(); 3381 EVT SrcVT = LD->getMemoryVT(); 3382 ISD::LoadExtType ExtType = LD->getExtensionType(); 3383 3384 unsigned NumElem = SrcVT.getVectorNumElements(); 3385 3386 EVT SrcEltVT = SrcVT.getScalarType(); 3387 EVT DstEltVT = LD->getValueType(0).getScalarType(); 3388 3389 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 3390 assert(SrcEltVT.isByteSized()); 3391 3392 EVT PtrVT = BasePTR.getValueType(); 3393 3394 SmallVector<SDValue, 8> Vals; 3395 SmallVector<SDValue, 8> LoadChains; 3396 3397 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 3398 SDValue ScalarLoad = 3399 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 3400 LD->getPointerInfo().getWithOffset(Idx * Stride), 3401 SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride), 3402 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3403 3404 BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR, 3405 DAG.getConstant(Stride, SL, PtrVT)); 3406 3407 Vals.push_back(ScalarLoad.getValue(0)); 3408 LoadChains.push_back(ScalarLoad.getValue(1)); 3409 } 3410 3411 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 3412 SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals); 3413 3414 return DAG.getMergeValues({ Value, NewChain }, SL); 3415 } 3416 3417 // FIXME: This relies on each element having a byte size, otherwise the stride 3418 // is 0 and just overwrites the same location. ExpandStore currently expects 3419 // this broken behavior. 3420 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 3421 SelectionDAG &DAG) const { 3422 SDLoc SL(ST); 3423 3424 SDValue Chain = ST->getChain(); 3425 SDValue BasePtr = ST->getBasePtr(); 3426 SDValue Value = ST->getValue(); 3427 EVT StVT = ST->getMemoryVT(); 3428 3429 // The type of the data we want to save 3430 EVT RegVT = Value.getValueType(); 3431 EVT RegSclVT = RegVT.getScalarType(); 3432 3433 // The type of data as saved in memory. 3434 EVT MemSclVT = StVT.getScalarType(); 3435 3436 EVT PtrVT = BasePtr.getValueType(); 3437 3438 // Store Stride in bytes 3439 unsigned Stride = MemSclVT.getSizeInBits() / 8; 3440 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout()); 3441 unsigned NumElem = StVT.getVectorNumElements(); 3442 3443 // Extract each of the elements from the original vector and save them into 3444 // memory individually. 3445 SmallVector<SDValue, 8> Stores; 3446 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 3447 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 3448 DAG.getConstant(Idx, SL, IdxVT)); 3449 3450 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 3451 DAG.getConstant(Idx * Stride, SL, PtrVT)); 3452 3453 // This scalar TruncStore may be illegal, but we legalize it later. 3454 SDValue Store = DAG.getTruncStore( 3455 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 3456 MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride), 3457 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 3458 3459 Stores.push_back(Store); 3460 } 3461 3462 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 3463 } 3464 3465 std::pair<SDValue, SDValue> 3466 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 3467 assert(LD->getAddressingMode() == ISD::UNINDEXED && 3468 "unaligned indexed loads not implemented!"); 3469 SDValue Chain = LD->getChain(); 3470 SDValue Ptr = LD->getBasePtr(); 3471 EVT VT = LD->getValueType(0); 3472 EVT LoadedVT = LD->getMemoryVT(); 3473 SDLoc dl(LD); 3474 if (VT.isFloatingPoint() || VT.isVector()) { 3475 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 3476 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 3477 if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) { 3478 // Scalarize the load and let the individual components be handled. 3479 SDValue Scalarized = scalarizeVectorLoad(LD, DAG); 3480 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1)); 3481 } 3482 3483 // Expand to a (misaligned) integer load of the same size, 3484 // then bitconvert to floating point or vector. 3485 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 3486 LD->getMemOperand()); 3487 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 3488 if (LoadedVT != VT) 3489 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 3490 ISD::ANY_EXTEND, dl, VT, Result); 3491 3492 return std::make_pair(Result, newLoad.getValue(1)); 3493 } 3494 3495 // Copy the value to a (aligned) stack slot using (unaligned) integer 3496 // loads and stores, then do a (aligned) load from the stack slot. 3497 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 3498 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8; 3499 unsigned RegBytes = RegVT.getSizeInBits() / 8; 3500 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 3501 3502 // Make sure the stack slot is also aligned for the register type. 3503 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 3504 3505 SmallVector<SDValue, 8> Stores; 3506 SDValue StackPtr = StackBase; 3507 unsigned Offset = 0; 3508 3509 EVT PtrVT = Ptr.getValueType(); 3510 EVT StackPtrVT = StackPtr.getValueType(); 3511 3512 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 3513 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 3514 3515 // Do all but one copies using the full register width. 3516 for (unsigned i = 1; i < NumRegs; i++) { 3517 // Load one integer register's worth from the original location. 3518 SDValue Load = DAG.getLoad( 3519 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 3520 MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(), 3521 LD->getAAInfo()); 3522 // Follow the load with a store to the stack slot. Remember the store. 3523 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr, 3524 MachinePointerInfo())); 3525 // Increment the pointers. 3526 Offset += RegBytes; 3527 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement); 3528 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr, 3529 StackPtrIncrement); 3530 } 3531 3532 // The last copy may be partial. Do an extending load. 3533 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 3534 8 * (LoadedBytes - Offset)); 3535 SDValue Load = 3536 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 3537 LD->getPointerInfo().getWithOffset(Offset), MemVT, 3538 MinAlign(LD->getAlignment(), Offset), 3539 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3540 // Follow the load with a store to the stack slot. Remember the store. 3541 // On big-endian machines this requires a truncating store to ensure 3542 // that the bits end up in the right place. 3543 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr, 3544 MachinePointerInfo(), MemVT)); 3545 3546 // The order of the stores doesn't matter - say it with a TokenFactor. 3547 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 3548 3549 // Finally, perform the original load only redirected to the stack slot. 3550 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 3551 MachinePointerInfo(), LoadedVT); 3552 3553 // Callers expect a MERGE_VALUES node. 3554 return std::make_pair(Load, TF); 3555 } 3556 3557 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 3558 "Unaligned load of unsupported type."); 3559 3560 // Compute the new VT that is half the size of the old one. This is an 3561 // integer MVT. 3562 unsigned NumBits = LoadedVT.getSizeInBits(); 3563 EVT NewLoadedVT; 3564 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 3565 NumBits >>= 1; 3566 3567 unsigned Alignment = LD->getAlignment(); 3568 unsigned IncrementSize = NumBits / 8; 3569 ISD::LoadExtType HiExtType = LD->getExtensionType(); 3570 3571 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 3572 if (HiExtType == ISD::NON_EXTLOAD) 3573 HiExtType = ISD::ZEXTLOAD; 3574 3575 // Load the value in two parts 3576 SDValue Lo, Hi; 3577 if (DAG.getDataLayout().isLittleEndian()) { 3578 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 3579 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 3580 LD->getAAInfo()); 3581 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 3582 DAG.getConstant(IncrementSize, dl, Ptr.getValueType())); 3583 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 3584 LD->getPointerInfo().getWithOffset(IncrementSize), 3585 NewLoadedVT, MinAlign(Alignment, IncrementSize), 3586 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3587 } else { 3588 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 3589 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 3590 LD->getAAInfo()); 3591 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 3592 DAG.getConstant(IncrementSize, dl, Ptr.getValueType())); 3593 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 3594 LD->getPointerInfo().getWithOffset(IncrementSize), 3595 NewLoadedVT, MinAlign(Alignment, IncrementSize), 3596 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3597 } 3598 3599 // aggregate the two parts 3600 SDValue ShiftAmount = 3601 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 3602 DAG.getDataLayout())); 3603 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 3604 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 3605 3606 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 3607 Hi.getValue(1)); 3608 3609 return std::make_pair(Result, TF); 3610 } 3611 3612 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 3613 SelectionDAG &DAG) const { 3614 assert(ST->getAddressingMode() == ISD::UNINDEXED && 3615 "unaligned indexed stores not implemented!"); 3616 SDValue Chain = ST->getChain(); 3617 SDValue Ptr = ST->getBasePtr(); 3618 SDValue Val = ST->getValue(); 3619 EVT VT = Val.getValueType(); 3620 int Alignment = ST->getAlignment(); 3621 3622 SDLoc dl(ST); 3623 if (ST->getMemoryVT().isFloatingPoint() || 3624 ST->getMemoryVT().isVector()) { 3625 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 3626 if (isTypeLegal(intVT)) { 3627 if (!isOperationLegalOrCustom(ISD::STORE, intVT)) { 3628 // Scalarize the store and let the individual components be handled. 3629 SDValue Result = scalarizeVectorStore(ST, DAG); 3630 3631 return Result; 3632 } 3633 // Expand to a bitconvert of the value to the integer type of the 3634 // same size, then a (misaligned) int store. 3635 // FIXME: Does not handle truncating floating point stores! 3636 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 3637 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 3638 Alignment, ST->getMemOperand()->getFlags()); 3639 return Result; 3640 } 3641 // Do a (aligned) store to a stack slot, then copy from the stack slot 3642 // to the final destination using (unaligned) integer loads and stores. 3643 EVT StoredVT = ST->getMemoryVT(); 3644 MVT RegVT = 3645 getRegisterType(*DAG.getContext(), 3646 EVT::getIntegerVT(*DAG.getContext(), 3647 StoredVT.getSizeInBits())); 3648 EVT PtrVT = Ptr.getValueType(); 3649 unsigned StoredBytes = StoredVT.getSizeInBits() / 8; 3650 unsigned RegBytes = RegVT.getSizeInBits() / 8; 3651 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 3652 3653 // Make sure the stack slot is also aligned for the register type. 3654 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT); 3655 3656 // Perform the original store, only redirected to the stack slot. 3657 SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr, 3658 MachinePointerInfo(), StoredVT); 3659 3660 EVT StackPtrVT = StackPtr.getValueType(); 3661 3662 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 3663 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 3664 SmallVector<SDValue, 8> Stores; 3665 unsigned Offset = 0; 3666 3667 // Do all but one copies using the full register width. 3668 for (unsigned i = 1; i < NumRegs; i++) { 3669 // Load one integer register's worth from the stack slot. 3670 SDValue Load = 3671 DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo()); 3672 // Store it to the final location. Remember the store. 3673 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 3674 ST->getPointerInfo().getWithOffset(Offset), 3675 MinAlign(ST->getAlignment(), Offset), 3676 ST->getMemOperand()->getFlags())); 3677 // Increment the pointers. 3678 Offset += RegBytes; 3679 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, 3680 StackPtr, StackPtrIncrement); 3681 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement); 3682 } 3683 3684 // The last store may be partial. Do a truncating store. On big-endian 3685 // machines this requires an extending load from the stack slot to ensure 3686 // that the bits are in the right place. 3687 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 3688 8 * (StoredBytes - Offset)); 3689 3690 // Load from the stack slot. 3691 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 3692 MachinePointerInfo(), MemVT); 3693 3694 Stores.push_back( 3695 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 3696 ST->getPointerInfo().getWithOffset(Offset), MemVT, 3697 MinAlign(ST->getAlignment(), Offset), 3698 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 3699 // The order of the stores doesn't matter - say it with a TokenFactor. 3700 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 3701 return Result; 3702 } 3703 3704 assert(ST->getMemoryVT().isInteger() && 3705 !ST->getMemoryVT().isVector() && 3706 "Unaligned store of unknown type."); 3707 // Get the half-size VT 3708 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext()); 3709 int NumBits = NewStoredVT.getSizeInBits(); 3710 int IncrementSize = NumBits / 8; 3711 3712 // Divide the stored value in two parts. 3713 SDValue ShiftAmount = 3714 DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(), 3715 DAG.getDataLayout())); 3716 SDValue Lo = Val; 3717 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 3718 3719 // Store the two parts 3720 SDValue Store1, Store2; 3721 Store1 = DAG.getTruncStore(Chain, dl, 3722 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 3723 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 3724 ST->getMemOperand()->getFlags()); 3725 3726 EVT PtrVT = Ptr.getValueType(); 3727 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3728 DAG.getConstant(IncrementSize, dl, PtrVT)); 3729 Alignment = MinAlign(Alignment, IncrementSize); 3730 Store2 = DAG.getTruncStore( 3731 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 3732 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 3733 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 3734 3735 SDValue Result = 3736 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 3737 return Result; 3738 } 3739 3740 SDValue 3741 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 3742 const SDLoc &DL, EVT DataVT, 3743 SelectionDAG &DAG, 3744 bool IsCompressedMemory) const { 3745 SDValue Increment; 3746 EVT AddrVT = Addr.getValueType(); 3747 EVT MaskVT = Mask.getValueType(); 3748 assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() && 3749 "Incompatible types of Data and Mask"); 3750 if (IsCompressedMemory) { 3751 // Incrementing the pointer according to number of '1's in the mask. 3752 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 3753 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 3754 if (MaskIntVT.getSizeInBits() < 32) { 3755 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 3756 MaskIntVT = MVT::i32; 3757 } 3758 3759 // Count '1's with POPCNT. 3760 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 3761 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 3762 // Scale is an element size in bytes. 3763 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 3764 AddrVT); 3765 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 3766 } else 3767 Increment = DAG.getConstant(DataVT.getSizeInBits() / 8, DL, AddrVT); 3768 3769 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 3770 } 3771 3772 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, 3773 SDValue Idx, 3774 EVT VecVT, 3775 const SDLoc &dl) { 3776 if (isa<ConstantSDNode>(Idx)) 3777 return Idx; 3778 3779 EVT IdxVT = Idx.getValueType(); 3780 unsigned NElts = VecVT.getVectorNumElements(); 3781 if (isPowerOf2_32(NElts)) { 3782 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), 3783 Log2_32(NElts)); 3784 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 3785 DAG.getConstant(Imm, dl, IdxVT)); 3786 } 3787 3788 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 3789 DAG.getConstant(NElts - 1, dl, IdxVT)); 3790 } 3791 3792 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 3793 SDValue VecPtr, EVT VecVT, 3794 SDValue Index) const { 3795 SDLoc dl(Index); 3796 // Make sure the index type is big enough to compute in. 3797 Index = DAG.getZExtOrTrunc(Index, dl, getPointerTy(DAG.getDataLayout())); 3798 3799 EVT EltVT = VecVT.getVectorElementType(); 3800 3801 // Calculate the element offset and add it to the pointer. 3802 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size. 3803 assert(EltSize * 8 == EltVT.getSizeInBits() && 3804 "Converting bits to bytes lost precision"); 3805 3806 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl); 3807 3808 EVT IdxVT = Index.getValueType(); 3809 3810 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 3811 DAG.getConstant(EltSize, dl, IdxVT)); 3812 return DAG.getNode(ISD::ADD, dl, IdxVT, Index, VecPtr); 3813 } 3814 3815 //===----------------------------------------------------------------------===// 3816 // Implementation of Emulated TLS Model 3817 //===----------------------------------------------------------------------===// 3818 3819 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 3820 SelectionDAG &DAG) const { 3821 // Access to address of TLS varialbe xyz is lowered to a function call: 3822 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 3823 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3824 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 3825 SDLoc dl(GA); 3826 3827 ArgListTy Args; 3828 ArgListEntry Entry; 3829 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 3830 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 3831 StringRef EmuTlsVarName(NameString); 3832 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 3833 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 3834 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 3835 Entry.Ty = VoidPtrType; 3836 Args.push_back(Entry); 3837 3838 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 3839 3840 TargetLowering::CallLoweringInfo CLI(DAG); 3841 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 3842 CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 3843 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3844 3845 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 3846 // At last for X86 targets, maybe good for other targets too? 3847 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 3848 MFI.setAdjustsStack(true); // Is this only for X86 target? 3849 MFI.setHasCalls(true); 3850 3851 assert((GA->getOffset() == 0) && 3852 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 3853 return CallResult.first; 3854 } 3855 3856 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 3857 SelectionDAG &DAG) const { 3858 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 3859 if (!isCtlzFast()) 3860 return SDValue(); 3861 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3862 SDLoc dl(Op); 3863 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 3864 if (C->isNullValue() && CC == ISD::SETEQ) { 3865 EVT VT = Op.getOperand(0).getValueType(); 3866 SDValue Zext = Op.getOperand(0); 3867 if (VT.bitsLT(MVT::i32)) { 3868 VT = MVT::i32; 3869 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 3870 } 3871 unsigned Log2b = Log2_32(VT.getSizeInBits()); 3872 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 3873 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 3874 DAG.getConstant(Log2b, dl, MVT::i32)); 3875 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 3876 } 3877 } 3878 return SDValue(); 3879 } 3880