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