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_F64 : 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 } 1151 // FALL THROUGH 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 bool TargetLowering::isConstFalseVal(const SDNode *N) const { 1238 if (!N) 1239 return false; 1240 1241 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N); 1242 if (!CN) { 1243 const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N); 1244 if (!BV) 1245 return false; 1246 1247 BitVector UndefElements; 1248 CN = BV->getConstantSplatNode(&UndefElements); 1249 // Only interested in constant splats, and we don't try to handle undef 1250 // elements in identifying boolean constants. 1251 if (!CN || UndefElements.none()) 1252 return false; 1253 } 1254 1255 if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent) 1256 return !CN->getAPIntValue()[0]; 1257 1258 return CN->isNullValue(); 1259 } 1260 1261 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT, 1262 bool SExt) const { 1263 if (VT == MVT::i1) 1264 return N->isOne(); 1265 1266 TargetLowering::BooleanContent Cnt = getBooleanContents(VT); 1267 switch (Cnt) { 1268 case TargetLowering::ZeroOrOneBooleanContent: 1269 // An extended value of 1 is always true, unless its original type is i1, 1270 // in which case it will be sign extended to -1. 1271 return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1)); 1272 case TargetLowering::UndefinedBooleanContent: 1273 case TargetLowering::ZeroOrNegativeOneBooleanContent: 1274 return N->isAllOnesValue() && SExt; 1275 } 1276 llvm_unreachable("Unexpected enumeration."); 1277 } 1278 1279 /// This helper function of SimplifySetCC tries to optimize the comparison when 1280 /// either operand of the SetCC node is a bitwise-and instruction. 1281 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1, 1282 ISD::CondCode Cond, 1283 DAGCombinerInfo &DCI, 1284 const SDLoc &DL) const { 1285 // Match these patterns in any of their permutations: 1286 // (X & Y) == Y 1287 // (X & Y) != Y 1288 if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND) 1289 std::swap(N0, N1); 1290 1291 EVT OpVT = N0.getValueType(); 1292 if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() || 1293 (Cond != ISD::SETEQ && Cond != ISD::SETNE)) 1294 return SDValue(); 1295 1296 SDValue X, Y; 1297 if (N0.getOperand(0) == N1) { 1298 X = N0.getOperand(1); 1299 Y = N0.getOperand(0); 1300 } else if (N0.getOperand(1) == N1) { 1301 X = N0.getOperand(0); 1302 Y = N0.getOperand(1); 1303 } else { 1304 return SDValue(); 1305 } 1306 1307 SelectionDAG &DAG = DCI.DAG; 1308 SDValue Zero = DAG.getConstant(0, DL, OpVT); 1309 if (DAG.isKnownToBeAPowerOfTwo(Y)) { 1310 // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set. 1311 // Note that where Y is variable and is known to have at most one bit set 1312 // (for example, if it is Z & 1) we cannot do this; the expressions are not 1313 // equivalent when Y == 0. 1314 Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true); 1315 if (DCI.isBeforeLegalizeOps() || 1316 isCondCodeLegal(Cond, N0.getSimpleValueType())) 1317 return DAG.getSetCC(DL, VT, N0, Zero, Cond); 1318 } else if (N0.hasOneUse() && hasAndNotCompare(Y)) { 1319 // If the target supports an 'and-not' or 'and-complement' logic operation, 1320 // try to use that to make a comparison operation more efficient. 1321 // But don't do this transform if the mask is a single bit because there are 1322 // more efficient ways to deal with that case (for example, 'bt' on x86 or 1323 // 'rlwinm' on PPC). 1324 1325 // Bail out if the compare operand that we want to turn into a zero is 1326 // already a zero (otherwise, infinite loop). 1327 auto *YConst = dyn_cast<ConstantSDNode>(Y); 1328 if (YConst && YConst->isNullValue()) 1329 return SDValue(); 1330 1331 // Transform this into: ~X & Y == 0. 1332 SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT); 1333 SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y); 1334 return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond); 1335 } 1336 1337 return SDValue(); 1338 } 1339 1340 /// Try to simplify a setcc built with the specified operands and cc. If it is 1341 /// unable to simplify it, return a null SDValue. 1342 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 1343 ISD::CondCode Cond, bool foldBooleans, 1344 DAGCombinerInfo &DCI, 1345 const SDLoc &dl) const { 1346 SelectionDAG &DAG = DCI.DAG; 1347 1348 // These setcc operations always fold. 1349 switch (Cond) { 1350 default: break; 1351 case ISD::SETFALSE: 1352 case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT); 1353 case ISD::SETTRUE: 1354 case ISD::SETTRUE2: { 1355 TargetLowering::BooleanContent Cnt = 1356 getBooleanContents(N0->getValueType(0)); 1357 return DAG.getConstant( 1358 Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl, 1359 VT); 1360 } 1361 } 1362 1363 // Ensure that the constant occurs on the RHS, and fold constant 1364 // comparisons. 1365 ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond); 1366 if (isa<ConstantSDNode>(N0.getNode()) && 1367 (DCI.isBeforeLegalizeOps() || 1368 isCondCodeLegal(SwappedCC, N0.getSimpleValueType()))) 1369 return DAG.getSetCC(dl, VT, N1, N0, SwappedCC); 1370 1371 if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) { 1372 const APInt &C1 = N1C->getAPIntValue(); 1373 1374 // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an 1375 // equality comparison, then we're just comparing whether X itself is 1376 // zero. 1377 if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) && 1378 N0.getOperand(0).getOpcode() == ISD::CTLZ && 1379 N0.getOperand(1).getOpcode() == ISD::Constant) { 1380 const APInt &ShAmt 1381 = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1382 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1383 ShAmt == Log2_32(N0.getValueType().getSizeInBits())) { 1384 if ((C1 == 0) == (Cond == ISD::SETEQ)) { 1385 // (srl (ctlz x), 5) == 0 -> X != 0 1386 // (srl (ctlz x), 5) != 1 -> X != 0 1387 Cond = ISD::SETNE; 1388 } else { 1389 // (srl (ctlz x), 5) != 0 -> X == 0 1390 // (srl (ctlz x), 5) == 1 -> X == 0 1391 Cond = ISD::SETEQ; 1392 } 1393 SDValue Zero = DAG.getConstant(0, dl, N0.getValueType()); 1394 return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), 1395 Zero, Cond); 1396 } 1397 } 1398 1399 SDValue CTPOP = N0; 1400 // Look through truncs that don't change the value of a ctpop. 1401 if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE) 1402 CTPOP = N0.getOperand(0); 1403 1404 if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP && 1405 (N0 == CTPOP || N0.getValueType().getSizeInBits() > 1406 Log2_32_Ceil(CTPOP.getValueType().getSizeInBits()))) { 1407 EVT CTVT = CTPOP.getValueType(); 1408 SDValue CTOp = CTPOP.getOperand(0); 1409 1410 // (ctpop x) u< 2 -> (x & x-1) == 0 1411 // (ctpop x) u> 1 -> (x & x-1) != 0 1412 if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){ 1413 SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp, 1414 DAG.getConstant(1, dl, CTVT)); 1415 SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub); 1416 ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE; 1417 return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC); 1418 } 1419 1420 // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal. 1421 } 1422 1423 // (zext x) == C --> x == (trunc C) 1424 // (sext x) == C --> x == (trunc C) 1425 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1426 DCI.isBeforeLegalize() && N0->hasOneUse()) { 1427 unsigned MinBits = N0.getValueSizeInBits(); 1428 SDValue PreExt; 1429 bool Signed = false; 1430 if (N0->getOpcode() == ISD::ZERO_EXTEND) { 1431 // ZExt 1432 MinBits = N0->getOperand(0).getValueSizeInBits(); 1433 PreExt = N0->getOperand(0); 1434 } else if (N0->getOpcode() == ISD::AND) { 1435 // DAGCombine turns costly ZExts into ANDs 1436 if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1))) 1437 if ((C->getAPIntValue()+1).isPowerOf2()) { 1438 MinBits = C->getAPIntValue().countTrailingOnes(); 1439 PreExt = N0->getOperand(0); 1440 } 1441 } else if (N0->getOpcode() == ISD::SIGN_EXTEND) { 1442 // SExt 1443 MinBits = N0->getOperand(0).getValueSizeInBits(); 1444 PreExt = N0->getOperand(0); 1445 Signed = true; 1446 } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) { 1447 // ZEXTLOAD / SEXTLOAD 1448 if (LN0->getExtensionType() == ISD::ZEXTLOAD) { 1449 MinBits = LN0->getMemoryVT().getSizeInBits(); 1450 PreExt = N0; 1451 } else if (LN0->getExtensionType() == ISD::SEXTLOAD) { 1452 Signed = true; 1453 MinBits = LN0->getMemoryVT().getSizeInBits(); 1454 PreExt = N0; 1455 } 1456 } 1457 1458 // Figure out how many bits we need to preserve this constant. 1459 unsigned ReqdBits = Signed ? 1460 C1.getBitWidth() - C1.getNumSignBits() + 1 : 1461 C1.getActiveBits(); 1462 1463 // Make sure we're not losing bits from the constant. 1464 if (MinBits > 0 && 1465 MinBits < C1.getBitWidth() && 1466 MinBits >= ReqdBits) { 1467 EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits); 1468 if (isTypeDesirableForOp(ISD::SETCC, MinVT)) { 1469 // Will get folded away. 1470 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt); 1471 if (MinBits == 1 && C1 == 1) 1472 // Invert the condition. 1473 return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1), 1474 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1475 SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT); 1476 return DAG.getSetCC(dl, VT, Trunc, C, Cond); 1477 } 1478 1479 // If truncating the setcc operands is not desirable, we can still 1480 // simplify the expression in some cases: 1481 // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc) 1482 // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc)) 1483 // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc)) 1484 // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc) 1485 // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc)) 1486 // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc) 1487 SDValue TopSetCC = N0->getOperand(0); 1488 unsigned N0Opc = N0->getOpcode(); 1489 bool SExt = (N0Opc == ISD::SIGN_EXTEND); 1490 if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 && 1491 TopSetCC.getOpcode() == ISD::SETCC && 1492 (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) && 1493 (isConstFalseVal(N1C) || 1494 isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) { 1495 1496 bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) || 1497 (!N1C->isNullValue() && Cond == ISD::SETNE); 1498 1499 if (!Inverse) 1500 return TopSetCC; 1501 1502 ISD::CondCode InvCond = ISD::getSetCCInverse( 1503 cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(), 1504 TopSetCC.getOperand(0).getValueType().isInteger()); 1505 return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0), 1506 TopSetCC.getOperand(1), 1507 InvCond); 1508 1509 } 1510 } 1511 } 1512 1513 // If the LHS is '(and load, const)', the RHS is 0, 1514 // the test is for equality or unsigned, and all 1 bits of the const are 1515 // in the same partial word, see if we can shorten the load. 1516 if (DCI.isBeforeLegalize() && 1517 !ISD::isSignedIntSetCC(Cond) && 1518 N0.getOpcode() == ISD::AND && C1 == 0 && 1519 N0.getNode()->hasOneUse() && 1520 isa<LoadSDNode>(N0.getOperand(0)) && 1521 N0.getOperand(0).getNode()->hasOneUse() && 1522 isa<ConstantSDNode>(N0.getOperand(1))) { 1523 LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0)); 1524 APInt bestMask; 1525 unsigned bestWidth = 0, bestOffset = 0; 1526 if (!Lod->isVolatile() && Lod->isUnindexed()) { 1527 unsigned origWidth = N0.getValueType().getSizeInBits(); 1528 unsigned maskWidth = origWidth; 1529 // We can narrow (e.g.) 16-bit extending loads on 32-bit target to 1530 // 8 bits, but have to be careful... 1531 if (Lod->getExtensionType() != ISD::NON_EXTLOAD) 1532 origWidth = Lod->getMemoryVT().getSizeInBits(); 1533 const APInt &Mask = 1534 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 1535 for (unsigned width = origWidth / 2; width>=8; width /= 2) { 1536 APInt newMask = APInt::getLowBitsSet(maskWidth, width); 1537 for (unsigned offset=0; offset<origWidth/width; offset++) { 1538 if ((newMask & Mask) == Mask) { 1539 if (!DAG.getDataLayout().isLittleEndian()) 1540 bestOffset = (origWidth/width - offset - 1) * (width/8); 1541 else 1542 bestOffset = (uint64_t)offset * (width/8); 1543 bestMask = Mask.lshr(offset * (width/8) * 8); 1544 bestWidth = width; 1545 break; 1546 } 1547 newMask = newMask << width; 1548 } 1549 } 1550 } 1551 if (bestWidth) { 1552 EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth); 1553 if (newVT.isRound()) { 1554 EVT PtrType = Lod->getOperand(1).getValueType(); 1555 SDValue Ptr = Lod->getBasePtr(); 1556 if (bestOffset != 0) 1557 Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(), 1558 DAG.getConstant(bestOffset, dl, PtrType)); 1559 unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset); 1560 SDValue NewLoad = DAG.getLoad( 1561 newVT, dl, Lod->getChain(), Ptr, 1562 Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign); 1563 return DAG.getSetCC(dl, VT, 1564 DAG.getNode(ISD::AND, dl, newVT, NewLoad, 1565 DAG.getConstant(bestMask.trunc(bestWidth), 1566 dl, newVT)), 1567 DAG.getConstant(0LL, dl, newVT), Cond); 1568 } 1569 } 1570 } 1571 1572 // If the LHS is a ZERO_EXTEND, perform the comparison on the input. 1573 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 1574 unsigned InSize = N0.getOperand(0).getValueType().getSizeInBits(); 1575 1576 // If the comparison constant has bits in the upper part, the 1577 // zero-extended value could never match. 1578 if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(), 1579 C1.getBitWidth() - InSize))) { 1580 switch (Cond) { 1581 case ISD::SETUGT: 1582 case ISD::SETUGE: 1583 case ISD::SETEQ: return DAG.getConstant(0, dl, VT); 1584 case ISD::SETULT: 1585 case ISD::SETULE: 1586 case ISD::SETNE: return DAG.getConstant(1, dl, VT); 1587 case ISD::SETGT: 1588 case ISD::SETGE: 1589 // True if the sign bit of C1 is set. 1590 return DAG.getConstant(C1.isNegative(), dl, VT); 1591 case ISD::SETLT: 1592 case ISD::SETLE: 1593 // True if the sign bit of C1 isn't set. 1594 return DAG.getConstant(C1.isNonNegative(), dl, VT); 1595 default: 1596 break; 1597 } 1598 } 1599 1600 // Otherwise, we can perform the comparison with the low bits. 1601 switch (Cond) { 1602 case ISD::SETEQ: 1603 case ISD::SETNE: 1604 case ISD::SETUGT: 1605 case ISD::SETUGE: 1606 case ISD::SETULT: 1607 case ISD::SETULE: { 1608 EVT newVT = N0.getOperand(0).getValueType(); 1609 if (DCI.isBeforeLegalizeOps() || 1610 (isOperationLegal(ISD::SETCC, newVT) && 1611 getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) { 1612 EVT NewSetCCVT = 1613 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT); 1614 SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT); 1615 1616 SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0), 1617 NewConst, Cond); 1618 return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType()); 1619 } 1620 break; 1621 } 1622 default: 1623 break; // todo, be more careful with signed comparisons 1624 } 1625 } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 1626 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1627 EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT(); 1628 unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits(); 1629 EVT ExtDstTy = N0.getValueType(); 1630 unsigned ExtDstTyBits = ExtDstTy.getSizeInBits(); 1631 1632 // If the constant doesn't fit into the number of bits for the source of 1633 // the sign extension, it is impossible for both sides to be equal. 1634 if (C1.getMinSignedBits() > ExtSrcTyBits) 1635 return DAG.getConstant(Cond == ISD::SETNE, dl, VT); 1636 1637 SDValue ZextOp; 1638 EVT Op0Ty = N0.getOperand(0).getValueType(); 1639 if (Op0Ty == ExtSrcTy) { 1640 ZextOp = N0.getOperand(0); 1641 } else { 1642 APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits); 1643 ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0), 1644 DAG.getConstant(Imm, dl, Op0Ty)); 1645 } 1646 if (!DCI.isCalledByLegalizer()) 1647 DCI.AddToWorklist(ZextOp.getNode()); 1648 // Otherwise, make this a use of a zext. 1649 return DAG.getSetCC(dl, VT, ZextOp, 1650 DAG.getConstant(C1 & APInt::getLowBitsSet( 1651 ExtDstTyBits, 1652 ExtSrcTyBits), 1653 dl, ExtDstTy), 1654 Cond); 1655 } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) && 1656 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) { 1657 // SETCC (SETCC), [0|1], [EQ|NE] -> SETCC 1658 if (N0.getOpcode() == ISD::SETCC && 1659 isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) { 1660 bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1); 1661 if (TrueWhenTrue) 1662 return DAG.getNode(ISD::TRUNCATE, dl, VT, N0); 1663 // Invert the condition. 1664 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 1665 CC = ISD::getSetCCInverse(CC, 1666 N0.getOperand(0).getValueType().isInteger()); 1667 if (DCI.isBeforeLegalizeOps() || 1668 isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType())) 1669 return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC); 1670 } 1671 1672 if ((N0.getOpcode() == ISD::XOR || 1673 (N0.getOpcode() == ISD::AND && 1674 N0.getOperand(0).getOpcode() == ISD::XOR && 1675 N0.getOperand(1) == N0.getOperand(0).getOperand(1))) && 1676 isa<ConstantSDNode>(N0.getOperand(1)) && 1677 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) { 1678 // If this is (X^1) == 0/1, swap the RHS and eliminate the xor. We 1679 // can only do this if the top bits are known zero. 1680 unsigned BitWidth = N0.getValueSizeInBits(); 1681 if (DAG.MaskedValueIsZero(N0, 1682 APInt::getHighBitsSet(BitWidth, 1683 BitWidth-1))) { 1684 // Okay, get the un-inverted input value. 1685 SDValue Val; 1686 if (N0.getOpcode() == ISD::XOR) 1687 Val = N0.getOperand(0); 1688 else { 1689 assert(N0.getOpcode() == ISD::AND && 1690 N0.getOperand(0).getOpcode() == ISD::XOR); 1691 // ((X^1)&1)^1 -> X & 1 1692 Val = DAG.getNode(ISD::AND, dl, N0.getValueType(), 1693 N0.getOperand(0).getOperand(0), 1694 N0.getOperand(1)); 1695 } 1696 1697 return DAG.getSetCC(dl, VT, Val, N1, 1698 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1699 } 1700 } else if (N1C->getAPIntValue() == 1 && 1701 (VT == MVT::i1 || 1702 getBooleanContents(N0->getValueType(0)) == 1703 ZeroOrOneBooleanContent)) { 1704 SDValue Op0 = N0; 1705 if (Op0.getOpcode() == ISD::TRUNCATE) 1706 Op0 = Op0.getOperand(0); 1707 1708 if ((Op0.getOpcode() == ISD::XOR) && 1709 Op0.getOperand(0).getOpcode() == ISD::SETCC && 1710 Op0.getOperand(1).getOpcode() == ISD::SETCC) { 1711 // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc) 1712 Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ; 1713 return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1), 1714 Cond); 1715 } 1716 if (Op0.getOpcode() == ISD::AND && 1717 isa<ConstantSDNode>(Op0.getOperand(1)) && 1718 cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) { 1719 // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0. 1720 if (Op0.getValueType().bitsGT(VT)) 1721 Op0 = DAG.getNode(ISD::AND, dl, VT, 1722 DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)), 1723 DAG.getConstant(1, dl, VT)); 1724 else if (Op0.getValueType().bitsLT(VT)) 1725 Op0 = DAG.getNode(ISD::AND, dl, VT, 1726 DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)), 1727 DAG.getConstant(1, dl, VT)); 1728 1729 return DAG.getSetCC(dl, VT, Op0, 1730 DAG.getConstant(0, dl, Op0.getValueType()), 1731 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1732 } 1733 if (Op0.getOpcode() == ISD::AssertZext && 1734 cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1) 1735 return DAG.getSetCC(dl, VT, Op0, 1736 DAG.getConstant(0, dl, Op0.getValueType()), 1737 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ); 1738 } 1739 } 1740 1741 APInt MinVal, MaxVal; 1742 unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits(); 1743 if (ISD::isSignedIntSetCC(Cond)) { 1744 MinVal = APInt::getSignedMinValue(OperandBitSize); 1745 MaxVal = APInt::getSignedMaxValue(OperandBitSize); 1746 } else { 1747 MinVal = APInt::getMinValue(OperandBitSize); 1748 MaxVal = APInt::getMaxValue(OperandBitSize); 1749 } 1750 1751 // Canonicalize GE/LE comparisons to use GT/LT comparisons. 1752 if (Cond == ISD::SETGE || Cond == ISD::SETUGE) { 1753 if (C1 == MinVal) return DAG.getConstant(1, dl, VT); // X >= MIN --> true 1754 // X >= C0 --> X > (C0 - 1) 1755 APInt C = C1 - 1; 1756 ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT; 1757 if ((DCI.isBeforeLegalizeOps() || 1758 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 1759 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 && 1760 isLegalICmpImmediate(C.getSExtValue())))) { 1761 return DAG.getSetCC(dl, VT, N0, 1762 DAG.getConstant(C, dl, N1.getValueType()), 1763 NewCC); 1764 } 1765 } 1766 1767 if (Cond == ISD::SETLE || Cond == ISD::SETULE) { 1768 if (C1 == MaxVal) return DAG.getConstant(1, dl, VT); // X <= MAX --> true 1769 // X <= C0 --> X < (C0 + 1) 1770 APInt C = C1 + 1; 1771 ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT; 1772 if ((DCI.isBeforeLegalizeOps() || 1773 isCondCodeLegal(NewCC, VT.getSimpleVT())) && 1774 (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 && 1775 isLegalICmpImmediate(C.getSExtValue())))) { 1776 return DAG.getSetCC(dl, VT, N0, 1777 DAG.getConstant(C, dl, N1.getValueType()), 1778 NewCC); 1779 } 1780 } 1781 1782 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal) 1783 return DAG.getConstant(0, dl, VT); // X < MIN --> false 1784 if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal) 1785 return DAG.getConstant(1, dl, VT); // X >= MIN --> true 1786 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal) 1787 return DAG.getConstant(0, dl, VT); // X > MAX --> false 1788 if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal) 1789 return DAG.getConstant(1, dl, VT); // X <= MAX --> true 1790 1791 // Canonicalize setgt X, Min --> setne X, Min 1792 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal) 1793 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1794 // Canonicalize setlt X, Max --> setne X, Max 1795 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal) 1796 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE); 1797 1798 // If we have setult X, 1, turn it into seteq X, 0 1799 if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1) 1800 return DAG.getSetCC(dl, VT, N0, 1801 DAG.getConstant(MinVal, dl, N0.getValueType()), 1802 ISD::SETEQ); 1803 // If we have setugt X, Max-1, turn it into seteq X, Max 1804 if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1) 1805 return DAG.getSetCC(dl, VT, N0, 1806 DAG.getConstant(MaxVal, dl, N0.getValueType()), 1807 ISD::SETEQ); 1808 1809 // If we have "setcc X, C0", check to see if we can shrink the immediate 1810 // by changing cc. 1811 1812 // SETUGT X, SINTMAX -> SETLT X, 0 1813 if (Cond == ISD::SETUGT && 1814 C1 == APInt::getSignedMaxValue(OperandBitSize)) 1815 return DAG.getSetCC(dl, VT, N0, 1816 DAG.getConstant(0, dl, N1.getValueType()), 1817 ISD::SETLT); 1818 1819 // SETULT X, SINTMIN -> SETGT X, -1 1820 if (Cond == ISD::SETULT && 1821 C1 == APInt::getSignedMinValue(OperandBitSize)) { 1822 SDValue ConstMinusOne = 1823 DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl, 1824 N1.getValueType()); 1825 return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT); 1826 } 1827 1828 // Fold bit comparisons when we can. 1829 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1830 (VT == N0.getValueType() || 1831 (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) && 1832 N0.getOpcode() == ISD::AND) { 1833 auto &DL = DAG.getDataLayout(); 1834 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1835 EVT ShiftTy = DCI.isBeforeLegalize() 1836 ? getPointerTy(DL) 1837 : getShiftAmountTy(N0.getValueType(), DL); 1838 if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0 --> (X & 8) >> 3 1839 // Perform the xform if the AND RHS is a single bit. 1840 if (AndRHS->getAPIntValue().isPowerOf2()) { 1841 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1842 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1843 DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl, 1844 ShiftTy))); 1845 } 1846 } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) { 1847 // (X & 8) == 8 --> (X & 8) >> 3 1848 // Perform the xform if C1 is a single bit. 1849 if (C1.isPowerOf2()) { 1850 return DAG.getNode(ISD::TRUNCATE, dl, VT, 1851 DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0, 1852 DAG.getConstant(C1.logBase2(), dl, 1853 ShiftTy))); 1854 } 1855 } 1856 } 1857 } 1858 1859 if (C1.getMinSignedBits() <= 64 && 1860 !isLegalICmpImmediate(C1.getSExtValue())) { 1861 // (X & -256) == 256 -> (X >> 8) == 1 1862 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 1863 N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 1864 if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 1865 const APInt &AndRHSC = AndRHS->getAPIntValue(); 1866 if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) { 1867 unsigned ShiftBits = AndRHSC.countTrailingZeros(); 1868 auto &DL = DAG.getDataLayout(); 1869 EVT ShiftTy = DCI.isBeforeLegalize() 1870 ? getPointerTy(DL) 1871 : getShiftAmountTy(N0.getValueType(), DL); 1872 EVT CmpTy = N0.getValueType(); 1873 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0), 1874 DAG.getConstant(ShiftBits, dl, 1875 ShiftTy)); 1876 SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy); 1877 return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond); 1878 } 1879 } 1880 } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE || 1881 Cond == ISD::SETULE || Cond == ISD::SETUGT) { 1882 bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT); 1883 // X < 0x100000000 -> (X >> 32) < 1 1884 // X >= 0x100000000 -> (X >> 32) >= 1 1885 // X <= 0x0ffffffff -> (X >> 32) < 1 1886 // X > 0x0ffffffff -> (X >> 32) >= 1 1887 unsigned ShiftBits; 1888 APInt NewC = C1; 1889 ISD::CondCode NewCond = Cond; 1890 if (AdjOne) { 1891 ShiftBits = C1.countTrailingOnes(); 1892 NewC = NewC + 1; 1893 NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1894 } else { 1895 ShiftBits = C1.countTrailingZeros(); 1896 } 1897 NewC = NewC.lshr(ShiftBits); 1898 if (ShiftBits && NewC.getMinSignedBits() <= 64 && 1899 isLegalICmpImmediate(NewC.getSExtValue())) { 1900 auto &DL = DAG.getDataLayout(); 1901 EVT ShiftTy = DCI.isBeforeLegalize() 1902 ? getPointerTy(DL) 1903 : getShiftAmountTy(N0.getValueType(), DL); 1904 EVT CmpTy = N0.getValueType(); 1905 SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0, 1906 DAG.getConstant(ShiftBits, dl, ShiftTy)); 1907 SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy); 1908 return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond); 1909 } 1910 } 1911 } 1912 } 1913 1914 if (isa<ConstantFPSDNode>(N0.getNode())) { 1915 // Constant fold or commute setcc. 1916 SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl); 1917 if (O.getNode()) return O; 1918 } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) { 1919 // If the RHS of an FP comparison is a constant, simplify it away in 1920 // some cases. 1921 if (CFP->getValueAPF().isNaN()) { 1922 // If an operand is known to be a nan, we can fold it. 1923 switch (ISD::getUnorderedFlavor(Cond)) { 1924 default: llvm_unreachable("Unknown flavor!"); 1925 case 0: // Known false. 1926 return DAG.getConstant(0, dl, VT); 1927 case 1: // Known true. 1928 return DAG.getConstant(1, dl, VT); 1929 case 2: // Undefined. 1930 return DAG.getUNDEF(VT); 1931 } 1932 } 1933 1934 // Otherwise, we know the RHS is not a NaN. Simplify the node to drop the 1935 // constant if knowing that the operand is non-nan is enough. We prefer to 1936 // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to 1937 // materialize 0.0. 1938 if (Cond == ISD::SETO || Cond == ISD::SETUO) 1939 return DAG.getSetCC(dl, VT, N0, N0, Cond); 1940 1941 // If the condition is not legal, see if we can find an equivalent one 1942 // which is legal. 1943 if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) { 1944 // If the comparison was an awkward floating-point == or != and one of 1945 // the comparison operands is infinity or negative infinity, convert the 1946 // condition to a less-awkward <= or >=. 1947 if (CFP->getValueAPF().isInfinity()) { 1948 if (CFP->getValueAPF().isNegative()) { 1949 if (Cond == ISD::SETOEQ && 1950 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 1951 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE); 1952 if (Cond == ISD::SETUEQ && 1953 isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType())) 1954 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE); 1955 if (Cond == ISD::SETUNE && 1956 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 1957 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT); 1958 if (Cond == ISD::SETONE && 1959 isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType())) 1960 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT); 1961 } else { 1962 if (Cond == ISD::SETOEQ && 1963 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 1964 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE); 1965 if (Cond == ISD::SETUEQ && 1966 isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType())) 1967 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE); 1968 if (Cond == ISD::SETUNE && 1969 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 1970 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT); 1971 if (Cond == ISD::SETONE && 1972 isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType())) 1973 return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT); 1974 } 1975 } 1976 } 1977 } 1978 1979 if (N0 == N1) { 1980 // The sext(setcc()) => setcc() optimization relies on the appropriate 1981 // constant being emitted. 1982 uint64_t EqVal = 0; 1983 switch (getBooleanContents(N0.getValueType())) { 1984 case UndefinedBooleanContent: 1985 case ZeroOrOneBooleanContent: 1986 EqVal = ISD::isTrueWhenEqual(Cond); 1987 break; 1988 case ZeroOrNegativeOneBooleanContent: 1989 EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0; 1990 break; 1991 } 1992 1993 // We can always fold X == X for integer setcc's. 1994 if (N0.getValueType().isInteger()) { 1995 return DAG.getConstant(EqVal, dl, VT); 1996 } 1997 unsigned UOF = ISD::getUnorderedFlavor(Cond); 1998 if (UOF == 2) // FP operators that are undefined on NaNs. 1999 return DAG.getConstant(EqVal, dl, VT); 2000 if (UOF == unsigned(ISD::isTrueWhenEqual(Cond))) 2001 return DAG.getConstant(EqVal, dl, VT); 2002 // Otherwise, we can't fold it. However, we can simplify it to SETUO/SETO 2003 // if it is not already. 2004 ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO; 2005 if (NewCond != Cond && (DCI.isBeforeLegalizeOps() || 2006 getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal)) 2007 return DAG.getSetCC(dl, VT, N0, N1, NewCond); 2008 } 2009 2010 if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && 2011 N0.getValueType().isInteger()) { 2012 if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB || 2013 N0.getOpcode() == ISD::XOR) { 2014 // Simplify (X+Y) == (X+Z) --> Y == Z 2015 if (N0.getOpcode() == N1.getOpcode()) { 2016 if (N0.getOperand(0) == N1.getOperand(0)) 2017 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond); 2018 if (N0.getOperand(1) == N1.getOperand(1)) 2019 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond); 2020 if (DAG.isCommutativeBinOp(N0.getOpcode())) { 2021 // If X op Y == Y op X, try other combinations. 2022 if (N0.getOperand(0) == N1.getOperand(1)) 2023 return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0), 2024 Cond); 2025 if (N0.getOperand(1) == N1.getOperand(0)) 2026 return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1), 2027 Cond); 2028 } 2029 } 2030 2031 // If RHS is a legal immediate value for a compare instruction, we need 2032 // to be careful about increasing register pressure needlessly. 2033 bool LegalRHSImm = false; 2034 2035 if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) { 2036 if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 2037 // Turn (X+C1) == C2 --> X == C2-C1 2038 if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) { 2039 return DAG.getSetCC(dl, VT, N0.getOperand(0), 2040 DAG.getConstant(RHSC->getAPIntValue()- 2041 LHSR->getAPIntValue(), 2042 dl, N0.getValueType()), Cond); 2043 } 2044 2045 // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0. 2046 if (N0.getOpcode() == ISD::XOR) 2047 // If we know that all of the inverted bits are zero, don't bother 2048 // performing the inversion. 2049 if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue())) 2050 return 2051 DAG.getSetCC(dl, VT, N0.getOperand(0), 2052 DAG.getConstant(LHSR->getAPIntValue() ^ 2053 RHSC->getAPIntValue(), 2054 dl, N0.getValueType()), 2055 Cond); 2056 } 2057 2058 // Turn (C1-X) == C2 --> X == C1-C2 2059 if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) { 2060 if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) { 2061 return 2062 DAG.getSetCC(dl, VT, N0.getOperand(1), 2063 DAG.getConstant(SUBC->getAPIntValue() - 2064 RHSC->getAPIntValue(), 2065 dl, N0.getValueType()), 2066 Cond); 2067 } 2068 } 2069 2070 // Could RHSC fold directly into a compare? 2071 if (RHSC->getValueType(0).getSizeInBits() <= 64) 2072 LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue()); 2073 } 2074 2075 // Simplify (X+Z) == X --> Z == 0 2076 // Don't do this if X is an immediate that can fold into a cmp 2077 // instruction and X+Z has other uses. It could be an induction variable 2078 // chain, and the transform would increase register pressure. 2079 if (!LegalRHSImm || N0.getNode()->hasOneUse()) { 2080 if (N0.getOperand(0) == N1) 2081 return DAG.getSetCC(dl, VT, N0.getOperand(1), 2082 DAG.getConstant(0, dl, N0.getValueType()), Cond); 2083 if (N0.getOperand(1) == N1) { 2084 if (DAG.isCommutativeBinOp(N0.getOpcode())) 2085 return DAG.getSetCC(dl, VT, N0.getOperand(0), 2086 DAG.getConstant(0, dl, N0.getValueType()), 2087 Cond); 2088 if (N0.getNode()->hasOneUse()) { 2089 assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!"); 2090 auto &DL = DAG.getDataLayout(); 2091 // (Z-X) == X --> Z == X<<1 2092 SDValue SH = DAG.getNode( 2093 ISD::SHL, dl, N1.getValueType(), N1, 2094 DAG.getConstant(1, dl, 2095 getShiftAmountTy(N1.getValueType(), DL))); 2096 if (!DCI.isCalledByLegalizer()) 2097 DCI.AddToWorklist(SH.getNode()); 2098 return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond); 2099 } 2100 } 2101 } 2102 } 2103 2104 if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB || 2105 N1.getOpcode() == ISD::XOR) { 2106 // Simplify X == (X+Z) --> Z == 0 2107 if (N1.getOperand(0) == N0) 2108 return DAG.getSetCC(dl, VT, N1.getOperand(1), 2109 DAG.getConstant(0, dl, N1.getValueType()), Cond); 2110 if (N1.getOperand(1) == N0) { 2111 if (DAG.isCommutativeBinOp(N1.getOpcode())) 2112 return DAG.getSetCC(dl, VT, N1.getOperand(0), 2113 DAG.getConstant(0, dl, N1.getValueType()), Cond); 2114 if (N1.getNode()->hasOneUse()) { 2115 assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!"); 2116 auto &DL = DAG.getDataLayout(); 2117 // X == (Z-X) --> X<<1 == Z 2118 SDValue SH = DAG.getNode( 2119 ISD::SHL, dl, N1.getValueType(), N0, 2120 DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL))); 2121 if (!DCI.isCalledByLegalizer()) 2122 DCI.AddToWorklist(SH.getNode()); 2123 return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond); 2124 } 2125 } 2126 } 2127 2128 if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl)) 2129 return V; 2130 } 2131 2132 // Fold away ALL boolean setcc's. 2133 SDValue Temp; 2134 if (N0.getValueType() == MVT::i1 && foldBooleans) { 2135 switch (Cond) { 2136 default: llvm_unreachable("Unknown integer setcc!"); 2137 case ISD::SETEQ: // X == Y -> ~(X^Y) 2138 Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 2139 N0 = DAG.getNOT(dl, Temp, MVT::i1); 2140 if (!DCI.isCalledByLegalizer()) 2141 DCI.AddToWorklist(Temp.getNode()); 2142 break; 2143 case ISD::SETNE: // X != Y --> (X^Y) 2144 N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1); 2145 break; 2146 case ISD::SETGT: // X >s Y --> X == 0 & Y == 1 --> ~X & Y 2147 case ISD::SETULT: // X <u Y --> X == 0 & Y == 1 --> ~X & Y 2148 Temp = DAG.getNOT(dl, N0, MVT::i1); 2149 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp); 2150 if (!DCI.isCalledByLegalizer()) 2151 DCI.AddToWorklist(Temp.getNode()); 2152 break; 2153 case ISD::SETLT: // X <s Y --> X == 1 & Y == 0 --> ~Y & X 2154 case ISD::SETUGT: // X >u Y --> X == 1 & Y == 0 --> ~Y & X 2155 Temp = DAG.getNOT(dl, N1, MVT::i1); 2156 N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp); 2157 if (!DCI.isCalledByLegalizer()) 2158 DCI.AddToWorklist(Temp.getNode()); 2159 break; 2160 case ISD::SETULE: // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 2161 case ISD::SETGE: // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 2162 Temp = DAG.getNOT(dl, N0, MVT::i1); 2163 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp); 2164 if (!DCI.isCalledByLegalizer()) 2165 DCI.AddToWorklist(Temp.getNode()); 2166 break; 2167 case ISD::SETUGE: // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 2168 case ISD::SETLE: // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 2169 Temp = DAG.getNOT(dl, N1, MVT::i1); 2170 N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp); 2171 break; 2172 } 2173 if (VT != MVT::i1) { 2174 if (!DCI.isCalledByLegalizer()) 2175 DCI.AddToWorklist(N0.getNode()); 2176 // FIXME: If running after legalize, we probably can't do this. 2177 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0); 2178 } 2179 return N0; 2180 } 2181 2182 // Could not fold it. 2183 return SDValue(); 2184 } 2185 2186 /// Returns true (and the GlobalValue and the offset) if the node is a 2187 /// GlobalAddress + offset. 2188 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA, 2189 int64_t &Offset) const { 2190 if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) { 2191 GA = GASD->getGlobal(); 2192 Offset += GASD->getOffset(); 2193 return true; 2194 } 2195 2196 if (N->getOpcode() == ISD::ADD) { 2197 SDValue N1 = N->getOperand(0); 2198 SDValue N2 = N->getOperand(1); 2199 if (isGAPlusOffset(N1.getNode(), GA, Offset)) { 2200 if (auto *V = dyn_cast<ConstantSDNode>(N2)) { 2201 Offset += V->getSExtValue(); 2202 return true; 2203 } 2204 } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) { 2205 if (auto *V = dyn_cast<ConstantSDNode>(N1)) { 2206 Offset += V->getSExtValue(); 2207 return true; 2208 } 2209 } 2210 } 2211 2212 return false; 2213 } 2214 2215 SDValue TargetLowering::PerformDAGCombine(SDNode *N, 2216 DAGCombinerInfo &DCI) const { 2217 // Default implementation: no optimization. 2218 return SDValue(); 2219 } 2220 2221 //===----------------------------------------------------------------------===// 2222 // Inline Assembler Implementation Methods 2223 //===----------------------------------------------------------------------===// 2224 2225 TargetLowering::ConstraintType 2226 TargetLowering::getConstraintType(StringRef Constraint) const { 2227 unsigned S = Constraint.size(); 2228 2229 if (S == 1) { 2230 switch (Constraint[0]) { 2231 default: break; 2232 case 'r': return C_RegisterClass; 2233 case 'm': // memory 2234 case 'o': // offsetable 2235 case 'V': // not offsetable 2236 return C_Memory; 2237 case 'i': // Simple Integer or Relocatable Constant 2238 case 'n': // Simple Integer 2239 case 'E': // Floating Point Constant 2240 case 'F': // Floating Point Constant 2241 case 's': // Relocatable Constant 2242 case 'p': // Address. 2243 case 'X': // Allow ANY value. 2244 case 'I': // Target registers. 2245 case 'J': 2246 case 'K': 2247 case 'L': 2248 case 'M': 2249 case 'N': 2250 case 'O': 2251 case 'P': 2252 case '<': 2253 case '>': 2254 return C_Other; 2255 } 2256 } 2257 2258 if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') { 2259 if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}" 2260 return C_Memory; 2261 return C_Register; 2262 } 2263 return C_Unknown; 2264 } 2265 2266 /// Try to replace an X constraint, which matches anything, with another that 2267 /// has more specific requirements based on the type of the corresponding 2268 /// operand. 2269 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{ 2270 if (ConstraintVT.isInteger()) 2271 return "r"; 2272 if (ConstraintVT.isFloatingPoint()) 2273 return "f"; // works for many targets 2274 return nullptr; 2275 } 2276 2277 /// Lower the specified operand into the Ops vector. 2278 /// If it is invalid, don't add anything to Ops. 2279 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op, 2280 std::string &Constraint, 2281 std::vector<SDValue> &Ops, 2282 SelectionDAG &DAG) const { 2283 2284 if (Constraint.length() > 1) return; 2285 2286 char ConstraintLetter = Constraint[0]; 2287 switch (ConstraintLetter) { 2288 default: break; 2289 case 'X': // Allows any operand; labels (basic block) use this. 2290 if (Op.getOpcode() == ISD::BasicBlock) { 2291 Ops.push_back(Op); 2292 return; 2293 } 2294 // fall through 2295 case 'i': // Simple Integer or Relocatable Constant 2296 case 'n': // Simple Integer 2297 case 's': { // Relocatable Constant 2298 // These operands are interested in values of the form (GV+C), where C may 2299 // be folded in as an offset of GV, or it may be explicitly added. Also, it 2300 // is possible and fine if either GV or C are missing. 2301 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 2302 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op); 2303 2304 // If we have "(add GV, C)", pull out GV/C 2305 if (Op.getOpcode() == ISD::ADD) { 2306 C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 2307 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0)); 2308 if (!C || !GA) { 2309 C = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 2310 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1)); 2311 } 2312 if (!C || !GA) { 2313 C = nullptr; 2314 GA = nullptr; 2315 } 2316 } 2317 2318 // If we find a valid operand, map to the TargetXXX version so that the 2319 // value itself doesn't get selected. 2320 if (GA) { // Either &GV or &GV+C 2321 if (ConstraintLetter != 'n') { 2322 int64_t Offs = GA->getOffset(); 2323 if (C) Offs += C->getZExtValue(); 2324 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), 2325 C ? SDLoc(C) : SDLoc(), 2326 Op.getValueType(), Offs)); 2327 } 2328 return; 2329 } 2330 if (C) { // just C, no GV. 2331 // Simple constants are not allowed for 's'. 2332 if (ConstraintLetter != 's') { 2333 // gcc prints these as sign extended. Sign extend value to 64 bits 2334 // now; without this it would get ZExt'd later in 2335 // ScheduleDAGSDNodes::EmitNode, which is very generic. 2336 Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(), 2337 SDLoc(C), MVT::i64)); 2338 } 2339 return; 2340 } 2341 break; 2342 } 2343 } 2344 } 2345 2346 std::pair<unsigned, const TargetRegisterClass *> 2347 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI, 2348 StringRef Constraint, 2349 MVT VT) const { 2350 if (Constraint.empty() || Constraint[0] != '{') 2351 return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr)); 2352 assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?"); 2353 2354 // Remove the braces from around the name. 2355 StringRef RegName(Constraint.data()+1, Constraint.size()-2); 2356 2357 std::pair<unsigned, const TargetRegisterClass*> R = 2358 std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr)); 2359 2360 // Figure out which register class contains this reg. 2361 for (TargetRegisterInfo::regclass_iterator RCI = RI->regclass_begin(), 2362 E = RI->regclass_end(); RCI != E; ++RCI) { 2363 const TargetRegisterClass *RC = *RCI; 2364 2365 // If none of the value types for this register class are valid, we 2366 // can't use it. For example, 64-bit reg classes on 32-bit targets. 2367 if (!isLegalRC(RC)) 2368 continue; 2369 2370 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); 2371 I != E; ++I) { 2372 if (RegName.equals_lower(RI->getRegAsmName(*I))) { 2373 std::pair<unsigned, const TargetRegisterClass*> S = 2374 std::make_pair(*I, RC); 2375 2376 // If this register class has the requested value type, return it, 2377 // otherwise keep searching and return the first class found 2378 // if no other is found which explicitly has the requested type. 2379 if (RC->hasType(VT)) 2380 return S; 2381 else if (!R.second) 2382 R = S; 2383 } 2384 } 2385 } 2386 2387 return R; 2388 } 2389 2390 //===----------------------------------------------------------------------===// 2391 // Constraint Selection. 2392 2393 /// Return true of this is an input operand that is a matching constraint like 2394 /// "4". 2395 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const { 2396 assert(!ConstraintCode.empty() && "No known constraint!"); 2397 return isdigit(static_cast<unsigned char>(ConstraintCode[0])); 2398 } 2399 2400 /// If this is an input matching constraint, this method returns the output 2401 /// operand it matches. 2402 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const { 2403 assert(!ConstraintCode.empty() && "No known constraint!"); 2404 return atoi(ConstraintCode.c_str()); 2405 } 2406 2407 /// Split up the constraint string from the inline assembly value into the 2408 /// specific constraints and their prefixes, and also tie in the associated 2409 /// operand values. 2410 /// If this returns an empty vector, and if the constraint string itself 2411 /// isn't empty, there was an error parsing. 2412 TargetLowering::AsmOperandInfoVector 2413 TargetLowering::ParseConstraints(const DataLayout &DL, 2414 const TargetRegisterInfo *TRI, 2415 ImmutableCallSite CS) const { 2416 /// Information about all of the constraints. 2417 AsmOperandInfoVector ConstraintOperands; 2418 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue()); 2419 unsigned maCount = 0; // Largest number of multiple alternative constraints. 2420 2421 // Do a prepass over the constraints, canonicalizing them, and building up the 2422 // ConstraintOperands list. 2423 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst. 2424 unsigned ResNo = 0; // ResNo - The result number of the next output. 2425 2426 for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) { 2427 ConstraintOperands.emplace_back(std::move(CI)); 2428 AsmOperandInfo &OpInfo = ConstraintOperands.back(); 2429 2430 // Update multiple alternative constraint count. 2431 if (OpInfo.multipleAlternatives.size() > maCount) 2432 maCount = OpInfo.multipleAlternatives.size(); 2433 2434 OpInfo.ConstraintVT = MVT::Other; 2435 2436 // Compute the value type for each operand. 2437 switch (OpInfo.Type) { 2438 case InlineAsm::isOutput: 2439 // Indirect outputs just consume an argument. 2440 if (OpInfo.isIndirect) { 2441 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2442 break; 2443 } 2444 2445 // The return value of the call is this value. As such, there is no 2446 // corresponding argument. 2447 assert(!CS.getType()->isVoidTy() && 2448 "Bad inline asm!"); 2449 if (StructType *STy = dyn_cast<StructType>(CS.getType())) { 2450 OpInfo.ConstraintVT = 2451 getSimpleValueType(DL, STy->getElementType(ResNo)); 2452 } else { 2453 assert(ResNo == 0 && "Asm only has one result!"); 2454 OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType()); 2455 } 2456 ++ResNo; 2457 break; 2458 case InlineAsm::isInput: 2459 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++)); 2460 break; 2461 case InlineAsm::isClobber: 2462 // Nothing to do. 2463 break; 2464 } 2465 2466 if (OpInfo.CallOperandVal) { 2467 llvm::Type *OpTy = OpInfo.CallOperandVal->getType(); 2468 if (OpInfo.isIndirect) { 2469 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy); 2470 if (!PtrTy) 2471 report_fatal_error("Indirect operand for inline asm not a pointer!"); 2472 OpTy = PtrTy->getElementType(); 2473 } 2474 2475 // Look for vector wrapped in a struct. e.g. { <16 x i8> }. 2476 if (StructType *STy = dyn_cast<StructType>(OpTy)) 2477 if (STy->getNumElements() == 1) 2478 OpTy = STy->getElementType(0); 2479 2480 // If OpTy is not a single value, it may be a struct/union that we 2481 // can tile with integers. 2482 if (!OpTy->isSingleValueType() && OpTy->isSized()) { 2483 unsigned BitSize = DL.getTypeSizeInBits(OpTy); 2484 switch (BitSize) { 2485 default: break; 2486 case 1: 2487 case 8: 2488 case 16: 2489 case 32: 2490 case 64: 2491 case 128: 2492 OpInfo.ConstraintVT = 2493 MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true); 2494 break; 2495 } 2496 } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) { 2497 unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace()); 2498 OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize); 2499 } else { 2500 OpInfo.ConstraintVT = MVT::getVT(OpTy, true); 2501 } 2502 } 2503 } 2504 2505 // If we have multiple alternative constraints, select the best alternative. 2506 if (!ConstraintOperands.empty()) { 2507 if (maCount) { 2508 unsigned bestMAIndex = 0; 2509 int bestWeight = -1; 2510 // weight: -1 = invalid match, and 0 = so-so match to 5 = good match. 2511 int weight = -1; 2512 unsigned maIndex; 2513 // Compute the sums of the weights for each alternative, keeping track 2514 // of the best (highest weight) one so far. 2515 for (maIndex = 0; maIndex < maCount; ++maIndex) { 2516 int weightSum = 0; 2517 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2518 cIndex != eIndex; ++cIndex) { 2519 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2520 if (OpInfo.Type == InlineAsm::isClobber) 2521 continue; 2522 2523 // If this is an output operand with a matching input operand, 2524 // look up the matching input. If their types mismatch, e.g. one 2525 // is an integer, the other is floating point, or their sizes are 2526 // different, flag it as an maCantMatch. 2527 if (OpInfo.hasMatchingInput()) { 2528 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2529 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2530 if ((OpInfo.ConstraintVT.isInteger() != 2531 Input.ConstraintVT.isInteger()) || 2532 (OpInfo.ConstraintVT.getSizeInBits() != 2533 Input.ConstraintVT.getSizeInBits())) { 2534 weightSum = -1; // Can't match. 2535 break; 2536 } 2537 } 2538 } 2539 weight = getMultipleConstraintMatchWeight(OpInfo, maIndex); 2540 if (weight == -1) { 2541 weightSum = -1; 2542 break; 2543 } 2544 weightSum += weight; 2545 } 2546 // Update best. 2547 if (weightSum > bestWeight) { 2548 bestWeight = weightSum; 2549 bestMAIndex = maIndex; 2550 } 2551 } 2552 2553 // Now select chosen alternative in each constraint. 2554 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2555 cIndex != eIndex; ++cIndex) { 2556 AsmOperandInfo& cInfo = ConstraintOperands[cIndex]; 2557 if (cInfo.Type == InlineAsm::isClobber) 2558 continue; 2559 cInfo.selectAlternative(bestMAIndex); 2560 } 2561 } 2562 } 2563 2564 // Check and hook up tied operands, choose constraint code to use. 2565 for (unsigned cIndex = 0, eIndex = ConstraintOperands.size(); 2566 cIndex != eIndex; ++cIndex) { 2567 AsmOperandInfo& OpInfo = ConstraintOperands[cIndex]; 2568 2569 // If this is an output operand with a matching input operand, look up the 2570 // matching input. If their types mismatch, e.g. one is an integer, the 2571 // other is floating point, or their sizes are different, flag it as an 2572 // error. 2573 if (OpInfo.hasMatchingInput()) { 2574 AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput]; 2575 2576 if (OpInfo.ConstraintVT != Input.ConstraintVT) { 2577 std::pair<unsigned, const TargetRegisterClass *> MatchRC = 2578 getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode, 2579 OpInfo.ConstraintVT); 2580 std::pair<unsigned, const TargetRegisterClass *> InputRC = 2581 getRegForInlineAsmConstraint(TRI, Input.ConstraintCode, 2582 Input.ConstraintVT); 2583 if ((OpInfo.ConstraintVT.isInteger() != 2584 Input.ConstraintVT.isInteger()) || 2585 (MatchRC.second != InputRC.second)) { 2586 report_fatal_error("Unsupported asm: input constraint" 2587 " with a matching output constraint of" 2588 " incompatible type!"); 2589 } 2590 } 2591 } 2592 } 2593 2594 return ConstraintOperands; 2595 } 2596 2597 /// Return an integer indicating how general CT is. 2598 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) { 2599 switch (CT) { 2600 case TargetLowering::C_Other: 2601 case TargetLowering::C_Unknown: 2602 return 0; 2603 case TargetLowering::C_Register: 2604 return 1; 2605 case TargetLowering::C_RegisterClass: 2606 return 2; 2607 case TargetLowering::C_Memory: 2608 return 3; 2609 } 2610 llvm_unreachable("Invalid constraint type"); 2611 } 2612 2613 /// Examine constraint type and operand type and determine a weight value. 2614 /// This object must already have been set up with the operand type 2615 /// and the current alternative constraint selected. 2616 TargetLowering::ConstraintWeight 2617 TargetLowering::getMultipleConstraintMatchWeight( 2618 AsmOperandInfo &info, int maIndex) const { 2619 InlineAsm::ConstraintCodeVector *rCodes; 2620 if (maIndex >= (int)info.multipleAlternatives.size()) 2621 rCodes = &info.Codes; 2622 else 2623 rCodes = &info.multipleAlternatives[maIndex].Codes; 2624 ConstraintWeight BestWeight = CW_Invalid; 2625 2626 // Loop over the options, keeping track of the most general one. 2627 for (unsigned i = 0, e = rCodes->size(); i != e; ++i) { 2628 ConstraintWeight weight = 2629 getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str()); 2630 if (weight > BestWeight) 2631 BestWeight = weight; 2632 } 2633 2634 return BestWeight; 2635 } 2636 2637 /// Examine constraint type and operand type and determine a weight value. 2638 /// This object must already have been set up with the operand type 2639 /// and the current alternative constraint selected. 2640 TargetLowering::ConstraintWeight 2641 TargetLowering::getSingleConstraintMatchWeight( 2642 AsmOperandInfo &info, const char *constraint) const { 2643 ConstraintWeight weight = CW_Invalid; 2644 Value *CallOperandVal = info.CallOperandVal; 2645 // If we don't have a value, we can't do a match, 2646 // but allow it at the lowest weight. 2647 if (!CallOperandVal) 2648 return CW_Default; 2649 // Look at the constraint type. 2650 switch (*constraint) { 2651 case 'i': // immediate integer. 2652 case 'n': // immediate integer with a known value. 2653 if (isa<ConstantInt>(CallOperandVal)) 2654 weight = CW_Constant; 2655 break; 2656 case 's': // non-explicit intregal immediate. 2657 if (isa<GlobalValue>(CallOperandVal)) 2658 weight = CW_Constant; 2659 break; 2660 case 'E': // immediate float if host format. 2661 case 'F': // immediate float. 2662 if (isa<ConstantFP>(CallOperandVal)) 2663 weight = CW_Constant; 2664 break; 2665 case '<': // memory operand with autodecrement. 2666 case '>': // memory operand with autoincrement. 2667 case 'm': // memory operand. 2668 case 'o': // offsettable memory operand 2669 case 'V': // non-offsettable memory operand 2670 weight = CW_Memory; 2671 break; 2672 case 'r': // general register. 2673 case 'g': // general register, memory operand or immediate integer. 2674 // note: Clang converts "g" to "imr". 2675 if (CallOperandVal->getType()->isIntegerTy()) 2676 weight = CW_Register; 2677 break; 2678 case 'X': // any operand. 2679 default: 2680 weight = CW_Default; 2681 break; 2682 } 2683 return weight; 2684 } 2685 2686 /// If there are multiple different constraints that we could pick for this 2687 /// operand (e.g. "imr") try to pick the 'best' one. 2688 /// This is somewhat tricky: constraints fall into four classes: 2689 /// Other -> immediates and magic values 2690 /// Register -> one specific register 2691 /// RegisterClass -> a group of regs 2692 /// Memory -> memory 2693 /// Ideally, we would pick the most specific constraint possible: if we have 2694 /// something that fits into a register, we would pick it. The problem here 2695 /// is that if we have something that could either be in a register or in 2696 /// memory that use of the register could cause selection of *other* 2697 /// operands to fail: they might only succeed if we pick memory. Because of 2698 /// this the heuristic we use is: 2699 /// 2700 /// 1) If there is an 'other' constraint, and if the operand is valid for 2701 /// that constraint, use it. This makes us take advantage of 'i' 2702 /// constraints when available. 2703 /// 2) Otherwise, pick the most general constraint present. This prefers 2704 /// 'm' over 'r', for example. 2705 /// 2706 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo, 2707 const TargetLowering &TLI, 2708 SDValue Op, SelectionDAG *DAG) { 2709 assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options"); 2710 unsigned BestIdx = 0; 2711 TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown; 2712 int BestGenerality = -1; 2713 2714 // Loop over the options, keeping track of the most general one. 2715 for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) { 2716 TargetLowering::ConstraintType CType = 2717 TLI.getConstraintType(OpInfo.Codes[i]); 2718 2719 // If this is an 'other' constraint, see if the operand is valid for it. 2720 // For example, on X86 we might have an 'rI' constraint. If the operand 2721 // is an integer in the range [0..31] we want to use I (saving a load 2722 // of a register), otherwise we must use 'r'. 2723 if (CType == TargetLowering::C_Other && Op.getNode()) { 2724 assert(OpInfo.Codes[i].size() == 1 && 2725 "Unhandled multi-letter 'other' constraint"); 2726 std::vector<SDValue> ResultOps; 2727 TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i], 2728 ResultOps, *DAG); 2729 if (!ResultOps.empty()) { 2730 BestType = CType; 2731 BestIdx = i; 2732 break; 2733 } 2734 } 2735 2736 // Things with matching constraints can only be registers, per gcc 2737 // documentation. This mainly affects "g" constraints. 2738 if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput()) 2739 continue; 2740 2741 // This constraint letter is more general than the previous one, use it. 2742 int Generality = getConstraintGenerality(CType); 2743 if (Generality > BestGenerality) { 2744 BestType = CType; 2745 BestIdx = i; 2746 BestGenerality = Generality; 2747 } 2748 } 2749 2750 OpInfo.ConstraintCode = OpInfo.Codes[BestIdx]; 2751 OpInfo.ConstraintType = BestType; 2752 } 2753 2754 /// Determines the constraint code and constraint type to use for the specific 2755 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType. 2756 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo, 2757 SDValue Op, 2758 SelectionDAG *DAG) const { 2759 assert(!OpInfo.Codes.empty() && "Must have at least one constraint"); 2760 2761 // Single-letter constraints ('r') are very common. 2762 if (OpInfo.Codes.size() == 1) { 2763 OpInfo.ConstraintCode = OpInfo.Codes[0]; 2764 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2765 } else { 2766 ChooseConstraint(OpInfo, *this, Op, DAG); 2767 } 2768 2769 // 'X' matches anything. 2770 if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) { 2771 // Labels and constants are handled elsewhere ('X' is the only thing 2772 // that matches labels). For Functions, the type here is the type of 2773 // the result, which is not what we want to look at; leave them alone. 2774 Value *v = OpInfo.CallOperandVal; 2775 if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) { 2776 OpInfo.CallOperandVal = v; 2777 return; 2778 } 2779 2780 // Otherwise, try to resolve it to something we know about by looking at 2781 // the actual operand type. 2782 if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) { 2783 OpInfo.ConstraintCode = Repl; 2784 OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode); 2785 } 2786 } 2787 } 2788 2789 /// \brief Given an exact SDIV by a constant, create a multiplication 2790 /// with the multiplicative inverse of the constant. 2791 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d, 2792 const SDLoc &dl, SelectionDAG &DAG, 2793 std::vector<SDNode *> &Created) { 2794 assert(d != 0 && "Division by zero!"); 2795 2796 // Shift the value upfront if it is even, so the LSB is one. 2797 unsigned ShAmt = d.countTrailingZeros(); 2798 if (ShAmt) { 2799 // TODO: For UDIV use SRL instead of SRA. 2800 SDValue Amt = 2801 DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(), 2802 DAG.getDataLayout())); 2803 SDNodeFlags Flags; 2804 Flags.setExact(true); 2805 Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags); 2806 Created.push_back(Op1.getNode()); 2807 d = d.ashr(ShAmt); 2808 } 2809 2810 // Calculate the multiplicative inverse, using Newton's method. 2811 APInt t, xn = d; 2812 while ((t = d*xn) != 1) 2813 xn *= APInt(d.getBitWidth(), 2) - t; 2814 2815 SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType()); 2816 SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2); 2817 Created.push_back(Mul.getNode()); 2818 return Mul; 2819 } 2820 2821 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 2822 SelectionDAG &DAG, 2823 std::vector<SDNode *> *Created) const { 2824 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 2825 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 2826 if (TLI.isIntDivCheap(N->getValueType(0), Attr)) 2827 return SDValue(N,0); // Lower SDIV as SDIV 2828 return SDValue(); 2829 } 2830 2831 /// \brief Given an ISD::SDIV node expressing a divide by constant, 2832 /// return a DAG expression to select that will generate the same value by 2833 /// multiplying by a magic number. 2834 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 2835 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor, 2836 SelectionDAG &DAG, bool IsAfterLegalization, 2837 std::vector<SDNode *> *Created) const { 2838 assert(Created && "No vector to hold sdiv ops."); 2839 2840 EVT VT = N->getValueType(0); 2841 SDLoc dl(N); 2842 2843 // Check to see if we can do this. 2844 // FIXME: We should be more aggressive here. 2845 if (!isTypeLegal(VT)) 2846 return SDValue(); 2847 2848 // If the sdiv has an 'exact' bit we can use a simpler lowering. 2849 if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact()) 2850 return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created); 2851 2852 APInt::ms magics = Divisor.magic(); 2853 2854 // Multiply the numerator (operand 0) by the magic value 2855 // FIXME: We should support doing a MUL in a wider type 2856 SDValue Q; 2857 if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) : 2858 isOperationLegalOrCustom(ISD::MULHS, VT)) 2859 Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0), 2860 DAG.getConstant(magics.m, dl, VT)); 2861 else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) : 2862 isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) 2863 Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), 2864 N->getOperand(0), 2865 DAG.getConstant(magics.m, dl, VT)).getNode(), 1); 2866 else 2867 return SDValue(); // No mulhs or equvialent 2868 // If d > 0 and m < 0, add the numerator 2869 if (Divisor.isStrictlyPositive() && magics.m.isNegative()) { 2870 Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0)); 2871 Created->push_back(Q.getNode()); 2872 } 2873 // If d < 0 and m > 0, subtract the numerator. 2874 if (Divisor.isNegative() && magics.m.isStrictlyPositive()) { 2875 Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0)); 2876 Created->push_back(Q.getNode()); 2877 } 2878 auto &DL = DAG.getDataLayout(); 2879 // Shift right algebraic if shift value is nonzero 2880 if (magics.s > 0) { 2881 Q = DAG.getNode( 2882 ISD::SRA, dl, VT, Q, 2883 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL))); 2884 Created->push_back(Q.getNode()); 2885 } 2886 // Extract the sign bit and add it to the quotient 2887 SDValue T = 2888 DAG.getNode(ISD::SRL, dl, VT, Q, 2889 DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, 2890 getShiftAmountTy(Q.getValueType(), DL))); 2891 Created->push_back(T.getNode()); 2892 return DAG.getNode(ISD::ADD, dl, VT, Q, T); 2893 } 2894 2895 /// \brief Given an ISD::UDIV node expressing a divide by constant, 2896 /// return a DAG expression to select that will generate the same value by 2897 /// multiplying by a magic number. 2898 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 2899 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor, 2900 SelectionDAG &DAG, bool IsAfterLegalization, 2901 std::vector<SDNode *> *Created) const { 2902 assert(Created && "No vector to hold udiv ops."); 2903 2904 EVT VT = N->getValueType(0); 2905 SDLoc dl(N); 2906 auto &DL = DAG.getDataLayout(); 2907 2908 // Check to see if we can do this. 2909 // FIXME: We should be more aggressive here. 2910 if (!isTypeLegal(VT)) 2911 return SDValue(); 2912 2913 // FIXME: We should use a narrower constant when the upper 2914 // bits are known to be zero. 2915 APInt::mu magics = Divisor.magicu(); 2916 2917 SDValue Q = N->getOperand(0); 2918 2919 // If the divisor is even, we can avoid using the expensive fixup by shifting 2920 // the divided value upfront. 2921 if (magics.a != 0 && !Divisor[0]) { 2922 unsigned Shift = Divisor.countTrailingZeros(); 2923 Q = DAG.getNode( 2924 ISD::SRL, dl, VT, Q, 2925 DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL))); 2926 Created->push_back(Q.getNode()); 2927 2928 // Get magic number for the shifted divisor. 2929 magics = Divisor.lshr(Shift).magicu(Shift); 2930 assert(magics.a == 0 && "Should use cheap fixup now"); 2931 } 2932 2933 // Multiply the numerator (operand 0) by the magic value 2934 // FIXME: We should support doing a MUL in a wider type 2935 if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) : 2936 isOperationLegalOrCustom(ISD::MULHU, VT)) 2937 Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT)); 2938 else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) : 2939 isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) 2940 Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q, 2941 DAG.getConstant(magics.m, dl, VT)).getNode(), 1); 2942 else 2943 return SDValue(); // No mulhu or equvialent 2944 2945 Created->push_back(Q.getNode()); 2946 2947 if (magics.a == 0) { 2948 assert(magics.s < Divisor.getBitWidth() && 2949 "We shouldn't generate an undefined shift!"); 2950 return DAG.getNode( 2951 ISD::SRL, dl, VT, Q, 2952 DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL))); 2953 } else { 2954 SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q); 2955 Created->push_back(NPQ.getNode()); 2956 NPQ = DAG.getNode( 2957 ISD::SRL, dl, VT, NPQ, 2958 DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL))); 2959 Created->push_back(NPQ.getNode()); 2960 NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q); 2961 Created->push_back(NPQ.getNode()); 2962 return DAG.getNode( 2963 ISD::SRL, dl, VT, NPQ, 2964 DAG.getConstant(magics.s - 1, dl, 2965 getShiftAmountTy(NPQ.getValueType(), DL))); 2966 } 2967 } 2968 2969 bool TargetLowering:: 2970 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const { 2971 if (!isa<ConstantSDNode>(Op.getOperand(0))) { 2972 DAG.getContext()->emitError("argument to '__builtin_return_address' must " 2973 "be a constant integer"); 2974 return true; 2975 } 2976 2977 return false; 2978 } 2979 2980 //===----------------------------------------------------------------------===// 2981 // Legalization Utilities 2982 //===----------------------------------------------------------------------===// 2983 2984 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT, 2985 SelectionDAG &DAG, SDValue LL, SDValue LH, 2986 SDValue RL, SDValue RH) const { 2987 EVT VT = N->getValueType(0); 2988 SDLoc dl(N); 2989 2990 bool HasMULHS = isOperationLegalOrCustom(ISD::MULHS, HiLoVT); 2991 bool HasMULHU = isOperationLegalOrCustom(ISD::MULHU, HiLoVT); 2992 bool HasSMUL_LOHI = isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT); 2993 bool HasUMUL_LOHI = isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT); 2994 if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) { 2995 unsigned OuterBitSize = VT.getSizeInBits(); 2996 unsigned InnerBitSize = HiLoVT.getSizeInBits(); 2997 unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0)); 2998 unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1)); 2999 3000 // LL, LH, RL, and RH must be either all NULL or all set to a value. 3001 assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) || 3002 (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode())); 3003 3004 if (!LL.getNode() && !RL.getNode() && 3005 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 3006 LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(0)); 3007 RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, N->getOperand(1)); 3008 } 3009 3010 if (!LL.getNode()) 3011 return false; 3012 3013 APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize); 3014 if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) && 3015 DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) { 3016 // The inputs are both zero-extended. 3017 if (HasUMUL_LOHI) { 3018 // We can emit a umul_lohi. 3019 Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL, 3020 RL); 3021 Hi = SDValue(Lo.getNode(), 1); 3022 return true; 3023 } 3024 if (HasMULHU) { 3025 // We can emit a mulhu+mul. 3026 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL); 3027 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL); 3028 return true; 3029 } 3030 } 3031 if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) { 3032 // The input values are both sign-extended. 3033 if (HasSMUL_LOHI) { 3034 // We can emit a smul_lohi. 3035 Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(HiLoVT, HiLoVT), LL, 3036 RL); 3037 Hi = SDValue(Lo.getNode(), 1); 3038 return true; 3039 } 3040 if (HasMULHS) { 3041 // We can emit a mulhs+mul. 3042 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL); 3043 Hi = DAG.getNode(ISD::MULHS, dl, HiLoVT, LL, RL); 3044 return true; 3045 } 3046 } 3047 3048 if (!LH.getNode() && !RH.getNode() && 3049 isOperationLegalOrCustom(ISD::SRL, VT) && 3050 isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) { 3051 auto &DL = DAG.getDataLayout(); 3052 unsigned ShiftAmt = VT.getSizeInBits() - HiLoVT.getSizeInBits(); 3053 SDValue Shift = DAG.getConstant(ShiftAmt, dl, getShiftAmountTy(VT, DL)); 3054 LH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(0), Shift); 3055 LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH); 3056 RH = DAG.getNode(ISD::SRL, dl, VT, N->getOperand(1), Shift); 3057 RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH); 3058 } 3059 3060 if (!LH.getNode()) 3061 return false; 3062 3063 if (HasUMUL_LOHI) { 3064 // Lo,Hi = umul LHS, RHS. 3065 SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl, 3066 DAG.getVTList(HiLoVT, HiLoVT), LL, RL); 3067 Lo = UMulLOHI; 3068 Hi = UMulLOHI.getValue(1); 3069 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 3070 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 3071 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 3072 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 3073 return true; 3074 } 3075 if (HasMULHU) { 3076 Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RL); 3077 Hi = DAG.getNode(ISD::MULHU, dl, HiLoVT, LL, RL); 3078 RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH); 3079 LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL); 3080 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH); 3081 Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH); 3082 return true; 3083 } 3084 } 3085 return false; 3086 } 3087 3088 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result, 3089 SelectionDAG &DAG) const { 3090 EVT VT = Node->getOperand(0).getValueType(); 3091 EVT NVT = Node->getValueType(0); 3092 SDLoc dl(SDValue(Node, 0)); 3093 3094 // FIXME: Only f32 to i64 conversions are supported. 3095 if (VT != MVT::f32 || NVT != MVT::i64) 3096 return false; 3097 3098 // Expand f32 -> i64 conversion 3099 // This algorithm comes from compiler-rt's implementation of fixsfdi: 3100 // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c 3101 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), 3102 VT.getSizeInBits()); 3103 SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT); 3104 SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT); 3105 SDValue Bias = DAG.getConstant(127, dl, IntVT); 3106 SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl, 3107 IntVT); 3108 SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT); 3109 SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT); 3110 3111 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0)); 3112 3113 auto &DL = DAG.getDataLayout(); 3114 SDValue ExponentBits = DAG.getNode( 3115 ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask), 3116 DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL))); 3117 SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias); 3118 3119 SDValue Sign = DAG.getNode( 3120 ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask), 3121 DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL))); 3122 Sign = DAG.getSExtOrTrunc(Sign, dl, NVT); 3123 3124 SDValue R = DAG.getNode(ISD::OR, dl, IntVT, 3125 DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask), 3126 DAG.getConstant(0x00800000, dl, IntVT)); 3127 3128 R = DAG.getZExtOrTrunc(R, dl, NVT); 3129 3130 R = DAG.getSelectCC( 3131 dl, Exponent, ExponentLoBit, 3132 DAG.getNode(ISD::SHL, dl, NVT, R, 3133 DAG.getZExtOrTrunc( 3134 DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit), 3135 dl, getShiftAmountTy(IntVT, DL))), 3136 DAG.getNode(ISD::SRL, dl, NVT, R, 3137 DAG.getZExtOrTrunc( 3138 DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent), 3139 dl, getShiftAmountTy(IntVT, DL))), 3140 ISD::SETGT); 3141 3142 SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT, 3143 DAG.getNode(ISD::XOR, dl, NVT, R, Sign), 3144 Sign); 3145 3146 Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT), 3147 DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT); 3148 return true; 3149 } 3150 3151 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD, 3152 SelectionDAG &DAG) const { 3153 SDLoc SL(LD); 3154 SDValue Chain = LD->getChain(); 3155 SDValue BasePTR = LD->getBasePtr(); 3156 EVT SrcVT = LD->getMemoryVT(); 3157 ISD::LoadExtType ExtType = LD->getExtensionType(); 3158 3159 unsigned NumElem = SrcVT.getVectorNumElements(); 3160 3161 EVT SrcEltVT = SrcVT.getScalarType(); 3162 EVT DstEltVT = LD->getValueType(0).getScalarType(); 3163 3164 unsigned Stride = SrcEltVT.getSizeInBits() / 8; 3165 assert(SrcEltVT.isByteSized()); 3166 3167 EVT PtrVT = BasePTR.getValueType(); 3168 3169 SmallVector<SDValue, 8> Vals; 3170 SmallVector<SDValue, 8> LoadChains; 3171 3172 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 3173 SDValue ScalarLoad = 3174 DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR, 3175 LD->getPointerInfo().getWithOffset(Idx * Stride), 3176 SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride), 3177 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3178 3179 BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR, 3180 DAG.getConstant(Stride, SL, PtrVT)); 3181 3182 Vals.push_back(ScalarLoad.getValue(0)); 3183 LoadChains.push_back(ScalarLoad.getValue(1)); 3184 } 3185 3186 SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains); 3187 SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, SL, LD->getValueType(0), Vals); 3188 3189 return DAG.getMergeValues({ Value, NewChain }, SL); 3190 } 3191 3192 // FIXME: This relies on each element having a byte size, otherwise the stride 3193 // is 0 and just overwrites the same location. ExpandStore currently expects 3194 // this broken behavior. 3195 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST, 3196 SelectionDAG &DAG) const { 3197 SDLoc SL(ST); 3198 3199 SDValue Chain = ST->getChain(); 3200 SDValue BasePtr = ST->getBasePtr(); 3201 SDValue Value = ST->getValue(); 3202 EVT StVT = ST->getMemoryVT(); 3203 3204 // The type of the data we want to save 3205 EVT RegVT = Value.getValueType(); 3206 EVT RegSclVT = RegVT.getScalarType(); 3207 3208 // The type of data as saved in memory. 3209 EVT MemSclVT = StVT.getScalarType(); 3210 3211 EVT PtrVT = BasePtr.getValueType(); 3212 3213 // Store Stride in bytes 3214 unsigned Stride = MemSclVT.getSizeInBits() / 8; 3215 EVT IdxVT = getVectorIdxTy(DAG.getDataLayout()); 3216 unsigned NumElem = StVT.getVectorNumElements(); 3217 3218 // Extract each of the elements from the original vector and save them into 3219 // memory individually. 3220 SmallVector<SDValue, 8> Stores; 3221 for (unsigned Idx = 0; Idx < NumElem; ++Idx) { 3222 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value, 3223 DAG.getConstant(Idx, SL, IdxVT)); 3224 3225 SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 3226 DAG.getConstant(Idx * Stride, SL, PtrVT)); 3227 3228 // This scalar TruncStore may be illegal, but we legalize it later. 3229 SDValue Store = DAG.getTruncStore( 3230 Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride), 3231 MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride), 3232 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 3233 3234 Stores.push_back(Store); 3235 } 3236 3237 return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores); 3238 } 3239 3240 std::pair<SDValue, SDValue> 3241 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const { 3242 assert(LD->getAddressingMode() == ISD::UNINDEXED && 3243 "unaligned indexed loads not implemented!"); 3244 SDValue Chain = LD->getChain(); 3245 SDValue Ptr = LD->getBasePtr(); 3246 EVT VT = LD->getValueType(0); 3247 EVT LoadedVT = LD->getMemoryVT(); 3248 SDLoc dl(LD); 3249 if (VT.isFloatingPoint() || VT.isVector()) { 3250 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits()); 3251 if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) { 3252 if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) { 3253 // Scalarize the load and let the individual components be handled. 3254 SDValue Scalarized = scalarizeVectorLoad(LD, DAG); 3255 return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1)); 3256 } 3257 3258 // Expand to a (misaligned) integer load of the same size, 3259 // then bitconvert to floating point or vector. 3260 SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, 3261 LD->getMemOperand()); 3262 SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad); 3263 if (LoadedVT != VT) 3264 Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND : 3265 ISD::ANY_EXTEND, dl, VT, Result); 3266 3267 return std::make_pair(Result, newLoad.getValue(1)); 3268 } 3269 3270 // Copy the value to a (aligned) stack slot using (unaligned) integer 3271 // loads and stores, then do a (aligned) load from the stack slot. 3272 MVT RegVT = getRegisterType(*DAG.getContext(), intVT); 3273 unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8; 3274 unsigned RegBytes = RegVT.getSizeInBits() / 8; 3275 unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes; 3276 3277 // Make sure the stack slot is also aligned for the register type. 3278 SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT); 3279 3280 SmallVector<SDValue, 8> Stores; 3281 SDValue StackPtr = StackBase; 3282 unsigned Offset = 0; 3283 3284 EVT PtrVT = Ptr.getValueType(); 3285 EVT StackPtrVT = StackPtr.getValueType(); 3286 3287 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 3288 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 3289 3290 // Do all but one copies using the full register width. 3291 for (unsigned i = 1; i < NumRegs; i++) { 3292 // Load one integer register's worth from the original location. 3293 SDValue Load = DAG.getLoad( 3294 RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset), 3295 MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(), 3296 LD->getAAInfo()); 3297 // Follow the load with a store to the stack slot. Remember the store. 3298 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr, 3299 MachinePointerInfo())); 3300 // Increment the pointers. 3301 Offset += RegBytes; 3302 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement); 3303 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr, 3304 StackPtrIncrement); 3305 } 3306 3307 // The last copy may be partial. Do an extending load. 3308 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 3309 8 * (LoadedBytes - Offset)); 3310 SDValue Load = 3311 DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr, 3312 LD->getPointerInfo().getWithOffset(Offset), MemVT, 3313 MinAlign(LD->getAlignment(), Offset), 3314 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3315 // Follow the load with a store to the stack slot. Remember the store. 3316 // On big-endian machines this requires a truncating store to ensure 3317 // that the bits end up in the right place. 3318 Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr, 3319 MachinePointerInfo(), MemVT)); 3320 3321 // The order of the stores doesn't matter - say it with a TokenFactor. 3322 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 3323 3324 // Finally, perform the original load only redirected to the stack slot. 3325 Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase, 3326 MachinePointerInfo(), LoadedVT); 3327 3328 // Callers expect a MERGE_VALUES node. 3329 return std::make_pair(Load, TF); 3330 } 3331 3332 assert(LoadedVT.isInteger() && !LoadedVT.isVector() && 3333 "Unaligned load of unsupported type."); 3334 3335 // Compute the new VT that is half the size of the old one. This is an 3336 // integer MVT. 3337 unsigned NumBits = LoadedVT.getSizeInBits(); 3338 EVT NewLoadedVT; 3339 NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2); 3340 NumBits >>= 1; 3341 3342 unsigned Alignment = LD->getAlignment(); 3343 unsigned IncrementSize = NumBits / 8; 3344 ISD::LoadExtType HiExtType = LD->getExtensionType(); 3345 3346 // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD. 3347 if (HiExtType == ISD::NON_EXTLOAD) 3348 HiExtType = ISD::ZEXTLOAD; 3349 3350 // Load the value in two parts 3351 SDValue Lo, Hi; 3352 if (DAG.getDataLayout().isLittleEndian()) { 3353 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(), 3354 NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(), 3355 LD->getAAInfo()); 3356 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, 3357 DAG.getConstant(IncrementSize, dl, Ptr.getValueType())); 3358 Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, 3359 LD->getPointerInfo().getWithOffset(IncrementSize), 3360 NewLoadedVT, MinAlign(Alignment, IncrementSize), 3361 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3362 } else { 3363 Hi = DAG.getExtLoad(HiExtType, 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 Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, 3369 LD->getPointerInfo().getWithOffset(IncrementSize), 3370 NewLoadedVT, MinAlign(Alignment, IncrementSize), 3371 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 3372 } 3373 3374 // aggregate the two parts 3375 SDValue ShiftAmount = 3376 DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(), 3377 DAG.getDataLayout())); 3378 SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount); 3379 Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo); 3380 3381 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), 3382 Hi.getValue(1)); 3383 3384 return std::make_pair(Result, TF); 3385 } 3386 3387 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST, 3388 SelectionDAG &DAG) const { 3389 assert(ST->getAddressingMode() == ISD::UNINDEXED && 3390 "unaligned indexed stores not implemented!"); 3391 SDValue Chain = ST->getChain(); 3392 SDValue Ptr = ST->getBasePtr(); 3393 SDValue Val = ST->getValue(); 3394 EVT VT = Val.getValueType(); 3395 int Alignment = ST->getAlignment(); 3396 3397 SDLoc dl(ST); 3398 if (ST->getMemoryVT().isFloatingPoint() || 3399 ST->getMemoryVT().isVector()) { 3400 EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 3401 if (isTypeLegal(intVT)) { 3402 if (!isOperationLegalOrCustom(ISD::STORE, intVT)) { 3403 // Scalarize the store and let the individual components be handled. 3404 SDValue Result = scalarizeVectorStore(ST, DAG); 3405 3406 return Result; 3407 } 3408 // Expand to a bitconvert of the value to the integer type of the 3409 // same size, then a (misaligned) int store. 3410 // FIXME: Does not handle truncating floating point stores! 3411 SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val); 3412 Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(), 3413 Alignment, ST->getMemOperand()->getFlags()); 3414 return Result; 3415 } 3416 // Do a (aligned) store to a stack slot, then copy from the stack slot 3417 // to the final destination using (unaligned) integer loads and stores. 3418 EVT StoredVT = ST->getMemoryVT(); 3419 MVT RegVT = 3420 getRegisterType(*DAG.getContext(), 3421 EVT::getIntegerVT(*DAG.getContext(), 3422 StoredVT.getSizeInBits())); 3423 EVT PtrVT = Ptr.getValueType(); 3424 unsigned StoredBytes = StoredVT.getSizeInBits() / 8; 3425 unsigned RegBytes = RegVT.getSizeInBits() / 8; 3426 unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes; 3427 3428 // Make sure the stack slot is also aligned for the register type. 3429 SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT); 3430 3431 // Perform the original store, only redirected to the stack slot. 3432 SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr, 3433 MachinePointerInfo(), StoredVT); 3434 3435 EVT StackPtrVT = StackPtr.getValueType(); 3436 3437 SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT); 3438 SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT); 3439 SmallVector<SDValue, 8> Stores; 3440 unsigned Offset = 0; 3441 3442 // Do all but one copies using the full register width. 3443 for (unsigned i = 1; i < NumRegs; i++) { 3444 // Load one integer register's worth from the stack slot. 3445 SDValue Load = 3446 DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo()); 3447 // Store it to the final location. Remember the store. 3448 Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr, 3449 ST->getPointerInfo().getWithOffset(Offset), 3450 MinAlign(ST->getAlignment(), Offset), 3451 ST->getMemOperand()->getFlags())); 3452 // Increment the pointers. 3453 Offset += RegBytes; 3454 StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, 3455 StackPtr, StackPtrIncrement); 3456 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement); 3457 } 3458 3459 // The last store may be partial. Do a truncating store. On big-endian 3460 // machines this requires an extending load from the stack slot to ensure 3461 // that the bits are in the right place. 3462 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), 3463 8 * (StoredBytes - Offset)); 3464 3465 // Load from the stack slot. 3466 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr, 3467 MachinePointerInfo(), MemVT); 3468 3469 Stores.push_back( 3470 DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr, 3471 ST->getPointerInfo().getWithOffset(Offset), MemVT, 3472 MinAlign(ST->getAlignment(), Offset), 3473 ST->getMemOperand()->getFlags(), ST->getAAInfo())); 3474 // The order of the stores doesn't matter - say it with a TokenFactor. 3475 SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); 3476 return Result; 3477 } 3478 3479 assert(ST->getMemoryVT().isInteger() && 3480 !ST->getMemoryVT().isVector() && 3481 "Unaligned store of unknown type."); 3482 // Get the half-size VT 3483 EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext()); 3484 int NumBits = NewStoredVT.getSizeInBits(); 3485 int IncrementSize = NumBits / 8; 3486 3487 // Divide the stored value in two parts. 3488 SDValue ShiftAmount = 3489 DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(), 3490 DAG.getDataLayout())); 3491 SDValue Lo = Val; 3492 SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount); 3493 3494 // Store the two parts 3495 SDValue Store1, Store2; 3496 Store1 = DAG.getTruncStore(Chain, dl, 3497 DAG.getDataLayout().isLittleEndian() ? Lo : Hi, 3498 Ptr, ST->getPointerInfo(), NewStoredVT, Alignment, 3499 ST->getMemOperand()->getFlags()); 3500 3501 EVT PtrVT = Ptr.getValueType(); 3502 Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, 3503 DAG.getConstant(IncrementSize, dl, PtrVT)); 3504 Alignment = MinAlign(Alignment, IncrementSize); 3505 Store2 = DAG.getTruncStore( 3506 Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr, 3507 ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment, 3508 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 3509 3510 SDValue Result = 3511 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2); 3512 return Result; 3513 } 3514 3515 //===----------------------------------------------------------------------===// 3516 // Implementation of Emulated TLS Model 3517 //===----------------------------------------------------------------------===// 3518 3519 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, 3520 SelectionDAG &DAG) const { 3521 // Access to address of TLS varialbe xyz is lowered to a function call: 3522 // __emutls_get_address( address of global variable named "__emutls_v.xyz" ) 3523 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3524 PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext()); 3525 SDLoc dl(GA); 3526 3527 ArgListTy Args; 3528 ArgListEntry Entry; 3529 std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str(); 3530 Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent()); 3531 StringRef EmuTlsVarName(NameString); 3532 GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName); 3533 assert(EmuTlsVar && "Cannot find EmuTlsVar "); 3534 Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT); 3535 Entry.Ty = VoidPtrType; 3536 Args.push_back(Entry); 3537 3538 SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT); 3539 3540 TargetLowering::CallLoweringInfo CLI(DAG); 3541 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()); 3542 CLI.setCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args)); 3543 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 3544 3545 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls. 3546 // At last for X86 targets, maybe good for other targets too? 3547 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); 3548 MFI->setAdjustsStack(true); // Is this only for X86 target? 3549 MFI->setHasCalls(true); 3550 3551 assert((GA->getOffset() == 0) && 3552 "Emulated TLS must have zero offset in GlobalAddressSDNode"); 3553 return CallResult.first; 3554 } 3555