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