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