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