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/TargetRegisterInfo.h" 24 #include "llvm/CodeGen/TargetSubtargetInfo.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/GlobalVariable.h" 28 #include "llvm/IR/LLVMContext.h" 29 #include "llvm/MC/MCAsmInfo.h" 30 #include "llvm/MC/MCExpr.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/KnownBits.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Target/TargetLoweringObjectFile.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 and NonNull because they don't affect the 59 // call sequence. 60 AttributeList CallerAttrs = F.getAttributes(); 61 if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex) 62 .removeAttribute(Attribute::NoAlias) 63 .removeAttribute(Attribute::NonNull) 64 .hasAttributes()) 65 return false; 66 67 // It's not safe to eliminate the sign / zero extension of the return value. 68 if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) || 69 CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt)) 70 return false; 71 72 // Check if the only use is a function return node. 73 return isUsedByReturnOnly(Node, Chain); 74 } 75 76 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI, 77 const uint32_t *CallerPreservedMask, 78 const SmallVectorImpl<CCValAssign> &ArgLocs, 79 const SmallVectorImpl<SDValue> &OutVals) const { 80 for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) { 81 const CCValAssign &ArgLoc = ArgLocs[I]; 82 if (!ArgLoc.isRegLoc()) 83 continue; 84 unsigned Reg = ArgLoc.getLocReg(); 85 // Only look at callee saved registers. 86 if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg)) 87 continue; 88 // Check that we pass the value used for the caller. 89 // (We look for a CopyFromReg reading a virtual register that is used 90 // for the function live-in value of register Reg) 91 SDValue Value = OutVals[I]; 92 if (Value->getOpcode() != ISD::CopyFromReg) 93 return false; 94 unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg(); 95 if (MRI.getLiveInPhysReg(ArgReg) != Reg) 96 return false; 97 } 98 return true; 99 } 100 101 /// Set CallLoweringInfo attribute flags based on a call instruction 102 /// and called function attributes. 103 void TargetLoweringBase::ArgListEntry::setAttributes(ImmutableCallSite *CS, 104 unsigned ArgIdx) { 105 IsSExt = CS->paramHasAttr(ArgIdx, Attribute::SExt); 106 IsZExt = CS->paramHasAttr(ArgIdx, Attribute::ZExt); 107 IsInReg = CS->paramHasAttr(ArgIdx, Attribute::InReg); 108 IsSRet = CS->paramHasAttr(ArgIdx, Attribute::StructRet); 109 IsNest = CS->paramHasAttr(ArgIdx, Attribute::Nest); 110 IsByVal = CS->paramHasAttr(ArgIdx, Attribute::ByVal); 111 IsInAlloca = CS->paramHasAttr(ArgIdx, Attribute::InAlloca); 112 IsReturned = CS->paramHasAttr(ArgIdx, Attribute::Returned); 113 IsSwiftSelf = CS->paramHasAttr(ArgIdx, Attribute::SwiftSelf); 114 IsSwiftError = CS->paramHasAttr(ArgIdx, Attribute::SwiftError); 115 Alignment = CS->getParamAlignment(ArgIdx); 116 } 117 118 /// Generate a libcall taking the given operands as arguments and returning a 119 /// result of type RetVT. 120 std::pair<SDValue, SDValue> 121 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT, 122 ArrayRef<SDValue> Ops, bool isSigned, 123 const SDLoc &dl, bool doesNotReturn, 124 bool isReturnValueUsed) const { 125 TargetLowering::ArgListTy Args; 126 Args.reserve(Ops.size()); 127 128 TargetLowering::ArgListEntry Entry; 129 for (SDValue Op : Ops) { 130 Entry.Node = Op; 131 Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext()); 132 Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned); 133 Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned); 134 Args.push_back(Entry); 135 } 136 137 if (LC == RTLIB::UNKNOWN_LIBCALL) 138 report_fatal_error("Unsupported library call operation!"); 139 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC), 140 getPointerTy(DAG.getDataLayout())); 141 142 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext()); 143 TargetLowering::CallLoweringInfo CLI(DAG); 144 bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned); 145 CLI.setDebugLoc(dl) 146 .setChain(DAG.getEntryNode()) 147 .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args)) 148 .setNoReturn(doesNotReturn) 149 .setDiscardResult(!isReturnValueUsed) 150 .setSExtResult(signExtend) 151 .setZExtResult(!signExtend); 152 return LowerCallTo(CLI); 153 } 154 155 /// Soften the operands of a comparison. This code is shared among BR_CC, 156 /// SELECT_CC, and SETCC handlers. 157 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT, 158 SDValue &NewLHS, SDValue &NewRHS, 159 ISD::CondCode &CCCode, 160 const SDLoc &dl) const { 161 assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128) 162 && "Unsupported setcc type!"); 163 164 // Expand into one or more soft-fp libcall(s). 165 RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL; 166 bool ShouldInvertCC = false; 167 switch (CCCode) { 168 case ISD::SETEQ: 169 case ISD::SETOEQ: 170 LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 171 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 172 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 173 break; 174 case ISD::SETNE: 175 case ISD::SETUNE: 176 LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : 177 (VT == MVT::f64) ? RTLIB::UNE_F64 : 178 (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128; 179 break; 180 case ISD::SETGE: 181 case ISD::SETOGE: 182 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 183 (VT == MVT::f64) ? RTLIB::OGE_F64 : 184 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 185 break; 186 case ISD::SETLT: 187 case ISD::SETOLT: 188 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 189 (VT == MVT::f64) ? RTLIB::OLT_F64 : 190 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 191 break; 192 case ISD::SETLE: 193 case ISD::SETOLE: 194 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 195 (VT == MVT::f64) ? RTLIB::OLE_F64 : 196 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 197 break; 198 case ISD::SETGT: 199 case ISD::SETOGT: 200 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 201 (VT == MVT::f64) ? RTLIB::OGT_F64 : 202 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 203 break; 204 case ISD::SETUO: 205 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 206 (VT == MVT::f64) ? RTLIB::UO_F64 : 207 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 208 break; 209 case ISD::SETO: 210 LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : 211 (VT == MVT::f64) ? RTLIB::O_F64 : 212 (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128; 213 break; 214 case ISD::SETONE: 215 // SETONE = SETOLT | SETOGT 216 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 217 (VT == MVT::f64) ? RTLIB::OLT_F64 : 218 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 219 LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 220 (VT == MVT::f64) ? RTLIB::OGT_F64 : 221 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 222 break; 223 case ISD::SETUEQ: 224 LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : 225 (VT == MVT::f64) ? RTLIB::UO_F64 : 226 (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128; 227 LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : 228 (VT == MVT::f64) ? RTLIB::OEQ_F64 : 229 (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128; 230 break; 231 default: 232 // Invert CC for unordered comparisons 233 ShouldInvertCC = true; 234 switch (CCCode) { 235 case ISD::SETULT: 236 LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : 237 (VT == MVT::f64) ? RTLIB::OGE_F64 : 238 (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128; 239 break; 240 case ISD::SETULE: 241 LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : 242 (VT == MVT::f64) ? RTLIB::OGT_F64 : 243 (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128; 244 break; 245 case ISD::SETUGT: 246 LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : 247 (VT == MVT::f64) ? RTLIB::OLE_F64 : 248 (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128; 249 break; 250 case ISD::SETUGE: 251 LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : 252 (VT == MVT::f64) ? RTLIB::OLT_F64 : 253 (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128; 254 break; 255 default: llvm_unreachable("Do not know how to soften this setcc!"); 256 } 257 } 258 259 // Use the target specific return value for comparions lib calls. 260 EVT RetVT = getCmpLibcallReturnType(); 261 SDValue Ops[2] = {NewLHS, NewRHS}; 262 NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/, 263 dl).first; 264 NewRHS = DAG.getConstant(0, dl, RetVT); 265 266 CCCode = getCmpLibcallCC(LC1); 267 if (ShouldInvertCC) 268 CCCode = getSetCCInverse(CCCode, /*isInteger=*/true); 269 270 if (LC2 != RTLIB::UNKNOWN_LIBCALL) { 271 SDValue Tmp = DAG.getNode( 272 ISD::SETCC, dl, 273 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT), 274 NewLHS, NewRHS, DAG.getCondCode(CCCode)); 275 NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/, 276 dl).first; 277 NewLHS = DAG.getNode( 278 ISD::SETCC, dl, 279 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT), 280 NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2))); 281 NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS); 282 NewRHS = SDValue(); 283 } 284 } 285 286 /// Return the entry encoding for a jump table in the current function. The 287 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum. 288 unsigned TargetLowering::getJumpTableEncoding() const { 289 // In non-pic modes, just use the address of a block. 290 if (!isPositionIndependent()) 291 return MachineJumpTableInfo::EK_BlockAddress; 292 293 // In PIC mode, if the target supports a GPRel32 directive, use it. 294 if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr) 295 return MachineJumpTableInfo::EK_GPRel32BlockAddress; 296 297 // Otherwise, use a label difference. 298 return MachineJumpTableInfo::EK_LabelDifference32; 299 } 300 301 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table, 302 SelectionDAG &DAG) const { 303 // If our PIC model is GP relative, use the global offset table as the base. 304 unsigned JTEncoding = getJumpTableEncoding(); 305 306 if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) || 307 (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress)) 308 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout())); 309 310 return Table; 311 } 312 313 /// This returns the relocation base for the given PIC jumptable, the same as 314 /// getPICJumpTableRelocBase, but as an MCExpr. 315 const MCExpr * 316 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF, 317 unsigned JTI,MCContext &Ctx) const{ 318 // The normal PIC reloc base is the label at the start of the jump table. 319 return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx); 320 } 321 322 bool 323 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 324 const TargetMachine &TM = getTargetMachine(); 325 const GlobalValue *GV = GA->getGlobal(); 326 327 // If the address is not even local to this DSO we will have to load it from 328 // a got and then add the offset. 329 if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV)) 330 return false; 331 332 // If the code is position independent we will have to add a base register. 333 if (isPositionIndependent()) 334 return false; 335 336 // Otherwise we can do it. 337 return true; 338 } 339 340 //===----------------------------------------------------------------------===// 341 // Optimization Methods 342 //===----------------------------------------------------------------------===// 343 344 /// If the specified instruction has a constant integer operand and there are 345 /// bits set in that constant that are not demanded, then clear those bits and 346 /// return true. 347 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, const APInt &Demanded, 348 TargetLoweringOpt &TLO) const { 349 SelectionDAG &DAG = TLO.DAG; 350 SDLoc DL(Op); 351 unsigned Opcode = Op.getOpcode(); 352 353 // Do target-specific constant optimization. 354 if (targetShrinkDemandedConstant(Op, Demanded, TLO)) 355 return TLO.New.getNode(); 356 357 // FIXME: ISD::SELECT, ISD::SELECT_CC 358 switch (Opcode) { 359 default: 360 break; 361 case ISD::XOR: 362 case ISD::AND: 363 case ISD::OR: { 364 auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 365 if (!Op1C) 366 return false; 367 368 // If this is a 'not' op, don't touch it because that's a canonical form. 369 const APInt &C = Op1C->getAPIntValue(); 370 if (Opcode == ISD::XOR && Demanded.isSubsetOf(C)) 371 return false; 372 373 if (!C.isSubsetOf(Demanded)) { 374 EVT VT = Op.getValueType(); 375 SDValue NewC = DAG.getConstant(Demanded & C, DL, VT); 376 SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC); 377 return TLO.CombineTo(Op, NewOp); 378 } 379 380 break; 381 } 382 } 383 384 return false; 385 } 386 387 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free. 388 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be 389 /// generalized for targets with other types of implicit widening casts. 390 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth, 391 const APInt &Demanded, 392 TargetLoweringOpt &TLO) const { 393 assert(Op.getNumOperands() == 2 && 394 "ShrinkDemandedOp only supports binary operators!"); 395 assert(Op.getNode()->getNumValues() == 1 && 396 "ShrinkDemandedOp only supports nodes with one result!"); 397 398 SelectionDAG &DAG = TLO.DAG; 399 SDLoc dl(Op); 400 401 // Early return, as this function cannot handle vector types. 402 if (Op.getValueType().isVector()) 403 return false; 404 405 // Don't do this if the node has another user, which may require the 406 // full value. 407 if (!Op.getNode()->hasOneUse()) 408 return false; 409 410 // Search for the smallest integer type with free casts to and from 411 // Op's type. For expedience, just check power-of-2 integer types. 412 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 413 unsigned DemandedSize = Demanded.getActiveBits(); 414 unsigned SmallVTBits = DemandedSize; 415 if (!isPowerOf2_32(SmallVTBits)) 416 SmallVTBits = NextPowerOf2(SmallVTBits); 417 for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) { 418 EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits); 419 if (TLI.isTruncateFree(Op.getValueType(), SmallVT) && 420 TLI.isZExtFree(SmallVT, Op.getValueType())) { 421 // We found a type with free casts. 422 SDValue X = DAG.getNode( 423 Op.getOpcode(), dl, SmallVT, 424 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)), 425 DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1))); 426 assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?"); 427 SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X); 428 return TLO.CombineTo(Op, Z); 429 } 430 } 431 return false; 432 } 433 434 bool 435 TargetLowering::SimplifyDemandedBits(SDNode *User, unsigned OpIdx, 436 const APInt &DemandedBits, 437 DAGCombinerInfo &DCI, 438 TargetLoweringOpt &TLO) const { 439 SDValue Op = User->getOperand(OpIdx); 440 KnownBits Known; 441 442 if (!SimplifyDemandedBits(Op, DemandedBits, Known, TLO, 0, true)) 443 return false; 444 445 446 // Old will not always be the same as Op. For example: 447 // 448 // Demanded = 0xffffff 449 // Op = i64 truncate (i32 and x, 0xffffff) 450 // In this case simplify demand bits will want to replace the 'and' node 451 // with the value 'x', which will give us: 452 // Old = i32 and x, 0xffffff 453 // New = x 454 if (TLO.Old.hasOneUse()) { 455 // For the one use case, we just commit the change. 456 DCI.CommitTargetLoweringOpt(TLO); 457 return true; 458 } 459 460 // If Old has more than one use then it must be Op, because the 461 // AssumeSingleUse flag is not propogated to recursive calls of 462 // SimplifyDemanded bits, so the only node with multiple use that 463 // it will attempt to combine will be Op. 464 assert(TLO.Old == Op); 465 466 SmallVector <SDValue, 4> NewOps; 467 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { 468 if (i == OpIdx) { 469 NewOps.push_back(TLO.New); 470 continue; 471 } 472 NewOps.push_back(User->getOperand(i)); 473 } 474 User = TLO.DAG.UpdateNodeOperands(User, NewOps); 475 // Op has less users now, so we may be able to perform additional combines 476 // with it. 477 DCI.AddToWorklist(Op.getNode()); 478 // User's operands have been updated, so we may be able to do new combines 479 // with it. 480 DCI.AddToWorklist(User); 481 return true; 482 } 483 484 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 485 DAGCombinerInfo &DCI) const { 486 SelectionDAG &DAG = DCI.DAG; 487 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 488 !DCI.isBeforeLegalizeOps()); 489 KnownBits Known; 490 491 bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO); 492 if (Simplified) { 493 DCI.AddToWorklist(Op.getNode()); 494 DCI.CommitTargetLoweringOpt(TLO); 495 } 496 return Simplified; 497 } 498 499 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 500 KnownBits &Known, 501 TargetLoweringOpt &TLO, 502 unsigned Depth, 503 bool AssumeSingleUse) const { 504 EVT VT = Op.getValueType(); 505 APInt DemandedElts = VT.isVector() 506 ? APInt::getAllOnesValue(VT.getVectorNumElements()) 507 : APInt(1, 1); 508 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth, 509 AssumeSingleUse); 510 } 511 512 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the 513 /// result of Op are ever used downstream. If we can use this information to 514 /// simplify Op, create a new simplified DAG node and return true, returning the 515 /// original and new nodes in Old and New. Otherwise, analyze the expression and 516 /// return a mask of Known bits for the expression (used to simplify the 517 /// caller). The Known bits may only be accurate for those bits in the 518 /// OriginalDemandedBits and OriginalDemandedElts. 519 bool TargetLowering::SimplifyDemandedBits( 520 SDValue Op, const APInt &OriginalDemandedBits, 521 const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO, 522 unsigned Depth, bool AssumeSingleUse) const { 523 unsigned BitWidth = OriginalDemandedBits.getBitWidth(); 524 assert(Op.getScalarValueSizeInBits() == BitWidth && 525 "Mask size mismatches value type size!"); 526 527 unsigned NumElts = OriginalDemandedElts.getBitWidth(); 528 assert((!Op.getValueType().isVector() || 529 NumElts == Op.getValueType().getVectorNumElements()) && 530 "Unexpected vector size"); 531 532 APInt DemandedBits = OriginalDemandedBits; 533 APInt DemandedElts = OriginalDemandedElts; 534 SDLoc dl(Op); 535 auto &DL = TLO.DAG.getDataLayout(); 536 537 // Don't know anything. 538 Known = KnownBits(BitWidth); 539 540 if (Op.getOpcode() == ISD::Constant) { 541 // We know all of the bits for a constant! 542 Known.One = cast<ConstantSDNode>(Op)->getAPIntValue(); 543 Known.Zero = ~Known.One; 544 return false; 545 } 546 547 // Other users may use these bits. 548 EVT VT = Op.getValueType(); 549 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) { 550 if (Depth != 0) { 551 // If not at the root, Just compute the Known bits to 552 // simplify things downstream. 553 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 554 return false; 555 } 556 // If this is the root being simplified, allow it to have multiple uses, 557 // just set the DemandedBits/Elts to all bits. 558 DemandedBits = APInt::getAllOnesValue(BitWidth); 559 DemandedElts = APInt::getAllOnesValue(NumElts); 560 } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) { 561 // Not demanding any bits/elts from Op. 562 if (!Op.isUndef()) 563 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 564 return false; 565 } else if (Depth == 6) { // Limit search depth. 566 return false; 567 } 568 569 KnownBits Known2, KnownOut; 570 switch (Op.getOpcode()) { 571 case ISD::BUILD_VECTOR: 572 // Collect the known bits that are shared by every constant vector element. 573 Known.Zero.setAllBits(); Known.One.setAllBits(); 574 for (SDValue SrcOp : Op->ops()) { 575 if (!isa<ConstantSDNode>(SrcOp)) { 576 // We can only handle all constant values - bail out with no known bits. 577 Known = KnownBits(BitWidth); 578 return false; 579 } 580 Known2.One = cast<ConstantSDNode>(SrcOp)->getAPIntValue(); 581 Known2.Zero = ~Known2.One; 582 583 // BUILD_VECTOR can implicitly truncate sources, we must handle this. 584 if (Known2.One.getBitWidth() != BitWidth) { 585 assert(Known2.getBitWidth() > BitWidth && 586 "Expected BUILD_VECTOR implicit truncation"); 587 Known2 = Known2.trunc(BitWidth); 588 } 589 590 // Known bits are the values that are shared by every element. 591 // TODO: support per-element known bits. 592 Known.One &= Known2.One; 593 Known.Zero &= Known2.Zero; 594 } 595 return false; // Don't fall through, will infinitely loop. 596 case ISD::CONCAT_VECTORS: { 597 Known.Zero.setAllBits(); 598 Known.One.setAllBits(); 599 EVT SubVT = Op.getOperand(0).getValueType(); 600 unsigned NumSubVecs = Op.getNumOperands(); 601 unsigned NumSubElts = SubVT.getVectorNumElements(); 602 for (unsigned i = 0; i != NumSubVecs; ++i) { 603 APInt DemandedSubElts = 604 DemandedElts.extractBits(NumSubElts, i * NumSubElts); 605 if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts, 606 Known2, TLO, Depth + 1)) 607 return true; 608 // Known bits are shared by every demanded subvector element. 609 if (!!DemandedSubElts) { 610 Known.One &= Known2.One; 611 Known.Zero &= Known2.Zero; 612 } 613 } 614 break; 615 } 616 case ISD::VECTOR_SHUFFLE: { 617 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 618 619 // Collect demanded elements from shuffle operands.. 620 APInt DemandedLHS(NumElts, 0); 621 APInt DemandedRHS(NumElts, 0); 622 for (unsigned i = 0; i != NumElts; ++i) { 623 if (!DemandedElts[i]) 624 continue; 625 int M = ShuffleMask[i]; 626 if (M < 0) { 627 // For UNDEF elements, we don't know anything about the common state of 628 // the shuffle result. 629 DemandedLHS.clearAllBits(); 630 DemandedRHS.clearAllBits(); 631 break; 632 } 633 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 634 if (M < (int)NumElts) 635 DemandedLHS.setBit(M); 636 else 637 DemandedRHS.setBit(M - NumElts); 638 } 639 640 if (!!DemandedLHS || !!DemandedRHS) { 641 Known.Zero.setAllBits(); 642 Known.One.setAllBits(); 643 if (!!DemandedLHS) { 644 if (SimplifyDemandedBits(Op.getOperand(0), DemandedBits, DemandedLHS, 645 Known2, TLO, Depth + 1)) 646 return true; 647 Known.One &= Known2.One; 648 Known.Zero &= Known2.Zero; 649 } 650 if (!!DemandedRHS) { 651 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedRHS, 652 Known2, TLO, Depth + 1)) 653 return true; 654 Known.One &= Known2.One; 655 Known.Zero &= Known2.Zero; 656 } 657 } 658 break; 659 } 660 case ISD::AND: { 661 SDValue Op0 = Op.getOperand(0); 662 SDValue Op1 = Op.getOperand(1); 663 664 // If the RHS is a constant, check to see if the LHS would be zero without 665 // using the bits from the RHS. Below, we use knowledge about the RHS to 666 // simplify the LHS, here we're using information from the LHS to simplify 667 // the RHS. 668 if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) { 669 // Do not increment Depth here; that can cause an infinite loop. 670 KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth); 671 // If the LHS already has zeros where RHSC does, this 'and' is dead. 672 if ((LHSKnown.Zero & DemandedBits) == 673 (~RHSC->getAPIntValue() & DemandedBits)) 674 return TLO.CombineTo(Op, Op0); 675 676 // If any of the set bits in the RHS are known zero on the LHS, shrink 677 // the constant. 678 if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, TLO)) 679 return true; 680 681 // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its 682 // constant, but if this 'and' is only clearing bits that were just set by 683 // the xor, then this 'and' can be eliminated by shrinking the mask of 684 // the xor. For example, for a 32-bit X: 685 // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1 686 if (isBitwiseNot(Op0) && Op0.hasOneUse() && 687 LHSKnown.One == ~RHSC->getAPIntValue()) { 688 SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1); 689 return TLO.CombineTo(Op, Xor); 690 } 691 } 692 693 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, Depth + 1)) 694 return true; 695 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 696 if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts, Known2, TLO, 697 Depth + 1)) 698 return true; 699 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 700 701 // If all of the demanded bits are known one on one side, return the other. 702 // These bits cannot contribute to the result of the 'and'. 703 if (DemandedBits.isSubsetOf(Known2.Zero | Known.One)) 704 return TLO.CombineTo(Op, Op0); 705 if (DemandedBits.isSubsetOf(Known.Zero | Known2.One)) 706 return TLO.CombineTo(Op, Op1); 707 // If all of the demanded bits in the inputs are known zeros, return zero. 708 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 709 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT)); 710 // If the RHS is a constant, see if we can simplify it. 711 if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, TLO)) 712 return true; 713 // If the operation can be done in a smaller type, do so. 714 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 715 return true; 716 717 // Output known-1 bits are only known if set in both the LHS & RHS. 718 Known.One &= Known2.One; 719 // Output known-0 are known to be clear if zero in either the LHS | RHS. 720 Known.Zero |= Known2.Zero; 721 break; 722 } 723 case ISD::OR: { 724 SDValue Op0 = Op.getOperand(0); 725 SDValue Op1 = Op.getOperand(1); 726 727 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, Depth + 1)) 728 return true; 729 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 730 if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts, Known2, TLO, 731 Depth + 1)) 732 return true; 733 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 734 735 // If all of the demanded bits are known zero on one side, return the other. 736 // These bits cannot contribute to the result of the 'or'. 737 if (DemandedBits.isSubsetOf(Known2.One | Known.Zero)) 738 return TLO.CombineTo(Op, Op0); 739 if (DemandedBits.isSubsetOf(Known.One | Known2.Zero)) 740 return TLO.CombineTo(Op, Op1); 741 // If the RHS is a constant, see if we can simplify it. 742 if (ShrinkDemandedConstant(Op, DemandedBits, TLO)) 743 return true; 744 // If the operation can be done in a smaller type, do so. 745 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 746 return true; 747 748 // Output known-0 bits are only known if clear in both the LHS & RHS. 749 Known.Zero &= Known2.Zero; 750 // Output known-1 are known to be set if set in either the LHS | RHS. 751 Known.One |= Known2.One; 752 break; 753 } 754 case ISD::XOR: { 755 SDValue Op0 = Op.getOperand(0); 756 SDValue Op1 = Op.getOperand(1); 757 758 if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO, Depth + 1)) 759 return true; 760 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 761 if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO, Depth + 1)) 762 return true; 763 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 764 765 // If all of the demanded bits are known zero on one side, return the other. 766 // These bits cannot contribute to the result of the 'xor'. 767 if (DemandedBits.isSubsetOf(Known.Zero)) 768 return TLO.CombineTo(Op, Op0); 769 if (DemandedBits.isSubsetOf(Known2.Zero)) 770 return TLO.CombineTo(Op, Op1); 771 // If the operation can be done in a smaller type, do so. 772 if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) 773 return true; 774 775 // If all of the unknown bits are known to be zero on one side or the other 776 // (but not both) turn this into an *inclusive* or. 777 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0 778 if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero)) 779 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1)); 780 781 // Output known-0 bits are known if clear or set in both the LHS & RHS. 782 KnownOut.Zero = (Known.Zero & Known2.Zero) | (Known.One & Known2.One); 783 // Output known-1 are known to be set if set in only one of the LHS, RHS. 784 KnownOut.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero); 785 786 if (ConstantSDNode *C = isConstOrConstSplat(Op1)) { 787 // If one side is a constant, and all of the known set bits on the other 788 // side are also set in the constant, turn this into an AND, as we know 789 // the bits will be cleared. 790 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2 791 // NB: it is okay if more bits are known than are requested 792 if (C->getAPIntValue() == Known2.One) { 793 SDValue ANDC = 794 TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT); 795 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC)); 796 } 797 798 // If the RHS is a constant, see if we can change it. Don't alter a -1 799 // constant because that's a 'not' op, and that is better for combining 800 // and codegen. 801 if (!C->isAllOnesValue()) { 802 if (DemandedBits.isSubsetOf(C->getAPIntValue())) { 803 // We're flipping all demanded bits. Flip the undemanded bits too. 804 SDValue New = TLO.DAG.getNOT(dl, Op0, VT); 805 return TLO.CombineTo(Op, New); 806 } 807 // If we can't turn this into a 'not', try to shrink the constant. 808 if (ShrinkDemandedConstant(Op, DemandedBits, TLO)) 809 return true; 810 } 811 } 812 813 Known = std::move(KnownOut); 814 break; 815 } 816 case ISD::SELECT: 817 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO, 818 Depth + 1)) 819 return true; 820 if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO, 821 Depth + 1)) 822 return true; 823 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 824 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 825 826 // If the operands are constants, see if we can simplify them. 827 if (ShrinkDemandedConstant(Op, DemandedBits, TLO)) 828 return true; 829 830 // Only known if known in both the LHS and RHS. 831 Known.One &= Known2.One; 832 Known.Zero &= Known2.Zero; 833 break; 834 case ISD::SELECT_CC: 835 if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO, 836 Depth + 1)) 837 return true; 838 if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO, 839 Depth + 1)) 840 return true; 841 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 842 assert(!Known2.hasConflict() && "Bits known to be one AND zero?"); 843 844 // If the operands are constants, see if we can simplify them. 845 if (ShrinkDemandedConstant(Op, DemandedBits, TLO)) 846 return true; 847 848 // Only known if known in both the LHS and RHS. 849 Known.One &= Known2.One; 850 Known.Zero &= Known2.Zero; 851 break; 852 case ISD::SETCC: { 853 SDValue Op0 = Op.getOperand(0); 854 SDValue Op1 = Op.getOperand(1); 855 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 856 // If (1) we only need the sign-bit, (2) the setcc operands are the same 857 // width as the setcc result, and (3) the result of a setcc conforms to 0 or 858 // -1, we may be able to bypass the setcc. 859 if (DemandedBits.isSignMask() && 860 Op0.getScalarValueSizeInBits() == BitWidth && 861 getBooleanContents(VT) == 862 BooleanContent::ZeroOrNegativeOneBooleanContent) { 863 // If we're testing X < 0, then this compare isn't needed - just use X! 864 // FIXME: We're limiting to integer types here, but this should also work 865 // if we don't care about FP signed-zero. The use of SETLT with FP means 866 // that we don't care about NaNs. 867 if (CC == ISD::SETLT && Op1.getValueType().isInteger() && 868 (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode()))) 869 return TLO.CombineTo(Op, Op0); 870 871 // TODO: Should we check for other forms of sign-bit comparisons? 872 // Examples: X <= -1, X >= 0 873 } 874 if (getBooleanContents(Op0.getValueType()) == 875 TargetLowering::ZeroOrOneBooleanContent && 876 BitWidth > 1) 877 Known.Zero.setBitsFrom(1); 878 break; 879 } 880 case ISD::SHL: { 881 SDValue Op0 = Op.getOperand(0); 882 SDValue Op1 = Op.getOperand(1); 883 884 if (ConstantSDNode *SA = isConstOrConstSplat(Op1)) { 885 // If the shift count is an invalid immediate, don't do anything. 886 if (SA->getAPIntValue().uge(BitWidth)) 887 break; 888 889 unsigned ShAmt = SA->getZExtValue(); 890 891 // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a 892 // single shift. We can do this if the bottom bits (which are shifted 893 // out) are never demanded. 894 if (Op0.getOpcode() == ISD::SRL) { 895 if (ShAmt && 896 (DemandedBits & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) { 897 if (ConstantSDNode *SA2 = isConstOrConstSplat(Op0.getOperand(1))) { 898 if (SA2->getAPIntValue().ult(BitWidth)) { 899 unsigned C1 = SA2->getZExtValue(); 900 unsigned Opc = ISD::SHL; 901 int Diff = ShAmt - C1; 902 if (Diff < 0) { 903 Diff = -Diff; 904 Opc = ISD::SRL; 905 } 906 907 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, Op1.getValueType()); 908 return TLO.CombineTo( 909 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 910 } 911 } 912 } 913 } 914 915 if (SimplifyDemandedBits(Op0, DemandedBits.lshr(ShAmt), DemandedElts, Known, TLO, 916 Depth + 1)) 917 return true; 918 919 // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits 920 // are not demanded. This will likely allow the anyext to be folded away. 921 if (Op0.getOpcode() == ISD::ANY_EXTEND) { 922 SDValue InnerOp = Op0.getOperand(0); 923 EVT InnerVT = InnerOp.getValueType(); 924 unsigned InnerBits = InnerVT.getScalarSizeInBits(); 925 if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits && 926 isTypeDesirableForOp(ISD::SHL, InnerVT)) { 927 EVT ShTy = getShiftAmountTy(InnerVT, DL); 928 if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits())) 929 ShTy = InnerVT; 930 SDValue NarrowShl = 931 TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp, 932 TLO.DAG.getConstant(ShAmt, dl, ShTy)); 933 return TLO.CombineTo( 934 Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl)); 935 } 936 // Repeat the SHL optimization above in cases where an extension 937 // intervenes: (shl (anyext (shr x, c1)), c2) to 938 // (shl (anyext x), c2-c1). This requires that the bottom c1 bits 939 // aren't demanded (as above) and that the shifted upper c1 bits of 940 // x aren't demanded. 941 if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL && 942 InnerOp.hasOneUse()) { 943 if (ConstantSDNode *SA2 = 944 isConstOrConstSplat(InnerOp.getOperand(1))) { 945 unsigned InnerShAmt = SA2->getLimitedValue(InnerBits); 946 if (InnerShAmt < ShAmt && InnerShAmt < InnerBits && 947 DemandedBits.getActiveBits() <= 948 (InnerBits - InnerShAmt + ShAmt) && 949 DemandedBits.countTrailingZeros() >= ShAmt) { 950 SDValue NewSA = TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, 951 Op1.getValueType()); 952 SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, 953 InnerOp.getOperand(0)); 954 return TLO.CombineTo( 955 Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA)); 956 } 957 } 958 } 959 } 960 961 Known.Zero <<= ShAmt; 962 Known.One <<= ShAmt; 963 // low bits known zero. 964 Known.Zero.setLowBits(ShAmt); 965 } 966 break; 967 } 968 case ISD::SRL: { 969 SDValue Op0 = Op.getOperand(0); 970 SDValue Op1 = Op.getOperand(1); 971 972 if (ConstantSDNode *SA = isConstOrConstSplat(Op1)) { 973 // If the shift count is an invalid immediate, don't do anything. 974 if (SA->getAPIntValue().uge(BitWidth)) 975 break; 976 977 unsigned ShAmt = SA->getZExtValue(); 978 APInt InDemandedMask = (DemandedBits << ShAmt); 979 980 // If the shift is exact, then it does demand the low bits (and knows that 981 // they are zero). 982 if (Op->getFlags().hasExact()) 983 InDemandedMask.setLowBits(ShAmt); 984 985 // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a 986 // single shift. We can do this if the top bits (which are shifted out) 987 // are never demanded. 988 if (Op0.getOpcode() == ISD::SHL) { 989 if (ConstantSDNode *SA2 = isConstOrConstSplat(Op0.getOperand(1))) { 990 if (ShAmt && 991 (DemandedBits & APInt::getHighBitsSet(BitWidth, ShAmt)) == 0) { 992 if (SA2->getAPIntValue().ult(BitWidth)) { 993 unsigned C1 = SA2->getZExtValue(); 994 unsigned Opc = ISD::SRL; 995 int Diff = ShAmt - C1; 996 if (Diff < 0) { 997 Diff = -Diff; 998 Opc = ISD::SHL; 999 } 1000 1001 SDValue NewSA = TLO.DAG.getConstant(Diff, dl, Op1.getValueType()); 1002 return TLO.CombineTo( 1003 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA)); 1004 } 1005 } 1006 } 1007 } 1008 1009 // Compute the new bits that are at the top now. 1010 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, Depth + 1)) 1011 return true; 1012 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1013 Known.Zero.lshrInPlace(ShAmt); 1014 Known.One.lshrInPlace(ShAmt); 1015 1016 Known.Zero.setHighBits(ShAmt); // High bits known zero. 1017 } 1018 break; 1019 } 1020 case ISD::SRA: { 1021 SDValue Op0 = Op.getOperand(0); 1022 SDValue Op1 = Op.getOperand(1); 1023 1024 // If this is an arithmetic shift right and only the low-bit is set, we can 1025 // always convert this into a logical shr, even if the shift amount is 1026 // variable. The low bit of the shift cannot be an input sign bit unless 1027 // the shift amount is >= the size of the datatype, which is undefined. 1028 if (DemandedBits.isOneValue()) 1029 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1)); 1030 1031 if (ConstantSDNode *SA = isConstOrConstSplat(Op1)) { 1032 // If the shift count is an invalid immediate, don't do anything. 1033 if (SA->getAPIntValue().uge(BitWidth)) 1034 break; 1035 1036 unsigned ShAmt = SA->getZExtValue(); 1037 APInt InDemandedMask = (DemandedBits << ShAmt); 1038 1039 // If the shift is exact, then it does demand the low bits (and knows that 1040 // they are zero). 1041 if (Op->getFlags().hasExact()) 1042 InDemandedMask.setLowBits(ShAmt); 1043 1044 // If any of the demanded bits are produced by the sign extension, we also 1045 // demand the input sign bit. 1046 if (DemandedBits.countLeadingZeros() < ShAmt) 1047 InDemandedMask.setSignBit(); 1048 1049 if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO, Depth + 1)) 1050 return true; 1051 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1052 Known.Zero.lshrInPlace(ShAmt); 1053 Known.One.lshrInPlace(ShAmt); 1054 1055 // If the input sign bit is known to be zero, or if none of the top bits 1056 // are demanded, turn this into an unsigned shift right. 1057 if (Known.Zero[BitWidth - ShAmt - 1] || 1058 DemandedBits.countLeadingZeros() >= ShAmt) { 1059 SDNodeFlags Flags; 1060 Flags.setExact(Op->getFlags().hasExact()); 1061 return TLO.CombineTo( 1062 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags)); 1063 } 1064 1065 int Log2 = DemandedBits.exactLogBase2(); 1066 if (Log2 >= 0) { 1067 // The bit must come from the sign. 1068 SDValue NewSA = 1069 TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, Op1.getValueType()); 1070 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA)); 1071 } 1072 1073 if (Known.One[BitWidth - ShAmt - 1]) 1074 // New bits are known one. 1075 Known.One.setHighBits(ShAmt); 1076 } 1077 break; 1078 } 1079 case ISD::SIGN_EXTEND_INREG: { 1080 SDValue Op0 = Op.getOperand(0); 1081 EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1082 unsigned ExVTBits = ExVT.getScalarSizeInBits(); 1083 1084 // If we only care about the highest bit, don't bother shifting right. 1085 if (DemandedBits.isSignMask()) { 1086 bool AlreadySignExtended = 1087 TLO.DAG.ComputeNumSignBits(Op0) >= BitWidth - ExVTBits + 1; 1088 // However if the input is already sign extended we expect the sign 1089 // extension to be dropped altogether later and do not simplify. 1090 if (!AlreadySignExtended) { 1091 // Compute the correct shift amount type, which must be getShiftAmountTy 1092 // for scalar types after legalization. 1093 EVT ShiftAmtTy = VT; 1094 if (TLO.LegalTypes() && !ShiftAmtTy.isVector()) 1095 ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL); 1096 1097 SDValue ShiftAmt = 1098 TLO.DAG.getConstant(BitWidth - ExVTBits, dl, ShiftAmtTy); 1099 return TLO.CombineTo(Op, 1100 TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt)); 1101 } 1102 } 1103 1104 // If none of the extended bits are demanded, eliminate the sextinreg. 1105 if (DemandedBits.getActiveBits() <= ExVTBits) 1106 return TLO.CombineTo(Op, Op0); 1107 1108 APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits); 1109 1110 // Since the sign extended bits are demanded, we know that the sign 1111 // bit is demanded. 1112 InputDemandedBits.setBit(ExVTBits - 1); 1113 1114 if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1)) 1115 return true; 1116 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1117 1118 // If the sign bit of the input is known set or clear, then we know the 1119 // top bits of the result. 1120 1121 // If the input sign bit is known zero, convert this into a zero extension. 1122 if (Known.Zero[ExVTBits - 1]) 1123 return TLO.CombineTo( 1124 Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT.getScalarType())); 1125 1126 APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits); 1127 if (Known.One[ExVTBits - 1]) { // Input sign bit known set 1128 Known.One.setBitsFrom(ExVTBits); 1129 Known.Zero &= Mask; 1130 } else { // Input sign bit unknown 1131 Known.Zero &= Mask; 1132 Known.One &= Mask; 1133 } 1134 break; 1135 } 1136 case ISD::BUILD_PAIR: { 1137 EVT HalfVT = Op.getOperand(0).getValueType(); 1138 unsigned HalfBitWidth = HalfVT.getScalarSizeInBits(); 1139 1140 APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth); 1141 APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth); 1142 1143 KnownBits KnownLo, KnownHi; 1144 1145 if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1)) 1146 return true; 1147 1148 if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1)) 1149 return true; 1150 1151 Known.Zero = KnownLo.Zero.zext(BitWidth) | 1152 KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth); 1153 1154 Known.One = KnownLo.One.zext(BitWidth) | 1155 KnownHi.One.zext(BitWidth).shl(HalfBitWidth); 1156 break; 1157 } 1158 case ISD::ZERO_EXTEND: { 1159 SDValue Src = Op.getOperand(0); 1160 unsigned InBits = Src.getScalarValueSizeInBits(); 1161 1162 // If none of the top bits are demanded, convert this into an any_extend. 1163 if (DemandedBits.getActiveBits() <= InBits) 1164 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, Src)); 1165 1166 APInt InDemandedBits = DemandedBits.trunc(InBits); 1167 if (SimplifyDemandedBits(Src, InDemandedBits, Known, TLO, Depth+1)) 1168 return true; 1169 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1170 Known = Known.zext(BitWidth); 1171 Known.Zero.setBitsFrom(InBits); 1172 break; 1173 } 1174 case ISD::SIGN_EXTEND: { 1175 SDValue Src = Op.getOperand(0); 1176 unsigned InBits = Src.getScalarValueSizeInBits(); 1177 1178 // If none of the top bits are demanded, convert this into an any_extend. 1179 if (DemandedBits.getActiveBits() <= InBits) 1180 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, Src)); 1181 1182 // Since some of the sign extended bits are demanded, we know that the sign 1183 // bit is demanded. 1184 APInt InDemandedBits = DemandedBits.trunc(InBits); 1185 InDemandedBits.setBit(InBits - 1); 1186 1187 if (SimplifyDemandedBits(Src, InDemandedBits, Known, TLO, Depth + 1)) 1188 return true; 1189 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1190 // If the sign bit is known one, the top bits match. 1191 Known = Known.sext(BitWidth); 1192 1193 // If the sign bit is known zero, convert this to a zero extend. 1194 if (Known.isNonNegative()) 1195 return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Src)); 1196 break; 1197 } 1198 case ISD::SIGN_EXTEND_VECTOR_INREG: { 1199 // TODO - merge this with SIGN_EXTEND above? 1200 SDValue Src = Op.getOperand(0); 1201 unsigned InBits = Src.getScalarValueSizeInBits(); 1202 1203 APInt InDemandedBits = DemandedBits.trunc(InBits); 1204 1205 // If some of the sign extended bits are demanded, we know that the sign 1206 // bit is demanded. 1207 if (InBits < DemandedBits.getActiveBits()) 1208 InDemandedBits.setBit(InBits - 1); 1209 1210 if (SimplifyDemandedBits(Src, InDemandedBits, Known, TLO, Depth + 1)) 1211 return true; 1212 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1213 // If the sign bit is known one, the top bits match. 1214 Known = Known.sext(BitWidth); 1215 break; 1216 } 1217 case ISD::ANY_EXTEND: { 1218 SDValue Src = Op.getOperand(0); 1219 unsigned InBits = Src.getScalarValueSizeInBits(); 1220 APInt InDemandedBits = DemandedBits.trunc(InBits); 1221 if (SimplifyDemandedBits(Src, InDemandedBits, Known, TLO, Depth+1)) 1222 return true; 1223 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1224 Known = Known.zext(BitWidth); 1225 break; 1226 } 1227 case ISD::TRUNCATE: { 1228 SDValue Src = Op.getOperand(0); 1229 1230 // Simplify the input, using demanded bit information, and compute the known 1231 // zero/one bits live out. 1232 unsigned OperandBitWidth = Src.getScalarValueSizeInBits(); 1233 APInt TruncMask = DemandedBits.zext(OperandBitWidth); 1234 if (SimplifyDemandedBits(Src, TruncMask, Known, TLO, Depth + 1)) 1235 return true; 1236 Known = Known.trunc(BitWidth); 1237 1238 // If the input is only used by this truncate, see if we can shrink it based 1239 // on the known demanded bits. 1240 if (Src.getNode()->hasOneUse()) { 1241 switch (Src.getOpcode()) { 1242 default: 1243 break; 1244 case ISD::SRL: 1245 // Shrink SRL by a constant if none of the high bits shifted in are 1246 // demanded. 1247 if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT)) 1248 // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is 1249 // undesirable. 1250 break; 1251 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Src.getOperand(1)); 1252 if (!ShAmt) 1253 break; 1254 SDValue Shift = Src.getOperand(1); 1255 if (TLO.LegalTypes()) { 1256 uint64_t ShVal = ShAmt->getZExtValue(); 1257 Shift = TLO.DAG.getConstant(ShVal, dl, getShiftAmountTy(VT, DL)); 1258 } 1259 1260 if (ShAmt->getZExtValue() < BitWidth) { 1261 APInt HighBits = APInt::getHighBitsSet(OperandBitWidth, 1262 OperandBitWidth - BitWidth); 1263 HighBits.lshrInPlace(ShAmt->getZExtValue()); 1264 HighBits = HighBits.trunc(BitWidth); 1265 1266 if (!(HighBits & DemandedBits)) { 1267 // None of the shifted in bits are needed. Add a truncate of the 1268 // shift input, then shift it. 1269 SDValue NewTrunc = 1270 TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0)); 1271 return TLO.CombineTo( 1272 Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, Shift)); 1273 } 1274 } 1275 break; 1276 } 1277 } 1278 1279 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1280 break; 1281 } 1282 case ISD::AssertZext: { 1283 // AssertZext demands all of the high bits, plus any of the low bits 1284 // demanded by its users. 1285 EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1286 APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits()); 1287 if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, 1288 Known, TLO, Depth+1)) 1289 return true; 1290 assert(!Known.hasConflict() && "Bits known to be one AND zero?"); 1291 1292 Known.Zero |= ~InMask; 1293 break; 1294 } 1295 case ISD::EXTRACT_VECTOR_ELT: { 1296 SDValue Src = Op.getOperand(0); 1297 SDValue Idx = Op.getOperand(1); 1298 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1299 unsigned EltBitWidth = Src.getScalarValueSizeInBits(); 1300 1301 // Demand the bits from every vector element without a constant index. 1302 APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts); 1303 if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx)) 1304 if (CIdx->getAPIntValue().ult(NumSrcElts)) 1305 DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue()); 1306 1307 // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know 1308 // anything about the extended bits. 1309 APInt DemandedSrcBits = DemandedBits; 1310 if (BitWidth > EltBitWidth) 1311 DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth); 1312 1313 if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO, 1314 Depth + 1)) 1315 return true; 1316 1317 Known = Known2; 1318 if (BitWidth > EltBitWidth) 1319 Known = Known.zext(BitWidth); 1320 break; 1321 } 1322 case ISD::BITCAST: { 1323 SDValue Src = Op.getOperand(0); 1324 EVT SrcVT = Src.getValueType(); 1325 unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits(); 1326 1327 // If this is an FP->Int bitcast and if the sign bit is the only 1328 // thing demanded, turn this into a FGETSIGN. 1329 if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() && 1330 DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) && 1331 SrcVT.isFloatingPoint()) { 1332 bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT); 1333 bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32); 1334 if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 && 1335 SrcVT != MVT::f128) { 1336 // Cannot eliminate/lower SHL for f128 yet. 1337 EVT Ty = OpVTLegal ? VT : MVT::i32; 1338 // Make a FGETSIGN + SHL to move the sign bit into the appropriate 1339 // place. We expect the SHL to be eliminated by other optimizations. 1340 SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src); 1341 unsigned OpVTSizeInBits = Op.getValueSizeInBits(); 1342 if (!OpVTLegal && OpVTSizeInBits > 32) 1343 Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign); 1344 unsigned ShVal = Op.getValueSizeInBits() - 1; 1345 SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT); 1346 return TLO.CombineTo(Op, 1347 TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt)); 1348 } 1349 } 1350 // If bitcast from a vector, see if we can use SimplifyDemandedVectorElts by 1351 // demanding the element if any bits from it are demanded. 1352 // TODO - bigendian once we have test coverage. 1353 // TODO - bool vectors once SimplifyDemandedVectorElts has SETCC support. 1354 if (SrcVT.isVector() && NumSrcEltBits > 1 && 1355 (BitWidth % NumSrcEltBits) == 0 && 1356 TLO.DAG.getDataLayout().isLittleEndian()) { 1357 unsigned Scale = BitWidth / NumSrcEltBits; 1358 auto GetDemandedSubMask = [&](APInt &DemandedSubElts) -> bool { 1359 DemandedSubElts = APInt::getNullValue(Scale); 1360 for (unsigned i = 0; i != Scale; ++i) { 1361 unsigned Offset = i * NumSrcEltBits; 1362 APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset); 1363 if (!Sub.isNullValue()) 1364 DemandedSubElts.setBit(i); 1365 } 1366 return true; 1367 }; 1368 1369 APInt DemandedSubElts; 1370 if (GetDemandedSubMask(DemandedSubElts)) { 1371 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 1372 APInt DemandedElts = APInt::getSplat(NumSrcElts, DemandedSubElts); 1373 1374 APInt KnownUndef, KnownZero; 1375 if (SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, KnownZero, 1376 TLO, Depth + 1)) 1377 return true; 1378 } 1379 } 1380 // If this is a bitcast, let computeKnownBits handle it. Only do this on a 1381 // recursive call where Known may be useful to the caller. 1382 if (Depth > 0) { 1383 Known = TLO.DAG.computeKnownBits(Op, Depth); 1384 return false; 1385 } 1386 break; 1387 } 1388 case ISD::ADD: 1389 case ISD::MUL: 1390 case ISD::SUB: { 1391 // Add, Sub, and Mul don't demand any bits in positions beyond that 1392 // of the highest bit demanded of them. 1393 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1); 1394 unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros(); 1395 APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ); 1396 if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO, Depth + 1) || 1397 SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO, Depth + 1) || 1398 // See if the operation should be performed at a smaller bit width. 1399 ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) { 1400 SDNodeFlags Flags = Op.getNode()->getFlags(); 1401 if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) { 1402 // Disable the nsw and nuw flags. We can no longer guarantee that we 1403 // won't wrap after simplification. 1404 Flags.setNoSignedWrap(false); 1405 Flags.setNoUnsignedWrap(false); 1406 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, 1407 Flags); 1408 return TLO.CombineTo(Op, NewOp); 1409 } 1410 return true; 1411 } 1412 1413 // If we have a constant operand, we may be able to turn it into -1 if we 1414 // do not demand the high bits. This can make the constant smaller to 1415 // encode, allow more general folding, or match specialized instruction 1416 // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that 1417 // is probably not useful (and could be detrimental). 1418 ConstantSDNode *C = isConstOrConstSplat(Op1); 1419 APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ); 1420 if (C && !C->isAllOnesValue() && !C->isOne() && 1421 (C->getAPIntValue() | HighMask).isAllOnesValue()) { 1422 SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT); 1423 // We can't guarantee that the new math op doesn't wrap, so explicitly 1424 // clear those flags to prevent folding with a potential existing node 1425 // that has those flags set. 1426 SDNodeFlags Flags; 1427 Flags.setNoSignedWrap(false); 1428 Flags.setNoUnsignedWrap(false); 1429 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags); 1430 return TLO.CombineTo(Op, NewOp); 1431 } 1432 1433 LLVM_FALLTHROUGH; 1434 } 1435 default: 1436 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 1437 if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts, 1438 Known, TLO, Depth)) 1439 return true; 1440 break; 1441 } 1442 1443 // Just use computeKnownBits to compute output bits. 1444 Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth); 1445 break; 1446 } 1447 1448 // If we know the value of all of the demanded bits, return this as a 1449 // constant. 1450 if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) { 1451 // Avoid folding to a constant if any OpaqueConstant is involved. 1452 const SDNode *N = Op.getNode(); 1453 for (SDNodeIterator I = SDNodeIterator::begin(N), 1454 E = SDNodeIterator::end(N); 1455 I != E; ++I) { 1456 SDNode *Op = *I; 1457 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) 1458 if (C->isOpaque()) 1459 return false; 1460 } 1461 // TODO: Handle float bits as well. 1462 if (VT.isInteger()) 1463 return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT)); 1464 } 1465 1466 return false; 1467 } 1468 1469 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op, 1470 const APInt &DemandedElts, 1471 APInt &KnownUndef, 1472 APInt &KnownZero, 1473 DAGCombinerInfo &DCI) const { 1474 SelectionDAG &DAG = DCI.DAG; 1475 TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 1476 !DCI.isBeforeLegalizeOps()); 1477 1478 bool Simplified = 1479 SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO); 1480 if (Simplified) { 1481 DCI.AddToWorklist(Op.getNode()); 1482 DCI.CommitTargetLoweringOpt(TLO); 1483 } 1484 return Simplified; 1485 } 1486 1487 bool TargetLowering::SimplifyDemandedVectorElts( 1488 SDValue Op, const APInt &DemandedEltMask, APInt &KnownUndef, 1489 APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth, 1490 bool AssumeSingleUse) const { 1491 EVT VT = Op.getValueType(); 1492 APInt DemandedElts = DemandedEltMask; 1493 unsigned NumElts = DemandedElts.getBitWidth(); 1494 assert(VT.isVector() && "Expected vector op"); 1495 assert(VT.getVectorNumElements() == NumElts && 1496 "Mask size mismatches value type element count!"); 1497 1498 KnownUndef = KnownZero = APInt::getNullValue(NumElts); 1499 1500 // Undef operand. 1501 if (Op.isUndef()) { 1502 KnownUndef.setAllBits(); 1503 return false; 1504 } 1505 1506 // If Op has other users, assume that all elements are needed. 1507 if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) 1508 DemandedElts.setAllBits(); 1509 1510 // Not demanding any elements from Op. 1511 if (DemandedElts == 0) { 1512 KnownUndef.setAllBits(); 1513 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1514 } 1515 1516 // Limit search depth. 1517 if (Depth >= 6) 1518 return false; 1519 1520 SDLoc DL(Op); 1521 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 1522 1523 switch (Op.getOpcode()) { 1524 case ISD::SCALAR_TO_VECTOR: { 1525 if (!DemandedElts[0]) { 1526 KnownUndef.setAllBits(); 1527 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1528 } 1529 KnownUndef.setHighBits(NumElts - 1); 1530 break; 1531 } 1532 case ISD::BITCAST: { 1533 SDValue Src = Op.getOperand(0); 1534 EVT SrcVT = Src.getValueType(); 1535 1536 // We only handle vectors here. 1537 // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits? 1538 if (!SrcVT.isVector()) 1539 break; 1540 1541 // Fast handling of 'identity' bitcasts. 1542 unsigned NumSrcElts = SrcVT.getVectorNumElements(); 1543 if (NumSrcElts == NumElts) 1544 return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef, 1545 KnownZero, TLO, Depth + 1); 1546 1547 APInt SrcZero, SrcUndef; 1548 APInt SrcDemandedElts = APInt::getNullValue(NumSrcElts); 1549 1550 // Bitcast from 'large element' src vector to 'small element' vector, we 1551 // must demand a source element if any DemandedElt maps to it. 1552 if ((NumElts % NumSrcElts) == 0) { 1553 unsigned Scale = NumElts / NumSrcElts; 1554 for (unsigned i = 0; i != NumElts; ++i) 1555 if (DemandedElts[i]) 1556 SrcDemandedElts.setBit(i / Scale); 1557 1558 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 1559 TLO, Depth + 1)) 1560 return true; 1561 1562 // Try calling SimplifyDemandedBits, converting demanded elts to the bits 1563 // of the large element. 1564 // TODO - bigendian once we have test coverage. 1565 if (TLO.DAG.getDataLayout().isLittleEndian()) { 1566 unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits(); 1567 APInt SrcDemandedBits = APInt::getNullValue(SrcEltSizeInBits); 1568 for (unsigned i = 0; i != NumElts; ++i) 1569 if (DemandedElts[i]) { 1570 unsigned Ofs = (i % Scale) * EltSizeInBits; 1571 SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits); 1572 } 1573 1574 KnownBits Known; 1575 if (SimplifyDemandedBits(Src, SrcDemandedBits, Known, TLO, Depth + 1)) 1576 return true; 1577 } 1578 1579 // If the src element is zero/undef then all the output elements will be - 1580 // only demanded elements are guaranteed to be correct. 1581 for (unsigned i = 0; i != NumSrcElts; ++i) { 1582 if (SrcDemandedElts[i]) { 1583 if (SrcZero[i]) 1584 KnownZero.setBits(i * Scale, (i + 1) * Scale); 1585 if (SrcUndef[i]) 1586 KnownUndef.setBits(i * Scale, (i + 1) * Scale); 1587 } 1588 } 1589 } 1590 1591 // Bitcast from 'small element' src vector to 'large element' vector, we 1592 // demand all smaller source elements covered by the larger demanded element 1593 // of this vector. 1594 if ((NumSrcElts % NumElts) == 0) { 1595 unsigned Scale = NumSrcElts / NumElts; 1596 for (unsigned i = 0; i != NumElts; ++i) 1597 if (DemandedElts[i]) 1598 SrcDemandedElts.setBits(i * Scale, (i + 1) * Scale); 1599 1600 if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero, 1601 TLO, Depth + 1)) 1602 return true; 1603 1604 // If all the src elements covering an output element are zero/undef, then 1605 // the output element will be as well, assuming it was demanded. 1606 for (unsigned i = 0; i != NumElts; ++i) { 1607 if (DemandedElts[i]) { 1608 if (SrcZero.extractBits(Scale, i * Scale).isAllOnesValue()) 1609 KnownZero.setBit(i); 1610 if (SrcUndef.extractBits(Scale, i * Scale).isAllOnesValue()) 1611 KnownUndef.setBit(i); 1612 } 1613 } 1614 } 1615 break; 1616 } 1617 case ISD::BUILD_VECTOR: { 1618 // Check all elements and simplify any unused elements with UNDEF. 1619 if (!DemandedElts.isAllOnesValue()) { 1620 // Don't simplify BROADCASTS. 1621 if (llvm::any_of(Op->op_values(), 1622 [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) { 1623 SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end()); 1624 bool Updated = false; 1625 for (unsigned i = 0; i != NumElts; ++i) { 1626 if (!DemandedElts[i] && !Ops[i].isUndef()) { 1627 Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType()); 1628 KnownUndef.setBit(i); 1629 Updated = true; 1630 } 1631 } 1632 if (Updated) 1633 return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops)); 1634 } 1635 } 1636 for (unsigned i = 0; i != NumElts; ++i) { 1637 SDValue SrcOp = Op.getOperand(i); 1638 if (SrcOp.isUndef()) { 1639 KnownUndef.setBit(i); 1640 } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() && 1641 (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) { 1642 KnownZero.setBit(i); 1643 } 1644 } 1645 break; 1646 } 1647 case ISD::CONCAT_VECTORS: { 1648 EVT SubVT = Op.getOperand(0).getValueType(); 1649 unsigned NumSubVecs = Op.getNumOperands(); 1650 unsigned NumSubElts = SubVT.getVectorNumElements(); 1651 for (unsigned i = 0; i != NumSubVecs; ++i) { 1652 SDValue SubOp = Op.getOperand(i); 1653 APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts); 1654 APInt SubUndef, SubZero; 1655 if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO, 1656 Depth + 1)) 1657 return true; 1658 KnownUndef.insertBits(SubUndef, i * NumSubElts); 1659 KnownZero.insertBits(SubZero, i * NumSubElts); 1660 } 1661 break; 1662 } 1663 case ISD::INSERT_SUBVECTOR: { 1664 if (!isa<ConstantSDNode>(Op.getOperand(2))) 1665 break; 1666 SDValue Base = Op.getOperand(0); 1667 SDValue Sub = Op.getOperand(1); 1668 EVT SubVT = Sub.getValueType(); 1669 unsigned NumSubElts = SubVT.getVectorNumElements(); 1670 const APInt& Idx = cast<ConstantSDNode>(Op.getOperand(2))->getAPIntValue(); 1671 if (Idx.ugt(NumElts - NumSubElts)) 1672 break; 1673 unsigned SubIdx = Idx.getZExtValue(); 1674 APInt SubElts = DemandedElts.extractBits(NumSubElts, SubIdx); 1675 APInt SubUndef, SubZero; 1676 if (SimplifyDemandedVectorElts(Sub, SubElts, SubUndef, SubZero, TLO, 1677 Depth + 1)) 1678 return true; 1679 APInt BaseElts = DemandedElts; 1680 BaseElts.insertBits(APInt::getNullValue(NumSubElts), SubIdx); 1681 if (SimplifyDemandedVectorElts(Base, BaseElts, KnownUndef, KnownZero, TLO, 1682 Depth + 1)) 1683 return true; 1684 KnownUndef.insertBits(SubUndef, SubIdx); 1685 KnownZero.insertBits(SubZero, SubIdx); 1686 break; 1687 } 1688 case ISD::EXTRACT_SUBVECTOR: { 1689 SDValue Src = Op.getOperand(0); 1690 ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 1691 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1692 if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) { 1693 // Offset the demanded elts by the subvector index. 1694 uint64_t Idx = SubIdx->getZExtValue(); 1695 APInt SrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx); 1696 APInt SrcUndef, SrcZero; 1697 if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO, 1698 Depth + 1)) 1699 return true; 1700 KnownUndef = SrcUndef.extractBits(NumElts, Idx); 1701 KnownZero = SrcZero.extractBits(NumElts, Idx); 1702 } 1703 break; 1704 } 1705 case ISD::INSERT_VECTOR_ELT: { 1706 SDValue Vec = Op.getOperand(0); 1707 SDValue Scl = Op.getOperand(1); 1708 auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 1709 1710 // For a legal, constant insertion index, if we don't need this insertion 1711 // then strip it, else remove it from the demanded elts. 1712 if (CIdx && CIdx->getAPIntValue().ult(NumElts)) { 1713 unsigned Idx = CIdx->getZExtValue(); 1714 if (!DemandedElts[Idx]) 1715 return TLO.CombineTo(Op, Vec); 1716 1717 APInt DemandedVecElts(DemandedElts); 1718 DemandedVecElts.clearBit(Idx); 1719 if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef, 1720 KnownZero, TLO, Depth + 1)) 1721 return true; 1722 1723 KnownUndef.clearBit(Idx); 1724 if (Scl.isUndef()) 1725 KnownUndef.setBit(Idx); 1726 1727 KnownZero.clearBit(Idx); 1728 if (isNullConstant(Scl) || isNullFPConstant(Scl)) 1729 KnownZero.setBit(Idx); 1730 break; 1731 } 1732 1733 APInt VecUndef, VecZero; 1734 if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO, 1735 Depth + 1)) 1736 return true; 1737 // Without knowing the insertion index we can't set KnownUndef/KnownZero. 1738 break; 1739 } 1740 case ISD::VSELECT: { 1741 // Try to transform the select condition based on the current demanded 1742 // elements. 1743 // TODO: If a condition element is undef, we can choose from one arm of the 1744 // select (and if one arm is undef, then we can propagate that to the 1745 // result). 1746 // TODO - add support for constant vselect masks (see IR version of this). 1747 APInt UnusedUndef, UnusedZero; 1748 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef, 1749 UnusedZero, TLO, Depth + 1)) 1750 return true; 1751 1752 // See if we can simplify either vselect operand. 1753 APInt DemandedLHS(DemandedElts); 1754 APInt DemandedRHS(DemandedElts); 1755 APInt UndefLHS, ZeroLHS; 1756 APInt UndefRHS, ZeroRHS; 1757 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS, 1758 ZeroLHS, TLO, Depth + 1)) 1759 return true; 1760 if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS, 1761 ZeroRHS, TLO, Depth + 1)) 1762 return true; 1763 1764 KnownUndef = UndefLHS & UndefRHS; 1765 KnownZero = ZeroLHS & ZeroRHS; 1766 break; 1767 } 1768 case ISD::VECTOR_SHUFFLE: { 1769 ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask(); 1770 1771 // Collect demanded elements from shuffle operands.. 1772 APInt DemandedLHS(NumElts, 0); 1773 APInt DemandedRHS(NumElts, 0); 1774 for (unsigned i = 0; i != NumElts; ++i) { 1775 int M = ShuffleMask[i]; 1776 if (M < 0 || !DemandedElts[i]) 1777 continue; 1778 assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range"); 1779 if (M < (int)NumElts) 1780 DemandedLHS.setBit(M); 1781 else 1782 DemandedRHS.setBit(M - NumElts); 1783 } 1784 1785 // See if we can simplify either shuffle operand. 1786 APInt UndefLHS, ZeroLHS; 1787 APInt UndefRHS, ZeroRHS; 1788 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS, 1789 ZeroLHS, TLO, Depth + 1)) 1790 return true; 1791 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS, 1792 ZeroRHS, TLO, Depth + 1)) 1793 return true; 1794 1795 // Simplify mask using undef elements from LHS/RHS. 1796 bool Updated = false; 1797 bool IdentityLHS = true, IdentityRHS = true; 1798 SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end()); 1799 for (unsigned i = 0; i != NumElts; ++i) { 1800 int &M = NewMask[i]; 1801 if (M < 0) 1802 continue; 1803 if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) || 1804 (M >= (int)NumElts && UndefRHS[M - NumElts])) { 1805 Updated = true; 1806 M = -1; 1807 } 1808 IdentityLHS &= (M < 0) || (M == (int)i); 1809 IdentityRHS &= (M < 0) || ((M - NumElts) == i); 1810 } 1811 1812 // Update legal shuffle masks based on demanded elements if it won't reduce 1813 // to Identity which can cause premature removal of the shuffle mask. 1814 if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps && 1815 isShuffleMaskLegal(NewMask, VT)) 1816 return TLO.CombineTo(Op, 1817 TLO.DAG.getVectorShuffle(VT, DL, Op.getOperand(0), 1818 Op.getOperand(1), NewMask)); 1819 1820 // Propagate undef/zero elements from LHS/RHS. 1821 for (unsigned i = 0; i != NumElts; ++i) { 1822 int M = ShuffleMask[i]; 1823 if (M < 0) { 1824 KnownUndef.setBit(i); 1825 } else if (M < (int)NumElts) { 1826 if (UndefLHS[M]) 1827 KnownUndef.setBit(i); 1828 if (ZeroLHS[M]) 1829 KnownZero.setBit(i); 1830 } else { 1831 if (UndefRHS[M - NumElts]) 1832 KnownUndef.setBit(i); 1833 if (ZeroRHS[M - NumElts]) 1834 KnownZero.setBit(i); 1835 } 1836 } 1837 break; 1838 } 1839 case ISD::SIGN_EXTEND_VECTOR_INREG: 1840 case ISD::ZERO_EXTEND_VECTOR_INREG: { 1841 APInt SrcUndef, SrcZero; 1842 SDValue Src = Op.getOperand(0); 1843 unsigned NumSrcElts = Src.getValueType().getVectorNumElements(); 1844 APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts); 1845 if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, 1846 SrcZero, TLO, Depth + 1)) 1847 return true; 1848 KnownZero = SrcZero.zextOrTrunc(NumElts); 1849 KnownUndef = SrcUndef.zextOrTrunc(NumElts); 1850 1851 if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 1852 // zext(undef) upper bits are guaranteed to be zero. 1853 if (DemandedElts.isSubsetOf(KnownUndef)) 1854 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 1855 KnownUndef.clearAllBits(); 1856 } 1857 break; 1858 } 1859 case ISD::OR: 1860 case ISD::XOR: 1861 case ISD::ADD: 1862 case ISD::SUB: 1863 case ISD::FADD: 1864 case ISD::FSUB: 1865 case ISD::FMUL: 1866 case ISD::FDIV: 1867 case ISD::FREM: { 1868 APInt SrcUndef, SrcZero; 1869 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, SrcUndef, 1870 SrcZero, TLO, Depth + 1)) 1871 return true; 1872 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 1873 KnownZero, TLO, Depth + 1)) 1874 return true; 1875 KnownZero &= SrcZero; 1876 KnownUndef &= SrcUndef; 1877 break; 1878 } 1879 case ISD::AND: { 1880 APInt SrcUndef, SrcZero; 1881 if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, SrcUndef, 1882 SrcZero, TLO, Depth + 1)) 1883 return true; 1884 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 1885 KnownZero, TLO, Depth + 1)) 1886 return true; 1887 1888 // If either side has a zero element, then the result element is zero, even 1889 // if the other is an UNDEF. 1890 KnownZero |= SrcZero; 1891 KnownUndef &= SrcUndef; 1892 KnownUndef &= ~KnownZero; 1893 break; 1894 } 1895 case ISD::TRUNCATE: 1896 case ISD::SIGN_EXTEND: 1897 case ISD::ZERO_EXTEND: 1898 if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef, 1899 KnownZero, TLO, Depth + 1)) 1900 return true; 1901 1902 if (Op.getOpcode() == ISD::ZERO_EXTEND) { 1903 // zext(undef) upper bits are guaranteed to be zero. 1904 if (DemandedElts.isSubsetOf(KnownUndef)) 1905 return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT)); 1906 KnownUndef.clearAllBits(); 1907 } 1908 break; 1909 default: { 1910 if (Op.getOpcode() >= ISD::BUILTIN_OP_END) { 1911 if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef, 1912 KnownZero, TLO, Depth)) 1913 return true; 1914 } else { 1915 KnownBits Known; 1916 APInt DemandedBits = APInt::getAllOnesValue(EltSizeInBits); 1917 if (SimplifyDemandedBits(Op, DemandedBits, DemandedEltMask, Known, TLO, 1918 Depth, AssumeSingleUse)) 1919 return true; 1920 } 1921 break; 1922 } 1923 } 1924 assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero"); 1925 1926 // Constant fold all undef cases. 1927 // TODO: Handle zero cases as well. 1928 if (DemandedElts.isSubsetOf(KnownUndef)) 1929 return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT)); 1930 1931 return false; 1932 } 1933 1934 /// Determine which of the bits specified in Mask are known to be either zero or 1935 /// one and return them in the Known. 1936 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 1937 KnownBits &Known, 1938 const APInt &DemandedElts, 1939 const SelectionDAG &DAG, 1940 unsigned Depth) const { 1941 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1942 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1943 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1944 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1945 "Should use MaskedValueIsZero if you don't know whether Op" 1946 " is a target node!"); 1947 Known.resetAll(); 1948 } 1949 1950 void TargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 1951 KnownBits &Known, 1952 const APInt &DemandedElts, 1953 const SelectionDAG &DAG, 1954 unsigned Depth) const { 1955 assert(isa<FrameIndexSDNode>(Op) && "expected FrameIndex"); 1956 1957 if (unsigned Align = DAG.InferPtrAlignment(Op)) { 1958 // The low bits are known zero if the pointer is aligned. 1959 Known.Zero.setLowBits(Log2_32(Align)); 1960 } 1961 } 1962 1963 /// This method can be implemented by targets that want to expose additional 1964 /// information about sign bits to the DAG Combiner. 1965 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op, 1966 const APInt &, 1967 const SelectionDAG &, 1968 unsigned Depth) const { 1969 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1970 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1971 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1972 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1973 "Should use ComputeNumSignBits if you don't know whether Op" 1974 " is a target node!"); 1975 return 1; 1976 } 1977 1978 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode( 1979 SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero, 1980 TargetLoweringOpt &TLO, unsigned Depth) const { 1981 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1982 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1983 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1984 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1985 "Should use SimplifyDemandedVectorElts if you don't know whether Op" 1986 " is a target node!"); 1987 return false; 1988 } 1989 1990 bool TargetLowering::SimplifyDemandedBitsForTargetNode( 1991 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 1992 KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const { 1993 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 1994 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1995 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 1996 Op.getOpcode() == ISD::INTRINSIC_VOID) && 1997 "Should use SimplifyDemandedBits if you don't know whether Op" 1998 " is a target node!"); 1999 computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth); 2000 return false; 2001 } 2002 2003 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 2004 const SelectionDAG &DAG, 2005 bool SNaN, 2006 unsigned Depth) const { 2007 assert((Op.getOpcode() >= ISD::BUILTIN_OP_END || 2008 Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 2009 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN || 2010 Op.getOpcode() == ISD::INTRINSIC_VOID) && 2011 "Should use isKnownNeverNaN if you don't know whether Op" 2012 " is a target node!"); 2013 return false; 2014 } 2015 2016 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must 2017 // work with truncating build vectors and vectors with elements of less than 2018 // 8 bits. 2019 bool TargetLowering::isConstTrueVal(const SDNode *N) const { 2020 if (!N) 2021 return false; 2022 2023 APInt CVal; 2024 if (auto *CN = dyn_cast<ConstantSDNode>(N)) { 2025 CVal = CN->getAPIntValue(); 2026 } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) { 2027 auto *CN = BV->getConstantSplatNode(); 2028 if (!CN) 2029 return false; 2030 2031 // If this is a truncating build vector, truncate the splat value. 2032 // Otherwise, we may fail to match the expected values below. 2033 unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits(); 2034 CVal = CN->getAPIntValue(); 2035 if (BVEltWidth < CVal.getBitWidth()) 2036 CVal = CVal.trunc(BVEltWidth); 2037 } else { 2038 return false; 2039 } 2040 2041 switch (getBooleanContents(N->getValueType(0))) { 2042 case UndefinedBooleanContent: 2043 return CVal[0]; 2044 case ZeroOrOneBooleanContent: 2045 return CVal.isOneValue(); 2046 case ZeroOrNegativeOneBooleanContent: 2047 return CVal.isAllOnesValue(); 2048 } 2049 2050 llvm_unreachable("Invalid boolean contents"); 2051 } 2052 2053 bool TargetLowering::isConstFalseVal(const SDNode *N) const { 2054 if (!N) 2055 return false; 2056 2057 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 2058 if (!CN) { 2059 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 2060 if (!BV) 2061 return false; 2062 2063 // Only interested in constant splats, we don't care about undef 2064 // elements in identifying boolean constants and getConstantSplatNode 2065 // returns NULL if all ops are undef; 2066 CN = BV->getConstantSplatNode(); 2067 if (!CN) 2068 return false; 2069 } 2070 2071 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 2072 return !CN->getAPIntValue()[0]; 2073 2074 return CN->isNullValue(); 2075 } 2076 2077 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 2078 bool SExt) const { 2079 if (VT == MVT::i1) 2080 return N->isOne(); 2081 2082 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 2083 switch (Cnt) { 2084 case TargetLowering::ZeroOrOneBooleanContent: 2085 // An extended value of 1 is always true, unless its original type is i1, 2086 // in which case it will be sign extended to -1. 2087 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 2088 case TargetLowering::UndefinedBooleanContent: 2089 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2090 return N->isAllOnesValue() && SExt; 2091 } 2092 llvm_unreachable("Unexpected enumeration."); 2093 } 2094 2095 /// This helper function of SimplifySetCC tries to optimize the comparison when 2096 /// either operand of the SetCC node is a bitwise-and instruction. 2097 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 2098 ISD::CondCode Cond, 2099 DAGCombinerInfo &DCI, 2100 const SDLoc &DL) const { 2101 // Match these patterns in any of their permutations: 2102 // (X & Y) == Y 2103 // (X & Y) != Y 2104 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 2105 std::swap(N0, N1); 2106 2107 EVT OpVT = N0.getValueType(); 2108 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 2109 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 2110 return SDValue(); 2111 2112 SDValue X, Y; 2113 if (N0.getOperand(0) == N1) { 2114 X = N0.getOperand(1); 2115 Y = N0.getOperand(0); 2116 } else if (N0.getOperand(1) == N1) { 2117 X = N0.getOperand(0); 2118 Y = N0.getOperand(1); 2119 } else { 2120 return SDValue(); 2121 } 2122 2123 SelectionDAG &DAG = DCI.DAG; 2124 SDValue Zero = DAG.getConstant(0, DL, OpVT); 2125 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 2126 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 2127 // Note that where Y is variable and is known to have at most one bit set 2128 // (for example, if it is Z & 1) we cannot do this; the expressions are not 2129 // equivalent when Y == 0. 2130 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 2131 if (DCI.isBeforeLegalizeOps() || 2132 isCondCodeLegal(Cond, N0.getSimpleValueType())) 2133 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 2134 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 2135 // If the target supports an 'and-not' or 'and-complement' logic operation, 2136 // try to use that to make a comparison operation more efficient. 2137 // But don't do this transform if the mask is a single bit because there are 2138 // more efficient ways to deal with that case (for example, 'bt' on x86 or 2139 // 'rlwinm' on PPC). 2140 2141 // Bail out if the compare operand that we want to turn into a zero is 2142 // already a zero (otherwise, infinite loop). 2143 auto *YConst = dyn_cast<ConstantSDNode>(Y); 2144 if (YConst && YConst->isNullValue()) 2145 return SDValue(); 2146 2147 // Transform this into: ~X & Y == 0. 2148 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 2149 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 2150 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 2151 } 2152 2153 return SDValue(); 2154 } 2155 2156 /// There are multiple IR patterns that could be checking whether certain 2157 /// truncation of a signed number would be lossy or not. The pattern which is 2158 /// best at IR level, may not lower optimally. Thus, we want to unfold it. 2159 /// We are looking for the following pattern: (KeptBits is a constant) 2160 /// (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits) 2161 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false. 2162 /// KeptBits also can't be 1, that would have been folded to %x dstcond 0 2163 /// We will unfold it into the natural trunc+sext pattern: 2164 /// ((%x << C) a>> C) dstcond %x 2165 /// Where C = bitwidth(x) - KeptBits and C u< bitwidth(x) 2166 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck( 2167 EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI, 2168 const SDLoc &DL) const { 2169 // We must be comparing with a constant. 2170 ConstantSDNode *C1; 2171 if (!(C1 = dyn_cast<ConstantSDNode>(N1))) 2172 return SDValue(); 2173 2174 // N0 should be: add %x, (1 << (KeptBits-1)) 2175 if (N0->getOpcode() != ISD::ADD) 2176 return SDValue(); 2177 2178 // And we must be 'add'ing a constant. 2179 ConstantSDNode *C01; 2180 if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1)))) 2181 return SDValue(); 2182 2183 SDValue X = N0->getOperand(0); 2184 EVT XVT = X.getValueType(); 2185 2186 // Validate constants ... 2187 2188 APInt I1 = C1->getAPIntValue(); 2189 2190 ISD::CondCode NewCond; 2191 if (Cond == ISD::CondCode::SETULT) { 2192 NewCond = ISD::CondCode::SETEQ; 2193 } else if (Cond == ISD::CondCode::SETULE) { 2194 NewCond = ISD::CondCode::SETEQ; 2195 // But need to 'canonicalize' the constant. 2196 I1 += 1; 2197 } else if (Cond == ISD::CondCode::SETUGT) { 2198 NewCond = ISD::CondCode::SETNE; 2199 // But need to 'canonicalize' the constant. 2200 I1 += 1; 2201 } else if (Cond == ISD::CondCode::SETUGE) { 2202 NewCond = ISD::CondCode::SETNE; 2203 } else 2204 return SDValue(); 2205 2206 APInt I01 = C01->getAPIntValue(); 2207 2208 auto checkConstants = [&I1, &I01]() -> bool { 2209 // Both of them must be power-of-two, and the constant from setcc is bigger. 2210 return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2(); 2211 }; 2212 2213 if (checkConstants()) { 2214 // Great, e.g. got icmp ult i16 (add i16 %x, 128), 256 2215 } else { 2216 // What if we invert constants? (and the target predicate) 2217 I1.negate(); 2218 I01.negate(); 2219 NewCond = getSetCCInverse(NewCond, /*isInteger=*/true); 2220 if (!checkConstants()) 2221 return SDValue(); 2222 // Great, e.g. got icmp uge i16 (add i16 %x, -128), -256 2223 } 2224 2225 // They are power-of-two, so which bit is set? 2226 const unsigned KeptBits = I1.logBase2(); 2227 const unsigned KeptBitsMinusOne = I01.logBase2(); 2228 2229 // Magic! 2230 if (KeptBits != (KeptBitsMinusOne + 1)) 2231 return SDValue(); 2232 assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable"); 2233 2234 // We don't want to do this in every single case. 2235 SelectionDAG &DAG = DCI.DAG; 2236 if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck( 2237 XVT, KeptBits)) 2238 return SDValue(); 2239 2240 const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits; 2241 assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable"); 2242 2243 // Unfold into: ((%x << C) a>> C) cond %x 2244 // Where 'cond' will be either 'eq' or 'ne'. 2245 SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT); 2246 SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt); 2247 SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt); 2248 SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond); 2249 2250 return T2; 2251 } 2252 2253 /// Try to simplify a setcc built with the specified operands and cc. If it is 2254 /// unable to simplify it, return a null SDValue. 2255 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 2256 ISD::CondCode Cond, bool foldBooleans, 2257 DAGCombinerInfo &DCI, 2258 const SDLoc &dl) const { 2259 SelectionDAG &DAG = DCI.DAG; 2260 EVT OpVT = N0.getValueType(); 2261 2262 // These setcc operations always fold. 2263 switch (Cond) { 2264 default: break; 2265 case ISD::SETFALSE: 2266 case ISD::SETFALSE2: return DAG.getBoolConstant(false, dl, VT, OpVT); 2267 case ISD::SETTRUE: 2268 case ISD::SETTRUE2: return DAG.getBoolConstant(true, dl, VT, OpVT); 2269 } 2270 2271 // Ensure that the constant occurs on the RHS and fold constant comparisons. 2272 // TODO: Handle non-splat vector constants. All undef causes trouble. 2273 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 2274 if (isConstOrConstSplat(N0) && 2275 (DCI.isBeforeLegalizeOps() || 2276 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 2277 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 2278 2279 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 2280 const APInt &C1 = N1C->getAPIntValue(); 2281 2282 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 2283 // equality comparison, then we're just comparing whether X itself is 2284 // zero. 2285 if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) && 2286 N0.getOperand(0).getOpcode() == ISD::CTLZ && 2287 N0.getOperand(1).getOpcode() == ISD::Constant) { 2288 const APInt &ShAmt 2289 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 2290 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2291 ShAmt == Log2_32(N0.getValueSizeInBits())) { 2292 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 2293 // (srl (ctlz x), 5) == 0 -> X != 0 2294 // (srl (ctlz x), 5) != 1 -> X != 0 2295 Cond = ISD::SETNE; 2296 } else { 2297 // (srl (ctlz x), 5) != 0 -> X == 0 2298 // (srl (ctlz x), 5) == 1 -> X == 0 2299 Cond = ISD::SETEQ; 2300 } 2301 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 2302 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), 2303 Zero, Cond); 2304 } 2305 } 2306 2307 SDValue CTPOP = N0; 2308 // Look through truncs that don't change the value of a ctpop. 2309 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE) 2310 CTPOP = N0.getOperand(0); 2311 2312 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP && 2313 (N0 == CTPOP || 2314 N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) { 2315 EVT CTVT = CTPOP.getValueType(); 2316 SDValue CTOp = CTPOP.getOperand(0); 2317 2318 // (ctpop x) u< 2 -> (x & x-1) == 0 2319 // (ctpop x) u> 1 -> (x & x-1) != 0 2320 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){ 2321 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp, 2322 DAG.getConstant(1, dl, CTVT)); 2323 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub); 2324 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 2325 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC); 2326 } 2327 2328 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal. 2329 } 2330 2331 // (zext x) == C --> x == (trunc C) 2332 // (sext x) == C --> x == (trunc C) 2333 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2334 DCI.isBeforeLegalize() && N0->hasOneUse()) { 2335 unsigned MinBits = N0.getValueSizeInBits(); 2336 SDValue PreExt; 2337 bool Signed = false; 2338 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 2339 // ZExt 2340 MinBits = N0->getOperand(0).getValueSizeInBits(); 2341 PreExt = N0->getOperand(0); 2342 } else if (N0->getOpcode() == ISD::AND) { 2343 // DAGCombine turns costly ZExts into ANDs 2344 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 2345 if ((C->getAPIntValue()+1).isPowerOf2()) { 2346 MinBits = C->getAPIntValue().countTrailingOnes(); 2347 PreExt = N0->getOperand(0); 2348 } 2349 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 2350 // SExt 2351 MinBits = N0->getOperand(0).getValueSizeInBits(); 2352 PreExt = N0->getOperand(0); 2353 Signed = true; 2354 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 2355 // ZEXTLOAD / SEXTLOAD 2356 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 2357 MinBits = LN0->getMemoryVT().getSizeInBits(); 2358 PreExt = N0; 2359 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 2360 Signed = true; 2361 MinBits = LN0->getMemoryVT().getSizeInBits(); 2362 PreExt = N0; 2363 } 2364 } 2365 2366 // Figure out how many bits we need to preserve this constant. 2367 unsigned ReqdBits = Signed ? 2368 C1.getBitWidth() - C1.getNumSignBits() + 1 : 2369 C1.getActiveBits(); 2370 2371 // Make sure we're not losing bits from the constant. 2372 if (MinBits > 0 && 2373 MinBits < C1.getBitWidth() && 2374 MinBits >= ReqdBits) { 2375 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 2376 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 2377 // Will get folded away. 2378 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 2379 if (MinBits == 1 && C1 == 1) 2380 // Invert the condition. 2381 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 2382 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 2383 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 2384 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 2385 } 2386 2387 // If truncating the setcc operands is not desirable, we can still 2388 // simplify the expression in some cases: 2389 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 2390 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 2391 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 2392 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 2393 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 2394 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 2395 SDValue TopSetCC = N0->getOperand(0); 2396 unsigned N0Opc = N0->getOpcode(); 2397 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 2398 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 2399 TopSetCC.getOpcode() == ISD::SETCC && 2400 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 2401 (isConstFalseVal(N1C) || 2402 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 2403 2404 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) || 2405 (!N1C->isNullValue() && Cond == ISD::SETNE); 2406 2407 if (!Inverse) 2408 return TopSetCC; 2409 2410 ISD::CondCode InvCond = ISD::getSetCCInverse( 2411 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 2412 TopSetCC.getOperand(0).getValueType().isInteger()); 2413 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 2414 TopSetCC.getOperand(1), 2415 InvCond); 2416 } 2417 } 2418 } 2419 2420 // If the LHS is '(and load, const)', the RHS is 0, the test is for 2421 // equality or unsigned, and all 1 bits of the const are in the same 2422 // partial word, see if we can shorten the load. 2423 if (DCI.isBeforeLegalize() && 2424 !ISD::isSignedIntSetCC(Cond) && 2425 N0.getOpcode() == ISD::AND && C1 == 0 && 2426 N0.getNode()->hasOneUse() && 2427 isa<LoadSDNode>(N0.getOperand(0)) && 2428 N0.getOperand(0).getNode()->hasOneUse() && 2429 isa<ConstantSDNode>(N0.getOperand(1))) { 2430 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 2431 APInt bestMask; 2432 unsigned bestWidth = 0, bestOffset = 0; 2433 if (!Lod->isVolatile() && Lod->isUnindexed()) { 2434 unsigned origWidth = N0.getValueSizeInBits(); 2435 unsigned maskWidth = origWidth; 2436 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 2437 // 8 bits, but have to be careful... 2438 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 2439 origWidth = Lod->getMemoryVT().getSizeInBits(); 2440 const APInt &Mask = 2441 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 2442 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 2443 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 2444 for (unsigned offset=0; offset<origWidth/width; offset++) { 2445 if (Mask.isSubsetOf(newMask)) { 2446 if (DAG.getDataLayout().isLittleEndian()) 2447 bestOffset = (uint64_t)offset * (width/8); 2448 else 2449 bestOffset = (origWidth/width - offset - 1) * (width/8); 2450 bestMask = Mask.lshr(offset * (width/8) * 8); 2451 bestWidth = width; 2452 break; 2453 } 2454 newMask <<= width; 2455 } 2456 } 2457 } 2458 if (bestWidth) { 2459 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 2460 if (newVT.isRound() && 2461 shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) { 2462 EVT PtrType = Lod->getOperand(1).getValueType(); 2463 SDValue Ptr = Lod->getBasePtr(); 2464 if (bestOffset != 0) 2465 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(), 2466 DAG.getConstant(bestOffset, dl, PtrType)); 2467 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset); 2468 SDValue NewLoad = DAG.getLoad( 2469 newVT, dl, Lod->getChain(), Ptr, 2470 Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign); 2471 return DAG.getSetCC(dl, VT, 2472 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 2473 DAG.getConstant(bestMask.trunc(bestWidth), 2474 dl, newVT)), 2475 DAG.getConstant(0LL, dl, newVT), Cond); 2476 } 2477 } 2478 } 2479 2480 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 2481 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 2482 unsigned InSize = N0.getOperand(0).getValueSizeInBits(); 2483 2484 // If the comparison constant has bits in the upper part, the 2485 // zero-extended value could never match. 2486 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 2487 C1.getBitWidth() - InSize))) { 2488 switch (Cond) { 2489 case ISD::SETUGT: 2490 case ISD::SETUGE: 2491 case ISD::SETEQ: 2492 return DAG.getConstant(0, dl, VT); 2493 case ISD::SETULT: 2494 case ISD::SETULE: 2495 case ISD::SETNE: 2496 return DAG.getConstant(1, dl, VT); 2497 case ISD::SETGT: 2498 case ISD::SETGE: 2499 // True if the sign bit of C1 is set. 2500 return DAG.getConstant(C1.isNegative(), dl, VT); 2501 case ISD::SETLT: 2502 case ISD::SETLE: 2503 // True if the sign bit of C1 isn't set. 2504 return DAG.getConstant(C1.isNonNegative(), dl, VT); 2505 default: 2506 break; 2507 } 2508 } 2509 2510 // Otherwise, we can perform the comparison with the low bits. 2511 switch (Cond) { 2512 case ISD::SETEQ: 2513 case ISD::SETNE: 2514 case ISD::SETUGT: 2515 case ISD::SETUGE: 2516 case ISD::SETULT: 2517 case ISD::SETULE: { 2518 EVT newVT = N0.getOperand(0).getValueType(); 2519 if (DCI.isBeforeLegalizeOps() || 2520 (isOperationLegal(ISD::SETCC, newVT) && 2521 isCondCodeLegal(Cond, newVT.getSimpleVT()))) { 2522 EVT NewSetCCVT = 2523 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT); 2524 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 2525 2526 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 2527 NewConst, Cond); 2528 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 2529 } 2530 break; 2531 } 2532 default: 2533 break; // todo, be more careful with signed comparisons 2534 } 2535 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 2536 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 2537 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 2538 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 2539 EVT ExtDstTy = N0.getValueType(); 2540 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 2541 2542 // If the constant doesn't fit into the number of bits for the source of 2543 // the sign extension, it is impossible for both sides to be equal. 2544 if (C1.getMinSignedBits() > ExtSrcTyBits) 2545 return DAG.getConstant(Cond == ISD::SETNE, dl, VT); 2546 2547 SDValue ZextOp; 2548 EVT Op0Ty = N0.getOperand(0).getValueType(); 2549 if (Op0Ty == ExtSrcTy) { 2550 ZextOp = N0.getOperand(0); 2551 } else { 2552 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 2553 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0), 2554 DAG.getConstant(Imm, dl, Op0Ty)); 2555 } 2556 if (!DCI.isCalledByLegalizer()) 2557 DCI.AddToWorklist(ZextOp.getNode()); 2558 // Otherwise, make this a use of a zext. 2559 return DAG.getSetCC(dl, VT, ZextOp, 2560 DAG.getConstant(C1 & APInt::getLowBitsSet( 2561 ExtDstTyBits, 2562 ExtSrcTyBits), 2563 dl, ExtDstTy), 2564 Cond); 2565 } else if ((N1C->isNullValue() || N1C->isOne()) && 2566 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 2567 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 2568 if (N0.getOpcode() == ISD::SETCC && 2569 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) { 2570 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne()); 2571 if (TrueWhenTrue) 2572 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 2573 // Invert the condition. 2574 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 2575 CC = ISD::getSetCCInverse(CC, 2576 N0.getOperand(0).getValueType().isInteger()); 2577 if (DCI.isBeforeLegalizeOps() || 2578 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 2579 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 2580 } 2581 2582 if ((N0.getOpcode() == ISD::XOR || 2583 (N0.getOpcode() == ISD::AND && 2584 N0.getOperand(0).getOpcode() == ISD::XOR && 2585 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 2586 isa<ConstantSDNode>(N0.getOperand(1)) && 2587 cast<ConstantSDNode>(N0.getOperand(1))->isOne()) { 2588 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 2589 // can only do this if the top bits are known zero. 2590 unsigned BitWidth = N0.getValueSizeInBits(); 2591 if (DAG.MaskedValueIsZero(N0, 2592 APInt::getHighBitsSet(BitWidth, 2593 BitWidth-1))) { 2594 // Okay, get the un-inverted input value. 2595 SDValue Val; 2596 if (N0.getOpcode() == ISD::XOR) { 2597 Val = N0.getOperand(0); 2598 } else { 2599 assert(N0.getOpcode() == ISD::AND && 2600 N0.getOperand(0).getOpcode() == ISD::XOR); 2601 // ((X^1)&1)^1 -> X & 1 2602 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 2603 N0.getOperand(0).getOperand(0), 2604 N0.getOperand(1)); 2605 } 2606 2607 return DAG.getSetCC(dl, VT, Val, N1, 2608 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 2609 } 2610 } else if (N1C->isOne() && 2611 (VT == MVT::i1 || 2612 getBooleanContents(N0->getValueType(0)) == 2613 ZeroOrOneBooleanContent)) { 2614 SDValue Op0 = N0; 2615 if (Op0.getOpcode() == ISD::TRUNCATE) 2616 Op0 = Op0.getOperand(0); 2617 2618 if ((Op0.getOpcode() == ISD::XOR) && 2619 Op0.getOperand(0).getOpcode() == ISD::SETCC && 2620 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 2621 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 2622 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 2623 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1), 2624 Cond); 2625 } 2626 if (Op0.getOpcode() == ISD::AND && 2627 isa<ConstantSDNode>(Op0.getOperand(1)) && 2628 cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) { 2629 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 2630 if (Op0.getValueType().bitsGT(VT)) 2631 Op0 = DAG.getNode(ISD::AND, dl, VT, 2632 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 2633 DAG.getConstant(1, dl, VT)); 2634 else if (Op0.getValueType().bitsLT(VT)) 2635 Op0 = DAG.getNode(ISD::AND, dl, VT, 2636 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 2637 DAG.getConstant(1, dl, VT)); 2638 2639 return DAG.getSetCC(dl, VT, Op0, 2640 DAG.getConstant(0, dl, Op0.getValueType()), 2641 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 2642 } 2643 if (Op0.getOpcode() == ISD::AssertZext && 2644 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 2645 return DAG.getSetCC(dl, VT, Op0, 2646 DAG.getConstant(0, dl, Op0.getValueType()), 2647 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 2648 } 2649 } 2650 2651 if (SDValue V = 2652 optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl)) 2653 return V; 2654 } 2655 2656 // These simplifications apply to splat vectors as well. 2657 // TODO: Handle more splat vector cases. 2658 if (auto *N1C = isConstOrConstSplat(N1)) { 2659 const APInt &C1 = N1C->getAPIntValue(); 2660 2661 APInt MinVal, MaxVal; 2662 unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits(); 2663 if (ISD::isSignedIntSetCC(Cond)) { 2664 MinVal = APInt::getSignedMinValue(OperandBitSize); 2665 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 2666 } else { 2667 MinVal = APInt::getMinValue(OperandBitSize); 2668 MaxVal = APInt::getMaxValue(OperandBitSize); 2669 } 2670 2671 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 2672 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 2673 // X >= MIN --> true 2674 if (C1 == MinVal) 2675 return DAG.getBoolConstant(true, dl, VT, OpVT); 2676 2677 if (!VT.isVector()) { // TODO: Support this for vectors. 2678 // X >= C0 --> X > (C0 - 1) 2679 APInt C = C1 - 1; 2680 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 2681 if ((DCI.isBeforeLegalizeOps() || 2682 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 2683 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 2684 isLegalICmpImmediate(C.getSExtValue())))) { 2685 return DAG.getSetCC(dl, VT, N0, 2686 DAG.getConstant(C, dl, N1.getValueType()), 2687 NewCC); 2688 } 2689 } 2690 } 2691 2692 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 2693 // X <= MAX --> true 2694 if (C1 == MaxVal) 2695 return DAG.getBoolConstant(true, dl, VT, OpVT); 2696 2697 // X <= C0 --> X < (C0 + 1) 2698 if (!VT.isVector()) { // TODO: Support this for vectors. 2699 APInt C = C1 + 1; 2700 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 2701 if ((DCI.isBeforeLegalizeOps() || 2702 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 2703 (!N1C->isOpaque() || (C.getBitWidth() <= 64 && 2704 isLegalICmpImmediate(C.getSExtValue())))) { 2705 return DAG.getSetCC(dl, VT, N0, 2706 DAG.getConstant(C, dl, N1.getValueType()), 2707 NewCC); 2708 } 2709 } 2710 } 2711 2712 if (Cond == ISD::SETLT || Cond == ISD::SETULT) { 2713 if (C1 == MinVal) 2714 return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false 2715 2716 // TODO: Support this for vectors after legalize ops. 2717 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 2718 // Canonicalize setlt X, Max --> setne X, Max 2719 if (C1 == MaxVal) 2720 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 2721 2722 // If we have setult X, 1, turn it into seteq X, 0 2723 if (C1 == MinVal+1) 2724 return DAG.getSetCC(dl, VT, N0, 2725 DAG.getConstant(MinVal, dl, N0.getValueType()), 2726 ISD::SETEQ); 2727 } 2728 } 2729 2730 if (Cond == ISD::SETGT || Cond == ISD::SETUGT) { 2731 if (C1 == MaxVal) 2732 return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false 2733 2734 // TODO: Support this for vectors after legalize ops. 2735 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 2736 // Canonicalize setgt X, Min --> setne X, Min 2737 if (C1 == MinVal) 2738 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 2739 2740 // If we have setugt X, Max-1, turn it into seteq X, Max 2741 if (C1 == MaxVal-1) 2742 return DAG.getSetCC(dl, VT, N0, 2743 DAG.getConstant(MaxVal, dl, N0.getValueType()), 2744 ISD::SETEQ); 2745 } 2746 } 2747 2748 // If we have "setcc X, C0", check to see if we can shrink the immediate 2749 // by changing cc. 2750 // TODO: Support this for vectors after legalize ops. 2751 if (!VT.isVector() || DCI.isBeforeLegalizeOps()) { 2752 // SETUGT X, SINTMAX -> SETLT X, 0 2753 if (Cond == ISD::SETUGT && 2754 C1 == APInt::getSignedMaxValue(OperandBitSize)) 2755 return DAG.getSetCC(dl, VT, N0, 2756 DAG.getConstant(0, dl, N1.getValueType()), 2757 ISD::SETLT); 2758 2759 // SETULT X, SINTMIN -> SETGT X, -1 2760 if (Cond == ISD::SETULT && 2761 C1 == APInt::getSignedMinValue(OperandBitSize)) { 2762 SDValue ConstMinusOne = 2763 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl, 2764 N1.getValueType()); 2765 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT); 2766 } 2767 } 2768 } 2769 2770 // Back to non-vector simplifications. 2771 // TODO: Can we do these for vector splats? 2772 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 2773 const APInt &C1 = N1C->getAPIntValue(); 2774 2775 // Fold bit comparisons when we can. 2776 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2777 (VT == N0.getValueType() || 2778 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) && 2779 N0.getOpcode() == ISD::AND) { 2780 auto &DL = DAG.getDataLayout(); 2781 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2782 EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL, 2783 !DCI.isBeforeLegalize()); 2784 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 2785 // Perform the xform if the AND RHS is a single bit. 2786 if (AndRHS->getAPIntValue().isPowerOf2()) { 2787 return DAG.getNode(ISD::TRUNCATE, dl, VT, 2788 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 2789 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl, 2790 ShiftTy))); 2791 } 2792 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 2793 // (X & 8) == 8 --> (X & 8) >> 3 2794 // Perform the xform if C1 is a single bit. 2795 if (C1.isPowerOf2()) { 2796 return DAG.getNode(ISD::TRUNCATE, dl, VT, 2797 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 2798 DAG.getConstant(C1.logBase2(), dl, 2799 ShiftTy))); 2800 } 2801 } 2802 } 2803 } 2804 2805 if (C1.getMinSignedBits() <= 64 && 2806 !isLegalICmpImmediate(C1.getSExtValue())) { 2807 // (X & -256) == 256 -> (X >> 8) == 1 2808 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2809 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 2810 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2811 const APInt &AndRHSC = AndRHS->getAPIntValue(); 2812 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 2813 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 2814 auto &DL = DAG.getDataLayout(); 2815 EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL, 2816 !DCI.isBeforeLegalize()); 2817 EVT CmpTy = N0.getValueType(); 2818 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0), 2819 DAG.getConstant(ShiftBits, dl, 2820 ShiftTy)); 2821 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy); 2822 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 2823 } 2824 } 2825 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 2826 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 2827 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 2828 // X < 0x100000000 -> (X >> 32) < 1 2829 // X >= 0x100000000 -> (X >> 32) >= 1 2830 // X <= 0x0ffffffff -> (X >> 32) < 1 2831 // X > 0x0ffffffff -> (X >> 32) >= 1 2832 unsigned ShiftBits; 2833 APInt NewC = C1; 2834 ISD::CondCode NewCond = Cond; 2835 if (AdjOne) { 2836 ShiftBits = C1.countTrailingOnes(); 2837 NewC = NewC + 1; 2838 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 2839 } else { 2840 ShiftBits = C1.countTrailingZeros(); 2841 } 2842 NewC.lshrInPlace(ShiftBits); 2843 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 2844 isLegalICmpImmediate(NewC.getSExtValue())) { 2845 auto &DL = DAG.getDataLayout(); 2846 EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL, 2847 !DCI.isBeforeLegalize()); 2848 EVT CmpTy = N0.getValueType(); 2849 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0, 2850 DAG.getConstant(ShiftBits, dl, ShiftTy)); 2851 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy); 2852 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 2853 } 2854 } 2855 } 2856 } 2857 2858 if (isa<ConstantFPSDNode>(N0.getNode())) { 2859 // Constant fold or commute setcc. 2860 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl); 2861 if (O.getNode()) return O; 2862 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) { 2863 // If the RHS of an FP comparison is a constant, simplify it away in 2864 // some cases. 2865 if (CFP->getValueAPF().isNaN()) { 2866 // If an operand is known to be a nan, we can fold it. 2867 switch (ISD::getUnorderedFlavor(Cond)) { 2868 default: llvm_unreachable("Unknown flavor!"); 2869 case 0: // Known false. 2870 return DAG.getBoolConstant(false, dl, VT, OpVT); 2871 case 1: // Known true. 2872 return DAG.getBoolConstant(true, dl, VT, OpVT); 2873 case 2: // Undefined. 2874 return DAG.getUNDEF(VT); 2875 } 2876 } 2877 2878 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 2879 // constant if knowing that the operand is non-nan is enough. We prefer to 2880 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 2881 // materialize 0.0. 2882 if (Cond == ISD::SETO || Cond == ISD::SETUO) 2883 return DAG.getSetCC(dl, VT, N0, N0, Cond); 2884 2885 // setcc (fneg x), C -> setcc swap(pred) x, -C 2886 if (N0.getOpcode() == ISD::FNEG) { 2887 ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond); 2888 if (DCI.isBeforeLegalizeOps() || 2889 isCondCodeLegal(SwapCond, N0.getSimpleValueType())) { 2890 SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1); 2891 return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond); 2892 } 2893 } 2894 2895 // If the condition is not legal, see if we can find an equivalent one 2896 // which is legal. 2897 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 2898 // If the comparison was an awkward floating-point == or != and one of 2899 // the comparison operands is infinity or negative infinity, convert the 2900 // condition to a less-awkward <= or >=. 2901 if (CFP->getValueAPF().isInfinity()) { 2902 if (CFP->getValueAPF().isNegative()) { 2903 if (Cond == ISD::SETOEQ && 2904 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 2905 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE); 2906 if (Cond == ISD::SETUEQ && 2907 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 2908 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE); 2909 if (Cond == ISD::SETUNE && 2910 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 2911 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT); 2912 if (Cond == ISD::SETONE && 2913 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 2914 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT); 2915 } else { 2916 if (Cond == ISD::SETOEQ && 2917 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 2918 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE); 2919 if (Cond == ISD::SETUEQ && 2920 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 2921 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE); 2922 if (Cond == ISD::SETUNE && 2923 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 2924 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT); 2925 if (Cond == ISD::SETONE && 2926 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 2927 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT); 2928 } 2929 } 2930 } 2931 } 2932 2933 if (N0 == N1) { 2934 // The sext(setcc()) => setcc() optimization relies on the appropriate 2935 // constant being emitted. 2936 2937 bool EqTrue = ISD::isTrueWhenEqual(Cond); 2938 2939 // We can always fold X == X for integer setcc's. 2940 if (N0.getValueType().isInteger()) 2941 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 2942 2943 unsigned UOF = ISD::getUnorderedFlavor(Cond); 2944 if (UOF == 2) // FP operators that are undefined on NaNs. 2945 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 2946 if (UOF == unsigned(EqTrue)) 2947 return DAG.getBoolConstant(EqTrue, dl, VT, OpVT); 2948 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 2949 // if it is not already. 2950 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 2951 if (NewCond != Cond && 2952 (DCI.isBeforeLegalizeOps() || 2953 isCondCodeLegal(NewCond, N0.getSimpleValueType()))) 2954 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 2955 } 2956 2957 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2958 N0.getValueType().isInteger()) { 2959 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 2960 N0.getOpcode() == ISD::XOR) { 2961 // Simplify (X+Y) == (X+Z) --> Y == Z 2962 if (N0.getOpcode() == N1.getOpcode()) { 2963 if (N0.getOperand(0) == N1.getOperand(0)) 2964 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 2965 if (N0.getOperand(1) == N1.getOperand(1)) 2966 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 2967 if (isCommutativeBinOp(N0.getOpcode())) { 2968 // If X op Y == Y op X, try other combinations. 2969 if (N0.getOperand(0) == N1.getOperand(1)) 2970 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 2971 Cond); 2972 if (N0.getOperand(1) == N1.getOperand(0)) 2973 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 2974 Cond); 2975 } 2976 } 2977 2978 // If RHS is a legal immediate value for a compare instruction, we need 2979 // to be careful about increasing register pressure needlessly. 2980 bool LegalRHSImm = false; 2981 2982 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 2983 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2984 // Turn (X+C1) == C2 --> X == C2-C1 2985 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 2986 return DAG.getSetCC(dl, VT, N0.getOperand(0), 2987 DAG.getConstant(RHSC->getAPIntValue()- 2988 LHSR->getAPIntValue(), 2989 dl, N0.getValueType()), Cond); 2990 } 2991 2992 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 2993 if (N0.getOpcode() == ISD::XOR) 2994 // If we know that all of the inverted bits are zero, don't bother 2995 // performing the inversion. 2996 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 2997 return 2998 DAG.getSetCC(dl, VT, N0.getOperand(0), 2999 DAG.getConstant(LHSR->getAPIntValue() ^ 3000 RHSC->getAPIntValue(), 3001 dl, N0.getValueType()), 3002 Cond); 3003 } 3004 3005 // Turn (C1-X) == C2 --> X == C1-C2 3006 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 3007 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 3008 return 3009 DAG.getSetCC(dl, VT, N0.getOperand(1), 3010 DAG.getConstant(SUBC->getAPIntValue() - 3011 RHSC->getAPIntValue(), 3012 dl, N0.getValueType()), 3013 Cond); 3014 } 3015 } 3016 3017 // Could RHSC fold directly into a compare? 3018 if (RHSC->getValueType(0).getSizeInBits() <= 64) 3019 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 3020 } 3021 3022 // Simplify (X+Z) == X --> Z == 0 3023 // Don't do this if X is an immediate that can fold into a cmp 3024 // instruction and X+Z has other uses. It could be an induction variable 3025 // chain, and the transform would increase register pressure. 3026 if (!LegalRHSImm || N0.getNode()->hasOneUse()) { 3027 if (N0.getOperand(0) == N1) 3028 return DAG.getSetCC(dl, VT, N0.getOperand(1), 3029 DAG.getConstant(0, dl, N0.getValueType()), Cond); 3030 if (N0.getOperand(1) == N1) { 3031 if (isCommutativeBinOp(N0.getOpcode())) 3032 return DAG.getSetCC(dl, VT, N0.getOperand(0), 3033 DAG.getConstant(0, dl, N0.getValueType()), 3034 Cond); 3035 if (N0.getNode()->hasOneUse()) { 3036 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!"); 3037 auto &DL = DAG.getDataLayout(); 3038 // (Z-X) == X --> Z == X<<1 3039 SDValue SH = DAG.getNode( 3040 ISD::SHL, dl, N1.getValueType(), N1, 3041 DAG.getConstant(1, dl, 3042 getShiftAmountTy(N1.getValueType(), DL, 3043 !DCI.isBeforeLegalize()))); 3044 if (!DCI.isCalledByLegalizer()) 3045 DCI.AddToWorklist(SH.getNode()); 3046 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond); 3047 } 3048 } 3049 } 3050 } 3051 3052 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 3053 N1.getOpcode() == ISD::XOR) { 3054 // Simplify X == (X+Z) --> Z == 0 3055 if (N1.getOperand(0) == N0) 3056 return DAG.getSetCC(dl, VT, N1.getOperand(1), 3057 DAG.getConstant(0, dl, N1.getValueType()), Cond); 3058 if (N1.getOperand(1) == N0) { 3059 if (isCommutativeBinOp(N1.getOpcode())) 3060 return DAG.getSetCC(dl, VT, N1.getOperand(0), 3061 DAG.getConstant(0, dl, N1.getValueType()), Cond); 3062 if (N1.getNode()->hasOneUse()) { 3063 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!"); 3064 auto &DL = DAG.getDataLayout(); 3065 // X == (Z-X) --> X<<1 == Z 3066 SDValue SH = DAG.getNode( 3067 ISD::SHL, dl, N1.getValueType(), N0, 3068 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL, 3069 !DCI.isBeforeLegalize()))); 3070 if (!DCI.isCalledByLegalizer()) 3071 DCI.AddToWorklist(SH.getNode()); 3072 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond); 3073 } 3074 } 3075 } 3076 3077 if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl)) 3078 return V; 3079 } 3080 3081 // Fold away ALL boolean setcc's. 3082 SDValue Temp; 3083 if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) { 3084 EVT OpVT = N0.getValueType(); 3085 switch (Cond) { 3086 default: llvm_unreachable("Unknown integer setcc!"); 3087 case ISD::SETEQ: // X == Y -> ~(X^Y) 3088 Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 3089 N0 = DAG.getNOT(dl, Temp, OpVT); 3090 if (!DCI.isCalledByLegalizer()) 3091 DCI.AddToWorklist(Temp.getNode()); 3092 break; 3093 case ISD::SETNE: // X != Y --> (X^Y) 3094 N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1); 3095 break; 3096 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 3097 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 3098 Temp = DAG.getNOT(dl, N0, OpVT); 3099 N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp); 3100 if (!DCI.isCalledByLegalizer()) 3101 DCI.AddToWorklist(Temp.getNode()); 3102 break; 3103 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 3104 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 3105 Temp = DAG.getNOT(dl, N1, OpVT); 3106 N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp); 3107 if (!DCI.isCalledByLegalizer()) 3108 DCI.AddToWorklist(Temp.getNode()); 3109 break; 3110 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 3111 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 3112 Temp = DAG.getNOT(dl, N0, OpVT); 3113 N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp); 3114 if (!DCI.isCalledByLegalizer()) 3115 DCI.AddToWorklist(Temp.getNode()); 3116 break; 3117 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 3118 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 3119 Temp = DAG.getNOT(dl, N1, OpVT); 3120 N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp); 3121 break; 3122 } 3123 if (VT.getScalarType() != MVT::i1) { 3124 if (!DCI.isCalledByLegalizer()) 3125 DCI.AddToWorklist(N0.getNode()); 3126 // FIXME: If running after legalize, we probably can't do this. 3127 ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT)); 3128 N0 = DAG.getNode(ExtendCode, dl, VT, N0); 3129 } 3130 return N0; 3131 } 3132 3133 // Could not fold it. 3134 return SDValue(); 3135 } 3136 3137 /// Returns true (and the GlobalValue and the offset) if the node is a 3138 /// GlobalAddress + offset. 3139 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA, 3140 int64_t &Offset) const { 3141 3142 SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode(); 3143 3144 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 3145 GA = GASD->getGlobal(); 3146 Offset += GASD->getOffset(); 3147 return true; 3148 } 3149 3150 if (N->getOpcode() == ISD::ADD) { 3151 SDValue N1 = N->getOperand(0); 3152 SDValue N2 = N->getOperand(1); 3153 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 3154 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 3155 Offset += V->getSExtValue(); 3156 return true; 3157 } 3158 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 3159 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 3160 Offset += V->getSExtValue(); 3161 return true; 3162 } 3163 } 3164 } 3165 3166 return false; 3167 } 3168 3169 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 3170 DAGCombinerInfo &DCI) const { 3171 // Default implementation: no optimization. 3172 return SDValue(); 3173 } 3174 3175 //===----------------------------------------------------------------------===// 3176 // Inline Assembler Implementation Methods 3177 //===----------------------------------------------------------------------===// 3178 3179 TargetLowering::ConstraintType 3180 TargetLowering::getConstraintType(StringRef Constraint) const { 3181 unsigned S = Constraint.size(); 3182 3183 if (S == 1) { 3184 switch (Constraint[0]) { 3185 default: break; 3186 case 'r': return C_RegisterClass; 3187 case 'm': // memory 3188 case 'o': // offsetable 3189 case 'V': // not offsetable 3190 return C_Memory; 3191 case 'i': // Simple Integer or Relocatable Constant 3192 case 'n': // Simple Integer 3193 case 'E': // Floating Point Constant 3194 case 'F': // Floating Point Constant 3195 case 's': // Relocatable Constant 3196 case 'p': // Address. 3197 case 'X': // Allow ANY value. 3198 case 'I': // Target registers. 3199 case 'J': 3200 case 'K': 3201 case 'L': 3202 case 'M': 3203 case 'N': 3204 case 'O': 3205 case 'P': 3206 case '<': 3207 case '>': 3208 return C_Other; 3209 } 3210 } 3211 3212 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') { 3213 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 3214 return C_Memory; 3215 return C_Register; 3216 } 3217 return C_Unknown; 3218 } 3219 3220 /// Try to replace an X constraint, which matches anything, with another that 3221 /// has more specific requirements based on the type of the corresponding 3222 /// operand. 3223 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{ 3224 if (ConstraintVT.isInteger()) 3225 return "r"; 3226 if (ConstraintVT.isFloatingPoint()) 3227 return "f"; // works for many targets 3228 return nullptr; 3229 } 3230 3231 /// Lower the specified operand into the Ops vector. 3232 /// If it is invalid, don't add anything to Ops. 3233 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 3234 std::string &Constraint, 3235 std::vector<SDValue> &Ops, 3236 SelectionDAG &DAG) const { 3237 3238 if (Constraint.length() > 1) return; 3239 3240 char ConstraintLetter = Constraint[0]; 3241 switch (ConstraintLetter) { 3242 default: break; 3243 case 'X': // Allows any operand; labels (basic block) use this. 3244 if (Op.getOpcode() == ISD::BasicBlock) { 3245 Ops.push_back(Op); 3246 return; 3247 } 3248 LLVM_FALLTHROUGH; 3249 case 'i': // Simple Integer or Relocatable Constant 3250 case 'n': // Simple Integer 3251 case 's': { // Relocatable Constant 3252 // These operands are interested in values of the form (GV+C), where C may 3253 // be folded in as an offset of GV, or it may be explicitly added. Also, it 3254 // is possible and fine if either GV or C are missing. 3255 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 3256 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op); 3257 3258 // If we have "(add GV, C)", pull out GV/C 3259 if (Op.getOpcode() == ISD::ADD) { 3260 C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 3261 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0)); 3262 if (!C || !GA) { 3263 C = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 3264 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1)); 3265 } 3266 if (!C || !GA) { 3267 C = nullptr; 3268 GA = nullptr; 3269 } 3270 } 3271 3272 // If we find a valid operand, map to the TargetXXX version so that the 3273 // value itself doesn't get selected. 3274 if (GA) { // Either &GV or &GV+C 3275 if (ConstraintLetter != 'n') { 3276 int64_t Offs = GA->getOffset(); 3277 if (C) Offs += C->getZExtValue(); 3278 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), 3279 C ? SDLoc(C) : SDLoc(), 3280 Op.getValueType(), Offs)); 3281 } 3282 return; 3283 } 3284 if (C) { // just C, no GV. 3285 // Simple constants are not allowed for 's'. 3286 if (ConstraintLetter != 's') { 3287 // gcc prints these as sign extended. Sign extend value to 64 bits 3288 // now; without this it would get ZExt'd later in 3289 // ScheduleDAGSDNodes::EmitNode, which is very generic. 3290 Ops.push_back(DAG.getTargetConstant(C->getSExtValue(), 3291 SDLoc(C), MVT::i64)); 3292 } 3293 return; 3294 } 3295 break; 3296 } 3297 } 3298 } 3299 3300 std::pair<unsigned, const TargetRegisterClass *> 3301 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 3302 StringRef Constraint, 3303 MVT VT) const { 3304 if (Constraint.empty() || Constraint[0] != '{') 3305 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr)); 3306 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?"); 3307 3308 // Remove the braces from around the name. 3309 StringRef RegName(Constraint.data()+1, Constraint.size()-2); 3310 3311 std::pair<unsigned, const TargetRegisterClass*> R = 3312 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr)); 3313 3314 // Figure out which register class contains this reg. 3315 for (const TargetRegisterClass *RC : RI->regclasses()) { 3316 // If none of the value types for this register class are valid, we 3317 // can't use it. For example, 64-bit reg classes on 32-bit targets. 3318 if (!isLegalRC(*RI, *RC)) 3319 continue; 3320 3321 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 3322 I != E; ++I) { 3323 if (RegName.equals_lower(RI->getRegAsmName(*I))) { 3324 std::pair<unsigned, const TargetRegisterClass*> S = 3325 std::make_pair(*I, RC); 3326 3327 // If this register class has the requested value type, return it, 3328 // otherwise keep searching and return the first class found 3329 // if no other is found which explicitly has the requested type. 3330 if (RI->isTypeLegalForClass(*RC, VT)) 3331 return S; 3332 if (!R.second) 3333 R = S; 3334 } 3335 } 3336 } 3337 3338 return R; 3339 } 3340 3341 //===----------------------------------------------------------------------===// 3342 // Constraint Selection. 3343 3344 /// Return true of this is an input operand that is a matching constraint like 3345 /// "4". 3346 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 3347 assert(!ConstraintCode.empty() && "No known constraint!"); 3348 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 3349 } 3350 3351 /// If this is an input matching constraint, this method returns the output 3352 /// operand it matches. 3353 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 3354 assert(!ConstraintCode.empty() && "No known constraint!"); 3355 return atoi(ConstraintCode.c_str()); 3356 } 3357 3358 /// Split up the constraint string from the inline assembly value into the 3359 /// specific constraints and their prefixes, and also tie in the associated 3360 /// operand values. 3361 /// If this returns an empty vector, and if the constraint string itself 3362 /// isn't empty, there was an error parsing. 3363 TargetLowering::AsmOperandInfoVector 3364 TargetLowering::ParseConstraints(const DataLayout &DL, 3365 const TargetRegisterInfo *TRI, 3366 ImmutableCallSite CS) const { 3367 /// Information about all of the constraints. 3368 AsmOperandInfoVector ConstraintOperands; 3369 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 3370 unsigned maCount = 0; // Largest number of multiple alternative constraints. 3371 3372 // Do a prepass over the constraints, canonicalizing them, and building up the 3373 // ConstraintOperands list. 3374 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 3375 unsigned ResNo = 0; // ResNo - The result number of the next output. 3376 3377 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 3378 ConstraintOperands.emplace_back(std::move(CI)); 3379 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 3380 3381 // Update multiple alternative constraint count. 3382 if (OpInfo.multipleAlternatives.size() > maCount) 3383 maCount = OpInfo.multipleAlternatives.size(); 3384 3385 OpInfo.ConstraintVT = MVT::Other; 3386 3387 // Compute the value type for each operand. 3388 switch (OpInfo.Type) { 3389 case InlineAsm::isOutput: 3390 // Indirect outputs just consume an argument. 3391 if (OpInfo.isIndirect) { 3392 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 3393 break; 3394 } 3395 3396 // The return value of the call is this value. As such, there is no 3397 // corresponding argument. 3398 assert(!CS.getType()->isVoidTy() && 3399 "Bad inline asm!"); 3400 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 3401 OpInfo.ConstraintVT = 3402 getSimpleValueType(DL, STy->getElementType(ResNo)); 3403 } else { 3404 assert(ResNo == 0 && "Asm only has one result!"); 3405 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType()); 3406 } 3407 ++ResNo; 3408 break; 3409 case InlineAsm::isInput: 3410 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 3411 break; 3412 case InlineAsm::isClobber: 3413 // Nothing to do. 3414 break; 3415 } 3416 3417 if (OpInfo.CallOperandVal) { 3418 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 3419 if (OpInfo.isIndirect) { 3420 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 3421 if (!PtrTy) 3422 report_fatal_error("Indirect operand for inline asm not a pointer!"); 3423 OpTy = PtrTy->getElementType(); 3424 } 3425 3426 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 3427 if (StructType *STy = dyn_cast<StructType>(OpTy)) 3428 if (STy->getNumElements() == 1) 3429 OpTy = STy->getElementType(0); 3430 3431 // If OpTy is not a single value, it may be a struct/union that we 3432 // can tile with integers. 3433 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 3434 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 3435 switch (BitSize) { 3436 default: break; 3437 case 1: 3438 case 8: 3439 case 16: 3440 case 32: 3441 case 64: 3442 case 128: 3443 OpInfo.ConstraintVT = 3444 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 3445 break; 3446 } 3447 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 3448 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 3449 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 3450 } else { 3451 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 3452 } 3453 } 3454 } 3455 3456 // If we have multiple alternative constraints, select the best alternative. 3457 if (!ConstraintOperands.empty()) { 3458 if (maCount) { 3459 unsigned bestMAIndex = 0; 3460 int bestWeight = -1; 3461 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 3462 int weight = -1; 3463 unsigned maIndex; 3464 // Compute the sums of the weights for each alternative, keeping track 3465 // of the best (highest weight) one so far. 3466 for (maIndex = 0; maIndex < maCount; ++maIndex) { 3467 int weightSum = 0; 3468 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 3469 cIndex != eIndex; ++cIndex) { 3470 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 3471 if (OpInfo.Type == InlineAsm::isClobber) 3472 continue; 3473 3474 // If this is an output operand with a matching input operand, 3475 // look up the matching input. If their types mismatch, e.g. one 3476 // is an integer, the other is floating point, or their sizes are 3477 // different, flag it as an maCantMatch. 3478 if (OpInfo.hasMatchingInput()) { 3479 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 3480 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 3481 if ((OpInfo.ConstraintVT.isInteger() != 3482 Input.ConstraintVT.isInteger()) || 3483 (OpInfo.ConstraintVT.getSizeInBits() != 3484 Input.ConstraintVT.getSizeInBits())) { 3485 weightSum = -1; // Can't match. 3486 break; 3487 } 3488 } 3489 } 3490 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 3491 if (weight == -1) { 3492 weightSum = -1; 3493 break; 3494 } 3495 weightSum += weight; 3496 } 3497 // Update best. 3498 if (weightSum > bestWeight) { 3499 bestWeight = weightSum; 3500 bestMAIndex = maIndex; 3501 } 3502 } 3503 3504 // Now select chosen alternative in each constraint. 3505 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 3506 cIndex != eIndex; ++cIndex) { 3507 AsmOperandInfo& cInfo = ConstraintOperands[cIndex]; 3508 if (cInfo.Type == InlineAsm::isClobber) 3509 continue; 3510 cInfo.selectAlternative(bestMAIndex); 3511 } 3512 } 3513 } 3514 3515 // Check and hook up tied operands, choose constraint code to use. 3516 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 3517 cIndex != eIndex; ++cIndex) { 3518 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 3519 3520 // If this is an output operand with a matching input operand, look up the 3521 // matching input. If their types mismatch, e.g. one is an integer, the 3522 // other is floating point, or their sizes are different, flag it as an 3523 // error. 3524 if (OpInfo.hasMatchingInput()) { 3525 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 3526 3527 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 3528 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 3529 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 3530 OpInfo.ConstraintVT); 3531 std::pair<unsigned, const TargetRegisterClass *> InputRC = 3532 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 3533 Input.ConstraintVT); 3534 if ((OpInfo.ConstraintVT.isInteger() != 3535 Input.ConstraintVT.isInteger()) || 3536 (MatchRC.second != InputRC.second)) { 3537 report_fatal_error("Unsupported asm: input constraint" 3538 " with a matching output constraint of" 3539 " incompatible type!"); 3540 } 3541 } 3542 } 3543 } 3544 3545 return ConstraintOperands; 3546 } 3547 3548 /// Return an integer indicating how general CT is. 3549 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 3550 switch (CT) { 3551 case TargetLowering::C_Other: 3552 case TargetLowering::C_Unknown: 3553 return 0; 3554 case TargetLowering::C_Register: 3555 return 1; 3556 case TargetLowering::C_RegisterClass: 3557 return 2; 3558 case TargetLowering::C_Memory: 3559 return 3; 3560 } 3561 llvm_unreachable("Invalid constraint type"); 3562 } 3563 3564 /// Examine constraint type and operand type and determine a weight value. 3565 /// This object must already have been set up with the operand type 3566 /// and the current alternative constraint selected. 3567 TargetLowering::ConstraintWeight 3568 TargetLowering::getMultipleConstraintMatchWeight( 3569 AsmOperandInfo &info, int maIndex) const { 3570 InlineAsm::ConstraintCodeVector *rCodes; 3571 if (maIndex >= (int)info.multipleAlternatives.size()) 3572 rCodes = &info.Codes; 3573 else 3574 rCodes = &info.multipleAlternatives[maIndex].Codes; 3575 ConstraintWeight BestWeight = CW_Invalid; 3576 3577 // Loop over the options, keeping track of the most general one. 3578 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 3579 ConstraintWeight weight = 3580 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 3581 if (weight > BestWeight) 3582 BestWeight = weight; 3583 } 3584 3585 return BestWeight; 3586 } 3587 3588 /// Examine constraint type and operand type and determine a weight value. 3589 /// This object must already have been set up with the operand type 3590 /// and the current alternative constraint selected. 3591 TargetLowering::ConstraintWeight 3592 TargetLowering::getSingleConstraintMatchWeight( 3593 AsmOperandInfo &info, const char *constraint) const { 3594 ConstraintWeight weight = CW_Invalid; 3595 Value *CallOperandVal = info.CallOperandVal; 3596 // If we don't have a value, we can't do a match, 3597 // but allow it at the lowest weight. 3598 if (!CallOperandVal) 3599 return CW_Default; 3600 // Look at the constraint type. 3601 switch (*constraint) { 3602 case 'i': // immediate integer. 3603 case 'n': // immediate integer with a known value. 3604 if (isa<ConstantInt>(CallOperandVal)) 3605 weight = CW_Constant; 3606 break; 3607 case 's': // non-explicit intregal immediate. 3608 if (isa<GlobalValue>(CallOperandVal)) 3609 weight = CW_Constant; 3610 break; 3611 case 'E': // immediate float if host format. 3612 case 'F': // immediate float. 3613 if (isa<ConstantFP>(CallOperandVal)) 3614 weight = CW_Constant; 3615 break; 3616 case '<': // memory operand with autodecrement. 3617 case '>': // memory operand with autoincrement. 3618 case 'm': // memory operand. 3619 case 'o': // offsettable memory operand 3620 case 'V': // non-offsettable memory operand 3621 weight = CW_Memory; 3622 break; 3623 case 'r': // general register. 3624 case 'g': // general register, memory operand or immediate integer. 3625 // note: Clang converts "g" to "imr". 3626 if (CallOperandVal->getType()->isIntegerTy()) 3627 weight = CW_Register; 3628 break; 3629 case 'X': // any operand. 3630 default: 3631 weight = CW_Default; 3632 break; 3633 } 3634 return weight; 3635 } 3636 3637 /// If there are multiple different constraints that we could pick for this 3638 /// operand (e.g. "imr") try to pick the 'best' one. 3639 /// This is somewhat tricky: constraints fall into four classes: 3640 /// Other -> immediates and magic values 3641 /// Register -> one specific register 3642 /// RegisterClass -> a group of regs 3643 /// Memory -> memory 3644 /// Ideally, we would pick the most specific constraint possible: if we have 3645 /// something that fits into a register, we would pick it. The problem here 3646 /// is that if we have something that could either be in a register or in 3647 /// memory that use of the register could cause selection of *other* 3648 /// operands to fail: they might only succeed if we pick memory. Because of 3649 /// this the heuristic we use is: 3650 /// 3651 /// 1) If there is an 'other' constraint, and if the operand is valid for 3652 /// that constraint, use it. This makes us take advantage of 'i' 3653 /// constraints when available. 3654 /// 2) Otherwise, pick the most general constraint present. This prefers 3655 /// 'm' over 'r', for example. 3656 /// 3657 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 3658 const TargetLowering &TLI, 3659 SDValue Op, SelectionDAG *DAG) { 3660 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 3661 unsigned BestIdx = 0; 3662 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 3663 int BestGenerality = -1; 3664 3665 // Loop over the options, keeping track of the most general one. 3666 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 3667 TargetLowering::ConstraintType CType = 3668 TLI.getConstraintType(OpInfo.Codes[i]); 3669 3670 // If this is an 'other' constraint, see if the operand is valid for it. 3671 // For example, on X86 we might have an 'rI' constraint. If the operand 3672 // is an integer in the range [0..31] we want to use I (saving a load 3673 // of a register), otherwise we must use 'r'. 3674 if (CType == TargetLowering::C_Other && Op.getNode()) { 3675 assert(OpInfo.Codes[i].size() == 1 && 3676 "Unhandled multi-letter 'other' constraint"); 3677 std::vector<SDValue> ResultOps; 3678 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 3679 ResultOps, *DAG); 3680 if (!ResultOps.empty()) { 3681 BestType = CType; 3682 BestIdx = i; 3683 break; 3684 } 3685 } 3686 3687 // Things with matching constraints can only be registers, per gcc 3688 // documentation. This mainly affects "g" constraints. 3689 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 3690 continue; 3691 3692 // This constraint letter is more general than the previous one, use it. 3693 int Generality = getConstraintGenerality(CType); 3694 if (Generality > BestGenerality) { 3695 BestType = CType; 3696 BestIdx = i; 3697 BestGenerality = Generality; 3698 } 3699 } 3700 3701 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 3702 OpInfo.ConstraintType = BestType; 3703 } 3704 3705 /// Determines the constraint code and constraint type to use for the specific 3706 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 3707 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 3708 SDValue Op, 3709 SelectionDAG *DAG) const { 3710 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 3711 3712 // Single-letter constraints ('r') are very common. 3713 if (OpInfo.Codes.size() == 1) { 3714 OpInfo.ConstraintCode = OpInfo.Codes[0]; 3715 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 3716 } else { 3717 ChooseConstraint(OpInfo, *this, Op, DAG); 3718 } 3719 3720 // 'X' matches anything. 3721 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 3722 // Labels and constants are handled elsewhere ('X' is the only thing 3723 // that matches labels). For Functions, the type here is the type of 3724 // the result, which is not what we want to look at; leave them alone. 3725 Value *v = OpInfo.CallOperandVal; 3726 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 3727 OpInfo.CallOperandVal = v; 3728 return; 3729 } 3730 3731 // Otherwise, try to resolve it to something we know about by looking at 3732 // the actual operand type. 3733 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 3734 OpInfo.ConstraintCode = Repl; 3735 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 3736 } 3737 } 3738 } 3739 3740 /// Given an exact SDIV by a constant, create a multiplication 3741 /// with the multiplicative inverse of the constant. 3742 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N, 3743 const SDLoc &dl, SelectionDAG &DAG, 3744 SmallVectorImpl<SDNode *> &Created) { 3745 SDValue Op0 = N->getOperand(0); 3746 SDValue Op1 = N->getOperand(1); 3747 EVT VT = N->getValueType(0); 3748 EVT SVT = VT.getScalarType(); 3749 EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 3750 EVT ShSVT = ShVT.getScalarType(); 3751 3752 bool UseSRA = false; 3753 SmallVector<SDValue, 16> Shifts, Factors; 3754 3755 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 3756 if (C->isNullValue()) 3757 return false; 3758 APInt Divisor = C->getAPIntValue(); 3759 unsigned Shift = Divisor.countTrailingZeros(); 3760 if (Shift) { 3761 Divisor.ashrInPlace(Shift); 3762 UseSRA = true; 3763 } 3764 // Calculate the multiplicative inverse, using Newton's method. 3765 APInt t; 3766 APInt Factor = Divisor; 3767 while ((t = Divisor * Factor) != 1) 3768 Factor *= APInt(Divisor.getBitWidth(), 2) - t; 3769 Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT)); 3770 Factors.push_back(DAG.getConstant(Factor, dl, SVT)); 3771 return true; 3772 }; 3773 3774 // Collect all magic values from the build vector. 3775 if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern)) 3776 return SDValue(); 3777 3778 SDValue Shift, Factor; 3779 if (VT.isVector()) { 3780 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 3781 Factor = DAG.getBuildVector(VT, dl, Factors); 3782 } else { 3783 Shift = Shifts[0]; 3784 Factor = Factors[0]; 3785 } 3786 3787 SDValue Res = Op0; 3788 3789 // Shift the value upfront if it is even, so the LSB is one. 3790 if (UseSRA) { 3791 // TODO: For UDIV use SRL instead of SRA. 3792 SDNodeFlags Flags; 3793 Flags.setExact(true); 3794 Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags); 3795 Created.push_back(Res.getNode()); 3796 } 3797 3798 return DAG.getNode(ISD::MUL, dl, VT, Res, Factor); 3799 } 3800 3801 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 3802 SelectionDAG &DAG, 3803 SmallVectorImpl<SDNode *> &Created) const { 3804 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3805 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3806 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 3807 return SDValue(N,0); // Lower SDIV as SDIV 3808 return SDValue(); 3809 } 3810 3811 /// Given an ISD::SDIV node expressing a divide by constant, 3812 /// return a DAG expression to select that will generate the same value by 3813 /// multiplying by a magic number. 3814 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 3815 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG, 3816 bool IsAfterLegalization, 3817 SmallVectorImpl<SDNode *> &Created) const { 3818 SDLoc dl(N); 3819 EVT VT = N->getValueType(0); 3820 EVT SVT = VT.getScalarType(); 3821 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 3822 EVT ShSVT = ShVT.getScalarType(); 3823 unsigned EltBits = VT.getScalarSizeInBits(); 3824 3825 // Check to see if we can do this. 3826 // FIXME: We should be more aggressive here. 3827 if (!isTypeLegal(VT)) 3828 return SDValue(); 3829 3830 // If the sdiv has an 'exact' bit we can use a simpler lowering. 3831 if (N->getFlags().hasExact()) 3832 return BuildExactSDIV(*this, N, dl, DAG, Created); 3833 3834 SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks; 3835 3836 auto BuildSDIVPattern = [&](ConstantSDNode *C) { 3837 if (C->isNullValue()) 3838 return false; 3839 3840 const APInt &Divisor = C->getAPIntValue(); 3841 APInt::ms magics = Divisor.magic(); 3842 int NumeratorFactor = 0; 3843 int ShiftMask = -1; 3844 3845 if (Divisor.isOneValue() || Divisor.isAllOnesValue()) { 3846 // If d is +1/-1, we just multiply the numerator by +1/-1. 3847 NumeratorFactor = Divisor.getSExtValue(); 3848 magics.m = 0; 3849 magics.s = 0; 3850 ShiftMask = 0; 3851 } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 3852 // If d > 0 and m < 0, add the numerator. 3853 NumeratorFactor = 1; 3854 } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 3855 // If d < 0 and m > 0, subtract the numerator. 3856 NumeratorFactor = -1; 3857 } 3858 3859 MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT)); 3860 Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT)); 3861 Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT)); 3862 ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT)); 3863 return true; 3864 }; 3865 3866 SDValue N0 = N->getOperand(0); 3867 SDValue N1 = N->getOperand(1); 3868 3869 // Collect the shifts / magic values from each element. 3870 if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern)) 3871 return SDValue(); 3872 3873 SDValue MagicFactor, Factor, Shift, ShiftMask; 3874 if (VT.isVector()) { 3875 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 3876 Factor = DAG.getBuildVector(VT, dl, Factors); 3877 Shift = DAG.getBuildVector(ShVT, dl, Shifts); 3878 ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks); 3879 } else { 3880 MagicFactor = MagicFactors[0]; 3881 Factor = Factors[0]; 3882 Shift = Shifts[0]; 3883 ShiftMask = ShiftMasks[0]; 3884 } 3885 3886 // Multiply the numerator (operand 0) by the magic value. 3887 // FIXME: We should support doing a MUL in a wider type. 3888 SDValue Q; 3889 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) 3890 : isOperationLegalOrCustom(ISD::MULHS, VT)) 3891 Q = DAG.getNode(ISD::MULHS, dl, VT, N0, MagicFactor); 3892 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) 3893 : isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) { 3894 SDValue LoHi = 3895 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), N0, MagicFactor); 3896 Q = SDValue(LoHi.getNode(), 1); 3897 } else 3898 return SDValue(); // No mulhs or equivalent. 3899 Created.push_back(Q.getNode()); 3900 3901 // (Optionally) Add/subtract the numerator using Factor. 3902 Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor); 3903 Created.push_back(Factor.getNode()); 3904 Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor); 3905 Created.push_back(Q.getNode()); 3906 3907 // Shift right algebraic by shift value. 3908 Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift); 3909 Created.push_back(Q.getNode()); 3910 3911 // Extract the sign bit, mask it and add it to the quotient. 3912 SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT); 3913 SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift); 3914 Created.push_back(T.getNode()); 3915 T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask); 3916 Created.push_back(T.getNode()); 3917 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 3918 } 3919 3920 /// Given an ISD::UDIV node expressing a divide by constant, 3921 /// return a DAG expression to select that will generate the same value by 3922 /// multiplying by a magic number. 3923 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 3924 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG, 3925 bool IsAfterLegalization, 3926 SmallVectorImpl<SDNode *> &Created) const { 3927 SDLoc dl(N); 3928 EVT VT = N->getValueType(0); 3929 EVT SVT = VT.getScalarType(); 3930 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 3931 EVT ShSVT = ShVT.getScalarType(); 3932 unsigned EltBits = VT.getScalarSizeInBits(); 3933 3934 // Check to see if we can do this. 3935 // FIXME: We should be more aggressive here. 3936 if (!isTypeLegal(VT)) 3937 return SDValue(); 3938 3939 bool UseNPQ = false; 3940 SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors; 3941 3942 auto BuildUDIVPattern = [&](ConstantSDNode *C) { 3943 if (C->isNullValue()) 3944 return false; 3945 // FIXME: We should use a narrower constant when the upper 3946 // bits are known to be zero. 3947 APInt Divisor = C->getAPIntValue(); 3948 APInt::mu magics = Divisor.magicu(); 3949 unsigned PreShift = 0, PostShift = 0; 3950 3951 // If the divisor is even, we can avoid using the expensive fixup by 3952 // shifting the divided value upfront. 3953 if (magics.a != 0 && !Divisor[0]) { 3954 PreShift = Divisor.countTrailingZeros(); 3955 // Get magic number for the shifted divisor. 3956 magics = Divisor.lshr(PreShift).magicu(PreShift); 3957 assert(magics.a == 0 && "Should use cheap fixup now"); 3958 } 3959 3960 APInt Magic = magics.m; 3961 3962 unsigned SelNPQ; 3963 if (magics.a == 0 || Divisor.isOneValue()) { 3964 assert(magics.s < Divisor.getBitWidth() && 3965 "We shouldn't generate an undefined shift!"); 3966 PostShift = magics.s; 3967 SelNPQ = false; 3968 } else { 3969 PostShift = magics.s - 1; 3970 SelNPQ = true; 3971 } 3972 3973 PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT)); 3974 MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT)); 3975 NPQFactors.push_back( 3976 DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1) 3977 : APInt::getNullValue(EltBits), 3978 dl, SVT)); 3979 PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT)); 3980 UseNPQ |= SelNPQ; 3981 return true; 3982 }; 3983 3984 SDValue N0 = N->getOperand(0); 3985 SDValue N1 = N->getOperand(1); 3986 3987 // Collect the shifts/magic values from each element. 3988 if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern)) 3989 return SDValue(); 3990 3991 SDValue PreShift, PostShift, MagicFactor, NPQFactor; 3992 if (VT.isVector()) { 3993 PreShift = DAG.getBuildVector(ShVT, dl, PreShifts); 3994 MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors); 3995 NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors); 3996 PostShift = DAG.getBuildVector(ShVT, dl, PostShifts); 3997 } else { 3998 PreShift = PreShifts[0]; 3999 MagicFactor = MagicFactors[0]; 4000 PostShift = PostShifts[0]; 4001 } 4002 4003 SDValue Q = N0; 4004 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift); 4005 Created.push_back(Q.getNode()); 4006 4007 // FIXME: We should support doing a MUL in a wider type. 4008 auto GetMULHU = [&](SDValue X, SDValue Y) { 4009 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) 4010 : isOperationLegalOrCustom(ISD::MULHU, VT)) 4011 return DAG.getNode(ISD::MULHU, dl, VT, X, Y); 4012 if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) 4013 : isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) { 4014 SDValue LoHi = 4015 DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y); 4016 return SDValue(LoHi.getNode(), 1); 4017 } 4018 return SDValue(); // No mulhu or equivalent 4019 }; 4020 4021 // Multiply the numerator (operand 0) by the magic value. 4022 Q = GetMULHU(Q, MagicFactor); 4023 if (!Q) 4024 return SDValue(); 4025 4026 Created.push_back(Q.getNode()); 4027 4028 if (UseNPQ) { 4029 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q); 4030 Created.push_back(NPQ.getNode()); 4031 4032 // For vectors we might have a mix of non-NPQ/NPQ paths, so use 4033 // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero. 4034 if (VT.isVector()) 4035 NPQ = GetMULHU(NPQ, NPQFactor); 4036 else 4037 NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT)); 4038 4039 Created.push_back(NPQ.getNode()); 4040 4041 Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 4042 Created.push_back(Q.getNode()); 4043 } 4044 4045 Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift); 4046 Created.push_back(Q.getNode()); 4047 4048 SDValue One = DAG.getConstant(1, dl, VT); 4049 SDValue IsOne = DAG.getSetCC(dl, VT, N1, One, ISD::SETEQ); 4050 return DAG.getSelect(dl, VT, IsOne, N0, Q); 4051 } 4052 4053 bool TargetLowering:: 4054 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 4055 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 4056 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 4057 "be a constant integer"); 4058 return true; 4059 } 4060 4061 return false; 4062 } 4063 4064 //===----------------------------------------------------------------------===// 4065 // Legalization Utilities 4066 //===----------------------------------------------------------------------===// 4067 4068 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl, 4069 SDValue LHS, SDValue RHS, 4070 SmallVectorImpl<SDValue> &Result, 4071 EVT HiLoVT, SelectionDAG &DAG, 4072 MulExpansionKind Kind, SDValue LL, 4073 SDValue LH, SDValue RL, SDValue RH) const { 4074 assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI || 4075 Opcode == ISD::SMUL_LOHI); 4076 4077 bool HasMULHS = (Kind == MulExpansionKind::Always) || 4078 isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 4079 bool HasMULHU = (Kind == MulExpansionKind::Always) || 4080 isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 4081 bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) || 4082 isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 4083 bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) || 4084 isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 4085 4086 if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI) 4087 return false; 4088 4089 unsigned OuterBitSize = VT.getScalarSizeInBits(); 4090 unsigned InnerBitSize = HiLoVT.getScalarSizeInBits(); 4091 unsigned LHSSB = DAG.ComputeNumSignBits(LHS); 4092 unsigned RHSSB = DAG.ComputeNumSignBits(RHS); 4093 4094 // LL, LH, RL, and RH must be either all NULL or all set to a value. 4095 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 4096 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 4097 4098 SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT); 4099 auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi, 4100 bool Signed) -> bool { 4101 if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) { 4102 Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R); 4103 Hi = SDValue(Lo.getNode(), 1); 4104 return true; 4105 } 4106 if ((Signed && HasMULHS) || (!Signed && HasMULHU)) { 4107 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R); 4108 Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R); 4109 return true; 4110 } 4111 return false; 4112 }; 4113 4114 SDValue Lo, Hi; 4115 4116 if (!LL.getNode() && !RL.getNode() && 4117 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 4118 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS); 4119 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS); 4120 } 4121 4122 if (!LL.getNode()) 4123 return false; 4124 4125 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 4126 if (DAG.MaskedValueIsZero(LHS, HighMask) && 4127 DAG.MaskedValueIsZero(RHS, HighMask)) { 4128 // The inputs are both zero-extended. 4129 if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) { 4130 Result.push_back(Lo); 4131 Result.push_back(Hi); 4132 if (Opcode != ISD::MUL) { 4133 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 4134 Result.push_back(Zero); 4135 Result.push_back(Zero); 4136 } 4137 return true; 4138 } 4139 } 4140 4141 if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize && 4142 RHSSB > InnerBitSize) { 4143 // The input values are both sign-extended. 4144 // TODO non-MUL case? 4145 if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) { 4146 Result.push_back(Lo); 4147 Result.push_back(Hi); 4148 return true; 4149 } 4150 } 4151 4152 unsigned ShiftAmount = OuterBitSize - InnerBitSize; 4153 EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout()); 4154 if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) { 4155 // FIXME getShiftAmountTy does not always return a sensible result when VT 4156 // is an illegal type, and so the type may be too small to fit the shift 4157 // amount. Override it with i32. The shift will have to be legalized. 4158 ShiftAmountTy = MVT::i32; 4159 } 4160 SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy); 4161 4162 if (!LH.getNode() && !RH.getNode() && 4163 isOperationLegalOrCustom(ISD::SRL, VT) && 4164 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 4165 LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift); 4166 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 4167 RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift); 4168 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 4169 } 4170 4171 if (!LH.getNode()) 4172 return false; 4173 4174 if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false)) 4175 return false; 4176 4177 Result.push_back(Lo); 4178 4179 if (Opcode == ISD::MUL) { 4180 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 4181 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 4182 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 4183 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 4184 Result.push_back(Hi); 4185 return true; 4186 } 4187 4188 // Compute the full width result. 4189 auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue { 4190 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo); 4191 Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 4192 Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift); 4193 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 4194 }; 4195 4196 SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi); 4197 if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false)) 4198 return false; 4199 4200 // This is effectively the add part of a multiply-add of half-sized operands, 4201 // so it cannot overflow. 4202 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 4203 4204 if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false)) 4205 return false; 4206 4207 SDValue Zero = DAG.getConstant(0, dl, HiLoVT); 4208 EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 4209 4210 bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) && 4211 isOperationLegalOrCustom(ISD::ADDE, VT)); 4212 if (UseGlue) 4213 Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next, 4214 Merge(Lo, Hi)); 4215 else 4216 Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next, 4217 Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType)); 4218 4219 SDValue Carry = Next.getValue(1); 4220 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 4221 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 4222 4223 if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI)) 4224 return false; 4225 4226 if (UseGlue) 4227 Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero, 4228 Carry); 4229 else 4230 Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi, 4231 Zero, Carry); 4232 4233 Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi)); 4234 4235 if (Opcode == ISD::SMUL_LOHI) { 4236 SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 4237 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL)); 4238 Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT); 4239 4240 NextSub = DAG.getNode(ISD::SUB, dl, VT, Next, 4241 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL)); 4242 Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT); 4243 } 4244 4245 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 4246 Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift); 4247 Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next)); 4248 return true; 4249 } 4250 4251 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 4252 SelectionDAG &DAG, MulExpansionKind Kind, 4253 SDValue LL, SDValue LH, SDValue RL, 4254 SDValue RH) const { 4255 SmallVector<SDValue, 2> Result; 4256 bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N, 4257 N->getOperand(0), N->getOperand(1), Result, HiLoVT, 4258 DAG, Kind, LL, LH, RL, RH); 4259 if (Ok) { 4260 assert(Result.size() == 2); 4261 Lo = Result[0]; 4262 Hi = Result[1]; 4263 } 4264 return Ok; 4265 } 4266 4267 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result, 4268 SelectionDAG &DAG) const { 4269 EVT VT = Node->getValueType(0); 4270 4271 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 4272 !isOperationLegalOrCustom(ISD::SRL, VT) || 4273 !isOperationLegalOrCustom(ISD::SUB, VT) || 4274 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 4275 return false; 4276 4277 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW))) 4278 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW)) 4279 SDValue X = Node->getOperand(0); 4280 SDValue Y = Node->getOperand(1); 4281 SDValue Z = Node->getOperand(2); 4282 4283 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4284 bool IsFSHL = Node->getOpcode() == ISD::FSHL; 4285 SDLoc DL(SDValue(Node, 0)); 4286 4287 EVT ShVT = Z.getValueType(); 4288 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 4289 SDValue Zero = DAG.getConstant(0, DL, ShVT); 4290 4291 SDValue ShAmt; 4292 if (isPowerOf2_32(EltSizeInBits)) { 4293 SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 4294 ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask); 4295 } else { 4296 ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC); 4297 } 4298 4299 SDValue InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt); 4300 SDValue ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt); 4301 SDValue ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt); 4302 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShX, ShY); 4303 4304 // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth, 4305 // and that is undefined. We must compare and select to avoid UB. 4306 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShVT); 4307 4308 // For fshl, 0-shift returns the 1st arg (X). 4309 // For fshr, 0-shift returns the 2nd arg (Y). 4310 SDValue IsZeroShift = DAG.getSetCC(DL, CCVT, ShAmt, Zero, ISD::SETEQ); 4311 Result = DAG.getSelect(DL, VT, IsZeroShift, IsFSHL ? X : Y, Or); 4312 return true; 4313 } 4314 4315 // TODO: Merge with expandFunnelShift. 4316 bool TargetLowering::expandROT(SDNode *Node, SDValue &Result, 4317 SelectionDAG &DAG) const { 4318 EVT VT = Node->getValueType(0); 4319 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 4320 bool IsLeft = Node->getOpcode() == ISD::ROTL; 4321 SDValue Op0 = Node->getOperand(0); 4322 SDValue Op1 = Node->getOperand(1); 4323 SDLoc DL(SDValue(Node, 0)); 4324 4325 EVT ShVT = Op1.getValueType(); 4326 SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT); 4327 4328 // If a rotate in the other direction is legal, use it. 4329 unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL; 4330 if (isOperationLegal(RevRot, VT)) { 4331 SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1); 4332 Result = DAG.getNode(RevRot, DL, VT, Op0, Sub); 4333 return true; 4334 } 4335 4336 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) || 4337 !isOperationLegalOrCustom(ISD::SRL, VT) || 4338 !isOperationLegalOrCustom(ISD::SUB, VT) || 4339 !isOperationLegalOrCustomOrPromote(ISD::OR, VT) || 4340 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 4341 return false; 4342 4343 // Otherwise, 4344 // (rotl x, c) -> (or (shl x, (and c, w-1)), (srl x, (and w-c, w-1))) 4345 // (rotr x, c) -> (or (srl x, (and c, w-1)), (shl x, (and w-c, w-1))) 4346 // 4347 assert(isPowerOf2_32(EltSizeInBits) && EltSizeInBits > 1 && 4348 "Expecting the type bitwidth to be a power of 2"); 4349 unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL; 4350 unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL; 4351 SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT); 4352 SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1); 4353 SDValue And0 = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC); 4354 SDValue And1 = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC); 4355 Result = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ShOpc, DL, VT, Op0, And0), 4356 DAG.getNode(HsOpc, DL, VT, Op0, And1)); 4357 return true; 4358 } 4359 4360 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 4361 SelectionDAG &DAG) const { 4362 SDValue Src = Node->getOperand(0); 4363 EVT SrcVT = Src.getValueType(); 4364 EVT DstVT = Node->getValueType(0); 4365 SDLoc dl(SDValue(Node, 0)); 4366 4367 // FIXME: Only f32 to i64 conversions are supported. 4368 if (SrcVT != MVT::f32 || DstVT != MVT::i64) 4369 return false; 4370 4371 // Expand f32 -> i64 conversion 4372 // This algorithm comes from compiler-rt's implementation of fixsfdi: 4373 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c 4374 unsigned SrcEltBits = SrcVT.getScalarSizeInBits(); 4375 EVT IntVT = SrcVT.changeTypeToInteger(); 4376 EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout()); 4377 4378 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 4379 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 4380 SDValue Bias = DAG.getConstant(127, dl, IntVT); 4381 SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT); 4382 SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT); 4383 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 4384 4385 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src); 4386 4387 SDValue ExponentBits = DAG.getNode( 4388 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 4389 DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT)); 4390 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 4391 4392 SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT, 4393 DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 4394 DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT)); 4395 Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT); 4396 4397 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 4398 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 4399 DAG.getConstant(0x00800000, dl, IntVT)); 4400 4401 R = DAG.getZExtOrTrunc(R, dl, DstVT); 4402 4403 R = DAG.getSelectCC( 4404 dl, Exponent, ExponentLoBit, 4405 DAG.getNode(ISD::SHL, dl, DstVT, R, 4406 DAG.getZExtOrTrunc( 4407 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 4408 dl, IntShVT)), 4409 DAG.getNode(ISD::SRL, dl, DstVT, R, 4410 DAG.getZExtOrTrunc( 4411 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 4412 dl, IntShVT)), 4413 ISD::SETGT); 4414 4415 SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT, 4416 DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign); 4417 4418 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 4419 DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT); 4420 return true; 4421 } 4422 4423 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result, 4424 SelectionDAG &DAG) const { 4425 SDLoc dl(SDValue(Node, 0)); 4426 SDValue Src = Node->getOperand(0); 4427 4428 EVT SrcVT = Src.getValueType(); 4429 EVT DstVT = Node->getValueType(0); 4430 EVT SetCCVT = 4431 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 4432 4433 // Only expand vector types if we have the appropriate vector bit operations. 4434 if (DstVT.isVector() && (!isOperationLegalOrCustom(ISD::FP_TO_SINT, DstVT) || 4435 !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT))) 4436 return false; 4437 4438 // If the maximum float value is smaller then the signed integer range, 4439 // the destination signmask can't be represented by the float, so we can 4440 // just use FP_TO_SINT directly. 4441 const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT); 4442 APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits())); 4443 APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits()); 4444 if (APFloat::opOverflow & 4445 APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) { 4446 Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 4447 return true; 4448 } 4449 4450 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT); 4451 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT); 4452 4453 bool Strict = shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false); 4454 if (Strict) { 4455 // Expand based on maximum range of FP_TO_SINT, if the value exceeds the 4456 // signmask then offset (the result of which should be fully representable). 4457 // Sel = Src < 0x8000000000000000 4458 // Val = select Sel, Src, Src - 0x8000000000000000 4459 // Ofs = select Sel, 0, 0x8000000000000000 4460 // Result = fp_to_sint(Val) ^ Ofs 4461 4462 // TODO: Should any fast-math-flags be set for the FSUB? 4463 SDValue Val = DAG.getSelect(dl, SrcVT, Sel, Src, 4464 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 4465 SDValue Ofs = DAG.getSelect(dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), 4466 DAG.getConstant(SignMask, dl, DstVT)); 4467 Result = DAG.getNode(ISD::XOR, dl, DstVT, 4468 DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val), Ofs); 4469 } else { 4470 // Expand based on maximum range of FP_TO_SINT: 4471 // True = fp_to_sint(Src) 4472 // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000) 4473 // Result = select (Src < 0x8000000000000000), True, False 4474 4475 SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src); 4476 // TODO: Should any fast-math-flags be set for the FSUB? 4477 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, 4478 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst)); 4479 False = DAG.getNode(ISD::XOR, dl, DstVT, False, 4480 DAG.getConstant(SignMask, dl, DstVT)); 4481 Result = DAG.getSelect(dl, DstVT, Sel, True, False); 4482 } 4483 return true; 4484 } 4485 4486 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result, 4487 SelectionDAG &DAG) const { 4488 SDValue Src = Node->getOperand(0); 4489 EVT SrcVT = Src.getValueType(); 4490 EVT DstVT = Node->getValueType(0); 4491 4492 if (SrcVT.getScalarType() != MVT::i64) 4493 return false; 4494 4495 SDLoc dl(SDValue(Node, 0)); 4496 EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout()); 4497 4498 if (DstVT.getScalarType() == MVT::f32) { 4499 // Only expand vector types if we have the appropriate vector bit 4500 // operations. 4501 if (SrcVT.isVector() && 4502 (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 4503 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 4504 !isOperationLegalOrCustom(ISD::SINT_TO_FP, SrcVT) || 4505 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 4506 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 4507 return false; 4508 4509 // For unsigned conversions, convert them to signed conversions using the 4510 // algorithm from the x86_64 __floatundidf in compiler_rt. 4511 SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src); 4512 4513 SDValue ShiftConst = DAG.getConstant(1, dl, ShiftVT); 4514 SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Src, ShiftConst); 4515 SDValue AndConst = DAG.getConstant(1, dl, SrcVT); 4516 SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Src, AndConst); 4517 SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr); 4518 4519 SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Or); 4520 SDValue Slow = DAG.getNode(ISD::FADD, dl, DstVT, SignCvt, SignCvt); 4521 4522 // TODO: This really should be implemented using a branch rather than a 4523 // select. We happen to get lucky and machinesink does the right 4524 // thing most of the time. This would be a good candidate for a 4525 // pseudo-op, or, even better, for whole-function isel. 4526 EVT SetCCVT = 4527 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT); 4528 4529 SDValue SignBitTest = DAG.getSetCC( 4530 dl, SetCCVT, Src, DAG.getConstant(0, dl, SrcVT), ISD::SETLT); 4531 Result = DAG.getSelect(dl, DstVT, SignBitTest, Slow, Fast); 4532 return true; 4533 } 4534 4535 if (DstVT.getScalarType() == MVT::f64) { 4536 // Only expand vector types if we have the appropriate vector bit 4537 // operations. 4538 if (SrcVT.isVector() && 4539 (!isOperationLegalOrCustom(ISD::SRL, SrcVT) || 4540 !isOperationLegalOrCustom(ISD::FADD, DstVT) || 4541 !isOperationLegalOrCustom(ISD::FSUB, DstVT) || 4542 !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) || 4543 !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT))) 4544 return false; 4545 4546 // Implementation of unsigned i64 to f64 following the algorithm in 4547 // __floatundidf in compiler_rt. This implementation has the advantage 4548 // of performing rounding correctly, both in the default rounding mode 4549 // and in all alternate rounding modes. 4550 SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT); 4551 SDValue TwoP84PlusTwoP52 = DAG.getConstantFP( 4552 BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT); 4553 SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT); 4554 SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT); 4555 SDValue HiShift = DAG.getConstant(32, dl, ShiftVT); 4556 4557 SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask); 4558 SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift); 4559 SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52); 4560 SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84); 4561 SDValue LoFlt = DAG.getBitcast(DstVT, LoOr); 4562 SDValue HiFlt = DAG.getBitcast(DstVT, HiOr); 4563 SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52); 4564 Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub); 4565 return true; 4566 } 4567 4568 return false; 4569 } 4570 4571 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node, 4572 SelectionDAG &DAG) const { 4573 SDLoc dl(Node); 4574 unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ? 4575 ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 4576 EVT VT = Node->getValueType(0); 4577 if (isOperationLegalOrCustom(NewOp, VT)) { 4578 SDValue Quiet0 = Node->getOperand(0); 4579 SDValue Quiet1 = Node->getOperand(1); 4580 4581 if (!Node->getFlags().hasNoNaNs()) { 4582 // Insert canonicalizes if it's possible we need to quiet to get correct 4583 // sNaN behavior. 4584 if (!DAG.isKnownNeverSNaN(Quiet0)) { 4585 Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0, 4586 Node->getFlags()); 4587 } 4588 if (!DAG.isKnownNeverSNaN(Quiet1)) { 4589 Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1, 4590 Node->getFlags()); 4591 } 4592 } 4593 4594 return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags()); 4595 } 4596 4597 return SDValue(); 4598 } 4599 4600 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result, 4601 SelectionDAG &DAG) const { 4602 SDLoc dl(Node); 4603 EVT VT = Node->getValueType(0); 4604 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 4605 SDValue Op = Node->getOperand(0); 4606 unsigned Len = VT.getScalarSizeInBits(); 4607 assert(VT.isInteger() && "CTPOP not implemented for this type."); 4608 4609 // TODO: Add support for irregular type lengths. 4610 if (!(Len <= 128 && Len % 8 == 0)) 4611 return false; 4612 4613 // Only expand vector types if we have the appropriate vector bit operations. 4614 if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) || 4615 !isOperationLegalOrCustom(ISD::SUB, VT) || 4616 !isOperationLegalOrCustom(ISD::SRL, VT) || 4617 (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) || 4618 !isOperationLegalOrCustomOrPromote(ISD::AND, VT))) 4619 return false; 4620 4621 // This is the "best" algorithm from 4622 // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel 4623 SDValue Mask55 = 4624 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT); 4625 SDValue Mask33 = 4626 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT); 4627 SDValue Mask0F = 4628 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT); 4629 SDValue Mask01 = 4630 DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT); 4631 4632 // v = v - ((v >> 1) & 0x55555555...) 4633 Op = DAG.getNode(ISD::SUB, dl, VT, Op, 4634 DAG.getNode(ISD::AND, dl, VT, 4635 DAG.getNode(ISD::SRL, dl, VT, Op, 4636 DAG.getConstant(1, dl, ShVT)), 4637 Mask55)); 4638 // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...) 4639 Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33), 4640 DAG.getNode(ISD::AND, dl, VT, 4641 DAG.getNode(ISD::SRL, dl, VT, Op, 4642 DAG.getConstant(2, dl, ShVT)), 4643 Mask33)); 4644 // v = (v + (v >> 4)) & 0x0F0F0F0F... 4645 Op = DAG.getNode(ISD::AND, dl, VT, 4646 DAG.getNode(ISD::ADD, dl, VT, Op, 4647 DAG.getNode(ISD::SRL, dl, VT, Op, 4648 DAG.getConstant(4, dl, ShVT))), 4649 Mask0F); 4650 // v = (v * 0x01010101...) >> (Len - 8) 4651 if (Len > 8) 4652 Op = 4653 DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01), 4654 DAG.getConstant(Len - 8, dl, ShVT)); 4655 4656 Result = Op; 4657 return true; 4658 } 4659 4660 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result, 4661 SelectionDAG &DAG) const { 4662 SDLoc dl(Node); 4663 EVT VT = Node->getValueType(0); 4664 EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout()); 4665 SDValue Op = Node->getOperand(0); 4666 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 4667 4668 // If the non-ZERO_UNDEF version is supported we can use that instead. 4669 if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF && 4670 isOperationLegalOrCustom(ISD::CTLZ, VT)) { 4671 Result = DAG.getNode(ISD::CTLZ, dl, VT, Op); 4672 return true; 4673 } 4674 4675 // If the ZERO_UNDEF version is supported use that and handle the zero case. 4676 if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) { 4677 EVT SetCCVT = 4678 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 4679 SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op); 4680 SDValue Zero = DAG.getConstant(0, dl, VT); 4681 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 4682 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 4683 DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ); 4684 return true; 4685 } 4686 4687 // Only expand vector types if we have the appropriate vector bit operations. 4688 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 4689 !isOperationLegalOrCustom(ISD::CTPOP, VT) || 4690 !isOperationLegalOrCustom(ISD::SRL, VT) || 4691 !isOperationLegalOrCustomOrPromote(ISD::OR, VT))) 4692 return false; 4693 4694 // for now, we do this: 4695 // x = x | (x >> 1); 4696 // x = x | (x >> 2); 4697 // ... 4698 // x = x | (x >>16); 4699 // x = x | (x >>32); // for 64-bit input 4700 // return popcount(~x); 4701 // 4702 // Ref: "Hacker's Delight" by Henry Warren 4703 for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) { 4704 SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT); 4705 Op = DAG.getNode(ISD::OR, dl, VT, Op, 4706 DAG.getNode(ISD::SRL, dl, VT, Op, Tmp)); 4707 } 4708 Op = DAG.getNOT(dl, Op, VT); 4709 Result = DAG.getNode(ISD::CTPOP, dl, VT, Op); 4710 return true; 4711 } 4712 4713 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result, 4714 SelectionDAG &DAG) const { 4715 SDLoc dl(Node); 4716 EVT VT = Node->getValueType(0); 4717 SDValue Op = Node->getOperand(0); 4718 unsigned NumBitsPerElt = VT.getScalarSizeInBits(); 4719 4720 // If the non-ZERO_UNDEF version is supported we can use that instead. 4721 if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF && 4722 isOperationLegalOrCustom(ISD::CTTZ, VT)) { 4723 Result = DAG.getNode(ISD::CTTZ, dl, VT, Op); 4724 return true; 4725 } 4726 4727 // If the ZERO_UNDEF version is supported use that and handle the zero case. 4728 if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) { 4729 EVT SetCCVT = 4730 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 4731 SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op); 4732 SDValue Zero = DAG.getConstant(0, dl, VT); 4733 SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ); 4734 Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero, 4735 DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ); 4736 return true; 4737 } 4738 4739 // Only expand vector types if we have the appropriate vector bit operations. 4740 if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) || 4741 (!isOperationLegalOrCustom(ISD::CTPOP, VT) && 4742 !isOperationLegalOrCustom(ISD::CTLZ, VT)) || 4743 !isOperationLegalOrCustom(ISD::SUB, VT) || 4744 !isOperationLegalOrCustomOrPromote(ISD::AND, VT) || 4745 !isOperationLegalOrCustomOrPromote(ISD::XOR, VT))) 4746 return false; 4747 4748 // for now, we use: { return popcount(~x & (x - 1)); } 4749 // unless the target has ctlz but not ctpop, in which case we use: 4750 // { return 32 - nlz(~x & (x-1)); } 4751 // Ref: "Hacker's Delight" by Henry Warren 4752 SDValue Tmp = DAG.getNode( 4753 ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT), 4754 DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT))); 4755 4756 // If ISD::CTLZ is legal and CTPOP isn't, then do that instead. 4757 if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) { 4758 Result = 4759 DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT), 4760 DAG.getNode(ISD::CTLZ, dl, VT, Tmp)); 4761 return true; 4762 } 4763 4764 Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp); 4765 return true; 4766 } 4767 4768 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 4769 SelectionDAG &DAG) const { 4770 SDLoc SL(LD); 4771 SDValue Chain = LD->getChain(); 4772 SDValue BasePTR = LD->getBasePtr(); 4773 EVT SrcVT = LD->getMemoryVT(); 4774 ISD::LoadExtType ExtType = LD->getExtensionType(); 4775 4776 unsigned NumElem = SrcVT.getVectorNumElements(); 4777 4778 EVT SrcEltVT = SrcVT.getScalarType(); 4779 EVT DstEltVT = LD->getValueType(0).getScalarType(); 4780 4781 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 4782 assert(SrcEltVT.isByteSized()); 4783 4784 SmallVector<SDValue, 8> Vals; 4785 SmallVector<SDValue, 8> LoadChains; 4786 4787 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 4788 SDValue ScalarLoad = 4789 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 4790 LD->getPointerInfo().getWithOffset(Idx * Stride), 4791 SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride), 4792 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 4793 4794 BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, Stride); 4795 4796 Vals.push_back(ScalarLoad.getValue(0)); 4797 LoadChains.push_back(ScalarLoad.getValue(1)); 4798 } 4799 4800 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 4801 SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals); 4802 4803 return DAG.getMergeValues({ Value, NewChain }, SL); 4804 } 4805 4806 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 4807 SelectionDAG &DAG) const { 4808 SDLoc SL(ST); 4809 4810 SDValue Chain = ST->getChain(); 4811 SDValue BasePtr = ST->getBasePtr(); 4812 SDValue Value = ST->getValue(); 4813 EVT StVT = ST->getMemoryVT(); 4814 4815 // The type of the data we want to save 4816 EVT RegVT = Value.getValueType(); 4817 EVT RegSclVT = RegVT.getScalarType(); 4818 4819 // The type of data as saved in memory. 4820 EVT MemSclVT = StVT.getScalarType(); 4821 4822 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout()); 4823 unsigned NumElem = StVT.getVectorNumElements(); 4824 4825 // A vector must always be stored in memory as-is, i.e. without any padding 4826 // between the elements, since various code depend on it, e.g. in the 4827 // handling of a bitcast of a vector type to int, which may be done with a 4828 // vector store followed by an integer load. A vector that does not have 4829 // elements that are byte-sized must therefore be stored as an integer 4830 // built out of the extracted vector elements. 4831 if (!MemSclVT.isByteSized()) { 4832 unsigned NumBits = StVT.getSizeInBits(); 4833 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits); 4834 4835 SDValue CurrVal = DAG.getConstant(0, SL, IntVT); 4836 4837 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 4838 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 4839 DAG.getConstant(Idx, SL, IdxVT)); 4840 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt); 4841 SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc); 4842 unsigned ShiftIntoIdx = 4843 (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx); 4844 SDValue ShiftAmount = 4845 DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT); 4846 SDValue ShiftedElt = 4847 DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount); 4848 CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt); 4849 } 4850 4851 return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(), 4852 ST->getAlignment(), ST->getMemOperand()->getFlags(), 4853 ST->getAAInfo()); 4854 } 4855 4856 // Store Stride in bytes 4857 unsigned Stride = MemSclVT.getSizeInBits() / 8; 4858 assert (Stride && "Zero stride!"); 4859 // Extract each of the elements from the original vector and save them into 4860 // memory individually. 4861 SmallVector<SDValue, 8> Stores; 4862 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 4863 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 4864 DAG.getConstant(Idx, SL, IdxVT)); 4865 4866 SDValue Ptr = DAG.getObjectPtrOffset(SL, BasePtr, Idx * Stride); 4867 4868 // This scalar TruncStore may be illegal, but we legalize it later. 4869 SDValue Store = DAG.getTruncStore( 4870 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 4871 MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride), 4872 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 4873 4874 Stores.push_back(Store); 4875 } 4876 4877 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 4878 } 4879 4880 std::pair<SDValue, SDValue> 4881 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 4882 assert(LD->getAddressingMode() == ISD::UNINDEXED && 4883 "unaligned indexed loads not implemented!"); 4884 SDValue Chain = LD->getChain(); 4885 SDValue Ptr = LD->getBasePtr(); 4886 EVT VT = LD->getValueType(0); 4887 EVT LoadedVT = LD->getMemoryVT(); 4888 SDLoc dl(LD); 4889 auto &MF = DAG.getMachineFunction(); 4890 4891 if (VT.isFloatingPoint() || VT.isVector()) { 4892 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 4893 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 4894 if (!isOperationLegalOrCustom(ISD::LOAD, intVT) && 4895 LoadedVT.isVector()) { 4896 // Scalarize the load and let the individual components be handled. 4897 SDValue Scalarized = scalarizeVectorLoad(LD, DAG); 4898 if (Scalarized->getOpcode() == ISD::MERGE_VALUES) 4899 return std::make_pair(Scalarized.getOperand(0), Scalarized.getOperand(1)); 4900 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1)); 4901 } 4902 4903 // Expand to a (misaligned) integer load of the same size, 4904 // then bitconvert to floating point or vector. 4905 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 4906 LD->getMemOperand()); 4907 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 4908 if (LoadedVT != VT) 4909 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 4910 ISD::ANY_EXTEND, dl, VT, Result); 4911 4912 return std::make_pair(Result, newLoad.getValue(1)); 4913 } 4914 4915 // Copy the value to a (aligned) stack slot using (unaligned) integer 4916 // loads and stores, then do a (aligned) load from the stack slot. 4917 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 4918 unsigned LoadedBytes = LoadedVT.getStoreSize(); 4919 unsigned RegBytes = RegVT.getSizeInBits() / 8; 4920 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 4921 4922 // Make sure the stack slot is also aligned for the register type. 4923 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 4924 auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex(); 4925 SmallVector<SDValue, 8> Stores; 4926 SDValue StackPtr = StackBase; 4927 unsigned Offset = 0; 4928 4929 EVT PtrVT = Ptr.getValueType(); 4930 EVT StackPtrVT = StackPtr.getValueType(); 4931 4932 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 4933 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 4934 4935 // Do all but one copies using the full register width. 4936 for (unsigned i = 1; i < NumRegs; i++) { 4937 // Load one integer register's worth from the original location. 4938 SDValue Load = DAG.getLoad( 4939 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 4940 MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(), 4941 LD->getAAInfo()); 4942 // Follow the load with a store to the stack slot. Remember the store. 4943 Stores.push_back(DAG.getStore( 4944 Load.getValue(1), dl, Load, StackPtr, 4945 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset))); 4946 // Increment the pointers. 4947 Offset += RegBytes; 4948 4949 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 4950 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 4951 } 4952 4953 // The last copy may be partial. Do an extending load. 4954 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 4955 8 * (LoadedBytes - Offset)); 4956 SDValue Load = 4957 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 4958 LD->getPointerInfo().getWithOffset(Offset), MemVT, 4959 MinAlign(LD->getAlignment(), Offset), 4960 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 4961 // Follow the load with a store to the stack slot. Remember the store. 4962 // On big-endian machines this requires a truncating store to ensure 4963 // that the bits end up in the right place. 4964 Stores.push_back(DAG.getTruncStore( 4965 Load.getValue(1), dl, Load, StackPtr, 4966 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT)); 4967 4968 // The order of the stores doesn't matter - say it with a TokenFactor. 4969 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 4970 4971 // Finally, perform the original load only redirected to the stack slot. 4972 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 4973 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), 4974 LoadedVT); 4975 4976 // Callers expect a MERGE_VALUES node. 4977 return std::make_pair(Load, TF); 4978 } 4979 4980 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 4981 "Unaligned load of unsupported type."); 4982 4983 // Compute the new VT that is half the size of the old one. This is an 4984 // integer MVT. 4985 unsigned NumBits = LoadedVT.getSizeInBits(); 4986 EVT NewLoadedVT; 4987 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 4988 NumBits >>= 1; 4989 4990 unsigned Alignment = LD->getAlignment(); 4991 unsigned IncrementSize = NumBits / 8; 4992 ISD::LoadExtType HiExtType = LD->getExtensionType(); 4993 4994 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 4995 if (HiExtType == ISD::NON_EXTLOAD) 4996 HiExtType = ISD::ZEXTLOAD; 4997 4998 // Load the value in two parts 4999 SDValue Lo, Hi; 5000 if (DAG.getDataLayout().isLittleEndian()) { 5001 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 5002 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 5003 LD->getAAInfo()); 5004 5005 Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize); 5006 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 5007 LD->getPointerInfo().getWithOffset(IncrementSize), 5008 NewLoadedVT, MinAlign(Alignment, IncrementSize), 5009 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 5010 } else { 5011 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(), 5012 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 5013 LD->getAAInfo()); 5014 5015 Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize); 5016 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 5017 LD->getPointerInfo().getWithOffset(IncrementSize), 5018 NewLoadedVT, MinAlign(Alignment, IncrementSize), 5019 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 5020 } 5021 5022 // aggregate the two parts 5023 SDValue ShiftAmount = 5024 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 5025 DAG.getDataLayout())); 5026 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 5027 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 5028 5029 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 5030 Hi.getValue(1)); 5031 5032 return std::make_pair(Result, TF); 5033 } 5034 5035 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 5036 SelectionDAG &DAG) const { 5037 assert(ST->getAddressingMode() == ISD::UNINDEXED && 5038 "unaligned indexed stores not implemented!"); 5039 SDValue Chain = ST->getChain(); 5040 SDValue Ptr = ST->getBasePtr(); 5041 SDValue Val = ST->getValue(); 5042 EVT VT = Val.getValueType(); 5043 int Alignment = ST->getAlignment(); 5044 auto &MF = DAG.getMachineFunction(); 5045 EVT MemVT = ST->getMemoryVT(); 5046 5047 SDLoc dl(ST); 5048 if (MemVT.isFloatingPoint() || MemVT.isVector()) { 5049 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 5050 if (isTypeLegal(intVT)) { 5051 if (!isOperationLegalOrCustom(ISD::STORE, intVT) && 5052 MemVT.isVector()) { 5053 // Scalarize the store and let the individual components be handled. 5054 SDValue Result = scalarizeVectorStore(ST, DAG); 5055 5056 return Result; 5057 } 5058 // Expand to a bitconvert of the value to the integer type of the 5059 // same size, then a (misaligned) int store. 5060 // FIXME: Does not handle truncating floating point stores! 5061 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 5062 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 5063 Alignment, ST->getMemOperand()->getFlags()); 5064 return Result; 5065 } 5066 // Do a (aligned) store to a stack slot, then copy from the stack slot 5067 // to the final destination using (unaligned) integer loads and stores. 5068 EVT StoredVT = ST->getMemoryVT(); 5069 MVT RegVT = 5070 getRegisterType(*DAG.getContext(), 5071 EVT::getIntegerVT(*DAG.getContext(), 5072 StoredVT.getSizeInBits())); 5073 EVT PtrVT = Ptr.getValueType(); 5074 unsigned StoredBytes = StoredVT.getStoreSize(); 5075 unsigned RegBytes = RegVT.getSizeInBits() / 8; 5076 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 5077 5078 // Make sure the stack slot is also aligned for the register type. 5079 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT); 5080 auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex(); 5081 5082 // Perform the original store, only redirected to the stack slot. 5083 SDValue Store = DAG.getTruncStore( 5084 Chain, dl, Val, StackPtr, 5085 MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoredVT); 5086 5087 EVT StackPtrVT = StackPtr.getValueType(); 5088 5089 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 5090 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 5091 SmallVector<SDValue, 8> Stores; 5092 unsigned Offset = 0; 5093 5094 // Do all but one copies using the full register width. 5095 for (unsigned i = 1; i < NumRegs; i++) { 5096 // Load one integer register's worth from the stack slot. 5097 SDValue Load = DAG.getLoad( 5098 RegVT, dl, Store, StackPtr, 5099 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)); 5100 // Store it to the final location. Remember the store. 5101 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 5102 ST->getPointerInfo().getWithOffset(Offset), 5103 MinAlign(ST->getAlignment(), Offset), 5104 ST->getMemOperand()->getFlags())); 5105 // Increment the pointers. 5106 Offset += RegBytes; 5107 StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement); 5108 Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement); 5109 } 5110 5111 // The last store may be partial. Do a truncating store. On big-endian 5112 // machines this requires an extending load from the stack slot to ensure 5113 // that the bits are in the right place. 5114 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 5115 8 * (StoredBytes - Offset)); 5116 5117 // Load from the stack slot. 5118 SDValue Load = DAG.getExtLoad( 5119 ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 5120 MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT); 5121 5122 Stores.push_back( 5123 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 5124 ST->getPointerInfo().getWithOffset(Offset), MemVT, 5125 MinAlign(ST->getAlignment(), Offset), 5126 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 5127 // The order of the stores doesn't matter - say it with a TokenFactor. 5128 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 5129 return Result; 5130 } 5131 5132 assert(ST->getMemoryVT().isInteger() && 5133 !ST->getMemoryVT().isVector() && 5134 "Unaligned store of unknown type."); 5135 // Get the half-size VT 5136 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext()); 5137 int NumBits = NewStoredVT.getSizeInBits(); 5138 int IncrementSize = NumBits / 8; 5139 5140 // Divide the stored value in two parts. 5141 SDValue ShiftAmount = 5142 DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(), 5143 DAG.getDataLayout())); 5144 SDValue Lo = Val; 5145 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 5146 5147 // Store the two parts 5148 SDValue Store1, Store2; 5149 Store1 = DAG.getTruncStore(Chain, dl, 5150 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 5151 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 5152 ST->getMemOperand()->getFlags()); 5153 5154 Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize); 5155 Alignment = MinAlign(Alignment, IncrementSize); 5156 Store2 = DAG.getTruncStore( 5157 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 5158 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 5159 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 5160 5161 SDValue Result = 5162 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 5163 return Result; 5164 } 5165 5166 SDValue 5167 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask, 5168 const SDLoc &DL, EVT DataVT, 5169 SelectionDAG &DAG, 5170 bool IsCompressedMemory) const { 5171 SDValue Increment; 5172 EVT AddrVT = Addr.getValueType(); 5173 EVT MaskVT = Mask.getValueType(); 5174 assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() && 5175 "Incompatible types of Data and Mask"); 5176 if (IsCompressedMemory) { 5177 // Incrementing the pointer according to number of '1's in the mask. 5178 EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits()); 5179 SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask); 5180 if (MaskIntVT.getSizeInBits() < 32) { 5181 MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg); 5182 MaskIntVT = MVT::i32; 5183 } 5184 5185 // Count '1's with POPCNT. 5186 Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg); 5187 Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT); 5188 // Scale is an element size in bytes. 5189 SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL, 5190 AddrVT); 5191 Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale); 5192 } else 5193 Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT); 5194 5195 return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment); 5196 } 5197 5198 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, 5199 SDValue Idx, 5200 EVT VecVT, 5201 const SDLoc &dl) { 5202 if (isa<ConstantSDNode>(Idx)) 5203 return Idx; 5204 5205 EVT IdxVT = Idx.getValueType(); 5206 unsigned NElts = VecVT.getVectorNumElements(); 5207 if (isPowerOf2_32(NElts)) { 5208 APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), 5209 Log2_32(NElts)); 5210 return DAG.getNode(ISD::AND, dl, IdxVT, Idx, 5211 DAG.getConstant(Imm, dl, IdxVT)); 5212 } 5213 5214 return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, 5215 DAG.getConstant(NElts - 1, dl, IdxVT)); 5216 } 5217 5218 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG, 5219 SDValue VecPtr, EVT VecVT, 5220 SDValue Index) const { 5221 SDLoc dl(Index); 5222 // Make sure the index type is big enough to compute in. 5223 Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType()); 5224 5225 EVT EltVT = VecVT.getVectorElementType(); 5226 5227 // Calculate the element offset and add it to the pointer. 5228 unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size. 5229 assert(EltSize * 8 == EltVT.getSizeInBits() && 5230 "Converting bits to bytes lost precision"); 5231 5232 Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl); 5233 5234 EVT IdxVT = Index.getValueType(); 5235 5236 Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index, 5237 DAG.getConstant(EltSize, dl, IdxVT)); 5238 return DAG.getNode(ISD::ADD, dl, IdxVT, VecPtr, Index); 5239 } 5240 5241 //===----------------------------------------------------------------------===// 5242 // Implementation of Emulated TLS Model 5243 //===----------------------------------------------------------------------===// 5244 5245 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 5246 SelectionDAG &DAG) const { 5247 // Access to address of TLS varialbe xyz is lowered to a function call: 5248 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 5249 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5250 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 5251 SDLoc dl(GA); 5252 5253 ArgListTy Args; 5254 ArgListEntry Entry; 5255 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 5256 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 5257 StringRef EmuTlsVarName(NameString); 5258 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 5259 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 5260 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 5261 Entry.Ty = VoidPtrType; 5262 Args.push_back(Entry); 5263 5264 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 5265 5266 TargetLowering::CallLoweringInfo CLI(DAG); 5267 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 5268 CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 5269 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 5270 5271 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 5272 // At last for X86 targets, maybe good for other targets too? 5273 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5274 MFI.setAdjustsStack(true); // Is this only for X86 target? 5275 MFI.setHasCalls(true); 5276 5277 assert((GA->getOffset() == 0) && 5278 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 5279 return CallResult.first; 5280 } 5281 5282 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op, 5283 SelectionDAG &DAG) const { 5284 assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node."); 5285 if (!isCtlzFast()) 5286 return SDValue(); 5287 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 5288 SDLoc dl(Op); 5289 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 5290 if (C->isNullValue() && CC == ISD::SETEQ) { 5291 EVT VT = Op.getOperand(0).getValueType(); 5292 SDValue Zext = Op.getOperand(0); 5293 if (VT.bitsLT(MVT::i32)) { 5294 VT = MVT::i32; 5295 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); 5296 } 5297 unsigned Log2b = Log2_32(VT.getSizeInBits()); 5298 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); 5299 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, 5300 DAG.getConstant(Log2b, dl, MVT::i32)); 5301 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); 5302 } 5303 } 5304 return SDValue(); 5305 } 5306 5307 SDValue TargetLowering::getExpandedSaturationAdditionSubtraction( 5308 SDNode *Node, SelectionDAG &DAG) const { 5309 unsigned Opcode = Node->getOpcode(); 5310 unsigned OverflowOp; 5311 switch (Opcode) { 5312 case ISD::SADDSAT: 5313 OverflowOp = ISD::SADDO; 5314 break; 5315 case ISD::UADDSAT: 5316 OverflowOp = ISD::UADDO; 5317 break; 5318 case ISD::SSUBSAT: 5319 OverflowOp = ISD::SSUBO; 5320 break; 5321 case ISD::USUBSAT: 5322 OverflowOp = ISD::USUBO; 5323 break; 5324 default: 5325 llvm_unreachable("Expected method to receive signed or unsigned saturation " 5326 "addition or subtraction node."); 5327 } 5328 assert(Node->getNumOperands() == 2 && "Expected node to have 2 operands."); 5329 5330 SDLoc dl(Node); 5331 SDValue LHS = Node->getOperand(0); 5332 SDValue RHS = Node->getOperand(1); 5333 assert(LHS.getValueType().isScalarInteger() && 5334 "Expected operands to be integers. Vector of int arguments should " 5335 "already be unrolled."); 5336 assert(RHS.getValueType().isScalarInteger() && 5337 "Expected operands to be integers. Vector of int arguments should " 5338 "already be unrolled."); 5339 assert(LHS.getValueType() == RHS.getValueType() && 5340 "Expected both operands to be the same type"); 5341 5342 unsigned BitWidth = LHS.getValueSizeInBits(); 5343 EVT ResultType = LHS.getValueType(); 5344 EVT BoolVT = 5345 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ResultType); 5346 SDValue Result = 5347 DAG.getNode(OverflowOp, dl, DAG.getVTList(ResultType, BoolVT), LHS, RHS); 5348 SDValue SumDiff = Result.getValue(0); 5349 SDValue Overflow = Result.getValue(1); 5350 SDValue Zero = DAG.getConstant(0, dl, ResultType); 5351 5352 if (Opcode == ISD::UADDSAT) { 5353 // Just need to check overflow for SatMax. 5354 APInt MaxVal = APInt::getMaxValue(BitWidth); 5355 SDValue SatMax = DAG.getConstant(MaxVal, dl, ResultType); 5356 return DAG.getSelect(dl, ResultType, Overflow, SatMax, SumDiff); 5357 } else if (Opcode == ISD::USUBSAT) { 5358 // Just need to check overflow for SatMin. 5359 APInt MinVal = APInt::getMinValue(BitWidth); 5360 SDValue SatMin = DAG.getConstant(MinVal, dl, ResultType); 5361 return DAG.getSelect(dl, ResultType, Overflow, SatMin, SumDiff); 5362 } else { 5363 // SatMax -> Overflow && SumDiff < 0 5364 // SatMin -> Overflow && SumDiff >= 0 5365 APInt MinVal = APInt::getSignedMinValue(BitWidth); 5366 APInt MaxVal = APInt::getSignedMaxValue(BitWidth); 5367 SDValue SatMin = DAG.getConstant(MinVal, dl, ResultType); 5368 SDValue SatMax = DAG.getConstant(MaxVal, dl, ResultType); 5369 SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT); 5370 Result = DAG.getSelect(dl, ResultType, SumNeg, SatMax, SatMin); 5371 return DAG.getSelect(dl, ResultType, Overflow, Result, SumDiff); 5372 } 5373 } 5374 5375 SDValue 5376 TargetLowering::getExpandedFixedPointMultiplication(SDNode *Node, 5377 SelectionDAG &DAG) const { 5378 assert(Node->getOpcode() == ISD::SMULFIX && "Expected opcode to be SMULFIX."); 5379 assert(Node->getNumOperands() == 3 && 5380 "Expected signed fixed point multiplication to have 3 operands."); 5381 5382 SDLoc dl(Node); 5383 SDValue LHS = Node->getOperand(0); 5384 SDValue RHS = Node->getOperand(1); 5385 assert(LHS.getValueType().isScalarInteger() && 5386 "Expected operands to be integers. Vector of int arguments should " 5387 "already be unrolled."); 5388 assert(RHS.getValueType().isScalarInteger() && 5389 "Expected operands to be integers. Vector of int arguments should " 5390 "already be unrolled."); 5391 assert(LHS.getValueType() == RHS.getValueType() && 5392 "Expected both operands to be the same type"); 5393 5394 unsigned Scale = Node->getConstantOperandVal(2); 5395 EVT VT = LHS.getValueType(); 5396 assert(Scale < VT.getScalarSizeInBits() && 5397 "Expected scale to be less than the number of bits."); 5398 5399 if (!Scale) 5400 return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 5401 5402 // Get the upper and lower bits of the result. 5403 SDValue Lo, Hi; 5404 if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) { 5405 SDValue Result = 5406 DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), LHS, RHS); 5407 Lo = Result.getValue(0); 5408 Hi = Result.getValue(1); 5409 } else if (isOperationLegalOrCustom(ISD::MULHS, VT)) { 5410 Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS); 5411 Hi = DAG.getNode(ISD::MULHS, dl, VT, LHS, RHS); 5412 } else { 5413 report_fatal_error("Unable to expand signed fixed point multiplication."); 5414 } 5415 5416 // The result will need to be shifted right by the scale since both operands 5417 // are scaled. The result is given to us in 2 halves, so we only want part of 5418 // both in the result. 5419 EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout()); 5420 Lo = DAG.getNode(ISD::SRL, dl, VT, Lo, DAG.getConstant(Scale, dl, ShiftTy)); 5421 Hi = DAG.getNode( 5422 ISD::SHL, dl, VT, Hi, 5423 DAG.getConstant(VT.getScalarSizeInBits() - Scale, dl, ShiftTy)); 5424 return DAG.getNode(ISD::OR, dl, VT, Lo, Hi); 5425 } 5426