1 //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run 10 // both before and after the DAG is legalized. 11 // 12 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is 13 // primarily intended to handle simplification opportunities that are implicit 14 // in the LLVM IR and exposed by the various codegen lowering phases. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/APFloat.h" 19 #include "llvm/ADT/APInt.h" 20 #include "llvm/ADT/ArrayRef.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/IntervalMap.h" 23 #include "llvm/ADT/None.h" 24 #include "llvm/ADT/Optional.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SetVector.h" 27 #include "llvm/ADT/SmallBitVector.h" 28 #include "llvm/ADT/SmallPtrSet.h" 29 #include "llvm/ADT/SmallSet.h" 30 #include "llvm/ADT/SmallVector.h" 31 #include "llvm/ADT/Statistic.h" 32 #include "llvm/Analysis/AliasAnalysis.h" 33 #include "llvm/Analysis/MemoryLocation.h" 34 #include "llvm/CodeGen/DAGCombine.h" 35 #include "llvm/CodeGen/ISDOpcodes.h" 36 #include "llvm/CodeGen/MachineFrameInfo.h" 37 #include "llvm/CodeGen/MachineFunction.h" 38 #include "llvm/CodeGen/MachineMemOperand.h" 39 #include "llvm/CodeGen/RuntimeLibcalls.h" 40 #include "llvm/CodeGen/SelectionDAG.h" 41 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 42 #include "llvm/CodeGen/SelectionDAGNodes.h" 43 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 44 #include "llvm/CodeGen/TargetLowering.h" 45 #include "llvm/CodeGen/TargetRegisterInfo.h" 46 #include "llvm/CodeGen/TargetSubtargetInfo.h" 47 #include "llvm/CodeGen/ValueTypes.h" 48 #include "llvm/IR/Attributes.h" 49 #include "llvm/IR/Constant.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/IR/LLVMContext.h" 54 #include "llvm/IR/Metadata.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/CodeGen.h" 57 #include "llvm/Support/CommandLine.h" 58 #include "llvm/Support/Compiler.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/ErrorHandling.h" 61 #include "llvm/Support/KnownBits.h" 62 #include "llvm/Support/MachineValueType.h" 63 #include "llvm/Support/MathExtras.h" 64 #include "llvm/Support/raw_ostream.h" 65 #include "llvm/Target/TargetMachine.h" 66 #include "llvm/Target/TargetOptions.h" 67 #include <algorithm> 68 #include <cassert> 69 #include <cstdint> 70 #include <functional> 71 #include <iterator> 72 #include <string> 73 #include <tuple> 74 #include <utility> 75 76 using namespace llvm; 77 78 #define DEBUG_TYPE "dagcombine" 79 80 STATISTIC(NodesCombined , "Number of dag nodes combined"); 81 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 82 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 83 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 84 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 85 STATISTIC(SlicedLoads, "Number of load sliced"); 86 STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops"); 87 88 static cl::opt<bool> 89 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 90 cl::desc("Enable DAG combiner's use of IR alias analysis")); 91 92 static cl::opt<bool> 93 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 94 cl::desc("Enable DAG combiner's use of TBAA")); 95 96 #ifndef NDEBUG 97 static cl::opt<std::string> 98 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 99 cl::desc("Only use DAG-combiner alias analysis in this" 100 " function")); 101 #endif 102 103 /// Hidden option to stress test load slicing, i.e., when this option 104 /// is enabled, load slicing bypasses most of its profitability guards. 105 static cl::opt<bool> 106 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 107 cl::desc("Bypass the profitability model of load slicing"), 108 cl::init(false)); 109 110 static cl::opt<bool> 111 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 112 cl::desc("DAG combiner may split indexing from loads")); 113 114 namespace { 115 116 class DAGCombiner { 117 SelectionDAG &DAG; 118 const TargetLowering &TLI; 119 CombineLevel Level; 120 CodeGenOpt::Level OptLevel; 121 bool LegalOperations = false; 122 bool LegalTypes = false; 123 bool ForCodeSize; 124 125 /// Worklist of all of the nodes that need to be simplified. 126 /// 127 /// This must behave as a stack -- new nodes to process are pushed onto the 128 /// back and when processing we pop off of the back. 129 /// 130 /// The worklist will not contain duplicates but may contain null entries 131 /// due to nodes being deleted from the underlying DAG. 132 SmallVector<SDNode *, 64> Worklist; 133 134 /// Mapping from an SDNode to its position on the worklist. 135 /// 136 /// This is used to find and remove nodes from the worklist (by nulling 137 /// them) when they are deleted from the underlying DAG. It relies on 138 /// stable indices of nodes within the worklist. 139 DenseMap<SDNode *, unsigned> WorklistMap; 140 /// This records all nodes attempted to add to the worklist since we 141 /// considered a new worklist entry. As we keep do not add duplicate nodes 142 /// in the worklist, this is different from the tail of the worklist. 143 SmallSetVector<SDNode *, 32> PruningList; 144 145 /// Set of nodes which have been combined (at least once). 146 /// 147 /// This is used to allow us to reliably add any operands of a DAG node 148 /// which have not yet been combined to the worklist. 149 SmallPtrSet<SDNode *, 32> CombinedNodes; 150 151 // AA - Used for DAG load/store alias analysis. 152 AliasAnalysis *AA; 153 154 /// When an instruction is simplified, add all users of the instruction to 155 /// the work lists because they might get more simplified now. 156 void AddUsersToWorklist(SDNode *N) { 157 for (SDNode *Node : N->uses()) 158 AddToWorklist(Node); 159 } 160 161 // Prune potentially dangling nodes. This is called after 162 // any visit to a node, but should also be called during a visit after any 163 // failed combine which may have created a DAG node. 164 void clearAddedDanglingWorklistEntries() { 165 // Check any nodes added to the worklist to see if they are prunable. 166 while (!PruningList.empty()) { 167 auto *N = PruningList.pop_back_val(); 168 if (N->use_empty()) 169 recursivelyDeleteUnusedNodes(N); 170 } 171 } 172 173 SDNode *getNextWorklistEntry() { 174 // Before we do any work, remove nodes that are not in use. 175 clearAddedDanglingWorklistEntries(); 176 SDNode *N = nullptr; 177 // The Worklist holds the SDNodes in order, but it may contain null 178 // entries. 179 while (!N && !Worklist.empty()) { 180 N = Worklist.pop_back_val(); 181 } 182 183 if (N) { 184 bool GoodWorklistEntry = WorklistMap.erase(N); 185 (void)GoodWorklistEntry; 186 assert(GoodWorklistEntry && 187 "Found a worklist entry without a corresponding map entry!"); 188 } 189 return N; 190 } 191 192 /// Call the node-specific routine that folds each particular type of node. 193 SDValue visit(SDNode *N); 194 195 public: 196 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL) 197 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes), 198 OptLevel(OL), AA(AA) { 199 ForCodeSize = DAG.getMachineFunction().getFunction().hasOptSize(); 200 201 MaximumLegalStoreInBits = 0; 202 for (MVT VT : MVT::all_valuetypes()) 203 if (EVT(VT).isSimple() && VT != MVT::Other && 204 TLI.isTypeLegal(EVT(VT)) && 205 VT.getSizeInBits() >= MaximumLegalStoreInBits) 206 MaximumLegalStoreInBits = VT.getSizeInBits(); 207 } 208 209 void ConsiderForPruning(SDNode *N) { 210 // Mark this for potential pruning. 211 PruningList.insert(N); 212 } 213 214 /// Add to the worklist making sure its instance is at the back (next to be 215 /// processed.) 216 void AddToWorklist(SDNode *N) { 217 assert(N->getOpcode() != ISD::DELETED_NODE && 218 "Deleted Node added to Worklist"); 219 220 // Skip handle nodes as they can't usefully be combined and confuse the 221 // zero-use deletion strategy. 222 if (N->getOpcode() == ISD::HANDLENODE) 223 return; 224 225 ConsiderForPruning(N); 226 227 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 228 Worklist.push_back(N); 229 } 230 231 /// Remove all instances of N from the worklist. 232 void removeFromWorklist(SDNode *N) { 233 CombinedNodes.erase(N); 234 PruningList.remove(N); 235 236 auto It = WorklistMap.find(N); 237 if (It == WorklistMap.end()) 238 return; // Not in the worklist. 239 240 // Null out the entry rather than erasing it to avoid a linear operation. 241 Worklist[It->second] = nullptr; 242 WorklistMap.erase(It); 243 } 244 245 void deleteAndRecombine(SDNode *N); 246 bool recursivelyDeleteUnusedNodes(SDNode *N); 247 248 /// Replaces all uses of the results of one DAG node with new values. 249 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 250 bool AddTo = true); 251 252 /// Replaces all uses of the results of one DAG node with new values. 253 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 254 return CombineTo(N, &Res, 1, AddTo); 255 } 256 257 /// Replaces all uses of the results of one DAG node with new values. 258 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 259 bool AddTo = true) { 260 SDValue To[] = { Res0, Res1 }; 261 return CombineTo(N, To, 2, AddTo); 262 } 263 264 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 265 266 private: 267 unsigned MaximumLegalStoreInBits; 268 269 /// Check the specified integer node value to see if it can be simplified or 270 /// if things it uses can be simplified by bit propagation. 271 /// If so, return true. 272 bool SimplifyDemandedBits(SDValue Op) { 273 unsigned BitWidth = Op.getScalarValueSizeInBits(); 274 APInt DemandedBits = APInt::getAllOnesValue(BitWidth); 275 return SimplifyDemandedBits(Op, DemandedBits); 276 } 277 278 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) { 279 EVT VT = Op.getValueType(); 280 unsigned NumElts = VT.isVector() ? VT.getVectorNumElements() : 1; 281 APInt DemandedElts = APInt::getAllOnesValue(NumElts); 282 return SimplifyDemandedBits(Op, DemandedBits, DemandedElts); 283 } 284 285 /// Check the specified vector node value to see if it can be simplified or 286 /// if things it uses can be simplified as it only uses some of the 287 /// elements. If so, return true. 288 bool SimplifyDemandedVectorElts(SDValue Op) { 289 unsigned NumElts = Op.getValueType().getVectorNumElements(); 290 APInt DemandedElts = APInt::getAllOnesValue(NumElts); 291 return SimplifyDemandedVectorElts(Op, DemandedElts); 292 } 293 294 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 295 const APInt &DemandedElts); 296 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts, 297 bool AssumeSingleUse = false); 298 299 bool CombineToPreIndexedLoadStore(SDNode *N); 300 bool CombineToPostIndexedLoadStore(SDNode *N); 301 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 302 bool SliceUpLoad(SDNode *N); 303 304 // Scalars have size 0 to distinguish from singleton vectors. 305 SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD); 306 bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val); 307 bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val); 308 309 /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 310 /// load. 311 /// 312 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 313 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 314 /// \param EltNo index of the vector element to load. 315 /// \param OriginalLoad load that EVE came from to be replaced. 316 /// \returns EVE on success SDValue() on failure. 317 SDValue scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT, 318 SDValue EltNo, 319 LoadSDNode *OriginalLoad); 320 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 321 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 322 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 323 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 324 SDValue PromoteIntBinOp(SDValue Op); 325 SDValue PromoteIntShiftOp(SDValue Op); 326 SDValue PromoteExtend(SDValue Op); 327 bool PromoteLoad(SDValue Op); 328 329 /// Call the node-specific routine that knows how to fold each 330 /// particular type of node. If that doesn't do anything, try the 331 /// target-specific DAG combines. 332 SDValue combine(SDNode *N); 333 334 // Visitation implementation - Implement dag node combining for different 335 // node types. The semantics are as follows: 336 // Return Value: 337 // SDValue.getNode() == 0 - No change was made 338 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 339 // otherwise - N should be replaced by the returned Operand. 340 // 341 SDValue visitTokenFactor(SDNode *N); 342 SDValue visitMERGE_VALUES(SDNode *N); 343 SDValue visitADD(SDNode *N); 344 SDValue visitADDLike(SDNode *N); 345 SDValue visitADDLikeCommutative(SDValue N0, SDValue N1, SDNode *LocReference); 346 SDValue visitSUB(SDNode *N); 347 SDValue visitADDSAT(SDNode *N); 348 SDValue visitSUBSAT(SDNode *N); 349 SDValue visitADDC(SDNode *N); 350 SDValue visitADDO(SDNode *N); 351 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); 352 SDValue visitSUBC(SDNode *N); 353 SDValue visitSUBO(SDNode *N); 354 SDValue visitADDE(SDNode *N); 355 SDValue visitADDCARRY(SDNode *N); 356 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); 357 SDValue visitSUBE(SDNode *N); 358 SDValue visitSUBCARRY(SDNode *N); 359 SDValue visitMUL(SDNode *N); 360 SDValue useDivRem(SDNode *N); 361 SDValue visitSDIV(SDNode *N); 362 SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N); 363 SDValue visitUDIV(SDNode *N); 364 SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N); 365 SDValue visitREM(SDNode *N); 366 SDValue visitMULHU(SDNode *N); 367 SDValue visitMULHS(SDNode *N); 368 SDValue visitSMUL_LOHI(SDNode *N); 369 SDValue visitUMUL_LOHI(SDNode *N); 370 SDValue visitMULO(SDNode *N); 371 SDValue visitIMINMAX(SDNode *N); 372 SDValue visitAND(SDNode *N); 373 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N); 374 SDValue visitOR(SDNode *N); 375 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N); 376 SDValue visitXOR(SDNode *N); 377 SDValue SimplifyVBinOp(SDNode *N); 378 SDValue visitSHL(SDNode *N); 379 SDValue visitSRA(SDNode *N); 380 SDValue visitSRL(SDNode *N); 381 SDValue visitFunnelShift(SDNode *N); 382 SDValue visitRotate(SDNode *N); 383 SDValue visitABS(SDNode *N); 384 SDValue visitBSWAP(SDNode *N); 385 SDValue visitBITREVERSE(SDNode *N); 386 SDValue visitCTLZ(SDNode *N); 387 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 388 SDValue visitCTTZ(SDNode *N); 389 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 390 SDValue visitCTPOP(SDNode *N); 391 SDValue visitSELECT(SDNode *N); 392 SDValue visitVSELECT(SDNode *N); 393 SDValue visitSELECT_CC(SDNode *N); 394 SDValue visitSETCC(SDNode *N); 395 SDValue visitSETCCCARRY(SDNode *N); 396 SDValue visitSIGN_EXTEND(SDNode *N); 397 SDValue visitZERO_EXTEND(SDNode *N); 398 SDValue visitANY_EXTEND(SDNode *N); 399 SDValue visitAssertExt(SDNode *N); 400 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 401 SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N); 402 SDValue visitZERO_EXTEND_VECTOR_INREG(SDNode *N); 403 SDValue visitTRUNCATE(SDNode *N); 404 SDValue visitBITCAST(SDNode *N); 405 SDValue visitBUILD_PAIR(SDNode *N); 406 SDValue visitFADD(SDNode *N); 407 SDValue visitFSUB(SDNode *N); 408 SDValue visitFMUL(SDNode *N); 409 SDValue visitFMA(SDNode *N); 410 SDValue visitFDIV(SDNode *N); 411 SDValue visitFREM(SDNode *N); 412 SDValue visitFSQRT(SDNode *N); 413 SDValue visitFCOPYSIGN(SDNode *N); 414 SDValue visitFPOW(SDNode *N); 415 SDValue visitSINT_TO_FP(SDNode *N); 416 SDValue visitUINT_TO_FP(SDNode *N); 417 SDValue visitFP_TO_SINT(SDNode *N); 418 SDValue visitFP_TO_UINT(SDNode *N); 419 SDValue visitFP_ROUND(SDNode *N); 420 SDValue visitFP_ROUND_INREG(SDNode *N); 421 SDValue visitFP_EXTEND(SDNode *N); 422 SDValue visitFNEG(SDNode *N); 423 SDValue visitFABS(SDNode *N); 424 SDValue visitFCEIL(SDNode *N); 425 SDValue visitFTRUNC(SDNode *N); 426 SDValue visitFFLOOR(SDNode *N); 427 SDValue visitFMINNUM(SDNode *N); 428 SDValue visitFMAXNUM(SDNode *N); 429 SDValue visitFMINIMUM(SDNode *N); 430 SDValue visitFMAXIMUM(SDNode *N); 431 SDValue visitBRCOND(SDNode *N); 432 SDValue visitBR_CC(SDNode *N); 433 SDValue visitLOAD(SDNode *N); 434 435 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 436 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 437 438 SDValue visitSTORE(SDNode *N); 439 SDValue visitLIFETIME_END(SDNode *N); 440 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 441 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 442 SDValue visitBUILD_VECTOR(SDNode *N); 443 SDValue visitCONCAT_VECTORS(SDNode *N); 444 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 445 SDValue visitVECTOR_SHUFFLE(SDNode *N); 446 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 447 SDValue visitINSERT_SUBVECTOR(SDNode *N); 448 SDValue visitMLOAD(SDNode *N); 449 SDValue visitMSTORE(SDNode *N); 450 SDValue visitMGATHER(SDNode *N); 451 SDValue visitMSCATTER(SDNode *N); 452 SDValue visitFP_TO_FP16(SDNode *N); 453 SDValue visitFP16_TO_FP(SDNode *N); 454 SDValue visitVECREDUCE(SDNode *N); 455 456 SDValue visitFADDForFMACombine(SDNode *N); 457 SDValue visitFSUBForFMACombine(SDNode *N); 458 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 459 460 SDValue XformToShuffleWithZero(SDNode *N); 461 SDValue ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 462 SDValue N1, SDNodeFlags Flags); 463 464 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt); 465 466 SDValue foldSelectOfConstants(SDNode *N); 467 SDValue foldVSelectOfConstants(SDNode *N); 468 SDValue foldBinOpIntoSelect(SDNode *BO); 469 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 470 SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N); 471 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 472 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 473 SDValue N2, SDValue N3, ISD::CondCode CC, 474 bool NotExtCompare = false); 475 SDValue convertSelectOfFPConstantsToLoadOffset( 476 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3, 477 ISD::CondCode CC); 478 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 479 SDValue N2, SDValue N3, ISD::CondCode CC); 480 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 481 const SDLoc &DL); 482 SDValue unfoldMaskedMerge(SDNode *N); 483 SDValue unfoldExtremeBitClearingToShifts(SDNode *N); 484 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 485 const SDLoc &DL, bool foldBooleans); 486 SDValue rebuildSetCC(SDValue N); 487 488 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 489 SDValue &CC) const; 490 bool isOneUseSetCC(SDValue N) const; 491 492 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 493 unsigned HiOp); 494 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 495 SDValue CombineExtLoad(SDNode *N); 496 SDValue CombineZExtLogicopShiftLoad(SDNode *N); 497 SDValue combineRepeatedFPDivisors(SDNode *N); 498 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex); 499 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 500 SDValue BuildSDIV(SDNode *N); 501 SDValue BuildSDIVPow2(SDNode *N); 502 SDValue BuildUDIV(SDNode *N); 503 SDValue BuildLogBase2(SDValue V, const SDLoc &DL); 504 SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags); 505 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 506 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 507 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 508 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations, 509 SDNodeFlags Flags, bool Reciprocal); 510 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations, 511 SDNodeFlags Flags, bool Reciprocal); 512 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 513 bool DemandHighBits = true); 514 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 515 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 516 SDValue InnerPos, SDValue InnerNeg, 517 unsigned PosOpcode, unsigned NegOpcode, 518 const SDLoc &DL); 519 SDNode *MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 520 SDValue MatchLoadCombine(SDNode *N); 521 SDValue ReduceLoadWidth(SDNode *N); 522 SDValue ReduceLoadOpStoreWidth(SDNode *N); 523 SDValue splitMergedValStore(StoreSDNode *ST); 524 SDValue TransformFPLoadStorePair(SDNode *N); 525 SDValue convertBuildVecZextToZext(SDNode *N); 526 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 527 SDValue reduceBuildVecToShuffle(SDNode *N); 528 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 529 ArrayRef<int> VectorMask, SDValue VecIn1, 530 SDValue VecIn2, unsigned LeftIdx, 531 bool DidSplitVec); 532 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast); 533 534 /// Walk up chain skipping non-aliasing memory nodes, 535 /// looking for aliasing nodes and adding them to the Aliases vector. 536 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 537 SmallVectorImpl<SDValue> &Aliases); 538 539 /// Return true if there is any possibility that the two addresses overlap. 540 bool isAlias(SDNode *Op0, SDNode *Op1) const; 541 542 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 543 /// chain (aliasing node.) 544 SDValue FindBetterChain(SDNode *N, SDValue Chain); 545 546 /// Try to replace a store and any possibly adjacent stores on 547 /// consecutive chains with better chains. Return true only if St is 548 /// replaced. 549 /// 550 /// Notice that other chains may still be replaced even if the function 551 /// returns false. 552 bool findBetterNeighborChains(StoreSDNode *St); 553 554 // Helper for findBetterNeighborChains. Walk up store chain add additional 555 // chained stores that do not overlap and can be parallelized. 556 bool parallelizeChainedStores(StoreSDNode *St); 557 558 /// Holds a pointer to an LSBaseSDNode as well as information on where it 559 /// is located in a sequence of memory operations connected by a chain. 560 struct MemOpLink { 561 // Ptr to the mem node. 562 LSBaseSDNode *MemNode; 563 564 // Offset from the base ptr. 565 int64_t OffsetFromBase; 566 567 MemOpLink(LSBaseSDNode *N, int64_t Offset) 568 : MemNode(N), OffsetFromBase(Offset) {} 569 }; 570 571 /// This is a helper function for visitMUL to check the profitability 572 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 573 /// MulNode is the original multiply, AddNode is (add x, c1), 574 /// and ConstNode is c2. 575 bool isMulAddWithConstProfitable(SDNode *MulNode, 576 SDValue &AddNode, 577 SDValue &ConstNode); 578 579 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 580 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 581 /// the type of the loaded value to be extended. 582 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 583 EVT LoadResultTy, EVT &ExtVT); 584 585 /// Helper function to calculate whether the given Load/Store can have its 586 /// width reduced to ExtVT. 587 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType, 588 EVT &MemVT, unsigned ShAmt = 0); 589 590 /// Used by BackwardsPropagateMask to find suitable loads. 591 bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads, 592 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 593 ConstantSDNode *Mask, SDNode *&NodeToMask); 594 /// Attempt to propagate a given AND node back to load leaves so that they 595 /// can be combined into narrow loads. 596 bool BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG); 597 598 /// Helper function for MergeConsecutiveStores which merges the 599 /// component store chains. 600 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 601 unsigned NumStores); 602 603 /// This is a helper function for MergeConsecutiveStores. When the 604 /// source elements of the consecutive stores are all constants or 605 /// all extracted vector elements, try to merge them into one 606 /// larger store introducing bitcasts if necessary. \return True 607 /// if a merged store was created. 608 bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 609 EVT MemVT, unsigned NumStores, 610 bool IsConstantSrc, bool UseVector, 611 bool UseTrunc); 612 613 /// This is a helper function for MergeConsecutiveStores. Stores 614 /// that potentially may be merged with St are placed in 615 /// StoreNodes. RootNode is a chain predecessor to all store 616 /// candidates. 617 void getStoreMergeCandidates(StoreSDNode *St, 618 SmallVectorImpl<MemOpLink> &StoreNodes, 619 SDNode *&Root); 620 621 /// Helper function for MergeConsecutiveStores. Checks if 622 /// candidate stores have indirect dependency through their 623 /// operands. RootNode is the predecessor to all stores calculated 624 /// by getStoreMergeCandidates and is used to prune the dependency check. 625 /// \return True if safe to merge. 626 bool checkMergeStoreCandidatesForDependencies( 627 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 628 SDNode *RootNode); 629 630 /// Merge consecutive store operations into a wide store. 631 /// This optimization uses wide integers or vectors when possible. 632 /// \return number of stores that were merged into a merged store (the 633 /// affected nodes are stored as a prefix in \p StoreNodes). 634 bool MergeConsecutiveStores(StoreSDNode *St); 635 636 /// Try to transform a truncation where C is a constant: 637 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 638 /// 639 /// \p N needs to be a truncation and its first operand an AND. Other 640 /// requirements are checked by the function (e.g. that trunc is 641 /// single-use) and if missed an empty SDValue is returned. 642 SDValue distributeTruncateThroughAnd(SDNode *N); 643 644 /// Helper function to determine whether the target supports operation 645 /// given by \p Opcode for type \p VT, that is, whether the operation 646 /// is legal or custom before legalizing operations, and whether is 647 /// legal (but not custom) after legalization. 648 bool hasOperation(unsigned Opcode, EVT VT) { 649 if (LegalOperations) 650 return TLI.isOperationLegal(Opcode, VT); 651 return TLI.isOperationLegalOrCustom(Opcode, VT); 652 } 653 654 public: 655 /// Runs the dag combiner on all nodes in the work list 656 void Run(CombineLevel AtLevel); 657 658 SelectionDAG &getDAG() const { return DAG; } 659 660 /// Returns a type large enough to hold any valid shift amount - before type 661 /// legalization these can be huge. 662 EVT getShiftAmountTy(EVT LHSTy) { 663 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 664 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes); 665 } 666 667 /// This method returns true if we are running before type legalization or 668 /// if the specified VT is legal. 669 bool isTypeLegal(const EVT &VT) { 670 if (!LegalTypes) return true; 671 return TLI.isTypeLegal(VT); 672 } 673 674 /// Convenience wrapper around TargetLowering::getSetCCResultType 675 EVT getSetCCResultType(EVT VT) const { 676 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 677 } 678 679 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 680 SDValue OrigLoad, SDValue ExtLoad, 681 ISD::NodeType ExtType); 682 }; 683 684 /// This class is a DAGUpdateListener that removes any deleted 685 /// nodes from the worklist. 686 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 687 DAGCombiner &DC; 688 689 public: 690 explicit WorklistRemover(DAGCombiner &dc) 691 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 692 693 void NodeDeleted(SDNode *N, SDNode *E) override { 694 DC.removeFromWorklist(N); 695 } 696 }; 697 698 class WorklistInserter : public SelectionDAG::DAGUpdateListener { 699 DAGCombiner &DC; 700 701 public: 702 explicit WorklistInserter(DAGCombiner &dc) 703 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 704 705 // FIXME: Ideally we could add N to the worklist, but this causes exponential 706 // compile time costs in large DAGs, e.g. Halide. 707 void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); } 708 }; 709 710 } // end anonymous namespace 711 712 //===----------------------------------------------------------------------===// 713 // TargetLowering::DAGCombinerInfo implementation 714 //===----------------------------------------------------------------------===// 715 716 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 717 ((DAGCombiner*)DC)->AddToWorklist(N); 718 } 719 720 SDValue TargetLowering::DAGCombinerInfo:: 721 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 722 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 723 } 724 725 SDValue TargetLowering::DAGCombinerInfo:: 726 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 727 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 728 } 729 730 SDValue TargetLowering::DAGCombinerInfo:: 731 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 732 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 733 } 734 735 void TargetLowering::DAGCombinerInfo:: 736 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 737 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 738 } 739 740 //===----------------------------------------------------------------------===// 741 // Helper Functions 742 //===----------------------------------------------------------------------===// 743 744 void DAGCombiner::deleteAndRecombine(SDNode *N) { 745 removeFromWorklist(N); 746 747 // If the operands of this node are only used by the node, they will now be 748 // dead. Make sure to re-visit them and recursively delete dead nodes. 749 for (const SDValue &Op : N->ops()) 750 // For an operand generating multiple values, one of the values may 751 // become dead allowing further simplification (e.g. split index 752 // arithmetic from an indexed load). 753 if (Op->hasOneUse() || Op->getNumValues() > 1) 754 AddToWorklist(Op.getNode()); 755 756 DAG.DeleteNode(N); 757 } 758 759 /// Return 1 if we can compute the negated form of the specified expression for 760 /// the same cost as the expression itself, or 2 if we can compute the negated 761 /// form more cheaply than the expression itself. 762 static char isNegatibleForFree(SDValue Op, bool LegalOperations, 763 const TargetLowering &TLI, 764 const TargetOptions *Options, 765 bool ForCodeSize, 766 unsigned Depth = 0) { 767 // fneg is removable even if it has multiple uses. 768 if (Op.getOpcode() == ISD::FNEG) return 2; 769 770 // Don't allow anything with multiple uses unless we know it is free. 771 EVT VT = Op.getValueType(); 772 const SDNodeFlags Flags = Op->getFlags(); 773 if (!Op.hasOneUse()) 774 if (!(Op.getOpcode() == ISD::FP_EXTEND && 775 TLI.isFPExtFree(VT, Op.getOperand(0).getValueType()))) 776 return 0; 777 778 // Don't recurse exponentially. 779 if (Depth > 6) return 0; 780 781 switch (Op.getOpcode()) { 782 default: return false; 783 case ISD::ConstantFP: { 784 if (!LegalOperations) 785 return 1; 786 787 // Don't invert constant FP values after legalization unless the target says 788 // the negated constant is legal. 789 return TLI.isOperationLegal(ISD::ConstantFP, VT) || 790 TLI.isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT, 791 ForCodeSize); 792 } 793 case ISD::FADD: 794 if (!Options->UnsafeFPMath && !Flags.hasNoSignedZeros()) 795 return 0; 796 797 // After operation legalization, it might not be legal to create new FSUBs. 798 if (LegalOperations && !TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) 799 return 0; 800 801 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 802 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 803 Options, ForCodeSize, Depth + 1)) 804 return V; 805 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 806 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 807 ForCodeSize, Depth + 1); 808 case ISD::FSUB: 809 // We can't turn -(A-B) into B-A when we honor signed zeros. 810 if (!Options->NoSignedZerosFPMath && 811 !Flags.hasNoSignedZeros()) 812 return 0; 813 814 // fold (fneg (fsub A, B)) -> (fsub B, A) 815 return 1; 816 817 case ISD::FMUL: 818 case ISD::FDIV: 819 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y)) 820 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, 821 Options, ForCodeSize, Depth + 1)) 822 return V; 823 824 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options, 825 ForCodeSize, Depth + 1); 826 827 case ISD::FP_EXTEND: 828 case ISD::FP_ROUND: 829 case ISD::FSIN: 830 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options, 831 ForCodeSize, Depth + 1); 832 } 833 } 834 835 /// If isNegatibleForFree returns true, return the newly negated expression. 836 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG, 837 bool LegalOperations, bool ForCodeSize, 838 unsigned Depth = 0) { 839 const TargetOptions &Options = DAG.getTarget().Options; 840 // fneg is removable even if it has multiple uses. 841 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0); 842 843 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree"); 844 845 const SDNodeFlags Flags = Op.getNode()->getFlags(); 846 847 switch (Op.getOpcode()) { 848 default: llvm_unreachable("Unknown code"); 849 case ISD::ConstantFP: { 850 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF(); 851 V.changeSign(); 852 return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType()); 853 } 854 case ISD::FADD: 855 assert(Options.UnsafeFPMath || Flags.hasNoSignedZeros()); 856 857 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B) 858 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 859 DAG.getTargetLoweringInfo(), &Options, ForCodeSize, 860 Depth+1)) 861 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 862 GetNegatedExpression(Op.getOperand(0), DAG, 863 LegalOperations, ForCodeSize, 864 Depth+1), 865 Op.getOperand(1), Flags); 866 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A) 867 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 868 GetNegatedExpression(Op.getOperand(1), DAG, 869 LegalOperations, ForCodeSize, 870 Depth+1), 871 Op.getOperand(0), Flags); 872 case ISD::FSUB: 873 // fold (fneg (fsub 0, B)) -> B 874 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0))) 875 if (N0CFP->isZero()) 876 return Op.getOperand(1); 877 878 // fold (fneg (fsub A, B)) -> (fsub B, A) 879 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(), 880 Op.getOperand(1), Op.getOperand(0), Flags); 881 882 case ISD::FMUL: 883 case ISD::FDIV: 884 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) 885 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, 886 DAG.getTargetLoweringInfo(), &Options, ForCodeSize, 887 Depth+1)) 888 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 889 GetNegatedExpression(Op.getOperand(0), DAG, 890 LegalOperations, ForCodeSize, 891 Depth+1), 892 Op.getOperand(1), Flags); 893 894 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y)) 895 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 896 Op.getOperand(0), 897 GetNegatedExpression(Op.getOperand(1), DAG, 898 LegalOperations, ForCodeSize, 899 Depth+1), Flags); 900 901 case ISD::FP_EXTEND: 902 case ISD::FSIN: 903 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(), 904 GetNegatedExpression(Op.getOperand(0), DAG, 905 LegalOperations, ForCodeSize, 906 Depth+1)); 907 case ISD::FP_ROUND: 908 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(), 909 GetNegatedExpression(Op.getOperand(0), DAG, 910 LegalOperations, ForCodeSize, 911 Depth+1), 912 Op.getOperand(1)); 913 } 914 } 915 916 // APInts must be the same size for most operations, this helper 917 // function zero extends the shorter of the pair so that they match. 918 // We provide an Offset so that we can create bitwidths that won't overflow. 919 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 920 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 921 LHS = LHS.zextOrSelf(Bits); 922 RHS = RHS.zextOrSelf(Bits); 923 } 924 925 // Return true if this node is a setcc, or is a select_cc 926 // that selects between the target values used for true and false, making it 927 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 928 // the appropriate nodes based on the type of node we are checking. This 929 // simplifies life a bit for the callers. 930 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 931 SDValue &CC) const { 932 if (N.getOpcode() == ISD::SETCC) { 933 LHS = N.getOperand(0); 934 RHS = N.getOperand(1); 935 CC = N.getOperand(2); 936 return true; 937 } 938 939 if (N.getOpcode() != ISD::SELECT_CC || 940 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 941 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 942 return false; 943 944 if (TLI.getBooleanContents(N.getValueType()) == 945 TargetLowering::UndefinedBooleanContent) 946 return false; 947 948 LHS = N.getOperand(0); 949 RHS = N.getOperand(1); 950 CC = N.getOperand(4); 951 return true; 952 } 953 954 /// Return true if this is a SetCC-equivalent operation with only one use. 955 /// If this is true, it allows the users to invert the operation for free when 956 /// it is profitable to do so. 957 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 958 SDValue N0, N1, N2; 959 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 960 return true; 961 return false; 962 } 963 964 // Returns the SDNode if it is a constant float BuildVector 965 // or constant float. 966 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) { 967 if (isa<ConstantFPSDNode>(N)) 968 return N.getNode(); 969 if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode())) 970 return N.getNode(); 971 return nullptr; 972 } 973 974 // Determines if it is a constant integer or a build vector of constant 975 // integers (and undefs). 976 // Do not permit build vector implicit truncation. 977 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 978 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 979 return !(Const->isOpaque() && NoOpaques); 980 if (N.getOpcode() != ISD::BUILD_VECTOR) 981 return false; 982 unsigned BitWidth = N.getScalarValueSizeInBits(); 983 for (const SDValue &Op : N->op_values()) { 984 if (Op.isUndef()) 985 continue; 986 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 987 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 988 (Const->isOpaque() && NoOpaques)) 989 return false; 990 } 991 return true; 992 } 993 994 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 995 // undef's. 996 static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) { 997 if (V.getOpcode() != ISD::BUILD_VECTOR) 998 return false; 999 return isConstantOrConstantVector(V, NoOpaques) || 1000 ISD::isBuildVectorOfConstantFPSDNodes(V.getNode()); 1001 } 1002 1003 SDValue DAGCombiner::ReassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 1004 SDValue N1, SDNodeFlags Flags) { 1005 // Don't reassociate reductions. 1006 if (Flags.hasVectorReduction()) 1007 return SDValue(); 1008 1009 EVT VT = N0.getValueType(); 1010 if (N0.getOpcode() == Opc && !N0->getFlags().hasVectorReduction()) { 1011 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) { 1012 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 1013 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2)) 1014 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R)) 1015 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode); 1016 return SDValue(); 1017 } 1018 if (N0.hasOneUse()) { 1019 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one 1020 // use 1021 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1); 1022 if (!OpNode.getNode()) 1023 return SDValue(); 1024 AddToWorklist(OpNode.getNode()); 1025 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1)); 1026 } 1027 } 1028 } 1029 1030 if (N1.getOpcode() == Opc && !N1->getFlags().hasVectorReduction()) { 1031 if (SDNode *R = DAG.isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) { 1032 if (SDNode *L = DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 1033 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2)) 1034 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L)) 1035 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode); 1036 return SDValue(); 1037 } 1038 if (N1.hasOneUse()) { 1039 // reassoc. (op x, (op y, c1)) -> (op (op x, y), c1) iff x+c1 has one 1040 // use 1041 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0, N1.getOperand(0)); 1042 if (!OpNode.getNode()) 1043 return SDValue(); 1044 AddToWorklist(OpNode.getNode()); 1045 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1)); 1046 } 1047 } 1048 } 1049 1050 return SDValue(); 1051 } 1052 1053 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 1054 bool AddTo) { 1055 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 1056 ++NodesCombined; 1057 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: "; 1058 To[0].getNode()->dump(&DAG); 1059 dbgs() << " and " << NumTo - 1 << " other values\n"); 1060 for (unsigned i = 0, e = NumTo; i != e; ++i) 1061 assert((!To[i].getNode() || 1062 N->getValueType(i) == To[i].getValueType()) && 1063 "Cannot combine value to value of different type!"); 1064 1065 WorklistRemover DeadNodes(*this); 1066 DAG.ReplaceAllUsesWith(N, To); 1067 if (AddTo) { 1068 // Push the new nodes and any users onto the worklist 1069 for (unsigned i = 0, e = NumTo; i != e; ++i) { 1070 if (To[i].getNode()) { 1071 AddToWorklist(To[i].getNode()); 1072 AddUsersToWorklist(To[i].getNode()); 1073 } 1074 } 1075 } 1076 1077 // Finally, if the node is now dead, remove it from the graph. The node 1078 // may not be dead if the replacement process recursively simplified to 1079 // something else needing this node. 1080 if (N->use_empty()) 1081 deleteAndRecombine(N); 1082 return SDValue(N, 0); 1083 } 1084 1085 void DAGCombiner:: 1086 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 1087 // Replace all uses. If any nodes become isomorphic to other nodes and 1088 // are deleted, make sure to remove them from our worklist. 1089 WorklistRemover DeadNodes(*this); 1090 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 1091 1092 // Push the new node and any (possibly new) users onto the worklist. 1093 AddToWorklist(TLO.New.getNode()); 1094 AddUsersToWorklist(TLO.New.getNode()); 1095 1096 // Finally, if the node is now dead, remove it from the graph. The node 1097 // may not be dead if the replacement process recursively simplified to 1098 // something else needing this node. 1099 if (TLO.Old.getNode()->use_empty()) 1100 deleteAndRecombine(TLO.Old.getNode()); 1101 } 1102 1103 /// Check the specified integer node value to see if it can be simplified or if 1104 /// things it uses can be simplified by bit propagation. If so, return true. 1105 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 1106 const APInt &DemandedElts) { 1107 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1108 KnownBits Known; 1109 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO)) 1110 return false; 1111 1112 // Revisit the node. 1113 AddToWorklist(Op.getNode()); 1114 1115 // Replace the old value with the new one. 1116 ++NodesCombined; 1117 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1118 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); 1119 dbgs() << '\n'); 1120 1121 CommitTargetLoweringOpt(TLO); 1122 return true; 1123 } 1124 1125 /// Check the specified vector node value to see if it can be simplified or 1126 /// if things it uses can be simplified as it only uses some of the elements. 1127 /// If so, return true. 1128 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op, 1129 const APInt &DemandedElts, 1130 bool AssumeSingleUse) { 1131 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1132 APInt KnownUndef, KnownZero; 1133 if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, 1134 TLO, 0, AssumeSingleUse)) 1135 return false; 1136 1137 // Revisit the node. 1138 AddToWorklist(Op.getNode()); 1139 1140 // Replace the old value with the new one. 1141 ++NodesCombined; 1142 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1143 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); 1144 dbgs() << '\n'); 1145 1146 CommitTargetLoweringOpt(TLO); 1147 return true; 1148 } 1149 1150 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 1151 SDLoc DL(Load); 1152 EVT VT = Load->getValueType(0); 1153 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 1154 1155 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: "; 1156 Trunc.getNode()->dump(&DAG); dbgs() << '\n'); 1157 WorklistRemover DeadNodes(*this); 1158 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1159 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1160 deleteAndRecombine(Load); 1161 AddToWorklist(Trunc.getNode()); 1162 } 1163 1164 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1165 Replace = false; 1166 SDLoc DL(Op); 1167 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1168 LoadSDNode *LD = cast<LoadSDNode>(Op); 1169 EVT MemVT = LD->getMemoryVT(); 1170 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1171 : LD->getExtensionType(); 1172 Replace = true; 1173 return DAG.getExtLoad(ExtType, DL, PVT, 1174 LD->getChain(), LD->getBasePtr(), 1175 MemVT, LD->getMemOperand()); 1176 } 1177 1178 unsigned Opc = Op.getOpcode(); 1179 switch (Opc) { 1180 default: break; 1181 case ISD::AssertSext: 1182 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1183 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1184 break; 1185 case ISD::AssertZext: 1186 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1187 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1188 break; 1189 case ISD::Constant: { 1190 unsigned ExtOpc = 1191 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1192 return DAG.getNode(ExtOpc, DL, PVT, Op); 1193 } 1194 } 1195 1196 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1197 return SDValue(); 1198 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1199 } 1200 1201 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1202 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1203 return SDValue(); 1204 EVT OldVT = Op.getValueType(); 1205 SDLoc DL(Op); 1206 bool Replace = false; 1207 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1208 if (!NewOp.getNode()) 1209 return SDValue(); 1210 AddToWorklist(NewOp.getNode()); 1211 1212 if (Replace) 1213 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1214 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1215 DAG.getValueType(OldVT)); 1216 } 1217 1218 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1219 EVT OldVT = Op.getValueType(); 1220 SDLoc DL(Op); 1221 bool Replace = false; 1222 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1223 if (!NewOp.getNode()) 1224 return SDValue(); 1225 AddToWorklist(NewOp.getNode()); 1226 1227 if (Replace) 1228 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1229 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1230 } 1231 1232 /// Promote the specified integer binary operation if the target indicates it is 1233 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1234 /// i32 since i16 instructions are longer. 1235 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1236 if (!LegalOperations) 1237 return SDValue(); 1238 1239 EVT VT = Op.getValueType(); 1240 if (VT.isVector() || !VT.isInteger()) 1241 return SDValue(); 1242 1243 // If operation type is 'undesirable', e.g. i16 on x86, consider 1244 // promoting it. 1245 unsigned Opc = Op.getOpcode(); 1246 if (TLI.isTypeDesirableForOp(Opc, VT)) 1247 return SDValue(); 1248 1249 EVT PVT = VT; 1250 // Consult target whether it is a good idea to promote this operation and 1251 // what's the right type to promote it to. 1252 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1253 assert(PVT != VT && "Don't know what type to promote to!"); 1254 1255 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1256 1257 bool Replace0 = false; 1258 SDValue N0 = Op.getOperand(0); 1259 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1260 1261 bool Replace1 = false; 1262 SDValue N1 = Op.getOperand(1); 1263 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1264 SDLoc DL(Op); 1265 1266 SDValue RV = 1267 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1268 1269 // We are always replacing N0/N1's use in N and only need 1270 // additional replacements if there are additional uses. 1271 Replace0 &= !N0->hasOneUse(); 1272 Replace1 &= (N0 != N1) && !N1->hasOneUse(); 1273 1274 // Combine Op here so it is preserved past replacements. 1275 CombineTo(Op.getNode(), RV); 1276 1277 // If operands have a use ordering, make sure we deal with 1278 // predecessor first. 1279 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) { 1280 std::swap(N0, N1); 1281 std::swap(NN0, NN1); 1282 } 1283 1284 if (Replace0) { 1285 AddToWorklist(NN0.getNode()); 1286 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1287 } 1288 if (Replace1) { 1289 AddToWorklist(NN1.getNode()); 1290 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1291 } 1292 return Op; 1293 } 1294 return SDValue(); 1295 } 1296 1297 /// Promote the specified integer shift operation if the target indicates it is 1298 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1299 /// i32 since i16 instructions are longer. 1300 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) { 1301 if (!LegalOperations) 1302 return SDValue(); 1303 1304 EVT VT = Op.getValueType(); 1305 if (VT.isVector() || !VT.isInteger()) 1306 return SDValue(); 1307 1308 // If operation type is 'undesirable', e.g. i16 on x86, consider 1309 // promoting it. 1310 unsigned Opc = Op.getOpcode(); 1311 if (TLI.isTypeDesirableForOp(Opc, VT)) 1312 return SDValue(); 1313 1314 EVT PVT = VT; 1315 // Consult target whether it is a good idea to promote this operation and 1316 // what's the right type to promote it to. 1317 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1318 assert(PVT != VT && "Don't know what type to promote to!"); 1319 1320 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1321 1322 bool Replace = false; 1323 SDValue N0 = Op.getOperand(0); 1324 SDValue N1 = Op.getOperand(1); 1325 if (Opc == ISD::SRA) 1326 N0 = SExtPromoteOperand(N0, PVT); 1327 else if (Opc == ISD::SRL) 1328 N0 = ZExtPromoteOperand(N0, PVT); 1329 else 1330 N0 = PromoteOperand(N0, PVT, Replace); 1331 1332 if (!N0.getNode()) 1333 return SDValue(); 1334 1335 SDLoc DL(Op); 1336 SDValue RV = 1337 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1338 1339 AddToWorklist(N0.getNode()); 1340 if (Replace) 1341 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1342 1343 // Deal with Op being deleted. 1344 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1345 return RV; 1346 } 1347 return SDValue(); 1348 } 1349 1350 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1351 if (!LegalOperations) 1352 return SDValue(); 1353 1354 EVT VT = Op.getValueType(); 1355 if (VT.isVector() || !VT.isInteger()) 1356 return SDValue(); 1357 1358 // If operation type is 'undesirable', e.g. i16 on x86, consider 1359 // promoting it. 1360 unsigned Opc = Op.getOpcode(); 1361 if (TLI.isTypeDesirableForOp(Opc, VT)) 1362 return SDValue(); 1363 1364 EVT PVT = VT; 1365 // Consult target whether it is a good idea to promote this operation and 1366 // what's the right type to promote it to. 1367 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1368 assert(PVT != VT && "Don't know what type to promote to!"); 1369 // fold (aext (aext x)) -> (aext x) 1370 // fold (aext (zext x)) -> (zext x) 1371 // fold (aext (sext x)) -> (sext x) 1372 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1373 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1374 } 1375 return SDValue(); 1376 } 1377 1378 bool DAGCombiner::PromoteLoad(SDValue Op) { 1379 if (!LegalOperations) 1380 return false; 1381 1382 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1383 return false; 1384 1385 EVT VT = Op.getValueType(); 1386 if (VT.isVector() || !VT.isInteger()) 1387 return false; 1388 1389 // If operation type is 'undesirable', e.g. i16 on x86, consider 1390 // promoting it. 1391 unsigned Opc = Op.getOpcode(); 1392 if (TLI.isTypeDesirableForOp(Opc, VT)) 1393 return false; 1394 1395 EVT PVT = VT; 1396 // Consult target whether it is a good idea to promote this operation and 1397 // what's the right type to promote it to. 1398 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1399 assert(PVT != VT && "Don't know what type to promote to!"); 1400 1401 SDLoc DL(Op); 1402 SDNode *N = Op.getNode(); 1403 LoadSDNode *LD = cast<LoadSDNode>(N); 1404 EVT MemVT = LD->getMemoryVT(); 1405 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1406 : LD->getExtensionType(); 1407 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1408 LD->getChain(), LD->getBasePtr(), 1409 MemVT, LD->getMemOperand()); 1410 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1411 1412 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: "; 1413 Result.getNode()->dump(&DAG); dbgs() << '\n'); 1414 WorklistRemover DeadNodes(*this); 1415 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1416 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1417 deleteAndRecombine(N); 1418 AddToWorklist(Result.getNode()); 1419 return true; 1420 } 1421 return false; 1422 } 1423 1424 /// Recursively delete a node which has no uses and any operands for 1425 /// which it is the only use. 1426 /// 1427 /// Note that this both deletes the nodes and removes them from the worklist. 1428 /// It also adds any nodes who have had a user deleted to the worklist as they 1429 /// may now have only one use and subject to other combines. 1430 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1431 if (!N->use_empty()) 1432 return false; 1433 1434 SmallSetVector<SDNode *, 16> Nodes; 1435 Nodes.insert(N); 1436 do { 1437 N = Nodes.pop_back_val(); 1438 if (!N) 1439 continue; 1440 1441 if (N->use_empty()) { 1442 for (const SDValue &ChildN : N->op_values()) 1443 Nodes.insert(ChildN.getNode()); 1444 1445 removeFromWorklist(N); 1446 DAG.DeleteNode(N); 1447 } else { 1448 AddToWorklist(N); 1449 } 1450 } while (!Nodes.empty()); 1451 return true; 1452 } 1453 1454 //===----------------------------------------------------------------------===// 1455 // Main DAG Combiner implementation 1456 //===----------------------------------------------------------------------===// 1457 1458 void DAGCombiner::Run(CombineLevel AtLevel) { 1459 // set the instance variables, so that the various visit routines may use it. 1460 Level = AtLevel; 1461 LegalOperations = Level >= AfterLegalizeVectorOps; 1462 LegalTypes = Level >= AfterLegalizeTypes; 1463 1464 WorklistInserter AddNodes(*this); 1465 1466 // Add all the dag nodes to the worklist. 1467 for (SDNode &Node : DAG.allnodes()) 1468 AddToWorklist(&Node); 1469 1470 // Create a dummy node (which is not added to allnodes), that adds a reference 1471 // to the root node, preventing it from being deleted, and tracking any 1472 // changes of the root. 1473 HandleSDNode Dummy(DAG.getRoot()); 1474 1475 // While we have a valid worklist entry node, try to combine it. 1476 while (SDNode *N = getNextWorklistEntry()) { 1477 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1478 // N is deleted from the DAG, since they too may now be dead or may have a 1479 // reduced number of uses, allowing other xforms. 1480 if (recursivelyDeleteUnusedNodes(N)) 1481 continue; 1482 1483 WorklistRemover DeadNodes(*this); 1484 1485 // If this combine is running after legalizing the DAG, re-legalize any 1486 // nodes pulled off the worklist. 1487 if (Level == AfterLegalizeDAG) { 1488 SmallSetVector<SDNode *, 16> UpdatedNodes; 1489 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1490 1491 for (SDNode *LN : UpdatedNodes) { 1492 AddToWorklist(LN); 1493 AddUsersToWorklist(LN); 1494 } 1495 if (!NIsValid) 1496 continue; 1497 } 1498 1499 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1500 1501 // Add any operands of the new node which have not yet been combined to the 1502 // worklist as well. Because the worklist uniques things already, this 1503 // won't repeatedly process the same operand. 1504 CombinedNodes.insert(N); 1505 for (const SDValue &ChildN : N->op_values()) 1506 if (!CombinedNodes.count(ChildN.getNode())) 1507 AddToWorklist(ChildN.getNode()); 1508 1509 SDValue RV = combine(N); 1510 1511 if (!RV.getNode()) 1512 continue; 1513 1514 ++NodesCombined; 1515 1516 // If we get back the same node we passed in, rather than a new node or 1517 // zero, we know that the node must have defined multiple values and 1518 // CombineTo was used. Since CombineTo takes care of the worklist 1519 // mechanics for us, we have no work to do in this case. 1520 if (RV.getNode() == N) 1521 continue; 1522 1523 assert(N->getOpcode() != ISD::DELETED_NODE && 1524 RV.getOpcode() != ISD::DELETED_NODE && 1525 "Node was deleted but visit returned new node!"); 1526 1527 LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG)); 1528 1529 if (N->getNumValues() == RV.getNode()->getNumValues()) 1530 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1531 else { 1532 assert(N->getValueType(0) == RV.getValueType() && 1533 N->getNumValues() == 1 && "Type mismatch"); 1534 DAG.ReplaceAllUsesWith(N, &RV); 1535 } 1536 1537 // Push the new node and any users onto the worklist 1538 AddToWorklist(RV.getNode()); 1539 AddUsersToWorklist(RV.getNode()); 1540 1541 // Finally, if the node is now dead, remove it from the graph. The node 1542 // may not be dead if the replacement process recursively simplified to 1543 // something else needing this node. This will also take care of adding any 1544 // operands which have lost a user to the worklist. 1545 recursivelyDeleteUnusedNodes(N); 1546 } 1547 1548 // If the root changed (e.g. it was a dead load, update the root). 1549 DAG.setRoot(Dummy.getValue()); 1550 DAG.RemoveDeadNodes(); 1551 } 1552 1553 SDValue DAGCombiner::visit(SDNode *N) { 1554 switch (N->getOpcode()) { 1555 default: break; 1556 case ISD::TokenFactor: return visitTokenFactor(N); 1557 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1558 case ISD::ADD: return visitADD(N); 1559 case ISD::SUB: return visitSUB(N); 1560 case ISD::SADDSAT: 1561 case ISD::UADDSAT: return visitADDSAT(N); 1562 case ISD::SSUBSAT: 1563 case ISD::USUBSAT: return visitSUBSAT(N); 1564 case ISD::ADDC: return visitADDC(N); 1565 case ISD::SADDO: 1566 case ISD::UADDO: return visitADDO(N); 1567 case ISD::SUBC: return visitSUBC(N); 1568 case ISD::SSUBO: 1569 case ISD::USUBO: return visitSUBO(N); 1570 case ISD::ADDE: return visitADDE(N); 1571 case ISD::ADDCARRY: return visitADDCARRY(N); 1572 case ISD::SUBE: return visitSUBE(N); 1573 case ISD::SUBCARRY: return visitSUBCARRY(N); 1574 case ISD::MUL: return visitMUL(N); 1575 case ISD::SDIV: return visitSDIV(N); 1576 case ISD::UDIV: return visitUDIV(N); 1577 case ISD::SREM: 1578 case ISD::UREM: return visitREM(N); 1579 case ISD::MULHU: return visitMULHU(N); 1580 case ISD::MULHS: return visitMULHS(N); 1581 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1582 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1583 case ISD::SMULO: 1584 case ISD::UMULO: return visitMULO(N); 1585 case ISD::SMIN: 1586 case ISD::SMAX: 1587 case ISD::UMIN: 1588 case ISD::UMAX: return visitIMINMAX(N); 1589 case ISD::AND: return visitAND(N); 1590 case ISD::OR: return visitOR(N); 1591 case ISD::XOR: return visitXOR(N); 1592 case ISD::SHL: return visitSHL(N); 1593 case ISD::SRA: return visitSRA(N); 1594 case ISD::SRL: return visitSRL(N); 1595 case ISD::ROTR: 1596 case ISD::ROTL: return visitRotate(N); 1597 case ISD::FSHL: 1598 case ISD::FSHR: return visitFunnelShift(N); 1599 case ISD::ABS: return visitABS(N); 1600 case ISD::BSWAP: return visitBSWAP(N); 1601 case ISD::BITREVERSE: return visitBITREVERSE(N); 1602 case ISD::CTLZ: return visitCTLZ(N); 1603 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1604 case ISD::CTTZ: return visitCTTZ(N); 1605 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1606 case ISD::CTPOP: return visitCTPOP(N); 1607 case ISD::SELECT: return visitSELECT(N); 1608 case ISD::VSELECT: return visitVSELECT(N); 1609 case ISD::SELECT_CC: return visitSELECT_CC(N); 1610 case ISD::SETCC: return visitSETCC(N); 1611 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1612 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1613 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1614 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1615 case ISD::AssertSext: 1616 case ISD::AssertZext: return visitAssertExt(N); 1617 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1618 case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N); 1619 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitZERO_EXTEND_VECTOR_INREG(N); 1620 case ISD::TRUNCATE: return visitTRUNCATE(N); 1621 case ISD::BITCAST: return visitBITCAST(N); 1622 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1623 case ISD::FADD: return visitFADD(N); 1624 case ISD::FSUB: return visitFSUB(N); 1625 case ISD::FMUL: return visitFMUL(N); 1626 case ISD::FMA: return visitFMA(N); 1627 case ISD::FDIV: return visitFDIV(N); 1628 case ISD::FREM: return visitFREM(N); 1629 case ISD::FSQRT: return visitFSQRT(N); 1630 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1631 case ISD::FPOW: return visitFPOW(N); 1632 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1633 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1634 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1635 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1636 case ISD::FP_ROUND: return visitFP_ROUND(N); 1637 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N); 1638 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1639 case ISD::FNEG: return visitFNEG(N); 1640 case ISD::FABS: return visitFABS(N); 1641 case ISD::FFLOOR: return visitFFLOOR(N); 1642 case ISD::FMINNUM: return visitFMINNUM(N); 1643 case ISD::FMAXNUM: return visitFMAXNUM(N); 1644 case ISD::FMINIMUM: return visitFMINIMUM(N); 1645 case ISD::FMAXIMUM: return visitFMAXIMUM(N); 1646 case ISD::FCEIL: return visitFCEIL(N); 1647 case ISD::FTRUNC: return visitFTRUNC(N); 1648 case ISD::BRCOND: return visitBRCOND(N); 1649 case ISD::BR_CC: return visitBR_CC(N); 1650 case ISD::LOAD: return visitLOAD(N); 1651 case ISD::STORE: return visitSTORE(N); 1652 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1653 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1654 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1655 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1656 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1657 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1658 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1659 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1660 case ISD::MGATHER: return visitMGATHER(N); 1661 case ISD::MLOAD: return visitMLOAD(N); 1662 case ISD::MSCATTER: return visitMSCATTER(N); 1663 case ISD::MSTORE: return visitMSTORE(N); 1664 case ISD::LIFETIME_END: return visitLIFETIME_END(N); 1665 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1666 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1667 case ISD::VECREDUCE_FADD: 1668 case ISD::VECREDUCE_FMUL: 1669 case ISD::VECREDUCE_ADD: 1670 case ISD::VECREDUCE_MUL: 1671 case ISD::VECREDUCE_AND: 1672 case ISD::VECREDUCE_OR: 1673 case ISD::VECREDUCE_XOR: 1674 case ISD::VECREDUCE_SMAX: 1675 case ISD::VECREDUCE_SMIN: 1676 case ISD::VECREDUCE_UMAX: 1677 case ISD::VECREDUCE_UMIN: 1678 case ISD::VECREDUCE_FMAX: 1679 case ISD::VECREDUCE_FMIN: return visitVECREDUCE(N); 1680 } 1681 return SDValue(); 1682 } 1683 1684 SDValue DAGCombiner::combine(SDNode *N) { 1685 SDValue RV = visit(N); 1686 1687 // If nothing happened, try a target-specific DAG combine. 1688 if (!RV.getNode()) { 1689 assert(N->getOpcode() != ISD::DELETED_NODE && 1690 "Node was deleted but visit returned NULL!"); 1691 1692 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1693 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1694 1695 // Expose the DAG combiner to the target combiner impls. 1696 TargetLowering::DAGCombinerInfo 1697 DagCombineInfo(DAG, Level, false, this); 1698 1699 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1700 } 1701 } 1702 1703 // If nothing happened still, try promoting the operation. 1704 if (!RV.getNode()) { 1705 switch (N->getOpcode()) { 1706 default: break; 1707 case ISD::ADD: 1708 case ISD::SUB: 1709 case ISD::MUL: 1710 case ISD::AND: 1711 case ISD::OR: 1712 case ISD::XOR: 1713 RV = PromoteIntBinOp(SDValue(N, 0)); 1714 break; 1715 case ISD::SHL: 1716 case ISD::SRA: 1717 case ISD::SRL: 1718 RV = PromoteIntShiftOp(SDValue(N, 0)); 1719 break; 1720 case ISD::SIGN_EXTEND: 1721 case ISD::ZERO_EXTEND: 1722 case ISD::ANY_EXTEND: 1723 RV = PromoteExtend(SDValue(N, 0)); 1724 break; 1725 case ISD::LOAD: 1726 if (PromoteLoad(SDValue(N, 0))) 1727 RV = SDValue(N, 0); 1728 break; 1729 } 1730 } 1731 1732 // If N is a commutative binary node, try eliminate it if the commuted 1733 // version is already present in the DAG. 1734 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1735 N->getNumValues() == 1) { 1736 SDValue N0 = N->getOperand(0); 1737 SDValue N1 = N->getOperand(1); 1738 1739 // Constant operands are canonicalized to RHS. 1740 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) { 1741 SDValue Ops[] = {N1, N0}; 1742 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1743 N->getFlags()); 1744 if (CSENode) 1745 return SDValue(CSENode, 0); 1746 } 1747 } 1748 1749 return RV; 1750 } 1751 1752 /// Given a node, return its input chain if it has one, otherwise return a null 1753 /// sd operand. 1754 static SDValue getInputChainForNode(SDNode *N) { 1755 if (unsigned NumOps = N->getNumOperands()) { 1756 if (N->getOperand(0).getValueType() == MVT::Other) 1757 return N->getOperand(0); 1758 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1759 return N->getOperand(NumOps-1); 1760 for (unsigned i = 1; i < NumOps-1; ++i) 1761 if (N->getOperand(i).getValueType() == MVT::Other) 1762 return N->getOperand(i); 1763 } 1764 return SDValue(); 1765 } 1766 1767 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1768 // If N has two operands, where one has an input chain equal to the other, 1769 // the 'other' chain is redundant. 1770 if (N->getNumOperands() == 2) { 1771 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1772 return N->getOperand(0); 1773 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1774 return N->getOperand(1); 1775 } 1776 1777 // Don't simplify token factors if optnone. 1778 if (OptLevel == CodeGenOpt::None) 1779 return SDValue(); 1780 1781 // If the sole user is a token factor, we should make sure we have a 1782 // chance to merge them together. This prevents TF chains from inhibiting 1783 // optimizations. 1784 if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor) 1785 AddToWorklist(*(N->use_begin())); 1786 1787 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1788 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1789 SmallPtrSet<SDNode*, 16> SeenOps; 1790 bool Changed = false; // If we should replace this token factor. 1791 1792 // Start out with this token factor. 1793 TFs.push_back(N); 1794 1795 // Iterate through token factors. The TFs grows when new token factors are 1796 // encountered. 1797 for (unsigned i = 0; i < TFs.size(); ++i) { 1798 SDNode *TF = TFs[i]; 1799 1800 // Check each of the operands. 1801 for (const SDValue &Op : TF->op_values()) { 1802 switch (Op.getOpcode()) { 1803 case ISD::EntryToken: 1804 // Entry tokens don't need to be added to the list. They are 1805 // redundant. 1806 Changed = true; 1807 break; 1808 1809 case ISD::TokenFactor: 1810 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1811 // Queue up for processing. 1812 TFs.push_back(Op.getNode()); 1813 // Clean up in case the token factor is removed. 1814 AddToWorklist(Op.getNode()); 1815 Changed = true; 1816 break; 1817 } 1818 LLVM_FALLTHROUGH; 1819 1820 default: 1821 // Only add if it isn't already in the list. 1822 if (SeenOps.insert(Op.getNode()).second) 1823 Ops.push_back(Op); 1824 else 1825 Changed = true; 1826 break; 1827 } 1828 } 1829 } 1830 1831 // Remove Nodes that are chained to another node in the list. Do so 1832 // by walking up chains breath-first stopping when we've seen 1833 // another operand. In general we must climb to the EntryNode, but we can exit 1834 // early if we find all remaining work is associated with just one operand as 1835 // no further pruning is possible. 1836 1837 // List of nodes to search through and original Ops from which they originate. 1838 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1839 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1840 SmallPtrSet<SDNode *, 16> SeenChains; 1841 bool DidPruneOps = false; 1842 1843 unsigned NumLeftToConsider = 0; 1844 for (const SDValue &Op : Ops) { 1845 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1846 OpWorkCount.push_back(1); 1847 } 1848 1849 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1850 // If this is an Op, we can remove the op from the list. Remark any 1851 // search associated with it as from the current OpNumber. 1852 if (SeenOps.count(Op) != 0) { 1853 Changed = true; 1854 DidPruneOps = true; 1855 unsigned OrigOpNumber = 0; 1856 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1857 OrigOpNumber++; 1858 assert((OrigOpNumber != Ops.size()) && 1859 "expected to find TokenFactor Operand"); 1860 // Re-mark worklist from OrigOpNumber to OpNumber 1861 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1862 if (Worklist[i].second == OrigOpNumber) { 1863 Worklist[i].second = OpNumber; 1864 } 1865 } 1866 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1867 OpWorkCount[OrigOpNumber] = 0; 1868 NumLeftToConsider--; 1869 } 1870 // Add if it's a new chain 1871 if (SeenChains.insert(Op).second) { 1872 OpWorkCount[OpNumber]++; 1873 Worklist.push_back(std::make_pair(Op, OpNumber)); 1874 } 1875 }; 1876 1877 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1878 // We need at least be consider at least 2 Ops to prune. 1879 if (NumLeftToConsider <= 1) 1880 break; 1881 auto CurNode = Worklist[i].first; 1882 auto CurOpNumber = Worklist[i].second; 1883 assert((OpWorkCount[CurOpNumber] > 0) && 1884 "Node should not appear in worklist"); 1885 switch (CurNode->getOpcode()) { 1886 case ISD::EntryToken: 1887 // Hitting EntryToken is the only way for the search to terminate without 1888 // hitting 1889 // another operand's search. Prevent us from marking this operand 1890 // considered. 1891 NumLeftToConsider++; 1892 break; 1893 case ISD::TokenFactor: 1894 for (const SDValue &Op : CurNode->op_values()) 1895 AddToWorklist(i, Op.getNode(), CurOpNumber); 1896 break; 1897 case ISD::LIFETIME_START: 1898 case ISD::LIFETIME_END: 1899 case ISD::CopyFromReg: 1900 case ISD::CopyToReg: 1901 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1902 break; 1903 default: 1904 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1905 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1906 break; 1907 } 1908 OpWorkCount[CurOpNumber]--; 1909 if (OpWorkCount[CurOpNumber] == 0) 1910 NumLeftToConsider--; 1911 } 1912 1913 // If we've changed things around then replace token factor. 1914 if (Changed) { 1915 SDValue Result; 1916 if (Ops.empty()) { 1917 // The entry token is the only possible outcome. 1918 Result = DAG.getEntryNode(); 1919 } else { 1920 if (DidPruneOps) { 1921 SmallVector<SDValue, 8> PrunedOps; 1922 // 1923 for (const SDValue &Op : Ops) { 1924 if (SeenChains.count(Op.getNode()) == 0) 1925 PrunedOps.push_back(Op); 1926 } 1927 Result = DAG.getTokenFactor(SDLoc(N), PrunedOps); 1928 } else { 1929 Result = DAG.getTokenFactor(SDLoc(N), Ops); 1930 } 1931 } 1932 return Result; 1933 } 1934 return SDValue(); 1935 } 1936 1937 /// MERGE_VALUES can always be eliminated. 1938 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 1939 WorklistRemover DeadNodes(*this); 1940 // Replacing results may cause a different MERGE_VALUES to suddenly 1941 // be CSE'd with N, and carry its uses with it. Iterate until no 1942 // uses remain, to ensure that the node can be safely deleted. 1943 // First add the users of this node to the work list so that they 1944 // can be tried again once they have new operands. 1945 AddUsersToWorklist(N); 1946 do { 1947 // Do as a single replacement to avoid rewalking use lists. 1948 SmallVector<SDValue, 8> Ops; 1949 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 1950 Ops.push_back(N->getOperand(i)); 1951 DAG.ReplaceAllUsesWith(N, Ops.data()); 1952 } while (!N->use_empty()); 1953 deleteAndRecombine(N); 1954 return SDValue(N, 0); // Return N so it doesn't get rechecked! 1955 } 1956 1957 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 1958 /// ConstantSDNode pointer else nullptr. 1959 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 1960 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 1961 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 1962 } 1963 1964 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 1965 assert(ISD::isBinaryOp(BO) && "Unexpected binary operator"); 1966 1967 // Don't do this unless the old select is going away. We want to eliminate the 1968 // binary operator, not replace a binop with a select. 1969 // TODO: Handle ISD::SELECT_CC. 1970 unsigned SelOpNo = 0; 1971 SDValue Sel = BO->getOperand(0); 1972 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) { 1973 SelOpNo = 1; 1974 Sel = BO->getOperand(1); 1975 } 1976 1977 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 1978 return SDValue(); 1979 1980 SDValue CT = Sel.getOperand(1); 1981 if (!isConstantOrConstantVector(CT, true) && 1982 !isConstantFPBuildVectorOrConstantFP(CT)) 1983 return SDValue(); 1984 1985 SDValue CF = Sel.getOperand(2); 1986 if (!isConstantOrConstantVector(CF, true) && 1987 !isConstantFPBuildVectorOrConstantFP(CF)) 1988 return SDValue(); 1989 1990 // Bail out if any constants are opaque because we can't constant fold those. 1991 // The exception is "and" and "or" with either 0 or -1 in which case we can 1992 // propagate non constant operands into select. I.e.: 1993 // and (select Cond, 0, -1), X --> select Cond, 0, X 1994 // or X, (select Cond, -1, 0) --> select Cond, -1, X 1995 auto BinOpcode = BO->getOpcode(); 1996 bool CanFoldNonConst = 1997 (BinOpcode == ISD::AND || BinOpcode == ISD::OR) && 1998 (isNullOrNullSplat(CT) || isAllOnesOrAllOnesSplat(CT)) && 1999 (isNullOrNullSplat(CF) || isAllOnesOrAllOnesSplat(CF)); 2000 2001 SDValue CBO = BO->getOperand(SelOpNo ^ 1); 2002 if (!CanFoldNonConst && 2003 !isConstantOrConstantVector(CBO, true) && 2004 !isConstantFPBuildVectorOrConstantFP(CBO)) 2005 return SDValue(); 2006 2007 EVT VT = Sel.getValueType(); 2008 2009 // In case of shift value and shift amount may have different VT. For instance 2010 // on x86 shift amount is i8 regardles of LHS type. Bail out if we have 2011 // swapped operands and value types do not match. NB: x86 is fine if operands 2012 // are not swapped with shift amount VT being not bigger than shifted value. 2013 // TODO: that is possible to check for a shift operation, correct VTs and 2014 // still perform optimization on x86 if needed. 2015 if (SelOpNo && VT != CBO.getValueType()) 2016 return SDValue(); 2017 2018 // We have a select-of-constants followed by a binary operator with a 2019 // constant. Eliminate the binop by pulling the constant math into the select. 2020 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO 2021 SDLoc DL(Sel); 2022 SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT) 2023 : DAG.getNode(BinOpcode, DL, VT, CT, CBO); 2024 if (!CanFoldNonConst && !NewCT.isUndef() && 2025 !isConstantOrConstantVector(NewCT, true) && 2026 !isConstantFPBuildVectorOrConstantFP(NewCT)) 2027 return SDValue(); 2028 2029 SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF) 2030 : DAG.getNode(BinOpcode, DL, VT, CF, CBO); 2031 if (!CanFoldNonConst && !NewCF.isUndef() && 2032 !isConstantOrConstantVector(NewCF, true) && 2033 !isConstantFPBuildVectorOrConstantFP(NewCF)) 2034 return SDValue(); 2035 2036 return DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 2037 } 2038 2039 static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) { 2040 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 2041 "Expecting add or sub"); 2042 2043 // Match a constant operand and a zext operand for the math instruction: 2044 // add Z, C 2045 // sub C, Z 2046 bool IsAdd = N->getOpcode() == ISD::ADD; 2047 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0); 2048 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1); 2049 auto *CN = dyn_cast<ConstantSDNode>(C); 2050 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND) 2051 return SDValue(); 2052 2053 // Match the zext operand as a setcc of a boolean. 2054 if (Z.getOperand(0).getOpcode() != ISD::SETCC || 2055 Z.getOperand(0).getValueType() != MVT::i1) 2056 return SDValue(); 2057 2058 // Match the compare as: setcc (X & 1), 0, eq. 2059 SDValue SetCC = Z.getOperand(0); 2060 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 2061 if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) || 2062 SetCC.getOperand(0).getOpcode() != ISD::AND || 2063 !isOneConstant(SetCC.getOperand(0).getOperand(1))) 2064 return SDValue(); 2065 2066 // We are adding/subtracting a constant and an inverted low bit. Turn that 2067 // into a subtract/add of the low bit with incremented/decremented constant: 2068 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1)) 2069 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1)) 2070 EVT VT = C.getValueType(); 2071 SDLoc DL(N); 2072 SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT); 2073 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) : 2074 DAG.getConstant(CN->getAPIntValue() - 1, DL, VT); 2075 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit); 2076 } 2077 2078 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into 2079 /// a shift and add with a different constant. 2080 static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) { 2081 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 2082 "Expecting add or sub"); 2083 2084 // We need a constant operand for the add/sub, and the other operand is a 2085 // logical shift right: add (srl), C or sub C, (srl). 2086 bool IsAdd = N->getOpcode() == ISD::ADD; 2087 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0); 2088 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1); 2089 ConstantSDNode *C = isConstOrConstSplat(ConstantOp); 2090 if (!C || ShiftOp.getOpcode() != ISD::SRL) 2091 return SDValue(); 2092 2093 // The shift must be of a 'not' value. 2094 SDValue Not = ShiftOp.getOperand(0); 2095 if (!Not.hasOneUse() || !isBitwiseNot(Not)) 2096 return SDValue(); 2097 2098 // The shift must be moving the sign bit to the least-significant-bit. 2099 EVT VT = ShiftOp.getValueType(); 2100 SDValue ShAmt = ShiftOp.getOperand(1); 2101 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 2102 if (!ShAmtC || ShAmtC->getZExtValue() != VT.getScalarSizeInBits() - 1) 2103 return SDValue(); 2104 2105 // Eliminate the 'not' by adjusting the shift and add/sub constant: 2106 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1) 2107 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1) 2108 SDLoc DL(N); 2109 auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL; 2110 SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt); 2111 APInt NewC = IsAdd ? C->getAPIntValue() + 1 : C->getAPIntValue() - 1; 2112 return DAG.getNode(ISD::ADD, DL, VT, NewShift, DAG.getConstant(NewC, DL, VT)); 2113 } 2114 2115 /// Try to fold a node that behaves like an ADD (note that N isn't necessarily 2116 /// an ISD::ADD here, it could for example be an ISD::OR if we know that there 2117 /// are no common bits set in the operands). 2118 SDValue DAGCombiner::visitADDLike(SDNode *N) { 2119 SDValue N0 = N->getOperand(0); 2120 SDValue N1 = N->getOperand(1); 2121 EVT VT = N0.getValueType(); 2122 SDLoc DL(N); 2123 2124 // fold vector ops 2125 if (VT.isVector()) { 2126 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2127 return FoldedVOp; 2128 2129 // fold (add x, 0) -> x, vector edition 2130 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2131 return N0; 2132 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2133 return N1; 2134 } 2135 2136 // fold (add x, undef) -> undef 2137 if (N0.isUndef()) 2138 return N0; 2139 2140 if (N1.isUndef()) 2141 return N1; 2142 2143 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 2144 // canonicalize constant to RHS 2145 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2146 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 2147 // fold (add c1, c2) -> c1+c2 2148 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, N0.getNode(), 2149 N1.getNode()); 2150 } 2151 2152 // fold (add x, 0) -> x 2153 if (isNullConstant(N1)) 2154 return N0; 2155 2156 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 2157 // fold ((c1-A)+c2) -> (c1+c2)-A 2158 if (N0.getOpcode() == ISD::SUB && 2159 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 2160 // FIXME: Adding 2 constants should be handled by FoldConstantArithmetic. 2161 return DAG.getNode(ISD::SUB, DL, VT, 2162 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 2163 N0.getOperand(1)); 2164 } 2165 2166 // add (sext i1 X), 1 -> zext (not i1 X) 2167 // We don't transform this pattern: 2168 // add (zext i1 X), -1 -> sext (not i1 X) 2169 // because most (?) targets generate better code for the zext form. 2170 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 2171 isOneOrOneSplat(N1)) { 2172 SDValue X = N0.getOperand(0); 2173 if ((!LegalOperations || 2174 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 2175 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 2176 X.getScalarValueSizeInBits() == 1) { 2177 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 2178 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 2179 } 2180 } 2181 2182 // Undo the add -> or combine to merge constant offsets from a frame index. 2183 if (N0.getOpcode() == ISD::OR && 2184 isa<FrameIndexSDNode>(N0.getOperand(0)) && 2185 isa<ConstantSDNode>(N0.getOperand(1)) && 2186 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { 2187 SDValue Add0 = DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(1)); 2188 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0); 2189 } 2190 } 2191 2192 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2193 return NewSel; 2194 2195 // reassociate add 2196 if (SDValue RADD = ReassociateOps(ISD::ADD, DL, N0, N1, N->getFlags())) 2197 return RADD; 2198 2199 // fold ((0-A) + B) -> B-A 2200 if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0))) 2201 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2202 2203 // fold (A + (0-B)) -> A-B 2204 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0))) 2205 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 2206 2207 // fold (A+(B-A)) -> B 2208 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 2209 return N1.getOperand(0); 2210 2211 // fold ((B-A)+A) -> B 2212 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 2213 return N0.getOperand(0); 2214 2215 // fold ((A-B)+(C-A)) -> (C-B) 2216 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB && 2217 N0.getOperand(0) == N1.getOperand(1)) 2218 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2219 N0.getOperand(1)); 2220 2221 // fold ((A-B)+(B-C)) -> (A-C) 2222 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB && 2223 N0.getOperand(1) == N1.getOperand(0)) 2224 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2225 N1.getOperand(1)); 2226 2227 // fold (A+(B-(A+C))) to (B-C) 2228 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2229 N0 == N1.getOperand(1).getOperand(0)) 2230 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2231 N1.getOperand(1).getOperand(1)); 2232 2233 // fold (A+(B-(C+A))) to (B-C) 2234 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2235 N0 == N1.getOperand(1).getOperand(1)) 2236 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2237 N1.getOperand(1).getOperand(0)); 2238 2239 // fold (A+((B-A)+or-C)) to (B+or-C) 2240 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 2241 N1.getOperand(0).getOpcode() == ISD::SUB && 2242 N0 == N1.getOperand(0).getOperand(1)) 2243 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 2244 N1.getOperand(1)); 2245 2246 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 2247 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 2248 SDValue N00 = N0.getOperand(0); 2249 SDValue N01 = N0.getOperand(1); 2250 SDValue N10 = N1.getOperand(0); 2251 SDValue N11 = N1.getOperand(1); 2252 2253 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 2254 return DAG.getNode(ISD::SUB, DL, VT, 2255 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 2256 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 2257 } 2258 2259 // fold (add (umax X, C), -C) --> (usubsat X, C) 2260 if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) { 2261 auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) { 2262 return (!Max && !Op) || 2263 (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue())); 2264 }; 2265 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT, 2266 /*AllowUndefs*/ true)) 2267 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0), 2268 N0.getOperand(1)); 2269 } 2270 2271 if (SimplifyDemandedBits(SDValue(N, 0))) 2272 return SDValue(N, 0); 2273 2274 if (isOneOrOneSplat(N1)) { 2275 // fold (add (xor a, -1), 1) -> (sub 0, a) 2276 if (isBitwiseNot(N0)) 2277 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 2278 N0.getOperand(0)); 2279 2280 // fold (add (add (xor a, -1), b), 1) -> (sub b, a) 2281 if (N0.getOpcode() == ISD::ADD || 2282 N0.getOpcode() == ISD::UADDO || 2283 N0.getOpcode() == ISD::SADDO) { 2284 SDValue A, Xor; 2285 2286 if (isBitwiseNot(N0.getOperand(0))) { 2287 A = N0.getOperand(1); 2288 Xor = N0.getOperand(0); 2289 } else if (isBitwiseNot(N0.getOperand(1))) { 2290 A = N0.getOperand(0); 2291 Xor = N0.getOperand(1); 2292 } 2293 2294 if (Xor) 2295 return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0)); 2296 } 2297 } 2298 2299 if (SDValue Combined = visitADDLikeCommutative(N0, N1, N)) 2300 return Combined; 2301 2302 if (SDValue Combined = visitADDLikeCommutative(N1, N0, N)) 2303 return Combined; 2304 2305 return SDValue(); 2306 } 2307 2308 SDValue DAGCombiner::visitADD(SDNode *N) { 2309 SDValue N0 = N->getOperand(0); 2310 SDValue N1 = N->getOperand(1); 2311 EVT VT = N0.getValueType(); 2312 SDLoc DL(N); 2313 2314 if (SDValue Combined = visitADDLike(N)) 2315 return Combined; 2316 2317 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 2318 return V; 2319 2320 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 2321 return V; 2322 2323 // fold (a+b) -> (a|b) iff a and b share no bits. 2324 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 2325 DAG.haveNoCommonBitsSet(N0, N1)) 2326 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 2327 2328 return SDValue(); 2329 } 2330 2331 SDValue DAGCombiner::visitADDSAT(SDNode *N) { 2332 unsigned Opcode = N->getOpcode(); 2333 SDValue N0 = N->getOperand(0); 2334 SDValue N1 = N->getOperand(1); 2335 EVT VT = N0.getValueType(); 2336 SDLoc DL(N); 2337 2338 // fold vector ops 2339 if (VT.isVector()) { 2340 // TODO SimplifyVBinOp 2341 2342 // fold (add_sat x, 0) -> x, vector edition 2343 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2344 return N0; 2345 if (ISD::isBuildVectorAllZeros(N0.getNode())) 2346 return N1; 2347 } 2348 2349 // fold (add_sat x, undef) -> -1 2350 if (N0.isUndef() || N1.isUndef()) 2351 return DAG.getAllOnesConstant(DL, VT); 2352 2353 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 2354 // canonicalize constant to RHS 2355 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2356 return DAG.getNode(Opcode, DL, VT, N1, N0); 2357 // fold (add_sat c1, c2) -> c3 2358 return DAG.FoldConstantArithmetic(Opcode, DL, VT, N0.getNode(), 2359 N1.getNode()); 2360 } 2361 2362 // fold (add_sat x, 0) -> x 2363 if (isNullConstant(N1)) 2364 return N0; 2365 2366 // If it cannot overflow, transform into an add. 2367 if (Opcode == ISD::UADDSAT) 2368 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2369 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 2370 2371 return SDValue(); 2372 } 2373 2374 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 2375 bool Masked = false; 2376 2377 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 2378 while (true) { 2379 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 2380 V = V.getOperand(0); 2381 continue; 2382 } 2383 2384 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 2385 Masked = true; 2386 V = V.getOperand(0); 2387 continue; 2388 } 2389 2390 break; 2391 } 2392 2393 // If this is not a carry, return. 2394 if (V.getResNo() != 1) 2395 return SDValue(); 2396 2397 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2398 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2399 return SDValue(); 2400 2401 EVT VT = V.getNode()->getValueType(0); 2402 if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT)) 2403 return SDValue(); 2404 2405 // If the result is masked, then no matter what kind of bool it is we can 2406 // return. If it isn't, then we need to make sure the bool type is either 0 or 2407 // 1 and not other values. 2408 if (Masked || 2409 TLI.getBooleanContents(V.getValueType()) == 2410 TargetLoweringBase::ZeroOrOneBooleanContent) 2411 return V; 2412 2413 return SDValue(); 2414 } 2415 2416 /// Given the operands of an add/sub operation, see if the 2nd operand is a 2417 /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert 2418 /// the opcode and bypass the mask operation. 2419 static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1, 2420 SelectionDAG &DAG, const SDLoc &DL) { 2421 if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1))) 2422 return SDValue(); 2423 2424 EVT VT = N0.getValueType(); 2425 if (DAG.ComputeNumSignBits(N1.getOperand(0)) != VT.getScalarSizeInBits()) 2426 return SDValue(); 2427 2428 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X 2429 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X 2430 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N1.getOperand(0)); 2431 } 2432 2433 /// Helper for doing combines based on N0 and N1 being added to each other. 2434 SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1, 2435 SDNode *LocReference) { 2436 EVT VT = N0.getValueType(); 2437 SDLoc DL(LocReference); 2438 2439 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2440 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2441 isNullOrNullSplat(N1.getOperand(0).getOperand(0))) 2442 return DAG.getNode(ISD::SUB, DL, VT, N0, 2443 DAG.getNode(ISD::SHL, DL, VT, 2444 N1.getOperand(0).getOperand(1), 2445 N1.getOperand(1))); 2446 2447 if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL)) 2448 return V; 2449 2450 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1' 2451 // rather than 'add 0/-1' (the zext should get folded). 2452 // add (sext i1 Y), X --> sub X, (zext i1 Y) 2453 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2454 N0.getOperand(0).getScalarValueSizeInBits() == 1 && 2455 TLI.getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent) { 2456 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2457 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2458 } 2459 2460 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2461 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2462 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2463 if (TN->getVT() == MVT::i1) { 2464 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2465 DAG.getConstant(1, DL, VT)); 2466 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2467 } 2468 } 2469 2470 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2471 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) && 2472 N1.getResNo() == 0) 2473 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2474 N0, N1.getOperand(0), N1.getOperand(2)); 2475 2476 // (add X, Carry) -> (addcarry X, 0, Carry) 2477 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2478 if (SDValue Carry = getAsCarry(TLI, N1)) 2479 return DAG.getNode(ISD::ADDCARRY, DL, 2480 DAG.getVTList(VT, Carry.getValueType()), N0, 2481 DAG.getConstant(0, DL, VT), Carry); 2482 2483 return SDValue(); 2484 } 2485 2486 SDValue DAGCombiner::visitADDC(SDNode *N) { 2487 SDValue N0 = N->getOperand(0); 2488 SDValue N1 = N->getOperand(1); 2489 EVT VT = N0.getValueType(); 2490 SDLoc DL(N); 2491 2492 // If the flag result is dead, turn this into an ADD. 2493 if (!N->hasAnyUseOfValue(1)) 2494 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2495 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2496 2497 // canonicalize constant to RHS. 2498 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2499 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2500 if (N0C && !N1C) 2501 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2502 2503 // fold (addc x, 0) -> x + no carry out 2504 if (isNullConstant(N1)) 2505 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2506 DL, MVT::Glue)); 2507 2508 // If it cannot overflow, transform into an add. 2509 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2510 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2511 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2512 2513 return SDValue(); 2514 } 2515 2516 static SDValue flipBoolean(SDValue V, const SDLoc &DL, 2517 SelectionDAG &DAG, const TargetLowering &TLI) { 2518 EVT VT = V.getValueType(); 2519 2520 SDValue Cst; 2521 switch (TLI.getBooleanContents(VT)) { 2522 case TargetLowering::ZeroOrOneBooleanContent: 2523 case TargetLowering::UndefinedBooleanContent: 2524 Cst = DAG.getConstant(1, DL, VT); 2525 break; 2526 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2527 Cst = DAG.getConstant(-1, DL, VT); 2528 break; 2529 } 2530 2531 return DAG.getNode(ISD::XOR, DL, VT, V, Cst); 2532 } 2533 2534 static SDValue extractBooleanFlip(SDValue V, const TargetLowering &TLI) { 2535 if (V.getOpcode() != ISD::XOR) 2536 return SDValue(); 2537 2538 ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false); 2539 if (!Const) 2540 return SDValue(); 2541 2542 EVT VT = V.getValueType(); 2543 2544 bool IsFlip = false; 2545 switch(TLI.getBooleanContents(VT)) { 2546 case TargetLowering::ZeroOrOneBooleanContent: 2547 IsFlip = Const->isOne(); 2548 break; 2549 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2550 IsFlip = Const->isAllOnesValue(); 2551 break; 2552 case TargetLowering::UndefinedBooleanContent: 2553 IsFlip = (Const->getAPIntValue() & 0x01) == 1; 2554 break; 2555 } 2556 2557 if (IsFlip) 2558 return V.getOperand(0); 2559 return SDValue(); 2560 } 2561 2562 SDValue DAGCombiner::visitADDO(SDNode *N) { 2563 SDValue N0 = N->getOperand(0); 2564 SDValue N1 = N->getOperand(1); 2565 EVT VT = N0.getValueType(); 2566 bool IsSigned = (ISD::SADDO == N->getOpcode()); 2567 2568 EVT CarryVT = N->getValueType(1); 2569 SDLoc DL(N); 2570 2571 // If the flag result is dead, turn this into an ADD. 2572 if (!N->hasAnyUseOfValue(1)) 2573 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2574 DAG.getUNDEF(CarryVT)); 2575 2576 // canonicalize constant to RHS. 2577 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2578 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2579 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0); 2580 2581 // fold (addo x, 0) -> x + no carry out 2582 if (isNullOrNullSplat(N1)) 2583 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2584 2585 if (!IsSigned) { 2586 // If it cannot overflow, transform into an add. 2587 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2588 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2589 DAG.getConstant(0, DL, CarryVT)); 2590 2591 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry. 2592 if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) { 2593 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(), 2594 DAG.getConstant(0, DL, VT), N0.getOperand(0)); 2595 return CombineTo(N, Sub, 2596 flipBoolean(Sub.getValue(1), DL, DAG, TLI)); 2597 } 2598 2599 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2600 return Combined; 2601 2602 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2603 return Combined; 2604 } 2605 2606 return SDValue(); 2607 } 2608 2609 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2610 EVT VT = N0.getValueType(); 2611 if (VT.isVector()) 2612 return SDValue(); 2613 2614 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2615 // If Y + 1 cannot overflow. 2616 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2617 SDValue Y = N1.getOperand(0); 2618 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2619 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2620 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2621 N1.getOperand(2)); 2622 } 2623 2624 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2625 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2626 if (SDValue Carry = getAsCarry(TLI, N1)) 2627 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2628 DAG.getConstant(0, SDLoc(N), VT), Carry); 2629 2630 return SDValue(); 2631 } 2632 2633 SDValue DAGCombiner::visitADDE(SDNode *N) { 2634 SDValue N0 = N->getOperand(0); 2635 SDValue N1 = N->getOperand(1); 2636 SDValue CarryIn = N->getOperand(2); 2637 2638 // canonicalize constant to RHS 2639 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2640 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2641 if (N0C && !N1C) 2642 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2643 N1, N0, CarryIn); 2644 2645 // fold (adde x, y, false) -> (addc x, y) 2646 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2647 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2648 2649 return SDValue(); 2650 } 2651 2652 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2653 SDValue N0 = N->getOperand(0); 2654 SDValue N1 = N->getOperand(1); 2655 SDValue CarryIn = N->getOperand(2); 2656 SDLoc DL(N); 2657 2658 // canonicalize constant to RHS 2659 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2660 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2661 if (N0C && !N1C) 2662 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2663 2664 // fold (addcarry x, y, false) -> (uaddo x, y) 2665 if (isNullConstant(CarryIn)) { 2666 if (!LegalOperations || 2667 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0))) 2668 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2669 } 2670 2671 EVT CarryVT = CarryIn.getValueType(); 2672 2673 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2674 if (isNullConstant(N0) && isNullConstant(N1)) { 2675 EVT VT = N0.getValueType(); 2676 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2677 AddToWorklist(CarryExt.getNode()); 2678 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2679 DAG.getConstant(1, DL, VT)), 2680 DAG.getConstant(0, DL, CarryVT)); 2681 } 2682 2683 // fold (addcarry (xor a, -1), 0, !b) -> (subcarry 0, a, b) and flip carry. 2684 if (isBitwiseNot(N0) && isNullConstant(N1)) { 2685 if (SDValue B = extractBooleanFlip(CarryIn, TLI)) { 2686 SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), 2687 DAG.getConstant(0, DL, N0.getValueType()), 2688 N0.getOperand(0), B); 2689 return CombineTo(N, Sub, 2690 flipBoolean(Sub.getValue(1), DL, DAG, TLI)); 2691 } 2692 } 2693 2694 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2695 return Combined; 2696 2697 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2698 return Combined; 2699 2700 return SDValue(); 2701 } 2702 2703 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 2704 SDNode *N) { 2705 // Iff the flag result is dead: 2706 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 2707 if ((N0.getOpcode() == ISD::ADD || 2708 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0)) && 2709 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 2710 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 2711 N0.getOperand(0), N0.getOperand(1), CarryIn); 2712 2713 /** 2714 * When one of the addcarry argument is itself a carry, we may be facing 2715 * a diamond carry propagation. In which case we try to transform the DAG 2716 * to ensure linear carry propagation if that is possible. 2717 * 2718 * We are trying to get: 2719 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2720 */ 2721 if (auto Y = getAsCarry(TLI, N1)) { 2722 /** 2723 * (uaddo A, B) 2724 * / \ 2725 * Carry Sum 2726 * | \ 2727 * | (addcarry *, 0, Z) 2728 * | / 2729 * \ Carry 2730 * | / 2731 * (addcarry X, *, *) 2732 */ 2733 if (Y.getOpcode() == ISD::UADDO && 2734 CarryIn.getResNo() == 1 && 2735 CarryIn.getOpcode() == ISD::ADDCARRY && 2736 isNullConstant(CarryIn.getOperand(1)) && 2737 CarryIn.getOperand(0) == Y.getValue(0)) { 2738 auto NewY = DAG.getNode(ISD::ADDCARRY, SDLoc(N), Y->getVTList(), 2739 Y.getOperand(0), Y.getOperand(1), 2740 CarryIn.getOperand(2)); 2741 AddToWorklist(NewY.getNode()); 2742 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2743 DAG.getConstant(0, SDLoc(N), N0.getValueType()), 2744 NewY.getValue(1)); 2745 } 2746 } 2747 2748 return SDValue(); 2749 } 2750 2751 // Since it may not be valid to emit a fold to zero for vector initializers 2752 // check if we can before folding. 2753 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 2754 SelectionDAG &DAG, bool LegalOperations) { 2755 if (!VT.isVector()) 2756 return DAG.getConstant(0, DL, VT); 2757 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 2758 return DAG.getConstant(0, DL, VT); 2759 return SDValue(); 2760 } 2761 2762 SDValue DAGCombiner::visitSUB(SDNode *N) { 2763 SDValue N0 = N->getOperand(0); 2764 SDValue N1 = N->getOperand(1); 2765 EVT VT = N0.getValueType(); 2766 SDLoc DL(N); 2767 2768 // fold vector ops 2769 if (VT.isVector()) { 2770 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 2771 return FoldedVOp; 2772 2773 // fold (sub x, 0) -> x, vector edition 2774 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2775 return N0; 2776 } 2777 2778 // fold (sub x, x) -> 0 2779 // FIXME: Refactor this and xor and other similar operations together. 2780 if (N0 == N1) 2781 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 2782 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2783 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 2784 // fold (sub c1, c2) -> c1-c2 2785 return DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, N0.getNode(), 2786 N1.getNode()); 2787 } 2788 2789 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2790 return NewSel; 2791 2792 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 2793 2794 // fold (sub x, c) -> (add x, -c) 2795 if (N1C) { 2796 return DAG.getNode(ISD::ADD, DL, VT, N0, 2797 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 2798 } 2799 2800 if (isNullOrNullSplat(N0)) { 2801 unsigned BitWidth = VT.getScalarSizeInBits(); 2802 // Right-shifting everything out but the sign bit followed by negation is 2803 // the same as flipping arithmetic/logical shift type without the negation: 2804 // -(X >>u 31) -> (X >>s 31) 2805 // -(X >>s 31) -> (X >>u 31) 2806 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 2807 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 2808 if (ShiftAmt && ShiftAmt->getZExtValue() == BitWidth - 1) { 2809 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 2810 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 2811 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 2812 } 2813 } 2814 2815 // 0 - X --> 0 if the sub is NUW. 2816 if (N->getFlags().hasNoUnsignedWrap()) 2817 return N0; 2818 2819 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 2820 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 2821 // N1 must be 0 because negating the minimum signed value is undefined. 2822 if (N->getFlags().hasNoSignedWrap()) 2823 return N0; 2824 2825 // 0 - X --> X if X is 0 or the minimum signed value. 2826 return N1; 2827 } 2828 } 2829 2830 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 2831 if (isAllOnesOrAllOnesSplat(N0)) 2832 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 2833 2834 // fold (A - (0-B)) -> A+B 2835 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0))) 2836 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1)); 2837 2838 // fold A-(A-B) -> B 2839 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 2840 return N1.getOperand(1); 2841 2842 // fold (A+B)-A -> B 2843 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 2844 return N0.getOperand(1); 2845 2846 // fold (A+B)-B -> A 2847 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 2848 return N0.getOperand(0); 2849 2850 // fold C2-(A+C1) -> (C2-C1)-A 2851 if (N1.getOpcode() == ISD::ADD) { 2852 SDValue N11 = N1.getOperand(1); 2853 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 2854 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 2855 SDValue NewC = DAG.getNode(ISD::SUB, DL, VT, N0, N11); 2856 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 2857 } 2858 } 2859 2860 // fold ((A+(B+or-C))-B) -> A+or-C 2861 if (N0.getOpcode() == ISD::ADD && 2862 (N0.getOperand(1).getOpcode() == ISD::SUB || 2863 N0.getOperand(1).getOpcode() == ISD::ADD) && 2864 N0.getOperand(1).getOperand(0) == N1) 2865 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 2866 N0.getOperand(1).getOperand(1)); 2867 2868 // fold ((A+(C+B))-B) -> A+C 2869 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 2870 N0.getOperand(1).getOperand(1) == N1) 2871 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 2872 N0.getOperand(1).getOperand(0)); 2873 2874 // fold ((A-(B-C))-C) -> A-B 2875 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 2876 N0.getOperand(1).getOperand(1) == N1) 2877 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2878 N0.getOperand(1).getOperand(0)); 2879 2880 // fold (A-(B-C)) -> A+(C-B) 2881 if (N1.getOpcode() == ISD::SUB && N1.hasOneUse()) 2882 return DAG.getNode(ISD::ADD, DL, VT, N0, 2883 DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1), 2884 N1.getOperand(0))); 2885 2886 // fold (X - (-Y * Z)) -> (X + (Y * Z)) 2887 if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) { 2888 if (N1.getOperand(0).getOpcode() == ISD::SUB && 2889 isNullOrNullSplat(N1.getOperand(0).getOperand(0))) { 2890 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 2891 N1.getOperand(0).getOperand(1), 2892 N1.getOperand(1)); 2893 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 2894 } 2895 if (N1.getOperand(1).getOpcode() == ISD::SUB && 2896 isNullOrNullSplat(N1.getOperand(1).getOperand(0))) { 2897 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 2898 N1.getOperand(0), 2899 N1.getOperand(1).getOperand(1)); 2900 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 2901 } 2902 } 2903 2904 // If either operand of a sub is undef, the result is undef 2905 if (N0.isUndef()) 2906 return N0; 2907 if (N1.isUndef()) 2908 return N1; 2909 2910 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 2911 return V; 2912 2913 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 2914 return V; 2915 2916 if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N))) 2917 return V; 2918 2919 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1' 2920 // rather than 'sub 0/1' (the sext should get folded). 2921 // sub X, (zext i1 Y) --> add X, (sext i1 Y) 2922 if (N1.getOpcode() == ISD::ZERO_EXTEND && 2923 N1.getOperand(0).getScalarValueSizeInBits() == 1 && 2924 TLI.getBooleanContents(VT) == 2925 TargetLowering::ZeroOrNegativeOneBooleanContent) { 2926 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0)); 2927 return DAG.getNode(ISD::ADD, DL, VT, N0, SExt); 2928 } 2929 2930 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X) 2931 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 2932 if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) { 2933 SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1); 2934 SDValue S0 = N1.getOperand(0); 2935 if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) { 2936 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 2937 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 2938 if (C->getAPIntValue() == (OpSizeInBits - 1)) 2939 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0); 2940 } 2941 } 2942 } 2943 2944 // If the relocation model supports it, consider symbol offsets. 2945 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 2946 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 2947 // fold (sub Sym, c) -> Sym-c 2948 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 2949 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 2950 GA->getOffset() - 2951 (uint64_t)N1C->getSExtValue()); 2952 // fold (sub Sym+c1, Sym+c2) -> c1-c2 2953 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 2954 if (GA->getGlobal() == GB->getGlobal()) 2955 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 2956 DL, VT); 2957 } 2958 2959 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 2960 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2961 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2962 if (TN->getVT() == MVT::i1) { 2963 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2964 DAG.getConstant(1, DL, VT)); 2965 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 2966 } 2967 } 2968 2969 // Prefer an add for more folding potential and possibly better codegen: 2970 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1) 2971 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) { 2972 SDValue ShAmt = N1.getOperand(1); 2973 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 2974 if (ShAmtC && ShAmtC->getZExtValue() == N1.getScalarValueSizeInBits() - 1) { 2975 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt); 2976 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA); 2977 } 2978 } 2979 2980 return SDValue(); 2981 } 2982 2983 SDValue DAGCombiner::visitSUBSAT(SDNode *N) { 2984 SDValue N0 = N->getOperand(0); 2985 SDValue N1 = N->getOperand(1); 2986 EVT VT = N0.getValueType(); 2987 SDLoc DL(N); 2988 2989 // fold vector ops 2990 if (VT.isVector()) { 2991 // TODO SimplifyVBinOp 2992 2993 // fold (sub_sat x, 0) -> x, vector edition 2994 if (ISD::isBuildVectorAllZeros(N1.getNode())) 2995 return N0; 2996 } 2997 2998 // fold (sub_sat x, undef) -> 0 2999 if (N0.isUndef() || N1.isUndef()) 3000 return DAG.getConstant(0, DL, VT); 3001 3002 // fold (sub_sat x, x) -> 0 3003 if (N0 == N1) 3004 return DAG.getConstant(0, DL, VT); 3005 3006 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3007 DAG.isConstantIntBuildVectorOrConstantInt(N1)) { 3008 // fold (sub_sat c1, c2) -> c3 3009 return DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, N0.getNode(), 3010 N1.getNode()); 3011 } 3012 3013 // fold (sub_sat x, 0) -> x 3014 if (isNullConstant(N1)) 3015 return N0; 3016 3017 return SDValue(); 3018 } 3019 3020 SDValue DAGCombiner::visitSUBC(SDNode *N) { 3021 SDValue N0 = N->getOperand(0); 3022 SDValue N1 = N->getOperand(1); 3023 EVT VT = N0.getValueType(); 3024 SDLoc DL(N); 3025 3026 // If the flag result is dead, turn this into an SUB. 3027 if (!N->hasAnyUseOfValue(1)) 3028 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 3029 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3030 3031 // fold (subc x, x) -> 0 + no borrow 3032 if (N0 == N1) 3033 return CombineTo(N, DAG.getConstant(0, DL, VT), 3034 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3035 3036 // fold (subc x, 0) -> x + no borrow 3037 if (isNullConstant(N1)) 3038 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3039 3040 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 3041 if (isAllOnesConstant(N0)) 3042 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 3043 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3044 3045 return SDValue(); 3046 } 3047 3048 SDValue DAGCombiner::visitSUBO(SDNode *N) { 3049 SDValue N0 = N->getOperand(0); 3050 SDValue N1 = N->getOperand(1); 3051 EVT VT = N0.getValueType(); 3052 bool IsSigned = (ISD::SSUBO == N->getOpcode()); 3053 3054 EVT CarryVT = N->getValueType(1); 3055 SDLoc DL(N); 3056 3057 // If the flag result is dead, turn this into an SUB. 3058 if (!N->hasAnyUseOfValue(1)) 3059 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 3060 DAG.getUNDEF(CarryVT)); 3061 3062 // fold (subo x, x) -> 0 + no borrow 3063 if (N0 == N1) 3064 return CombineTo(N, DAG.getConstant(0, DL, VT), 3065 DAG.getConstant(0, DL, CarryVT)); 3066 3067 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3068 3069 // fold (subox, c) -> (addo x, -c) 3070 if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) { 3071 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, 3072 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 3073 } 3074 3075 // fold (subo x, 0) -> x + no borrow 3076 if (isNullOrNullSplat(N1)) 3077 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 3078 3079 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 3080 if (!IsSigned && isAllOnesOrAllOnesSplat(N0)) 3081 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 3082 DAG.getConstant(0, DL, CarryVT)); 3083 3084 return SDValue(); 3085 } 3086 3087 SDValue DAGCombiner::visitSUBE(SDNode *N) { 3088 SDValue N0 = N->getOperand(0); 3089 SDValue N1 = N->getOperand(1); 3090 SDValue CarryIn = N->getOperand(2); 3091 3092 // fold (sube x, y, false) -> (subc x, y) 3093 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 3094 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 3095 3096 return SDValue(); 3097 } 3098 3099 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 3100 SDValue N0 = N->getOperand(0); 3101 SDValue N1 = N->getOperand(1); 3102 SDValue CarryIn = N->getOperand(2); 3103 3104 // fold (subcarry x, y, false) -> (usubo x, y) 3105 if (isNullConstant(CarryIn)) { 3106 if (!LegalOperations || 3107 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0))) 3108 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 3109 } 3110 3111 return SDValue(); 3112 } 3113 3114 SDValue DAGCombiner::visitMUL(SDNode *N) { 3115 SDValue N0 = N->getOperand(0); 3116 SDValue N1 = N->getOperand(1); 3117 EVT VT = N0.getValueType(); 3118 3119 // fold (mul x, undef) -> 0 3120 if (N0.isUndef() || N1.isUndef()) 3121 return DAG.getConstant(0, SDLoc(N), VT); 3122 3123 bool N0IsConst = false; 3124 bool N1IsConst = false; 3125 bool N1IsOpaqueConst = false; 3126 bool N0IsOpaqueConst = false; 3127 APInt ConstValue0, ConstValue1; 3128 // fold vector ops 3129 if (VT.isVector()) { 3130 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3131 return FoldedVOp; 3132 3133 N0IsConst = ISD::isConstantSplatVector(N0.getNode(), ConstValue0); 3134 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 3135 assert((!N0IsConst || 3136 ConstValue0.getBitWidth() == VT.getScalarSizeInBits()) && 3137 "Splat APInt should be element width"); 3138 assert((!N1IsConst || 3139 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && 3140 "Splat APInt should be element width"); 3141 } else { 3142 N0IsConst = isa<ConstantSDNode>(N0); 3143 if (N0IsConst) { 3144 ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue(); 3145 N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque(); 3146 } 3147 N1IsConst = isa<ConstantSDNode>(N1); 3148 if (N1IsConst) { 3149 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 3150 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 3151 } 3152 } 3153 3154 // fold (mul c1, c2) -> c1*c2 3155 if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst) 3156 return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, 3157 N0.getNode(), N1.getNode()); 3158 3159 // canonicalize constant to RHS (vector doesn't have to splat) 3160 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3161 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3162 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 3163 // fold (mul x, 0) -> 0 3164 if (N1IsConst && ConstValue1.isNullValue()) 3165 return N1; 3166 // fold (mul x, 1) -> x 3167 if (N1IsConst && ConstValue1.isOneValue()) 3168 return N0; 3169 3170 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3171 return NewSel; 3172 3173 // fold (mul x, -1) -> 0-x 3174 if (N1IsConst && ConstValue1.isAllOnesValue()) { 3175 SDLoc DL(N); 3176 return DAG.getNode(ISD::SUB, DL, VT, 3177 DAG.getConstant(0, DL, VT), N0); 3178 } 3179 // fold (mul x, (1 << c)) -> x << c 3180 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 3181 DAG.isKnownToBeAPowerOfTwo(N1) && 3182 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) { 3183 SDLoc DL(N); 3184 SDValue LogBase2 = BuildLogBase2(N1, DL); 3185 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 3186 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 3187 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc); 3188 } 3189 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 3190 if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2()) { 3191 unsigned Log2Val = (-ConstValue1).logBase2(); 3192 SDLoc DL(N); 3193 // FIXME: If the input is something that is easily negated (e.g. a 3194 // single-use add), we should put the negate there. 3195 return DAG.getNode(ISD::SUB, DL, VT, 3196 DAG.getConstant(0, DL, VT), 3197 DAG.getNode(ISD::SHL, DL, VT, N0, 3198 DAG.getConstant(Log2Val, DL, 3199 getShiftAmountTy(N0.getValueType())))); 3200 } 3201 3202 // Try to transform multiply-by-(power-of-2 +/- 1) into shift and add/sub. 3203 // mul x, (2^N + 1) --> add (shl x, N), x 3204 // mul x, (2^N - 1) --> sub (shl x, N), x 3205 // Examples: x * 33 --> (x << 5) + x 3206 // x * 15 --> (x << 4) - x 3207 // x * -33 --> -((x << 5) + x) 3208 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4) 3209 if (N1IsConst && TLI.decomposeMulByConstant(VT, N1)) { 3210 // TODO: We could handle more general decomposition of any constant by 3211 // having the target set a limit on number of ops and making a 3212 // callback to determine that sequence (similar to sqrt expansion). 3213 unsigned MathOp = ISD::DELETED_NODE; 3214 APInt MulC = ConstValue1.abs(); 3215 if ((MulC - 1).isPowerOf2()) 3216 MathOp = ISD::ADD; 3217 else if ((MulC + 1).isPowerOf2()) 3218 MathOp = ISD::SUB; 3219 3220 if (MathOp != ISD::DELETED_NODE) { 3221 unsigned ShAmt = MathOp == ISD::ADD ? (MulC - 1).logBase2() 3222 : (MulC + 1).logBase2(); 3223 assert(ShAmt > 0 && ShAmt < VT.getScalarSizeInBits() && 3224 "Not expecting multiply-by-constant that could have simplified"); 3225 SDLoc DL(N); 3226 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, N0, 3227 DAG.getConstant(ShAmt, DL, VT)); 3228 SDValue R = DAG.getNode(MathOp, DL, VT, Shl, N0); 3229 if (ConstValue1.isNegative()) 3230 R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R); 3231 return R; 3232 } 3233 } 3234 3235 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 3236 if (N0.getOpcode() == ISD::SHL && 3237 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 3238 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 3239 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 3240 if (isConstantOrConstantVector(C3)) 3241 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 3242 } 3243 3244 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 3245 // use. 3246 { 3247 SDValue Sh(nullptr, 0), Y(nullptr, 0); 3248 3249 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 3250 if (N0.getOpcode() == ISD::SHL && 3251 isConstantOrConstantVector(N0.getOperand(1)) && 3252 N0.getNode()->hasOneUse()) { 3253 Sh = N0; Y = N1; 3254 } else if (N1.getOpcode() == ISD::SHL && 3255 isConstantOrConstantVector(N1.getOperand(1)) && 3256 N1.getNode()->hasOneUse()) { 3257 Sh = N1; Y = N0; 3258 } 3259 3260 if (Sh.getNode()) { 3261 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 3262 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 3263 } 3264 } 3265 3266 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 3267 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 3268 N0.getOpcode() == ISD::ADD && 3269 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 3270 isMulAddWithConstProfitable(N, N0, N1)) 3271 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 3272 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 3273 N0.getOperand(0), N1), 3274 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 3275 N0.getOperand(1), N1)); 3276 3277 // reassociate mul 3278 if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags())) 3279 return RMUL; 3280 3281 return SDValue(); 3282 } 3283 3284 /// Return true if divmod libcall is available. 3285 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 3286 const TargetLowering &TLI) { 3287 RTLIB::Libcall LC; 3288 EVT NodeType = Node->getValueType(0); 3289 if (!NodeType.isSimple()) 3290 return false; 3291 switch (NodeType.getSimpleVT().SimpleTy) { 3292 default: return false; // No libcall for vector types. 3293 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 3294 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 3295 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 3296 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 3297 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 3298 } 3299 3300 return TLI.getLibcallName(LC) != nullptr; 3301 } 3302 3303 /// Issue divrem if both quotient and remainder are needed. 3304 SDValue DAGCombiner::useDivRem(SDNode *Node) { 3305 if (Node->use_empty()) 3306 return SDValue(); // This is a dead node, leave it alone. 3307 3308 unsigned Opcode = Node->getOpcode(); 3309 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 3310 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 3311 3312 // DivMod lib calls can still work on non-legal types if using lib-calls. 3313 EVT VT = Node->getValueType(0); 3314 if (VT.isVector() || !VT.isInteger()) 3315 return SDValue(); 3316 3317 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 3318 return SDValue(); 3319 3320 // If DIVREM is going to get expanded into a libcall, 3321 // but there is no libcall available, then don't combine. 3322 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 3323 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 3324 return SDValue(); 3325 3326 // If div is legal, it's better to do the normal expansion 3327 unsigned OtherOpcode = 0; 3328 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 3329 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 3330 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 3331 return SDValue(); 3332 } else { 3333 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 3334 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 3335 return SDValue(); 3336 } 3337 3338 SDValue Op0 = Node->getOperand(0); 3339 SDValue Op1 = Node->getOperand(1); 3340 SDValue combined; 3341 for (SDNode::use_iterator UI = Op0.getNode()->use_begin(), 3342 UE = Op0.getNode()->use_end(); UI != UE; ++UI) { 3343 SDNode *User = *UI; 3344 if (User == Node || User->getOpcode() == ISD::DELETED_NODE || 3345 User->use_empty()) 3346 continue; 3347 // Convert the other matching node(s), too; 3348 // otherwise, the DIVREM may get target-legalized into something 3349 // target-specific that we won't be able to recognize. 3350 unsigned UserOpc = User->getOpcode(); 3351 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 3352 User->getOperand(0) == Op0 && 3353 User->getOperand(1) == Op1) { 3354 if (!combined) { 3355 if (UserOpc == OtherOpcode) { 3356 SDVTList VTs = DAG.getVTList(VT, VT); 3357 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 3358 } else if (UserOpc == DivRemOpc) { 3359 combined = SDValue(User, 0); 3360 } else { 3361 assert(UserOpc == Opcode); 3362 continue; 3363 } 3364 } 3365 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 3366 CombineTo(User, combined); 3367 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 3368 CombineTo(User, combined.getValue(1)); 3369 } 3370 } 3371 return combined; 3372 } 3373 3374 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 3375 SDValue N0 = N->getOperand(0); 3376 SDValue N1 = N->getOperand(1); 3377 EVT VT = N->getValueType(0); 3378 SDLoc DL(N); 3379 3380 unsigned Opc = N->getOpcode(); 3381 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc); 3382 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3383 3384 // X / undef -> undef 3385 // X % undef -> undef 3386 // X / 0 -> undef 3387 // X % 0 -> undef 3388 // NOTE: This includes vectors where any divisor element is zero/undef. 3389 if (DAG.isUndef(Opc, {N0, N1})) 3390 return DAG.getUNDEF(VT); 3391 3392 // undef / X -> 0 3393 // undef % X -> 0 3394 if (N0.isUndef()) 3395 return DAG.getConstant(0, DL, VT); 3396 3397 // 0 / X -> 0 3398 // 0 % X -> 0 3399 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3400 if (N0C && N0C->isNullValue()) 3401 return N0; 3402 3403 // X / X -> 1 3404 // X % X -> 0 3405 if (N0 == N1) 3406 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT); 3407 3408 // X / 1 -> X 3409 // X % 1 -> 0 3410 // If this is a boolean op (single-bit element type), we can't have 3411 // division-by-zero or remainder-by-zero, so assume the divisor is 1. 3412 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume 3413 // it's a 1. 3414 if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1)) 3415 return IsDiv ? N0 : DAG.getConstant(0, DL, VT); 3416 3417 return SDValue(); 3418 } 3419 3420 SDValue DAGCombiner::visitSDIV(SDNode *N) { 3421 SDValue N0 = N->getOperand(0); 3422 SDValue N1 = N->getOperand(1); 3423 EVT VT = N->getValueType(0); 3424 EVT CCVT = getSetCCResultType(VT); 3425 3426 // fold vector ops 3427 if (VT.isVector()) 3428 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3429 return FoldedVOp; 3430 3431 SDLoc DL(N); 3432 3433 // fold (sdiv c1, c2) -> c1/c2 3434 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3435 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3436 if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque()) 3437 return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C); 3438 // fold (sdiv X, -1) -> 0-X 3439 if (N1C && N1C->isAllOnesValue()) 3440 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 3441 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0) 3442 if (N1C && N1C->getAPIntValue().isMinSignedValue()) 3443 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3444 DAG.getConstant(1, DL, VT), 3445 DAG.getConstant(0, DL, VT)); 3446 3447 if (SDValue V = simplifyDivRem(N, DAG)) 3448 return V; 3449 3450 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3451 return NewSel; 3452 3453 // If we know the sign bits of both operands are zero, strength reduce to a 3454 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 3455 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3456 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 3457 3458 if (SDValue V = visitSDIVLike(N0, N1, N)) { 3459 // If the corresponding remainder node exists, update its users with 3460 // (Dividend - (Quotient * Divisor). 3461 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(), 3462 { N0, N1 })) { 3463 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1); 3464 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 3465 AddToWorklist(Mul.getNode()); 3466 AddToWorklist(Sub.getNode()); 3467 CombineTo(RemNode, Sub); 3468 } 3469 return V; 3470 } 3471 3472 // sdiv, srem -> sdivrem 3473 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3474 // true. Otherwise, we break the simplification logic in visitREM(). 3475 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3476 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3477 if (SDValue DivRem = useDivRem(N)) 3478 return DivRem; 3479 3480 return SDValue(); 3481 } 3482 3483 SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) { 3484 SDLoc DL(N); 3485 EVT VT = N->getValueType(0); 3486 EVT CCVT = getSetCCResultType(VT); 3487 unsigned BitWidth = VT.getScalarSizeInBits(); 3488 3489 // Helper for determining whether a value is a power-2 constant scalar or a 3490 // vector of such elements. 3491 auto IsPowerOfTwo = [](ConstantSDNode *C) { 3492 if (C->isNullValue() || C->isOpaque()) 3493 return false; 3494 if (C->getAPIntValue().isPowerOf2()) 3495 return true; 3496 if ((-C->getAPIntValue()).isPowerOf2()) 3497 return true; 3498 return false; 3499 }; 3500 3501 // fold (sdiv X, pow2) -> simple ops after legalize 3502 // FIXME: We check for the exact bit here because the generic lowering gives 3503 // better results in that case. The target-specific lowering should learn how 3504 // to handle exact sdivs efficiently. 3505 if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) { 3506 // Target-specific implementation of sdiv x, pow2. 3507 if (SDValue Res = BuildSDIVPow2(N)) 3508 return Res; 3509 3510 // Create constants that are functions of the shift amount value. 3511 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 3512 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy); 3513 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1); 3514 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy); 3515 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1); 3516 if (!isConstantOrConstantVector(Inexact)) 3517 return SDValue(); 3518 3519 // Splat the sign bit into the register 3520 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0, 3521 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy)); 3522 AddToWorklist(Sign.getNode()); 3523 3524 // Add (N0 < 0) ? abs2 - 1 : 0; 3525 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact); 3526 AddToWorklist(Srl.getNode()); 3527 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl); 3528 AddToWorklist(Add.getNode()); 3529 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1); 3530 AddToWorklist(Sra.getNode()); 3531 3532 // Special case: (sdiv X, 1) -> X 3533 // Special Case: (sdiv X, -1) -> 0-X 3534 SDValue One = DAG.getConstant(1, DL, VT); 3535 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 3536 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ); 3537 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ); 3538 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes); 3539 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra); 3540 3541 // If dividing by a positive value, we're done. Otherwise, the result must 3542 // be negated. 3543 SDValue Zero = DAG.getConstant(0, DL, VT); 3544 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra); 3545 3546 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding. 3547 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT); 3548 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra); 3549 return Res; 3550 } 3551 3552 // If integer divide is expensive and we satisfy the requirements, emit an 3553 // alternate sequence. Targets may check function attributes for size/speed 3554 // trade-offs. 3555 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3556 if (isConstantOrConstantVector(N1) && 3557 !TLI.isIntDivCheap(N->getValueType(0), Attr)) 3558 if (SDValue Op = BuildSDIV(N)) 3559 return Op; 3560 3561 return SDValue(); 3562 } 3563 3564 SDValue DAGCombiner::visitUDIV(SDNode *N) { 3565 SDValue N0 = N->getOperand(0); 3566 SDValue N1 = N->getOperand(1); 3567 EVT VT = N->getValueType(0); 3568 EVT CCVT = getSetCCResultType(VT); 3569 3570 // fold vector ops 3571 if (VT.isVector()) 3572 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3573 return FoldedVOp; 3574 3575 SDLoc DL(N); 3576 3577 // fold (udiv c1, c2) -> c1/c2 3578 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3579 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3580 if (N0C && N1C) 3581 if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, 3582 N0C, N1C)) 3583 return Folded; 3584 // fold (udiv X, -1) -> select(X == -1, 1, 0) 3585 if (N1C && N1C->getAPIntValue().isAllOnesValue()) 3586 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3587 DAG.getConstant(1, DL, VT), 3588 DAG.getConstant(0, DL, VT)); 3589 3590 if (SDValue V = simplifyDivRem(N, DAG)) 3591 return V; 3592 3593 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3594 return NewSel; 3595 3596 if (SDValue V = visitUDIVLike(N0, N1, N)) { 3597 // If the corresponding remainder node exists, update its users with 3598 // (Dividend - (Quotient * Divisor). 3599 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(), 3600 { N0, N1 })) { 3601 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1); 3602 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 3603 AddToWorklist(Mul.getNode()); 3604 AddToWorklist(Sub.getNode()); 3605 CombineTo(RemNode, Sub); 3606 } 3607 return V; 3608 } 3609 3610 // sdiv, srem -> sdivrem 3611 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 3612 // true. Otherwise, we break the simplification logic in visitREM(). 3613 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3614 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 3615 if (SDValue DivRem = useDivRem(N)) 3616 return DivRem; 3617 3618 return SDValue(); 3619 } 3620 3621 SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) { 3622 SDLoc DL(N); 3623 EVT VT = N->getValueType(0); 3624 3625 // fold (udiv x, (1 << c)) -> x >>u c 3626 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 3627 DAG.isKnownToBeAPowerOfTwo(N1)) { 3628 SDValue LogBase2 = BuildLogBase2(N1, DL); 3629 AddToWorklist(LogBase2.getNode()); 3630 3631 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 3632 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 3633 AddToWorklist(Trunc.getNode()); 3634 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 3635 } 3636 3637 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 3638 if (N1.getOpcode() == ISD::SHL) { 3639 SDValue N10 = N1.getOperand(0); 3640 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 3641 DAG.isKnownToBeAPowerOfTwo(N10)) { 3642 SDValue LogBase2 = BuildLogBase2(N10, DL); 3643 AddToWorklist(LogBase2.getNode()); 3644 3645 EVT ADDVT = N1.getOperand(1).getValueType(); 3646 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 3647 AddToWorklist(Trunc.getNode()); 3648 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 3649 AddToWorklist(Add.getNode()); 3650 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 3651 } 3652 } 3653 3654 // fold (udiv x, c) -> alternate 3655 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3656 if (isConstantOrConstantVector(N1) && 3657 !TLI.isIntDivCheap(N->getValueType(0), Attr)) 3658 if (SDValue Op = BuildUDIV(N)) 3659 return Op; 3660 3661 return SDValue(); 3662 } 3663 3664 // handles ISD::SREM and ISD::UREM 3665 SDValue DAGCombiner::visitREM(SDNode *N) { 3666 unsigned Opcode = N->getOpcode(); 3667 SDValue N0 = N->getOperand(0); 3668 SDValue N1 = N->getOperand(1); 3669 EVT VT = N->getValueType(0); 3670 EVT CCVT = getSetCCResultType(VT); 3671 3672 bool isSigned = (Opcode == ISD::SREM); 3673 SDLoc DL(N); 3674 3675 // fold (rem c1, c2) -> c1%c2 3676 ConstantSDNode *N0C = isConstOrConstSplat(N0); 3677 ConstantSDNode *N1C = isConstOrConstSplat(N1); 3678 if (N0C && N1C) 3679 if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C)) 3680 return Folded; 3681 // fold (urem X, -1) -> select(X == -1, 0, x) 3682 if (!isSigned && N1C && N1C->getAPIntValue().isAllOnesValue()) 3683 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 3684 DAG.getConstant(0, DL, VT), N0); 3685 3686 if (SDValue V = simplifyDivRem(N, DAG)) 3687 return V; 3688 3689 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3690 return NewSel; 3691 3692 if (isSigned) { 3693 // If we know the sign bits of both operands are zero, strength reduce to a 3694 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 3695 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 3696 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 3697 } else { 3698 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 3699 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 3700 // fold (urem x, pow2) -> (and x, pow2-1) 3701 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3702 AddToWorklist(Add.getNode()); 3703 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3704 } 3705 if (N1.getOpcode() == ISD::SHL && 3706 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 3707 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 3708 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 3709 AddToWorklist(Add.getNode()); 3710 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 3711 } 3712 } 3713 3714 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 3715 3716 // If X/C can be simplified by the division-by-constant logic, lower 3717 // X%C to the equivalent of X-X/C*C. 3718 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the 3719 // speculative DIV must not cause a DIVREM conversion. We guard against this 3720 // by skipping the simplification if isIntDivCheap(). When div is not cheap, 3721 // combine will not return a DIVREM. Regardless, checking cheapness here 3722 // makes sense since the simplification results in fatter code. 3723 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) { 3724 SDValue OptimizedDiv = 3725 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N); 3726 if (OptimizedDiv.getNode()) { 3727 // If the equivalent Div node also exists, update its users. 3728 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 3729 if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(), 3730 { N0, N1 })) 3731 CombineTo(DivNode, OptimizedDiv); 3732 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 3733 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 3734 AddToWorklist(OptimizedDiv.getNode()); 3735 AddToWorklist(Mul.getNode()); 3736 return Sub; 3737 } 3738 } 3739 3740 // sdiv, srem -> sdivrem 3741 if (SDValue DivRem = useDivRem(N)) 3742 return DivRem.getValue(1); 3743 3744 return SDValue(); 3745 } 3746 3747 SDValue DAGCombiner::visitMULHS(SDNode *N) { 3748 SDValue N0 = N->getOperand(0); 3749 SDValue N1 = N->getOperand(1); 3750 EVT VT = N->getValueType(0); 3751 SDLoc DL(N); 3752 3753 if (VT.isVector()) { 3754 // fold (mulhs x, 0) -> 0 3755 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3756 return N1; 3757 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3758 return N0; 3759 } 3760 3761 // fold (mulhs x, 0) -> 0 3762 if (isNullConstant(N1)) 3763 return N1; 3764 // fold (mulhs x, 1) -> (sra x, size(x)-1) 3765 if (isOneConstant(N1)) 3766 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 3767 DAG.getConstant(N0.getValueSizeInBits() - 1, DL, 3768 getShiftAmountTy(N0.getValueType()))); 3769 3770 // fold (mulhs x, undef) -> 0 3771 if (N0.isUndef() || N1.isUndef()) 3772 return DAG.getConstant(0, DL, VT); 3773 3774 // If the type twice as wide is legal, transform the mulhs to a wider multiply 3775 // plus a shift. 3776 if (VT.isSimple() && !VT.isVector()) { 3777 MVT Simple = VT.getSimpleVT(); 3778 unsigned SimpleSize = Simple.getSizeInBits(); 3779 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3780 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3781 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 3782 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 3783 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3784 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3785 DAG.getConstant(SimpleSize, DL, 3786 getShiftAmountTy(N1.getValueType()))); 3787 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3788 } 3789 } 3790 3791 return SDValue(); 3792 } 3793 3794 SDValue DAGCombiner::visitMULHU(SDNode *N) { 3795 SDValue N0 = N->getOperand(0); 3796 SDValue N1 = N->getOperand(1); 3797 EVT VT = N->getValueType(0); 3798 SDLoc DL(N); 3799 3800 if (VT.isVector()) { 3801 // fold (mulhu x, 0) -> 0 3802 if (ISD::isBuildVectorAllZeros(N1.getNode())) 3803 return N1; 3804 if (ISD::isBuildVectorAllZeros(N0.getNode())) 3805 return N0; 3806 } 3807 3808 // fold (mulhu x, 0) -> 0 3809 if (isNullConstant(N1)) 3810 return N1; 3811 // fold (mulhu x, 1) -> 0 3812 if (isOneConstant(N1)) 3813 return DAG.getConstant(0, DL, N0.getValueType()); 3814 // fold (mulhu x, undef) -> 0 3815 if (N0.isUndef() || N1.isUndef()) 3816 return DAG.getConstant(0, DL, VT); 3817 3818 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c) 3819 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 3820 DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) { 3821 SDLoc DL(N); 3822 unsigned NumEltBits = VT.getScalarSizeInBits(); 3823 SDValue LogBase2 = BuildLogBase2(N1, DL); 3824 SDValue SRLAmt = DAG.getNode( 3825 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2); 3826 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 3827 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT); 3828 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 3829 } 3830 3831 // If the type twice as wide is legal, transform the mulhu to a wider multiply 3832 // plus a shift. 3833 if (VT.isSimple() && !VT.isVector()) { 3834 MVT Simple = VT.getSimpleVT(); 3835 unsigned SimpleSize = Simple.getSizeInBits(); 3836 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3837 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3838 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 3839 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 3840 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 3841 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 3842 DAG.getConstant(SimpleSize, DL, 3843 getShiftAmountTy(N1.getValueType()))); 3844 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 3845 } 3846 } 3847 3848 return SDValue(); 3849 } 3850 3851 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 3852 /// give the opcodes for the two computations that are being performed. Return 3853 /// true if a simplification was made. 3854 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 3855 unsigned HiOp) { 3856 // If the high half is not needed, just compute the low half. 3857 bool HiExists = N->hasAnyUseOfValue(1); 3858 if (!HiExists && (!LegalOperations || 3859 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 3860 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3861 return CombineTo(N, Res, Res); 3862 } 3863 3864 // If the low half is not needed, just compute the high half. 3865 bool LoExists = N->hasAnyUseOfValue(0); 3866 if (!LoExists && (!LegalOperations || 3867 TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) { 3868 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3869 return CombineTo(N, Res, Res); 3870 } 3871 3872 // If both halves are used, return as it is. 3873 if (LoExists && HiExists) 3874 return SDValue(); 3875 3876 // If the two computed results can be simplified separately, separate them. 3877 if (LoExists) { 3878 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 3879 AddToWorklist(Lo.getNode()); 3880 SDValue LoOpt = combine(Lo.getNode()); 3881 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 3882 (!LegalOperations || 3883 TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType()))) 3884 return CombineTo(N, LoOpt, LoOpt); 3885 } 3886 3887 if (HiExists) { 3888 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 3889 AddToWorklist(Hi.getNode()); 3890 SDValue HiOpt = combine(Hi.getNode()); 3891 if (HiOpt.getNode() && HiOpt != Hi && 3892 (!LegalOperations || 3893 TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType()))) 3894 return CombineTo(N, HiOpt, HiOpt); 3895 } 3896 3897 return SDValue(); 3898 } 3899 3900 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 3901 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 3902 return Res; 3903 3904 EVT VT = N->getValueType(0); 3905 SDLoc DL(N); 3906 3907 // If the type is twice as wide is legal, transform the mulhu to a wider 3908 // multiply plus a shift. 3909 if (VT.isSimple() && !VT.isVector()) { 3910 MVT Simple = VT.getSimpleVT(); 3911 unsigned SimpleSize = Simple.getSizeInBits(); 3912 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3913 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3914 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 3915 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 3916 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3917 // Compute the high part as N1. 3918 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3919 DAG.getConstant(SimpleSize, DL, 3920 getShiftAmountTy(Lo.getValueType()))); 3921 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3922 // Compute the low part as N0. 3923 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3924 return CombineTo(N, Lo, Hi); 3925 } 3926 } 3927 3928 return SDValue(); 3929 } 3930 3931 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 3932 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 3933 return Res; 3934 3935 EVT VT = N->getValueType(0); 3936 SDLoc DL(N); 3937 3938 // If the type is twice as wide is legal, transform the mulhu to a wider 3939 // multiply plus a shift. 3940 if (VT.isSimple() && !VT.isVector()) { 3941 MVT Simple = VT.getSimpleVT(); 3942 unsigned SimpleSize = Simple.getSizeInBits(); 3943 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 3944 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 3945 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 3946 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 3947 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 3948 // Compute the high part as N1. 3949 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 3950 DAG.getConstant(SimpleSize, DL, 3951 getShiftAmountTy(Lo.getValueType()))); 3952 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 3953 // Compute the low part as N0. 3954 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 3955 return CombineTo(N, Lo, Hi); 3956 } 3957 } 3958 3959 return SDValue(); 3960 } 3961 3962 SDValue DAGCombiner::visitMULO(SDNode *N) { 3963 bool IsSigned = (ISD::SMULO == N->getOpcode()); 3964 3965 // (mulo x, 2) -> (addo x, x) 3966 if (ConstantSDNode *C2 = isConstOrConstSplat(N->getOperand(1))) 3967 if (C2->getAPIntValue() == 2) 3968 return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, SDLoc(N), 3969 N->getVTList(), N->getOperand(0), N->getOperand(0)); 3970 3971 return SDValue(); 3972 } 3973 3974 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 3975 SDValue N0 = N->getOperand(0); 3976 SDValue N1 = N->getOperand(1); 3977 EVT VT = N0.getValueType(); 3978 3979 // fold vector ops 3980 if (VT.isVector()) 3981 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 3982 return FoldedVOp; 3983 3984 // fold operation with constant operands. 3985 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 3986 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3987 if (N0C && N1C) 3988 return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C); 3989 3990 // canonicalize constant to RHS 3991 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3992 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3993 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 3994 3995 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX. 3996 // Only do this if the current op isn't legal and the flipped is. 3997 unsigned Opcode = N->getOpcode(); 3998 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 3999 if (!TLI.isOperationLegal(Opcode, VT) && 4000 (N0.isUndef() || DAG.SignBitIsZero(N0)) && 4001 (N1.isUndef() || DAG.SignBitIsZero(N1))) { 4002 unsigned AltOpcode; 4003 switch (Opcode) { 4004 case ISD::SMIN: AltOpcode = ISD::UMIN; break; 4005 case ISD::SMAX: AltOpcode = ISD::UMAX; break; 4006 case ISD::UMIN: AltOpcode = ISD::SMIN; break; 4007 case ISD::UMAX: AltOpcode = ISD::SMAX; break; 4008 default: llvm_unreachable("Unknown MINMAX opcode"); 4009 } 4010 if (TLI.isOperationLegal(AltOpcode, VT)) 4011 return DAG.getNode(AltOpcode, SDLoc(N), VT, N0, N1); 4012 } 4013 4014 return SDValue(); 4015 } 4016 4017 /// If this is a bitwise logic instruction and both operands have the same 4018 /// opcode, try to sink the other opcode after the logic instruction. 4019 SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) { 4020 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 4021 EVT VT = N0.getValueType(); 4022 unsigned LogicOpcode = N->getOpcode(); 4023 unsigned HandOpcode = N0.getOpcode(); 4024 assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR || 4025 LogicOpcode == ISD::XOR) && "Expected logic opcode"); 4026 assert(HandOpcode == N1.getOpcode() && "Bad input!"); 4027 4028 // Bail early if none of these transforms apply. 4029 if (N0.getNumOperands() == 0) 4030 return SDValue(); 4031 4032 // FIXME: We should check number of uses of the operands to not increase 4033 // the instruction count for all transforms. 4034 4035 // Handle size-changing casts. 4036 SDValue X = N0.getOperand(0); 4037 SDValue Y = N1.getOperand(0); 4038 EVT XVT = X.getValueType(); 4039 SDLoc DL(N); 4040 if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND || 4041 HandOpcode == ISD::SIGN_EXTEND) { 4042 // If both operands have other uses, this transform would create extra 4043 // instructions without eliminating anything. 4044 if (!N0.hasOneUse() && !N1.hasOneUse()) 4045 return SDValue(); 4046 // We need matching integer source types. 4047 if (XVT != Y.getValueType()) 4048 return SDValue(); 4049 // Don't create an illegal op during or after legalization. Don't ever 4050 // create an unsupported vector op. 4051 if ((VT.isVector() || LegalOperations) && 4052 !TLI.isOperationLegalOrCustom(LogicOpcode, XVT)) 4053 return SDValue(); 4054 // Avoid infinite looping with PromoteIntBinOp. 4055 // TODO: Should we apply desirable/legal constraints to all opcodes? 4056 if (HandOpcode == ISD::ANY_EXTEND && LegalTypes && 4057 !TLI.isTypeDesirableForOp(LogicOpcode, XVT)) 4058 return SDValue(); 4059 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y) 4060 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4061 return DAG.getNode(HandOpcode, DL, VT, Logic); 4062 } 4063 4064 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y) 4065 if (HandOpcode == ISD::TRUNCATE) { 4066 // If both operands have other uses, this transform would create extra 4067 // instructions without eliminating anything. 4068 if (!N0.hasOneUse() && !N1.hasOneUse()) 4069 return SDValue(); 4070 // We need matching source types. 4071 if (XVT != Y.getValueType()) 4072 return SDValue(); 4073 // Don't create an illegal op during or after legalization. 4074 if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT)) 4075 return SDValue(); 4076 // Be extra careful sinking truncate. If it's free, there's no benefit in 4077 // widening a binop. Also, don't create a logic op on an illegal type. 4078 if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT)) 4079 return SDValue(); 4080 if (!TLI.isTypeLegal(XVT)) 4081 return SDValue(); 4082 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4083 return DAG.getNode(HandOpcode, DL, VT, Logic); 4084 } 4085 4086 // For binops SHL/SRL/SRA/AND: 4087 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z 4088 if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL || 4089 HandOpcode == ISD::SRA || HandOpcode == ISD::AND) && 4090 N0.getOperand(1) == N1.getOperand(1)) { 4091 // If either operand has other uses, this transform is not an improvement. 4092 if (!N0.hasOneUse() || !N1.hasOneUse()) 4093 return SDValue(); 4094 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4095 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1)); 4096 } 4097 4098 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y) 4099 if (HandOpcode == ISD::BSWAP) { 4100 // If either operand has other uses, this transform is not an improvement. 4101 if (!N0.hasOneUse() || !N1.hasOneUse()) 4102 return SDValue(); 4103 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4104 return DAG.getNode(HandOpcode, DL, VT, Logic); 4105 } 4106 4107 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 4108 // Only perform this optimization up until type legalization, before 4109 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 4110 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 4111 // we don't want to undo this promotion. 4112 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 4113 // on scalars. 4114 if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) && 4115 Level <= AfterLegalizeTypes) { 4116 // Input types must be integer and the same. 4117 if (XVT.isInteger() && XVT == Y.getValueType()) { 4118 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4119 return DAG.getNode(HandOpcode, DL, VT, Logic); 4120 } 4121 } 4122 4123 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 4124 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 4125 // If both shuffles use the same mask, and both shuffle within a single 4126 // vector, then it is worthwhile to move the swizzle after the operation. 4127 // The type-legalizer generates this pattern when loading illegal 4128 // vector types from memory. In many cases this allows additional shuffle 4129 // optimizations. 4130 // There are other cases where moving the shuffle after the xor/and/or 4131 // is profitable even if shuffles don't perform a swizzle. 4132 // If both shuffles use the same mask, and both shuffles have the same first 4133 // or second operand, then it might still be profitable to move the shuffle 4134 // after the xor/and/or operation. 4135 if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 4136 auto *SVN0 = cast<ShuffleVectorSDNode>(N0); 4137 auto *SVN1 = cast<ShuffleVectorSDNode>(N1); 4138 assert(X.getValueType() == Y.getValueType() && 4139 "Inputs to shuffles are not the same type"); 4140 4141 // Check that both shuffles use the same mask. The masks are known to be of 4142 // the same length because the result vector type is the same. 4143 // Check also that shuffles have only one use to avoid introducing extra 4144 // instructions. 4145 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() || 4146 !SVN0->getMask().equals(SVN1->getMask())) 4147 return SDValue(); 4148 4149 // Don't try to fold this node if it requires introducing a 4150 // build vector of all zeros that might be illegal at this stage. 4151 SDValue ShOp = N0.getOperand(1); 4152 if (LogicOpcode == ISD::XOR && !ShOp.isUndef()) 4153 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 4154 4155 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C) 4156 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 4157 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, 4158 N0.getOperand(0), N1.getOperand(0)); 4159 return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask()); 4160 } 4161 4162 // Don't try to fold this node if it requires introducing a 4163 // build vector of all zeros that might be illegal at this stage. 4164 ShOp = N0.getOperand(0); 4165 if (LogicOpcode == ISD::XOR && !ShOp.isUndef()) 4166 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 4167 4168 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B)) 4169 if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) { 4170 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1), 4171 N1.getOperand(1)); 4172 return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask()); 4173 } 4174 } 4175 4176 return SDValue(); 4177 } 4178 4179 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 4180 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 4181 const SDLoc &DL) { 4182 SDValue LL, LR, RL, RR, N0CC, N1CC; 4183 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 4184 !isSetCCEquivalent(N1, RL, RR, N1CC)) 4185 return SDValue(); 4186 4187 assert(N0.getValueType() == N1.getValueType() && 4188 "Unexpected operand types for bitwise logic op"); 4189 assert(LL.getValueType() == LR.getValueType() && 4190 RL.getValueType() == RR.getValueType() && 4191 "Unexpected operand types for setcc"); 4192 4193 // If we're here post-legalization or the logic op type is not i1, the logic 4194 // op type must match a setcc result type. Also, all folds require new 4195 // operations on the left and right operands, so those types must match. 4196 EVT VT = N0.getValueType(); 4197 EVT OpVT = LL.getValueType(); 4198 if (LegalOperations || VT.getScalarType() != MVT::i1) 4199 if (VT != getSetCCResultType(OpVT)) 4200 return SDValue(); 4201 if (OpVT != RL.getValueType()) 4202 return SDValue(); 4203 4204 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 4205 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 4206 bool IsInteger = OpVT.isInteger(); 4207 if (LR == RR && CC0 == CC1 && IsInteger) { 4208 bool IsZero = isNullOrNullSplat(LR); 4209 bool IsNeg1 = isAllOnesOrAllOnesSplat(LR); 4210 4211 // All bits clear? 4212 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 4213 // All sign bits clear? 4214 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 4215 // Any bits set? 4216 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 4217 // Any sign bits set? 4218 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 4219 4220 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 4221 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 4222 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 4223 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 4224 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 4225 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 4226 AddToWorklist(Or.getNode()); 4227 return DAG.getSetCC(DL, VT, Or, LR, CC1); 4228 } 4229 4230 // All bits set? 4231 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 4232 // All sign bits set? 4233 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 4234 // Any bits clear? 4235 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 4236 // Any sign bits clear? 4237 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 4238 4239 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 4240 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 4241 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 4242 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 4243 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 4244 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 4245 AddToWorklist(And.getNode()); 4246 return DAG.getSetCC(DL, VT, And, LR, CC1); 4247 } 4248 } 4249 4250 // TODO: What is the 'or' equivalent of this fold? 4251 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 4252 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && 4253 IsInteger && CC0 == ISD::SETNE && 4254 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 4255 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 4256 SDValue One = DAG.getConstant(1, DL, OpVT); 4257 SDValue Two = DAG.getConstant(2, DL, OpVT); 4258 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 4259 AddToWorklist(Add.getNode()); 4260 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 4261 } 4262 4263 // Try more general transforms if the predicates match and the only user of 4264 // the compares is the 'and' or 'or'. 4265 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 4266 N0.hasOneUse() && N1.hasOneUse()) { 4267 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 4268 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 4269 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 4270 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 4271 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 4272 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 4273 SDValue Zero = DAG.getConstant(0, DL, OpVT); 4274 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 4275 } 4276 4277 // Turn compare of constants whose difference is 1 bit into add+and+setcc. 4278 if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) { 4279 // Match a shared variable operand and 2 non-opaque constant operands. 4280 ConstantSDNode *C0 = isConstOrConstSplat(LR); 4281 ConstantSDNode *C1 = isConstOrConstSplat(RR); 4282 if (LL == RL && C0 && C1 && !C0->isOpaque() && !C1->isOpaque()) { 4283 // Canonicalize larger constant as C0. 4284 if (C1->getAPIntValue().ugt(C0->getAPIntValue())) 4285 std::swap(C0, C1); 4286 4287 // The difference of the constants must be a single bit. 4288 const APInt &C0Val = C0->getAPIntValue(); 4289 const APInt &C1Val = C1->getAPIntValue(); 4290 if ((C0Val - C1Val).isPowerOf2()) { 4291 // and/or (setcc X, C0, ne), (setcc X, C1, ne/eq) --> 4292 // setcc ((add X, -C1), ~(C0 - C1)), 0, ne/eq 4293 SDValue OffsetC = DAG.getConstant(-C1Val, DL, OpVT); 4294 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LL, OffsetC); 4295 SDValue MaskC = DAG.getConstant(~(C0Val - C1Val), DL, OpVT); 4296 SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Add, MaskC); 4297 SDValue Zero = DAG.getConstant(0, DL, OpVT); 4298 return DAG.getSetCC(DL, VT, And, Zero, CC0); 4299 } 4300 } 4301 } 4302 } 4303 4304 // Canonicalize equivalent operands to LL == RL. 4305 if (LL == RR && LR == RL) { 4306 CC1 = ISD::getSetCCSwappedOperands(CC1); 4307 std::swap(RL, RR); 4308 } 4309 4310 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 4311 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 4312 if (LL == RL && LR == RR) { 4313 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, IsInteger) 4314 : ISD::getSetCCOrOperation(CC0, CC1, IsInteger); 4315 if (NewCC != ISD::SETCC_INVALID && 4316 (!LegalOperations || 4317 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 4318 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 4319 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 4320 } 4321 4322 return SDValue(); 4323 } 4324 4325 /// This contains all DAGCombine rules which reduce two values combined by 4326 /// an And operation to a single value. This makes them reusable in the context 4327 /// of visitSELECT(). Rules involving constants are not included as 4328 /// visitSELECT() already handles those cases. 4329 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 4330 EVT VT = N1.getValueType(); 4331 SDLoc DL(N); 4332 4333 // fold (and x, undef) -> 0 4334 if (N0.isUndef() || N1.isUndef()) 4335 return DAG.getConstant(0, DL, VT); 4336 4337 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 4338 return V; 4339 4340 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 4341 VT.getSizeInBits() <= 64) { 4342 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4343 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 4344 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 4345 // immediate for an add, but it is legal if its top c2 bits are set, 4346 // transform the ADD so the immediate doesn't need to be materialized 4347 // in a register. 4348 APInt ADDC = ADDI->getAPIntValue(); 4349 APInt SRLC = SRLI->getAPIntValue(); 4350 if (ADDC.getMinSignedBits() <= 64 && 4351 SRLC.ult(VT.getSizeInBits()) && 4352 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 4353 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 4354 SRLC.getZExtValue()); 4355 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 4356 ADDC |= Mask; 4357 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 4358 SDLoc DL0(N0); 4359 SDValue NewAdd = 4360 DAG.getNode(ISD::ADD, DL0, VT, 4361 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 4362 CombineTo(N0.getNode(), NewAdd); 4363 // Return N so it doesn't get rechecked! 4364 return SDValue(N, 0); 4365 } 4366 } 4367 } 4368 } 4369 } 4370 } 4371 4372 // Reduce bit extract of low half of an integer to the narrower type. 4373 // (and (srl i64:x, K), KMask) -> 4374 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 4375 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 4376 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 4377 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 4378 unsigned Size = VT.getSizeInBits(); 4379 const APInt &AndMask = CAnd->getAPIntValue(); 4380 unsigned ShiftBits = CShift->getZExtValue(); 4381 4382 // Bail out, this node will probably disappear anyway. 4383 if (ShiftBits == 0) 4384 return SDValue(); 4385 4386 unsigned MaskBits = AndMask.countTrailingOnes(); 4387 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 4388 4389 if (AndMask.isMask() && 4390 // Required bits must not span the two halves of the integer and 4391 // must fit in the half size type. 4392 (ShiftBits + MaskBits <= Size / 2) && 4393 TLI.isNarrowingProfitable(VT, HalfVT) && 4394 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 4395 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 4396 TLI.isTruncateFree(VT, HalfVT) && 4397 TLI.isZExtFree(HalfVT, VT)) { 4398 // The isNarrowingProfitable is to avoid regressions on PPC and 4399 // AArch64 which match a few 64-bit bit insert / bit extract patterns 4400 // on downstream users of this. Those patterns could probably be 4401 // extended to handle extensions mixed in. 4402 4403 SDValue SL(N0); 4404 assert(MaskBits <= Size); 4405 4406 // Extracting the highest bit of the low half. 4407 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 4408 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 4409 N0.getOperand(0)); 4410 4411 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 4412 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 4413 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 4414 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 4415 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 4416 } 4417 } 4418 } 4419 } 4420 4421 return SDValue(); 4422 } 4423 4424 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 4425 EVT LoadResultTy, EVT &ExtVT) { 4426 if (!AndC->getAPIntValue().isMask()) 4427 return false; 4428 4429 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 4430 4431 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 4432 EVT LoadedVT = LoadN->getMemoryVT(); 4433 4434 if (ExtVT == LoadedVT && 4435 (!LegalOperations || 4436 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 4437 // ZEXTLOAD will match without needing to change the size of the value being 4438 // loaded. 4439 return true; 4440 } 4441 4442 // Do not change the width of a volatile load. 4443 if (LoadN->isVolatile()) 4444 return false; 4445 4446 // Do not generate loads of non-round integer types since these can 4447 // be expensive (and would be wrong if the type is not byte sized). 4448 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 4449 return false; 4450 4451 if (LegalOperations && 4452 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 4453 return false; 4454 4455 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 4456 return false; 4457 4458 return true; 4459 } 4460 4461 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST, 4462 ISD::LoadExtType ExtType, EVT &MemVT, 4463 unsigned ShAmt) { 4464 if (!LDST) 4465 return false; 4466 // Only allow byte offsets. 4467 if (ShAmt % 8) 4468 return false; 4469 4470 // Do not generate loads of non-round integer types since these can 4471 // be expensive (and would be wrong if the type is not byte sized). 4472 if (!MemVT.isRound()) 4473 return false; 4474 4475 // Don't change the width of a volatile load. 4476 if (LDST->isVolatile()) 4477 return false; 4478 4479 // Verify that we are actually reducing a load width here. 4480 if (LDST->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits()) 4481 return false; 4482 4483 // Ensure that this isn't going to produce an unsupported unaligned access. 4484 if (ShAmt && 4485 !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 4486 LDST->getAddressSpace(), ShAmt / 8)) 4487 return false; 4488 4489 // It's not possible to generate a constant of extended or untyped type. 4490 EVT PtrType = LDST->getBasePtr().getValueType(); 4491 if (PtrType == MVT::Untyped || PtrType.isExtended()) 4492 return false; 4493 4494 if (isa<LoadSDNode>(LDST)) { 4495 LoadSDNode *Load = cast<LoadSDNode>(LDST); 4496 // Don't transform one with multiple uses, this would require adding a new 4497 // load. 4498 if (!SDValue(Load, 0).hasOneUse()) 4499 return false; 4500 4501 if (LegalOperations && 4502 !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT)) 4503 return false; 4504 4505 // For the transform to be legal, the load must produce only two values 4506 // (the value loaded and the chain). Don't transform a pre-increment 4507 // load, for example, which produces an extra value. Otherwise the 4508 // transformation is not equivalent, and the downstream logic to replace 4509 // uses gets things wrong. 4510 if (Load->getNumValues() > 2) 4511 return false; 4512 4513 // If the load that we're shrinking is an extload and we're not just 4514 // discarding the extension we can't simply shrink the load. Bail. 4515 // TODO: It would be possible to merge the extensions in some cases. 4516 if (Load->getExtensionType() != ISD::NON_EXTLOAD && 4517 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 4518 return false; 4519 4520 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT)) 4521 return false; 4522 } else { 4523 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode"); 4524 StoreSDNode *Store = cast<StoreSDNode>(LDST); 4525 // Can't write outside the original store 4526 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 4527 return false; 4528 4529 if (LegalOperations && 4530 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT)) 4531 return false; 4532 } 4533 return true; 4534 } 4535 4536 bool DAGCombiner::SearchForAndLoads(SDNode *N, 4537 SmallVectorImpl<LoadSDNode*> &Loads, 4538 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 4539 ConstantSDNode *Mask, 4540 SDNode *&NodeToMask) { 4541 // Recursively search for the operands, looking for loads which can be 4542 // narrowed. 4543 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) { 4544 SDValue Op = N->getOperand(i); 4545 4546 if (Op.getValueType().isVector()) 4547 return false; 4548 4549 // Some constants may need fixing up later if they are too large. 4550 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 4551 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) && 4552 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue()) 4553 NodesWithConsts.insert(N); 4554 continue; 4555 } 4556 4557 if (!Op.hasOneUse()) 4558 return false; 4559 4560 switch(Op.getOpcode()) { 4561 case ISD::LOAD: { 4562 auto *Load = cast<LoadSDNode>(Op); 4563 EVT ExtVT; 4564 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) && 4565 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) { 4566 4567 // ZEXTLOAD is already small enough. 4568 if (Load->getExtensionType() == ISD::ZEXTLOAD && 4569 ExtVT.bitsGE(Load->getMemoryVT())) 4570 continue; 4571 4572 // Use LE to convert equal sized loads to zext. 4573 if (ExtVT.bitsLE(Load->getMemoryVT())) 4574 Loads.push_back(Load); 4575 4576 continue; 4577 } 4578 return false; 4579 } 4580 case ISD::ZERO_EXTEND: 4581 case ISD::AssertZext: { 4582 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes(); 4583 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 4584 EVT VT = Op.getOpcode() == ISD::AssertZext ? 4585 cast<VTSDNode>(Op.getOperand(1))->getVT() : 4586 Op.getOperand(0).getValueType(); 4587 4588 // We can accept extending nodes if the mask is wider or an equal 4589 // width to the original type. 4590 if (ExtVT.bitsGE(VT)) 4591 continue; 4592 break; 4593 } 4594 case ISD::OR: 4595 case ISD::XOR: 4596 case ISD::AND: 4597 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask, 4598 NodeToMask)) 4599 return false; 4600 continue; 4601 } 4602 4603 // Allow one node which will masked along with any loads found. 4604 if (NodeToMask) 4605 return false; 4606 4607 // Also ensure that the node to be masked only produces one data result. 4608 NodeToMask = Op.getNode(); 4609 if (NodeToMask->getNumValues() > 1) { 4610 bool HasValue = false; 4611 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) { 4612 MVT VT = SDValue(NodeToMask, i).getSimpleValueType(); 4613 if (VT != MVT::Glue && VT != MVT::Other) { 4614 if (HasValue) { 4615 NodeToMask = nullptr; 4616 return false; 4617 } 4618 HasValue = true; 4619 } 4620 } 4621 assert(HasValue && "Node to be masked has no data result?"); 4622 } 4623 } 4624 return true; 4625 } 4626 4627 bool DAGCombiner::BackwardsPropagateMask(SDNode *N, SelectionDAG &DAG) { 4628 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1)); 4629 if (!Mask) 4630 return false; 4631 4632 if (!Mask->getAPIntValue().isMask()) 4633 return false; 4634 4635 // No need to do anything if the and directly uses a load. 4636 if (isa<LoadSDNode>(N->getOperand(0))) 4637 return false; 4638 4639 SmallVector<LoadSDNode*, 8> Loads; 4640 SmallPtrSet<SDNode*, 2> NodesWithConsts; 4641 SDNode *FixupNode = nullptr; 4642 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) { 4643 if (Loads.size() == 0) 4644 return false; 4645 4646 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump()); 4647 SDValue MaskOp = N->getOperand(1); 4648 4649 // If it exists, fixup the single node we allow in the tree that needs 4650 // masking. 4651 if (FixupNode) { 4652 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump()); 4653 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode), 4654 FixupNode->getValueType(0), 4655 SDValue(FixupNode, 0), MaskOp); 4656 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And); 4657 if (And.getOpcode() == ISD ::AND) 4658 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp); 4659 } 4660 4661 // Narrow any constants that need it. 4662 for (auto *LogicN : NodesWithConsts) { 4663 SDValue Op0 = LogicN->getOperand(0); 4664 SDValue Op1 = LogicN->getOperand(1); 4665 4666 if (isa<ConstantSDNode>(Op0)) 4667 std::swap(Op0, Op1); 4668 4669 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), 4670 Op1, MaskOp); 4671 4672 DAG.UpdateNodeOperands(LogicN, Op0, And); 4673 } 4674 4675 // Create narrow loads. 4676 for (auto *Load : Loads) { 4677 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump()); 4678 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0), 4679 SDValue(Load, 0), MaskOp); 4680 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And); 4681 if (And.getOpcode() == ISD ::AND) 4682 And = SDValue( 4683 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0); 4684 SDValue NewLoad = ReduceLoadWidth(And.getNode()); 4685 assert(NewLoad && 4686 "Shouldn't be masking the load if it can't be narrowed"); 4687 CombineTo(Load, NewLoad, NewLoad.getValue(1)); 4688 } 4689 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode()); 4690 return true; 4691 } 4692 return false; 4693 } 4694 4695 // Unfold 4696 // x & (-1 'logical shift' y) 4697 // To 4698 // (x 'opposite logical shift' y) 'logical shift' y 4699 // if it is better for performance. 4700 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) { 4701 assert(N->getOpcode() == ISD::AND); 4702 4703 SDValue N0 = N->getOperand(0); 4704 SDValue N1 = N->getOperand(1); 4705 4706 // Do we actually prefer shifts over mask? 4707 if (!TLI.shouldFoldMaskToVariableShiftPair(N0)) 4708 return SDValue(); 4709 4710 // Try to match (-1 '[outer] logical shift' y) 4711 unsigned OuterShift; 4712 unsigned InnerShift; // The opposite direction to the OuterShift. 4713 SDValue Y; // Shift amount. 4714 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool { 4715 if (!M.hasOneUse()) 4716 return false; 4717 OuterShift = M->getOpcode(); 4718 if (OuterShift == ISD::SHL) 4719 InnerShift = ISD::SRL; 4720 else if (OuterShift == ISD::SRL) 4721 InnerShift = ISD::SHL; 4722 else 4723 return false; 4724 if (!isAllOnesConstant(M->getOperand(0))) 4725 return false; 4726 Y = M->getOperand(1); 4727 return true; 4728 }; 4729 4730 SDValue X; 4731 if (matchMask(N1)) 4732 X = N0; 4733 else if (matchMask(N0)) 4734 X = N1; 4735 else 4736 return SDValue(); 4737 4738 SDLoc DL(N); 4739 EVT VT = N->getValueType(0); 4740 4741 // tmp = x 'opposite logical shift' y 4742 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y); 4743 // ret = tmp 'logical shift' y 4744 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y); 4745 4746 return T1; 4747 } 4748 4749 SDValue DAGCombiner::visitAND(SDNode *N) { 4750 SDValue N0 = N->getOperand(0); 4751 SDValue N1 = N->getOperand(1); 4752 EVT VT = N1.getValueType(); 4753 4754 // x & x --> x 4755 if (N0 == N1) 4756 return N0; 4757 4758 // fold vector ops 4759 if (VT.isVector()) { 4760 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 4761 return FoldedVOp; 4762 4763 // fold (and x, 0) -> 0, vector edition 4764 if (ISD::isBuildVectorAllZeros(N0.getNode())) 4765 // do not return N0, because undef node may exist in N0 4766 return DAG.getConstant(APInt::getNullValue(N0.getScalarValueSizeInBits()), 4767 SDLoc(N), N0.getValueType()); 4768 if (ISD::isBuildVectorAllZeros(N1.getNode())) 4769 // do not return N1, because undef node may exist in N1 4770 return DAG.getConstant(APInt::getNullValue(N1.getScalarValueSizeInBits()), 4771 SDLoc(N), N1.getValueType()); 4772 4773 // fold (and x, -1) -> x, vector edition 4774 if (ISD::isBuildVectorAllOnes(N0.getNode())) 4775 return N1; 4776 if (ISD::isBuildVectorAllOnes(N1.getNode())) 4777 return N0; 4778 } 4779 4780 // fold (and c1, c2) -> c1&c2 4781 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 4782 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4783 if (N0C && N1C && !N1C->isOpaque()) 4784 return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C); 4785 // canonicalize constant to RHS 4786 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4787 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4788 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 4789 // fold (and x, -1) -> x 4790 if (isAllOnesConstant(N1)) 4791 return N0; 4792 // if (and x, c) is known to be zero, return 0 4793 unsigned BitWidth = VT.getScalarSizeInBits(); 4794 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 4795 APInt::getAllOnesValue(BitWidth))) 4796 return DAG.getConstant(0, SDLoc(N), VT); 4797 4798 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4799 return NewSel; 4800 4801 // reassociate and 4802 if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags())) 4803 return RAND; 4804 4805 // Try to convert a constant mask AND into a shuffle clear mask. 4806 if (VT.isVector()) 4807 if (SDValue Shuffle = XformToShuffleWithZero(N)) 4808 return Shuffle; 4809 4810 // fold (and (or x, C), D) -> D if (C & D) == D 4811 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 4812 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue()); 4813 }; 4814 if (N0.getOpcode() == ISD::OR && 4815 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset)) 4816 return N1; 4817 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 4818 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 4819 SDValue N0Op0 = N0.getOperand(0); 4820 APInt Mask = ~N1C->getAPIntValue(); 4821 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 4822 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 4823 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 4824 N0.getValueType(), N0Op0); 4825 4826 // Replace uses of the AND with uses of the Zero extend node. 4827 CombineTo(N, Zext); 4828 4829 // We actually want to replace all uses of the any_extend with the 4830 // zero_extend, to avoid duplicating things. This will later cause this 4831 // AND to be folded. 4832 CombineTo(N0.getNode(), Zext); 4833 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4834 } 4835 } 4836 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 4837 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 4838 // already be zero by virtue of the width of the base type of the load. 4839 // 4840 // the 'X' node here can either be nothing or an extract_vector_elt to catch 4841 // more cases. 4842 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 4843 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 4844 N0.getOperand(0).getOpcode() == ISD::LOAD && 4845 N0.getOperand(0).getResNo() == 0) || 4846 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 4847 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 4848 N0 : N0.getOperand(0) ); 4849 4850 // Get the constant (if applicable) the zero'th operand is being ANDed with. 4851 // This can be a pure constant or a vector splat, in which case we treat the 4852 // vector as a scalar and use the splat value. 4853 APInt Constant = APInt::getNullValue(1); 4854 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 4855 Constant = C->getAPIntValue(); 4856 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 4857 APInt SplatValue, SplatUndef; 4858 unsigned SplatBitSize; 4859 bool HasAnyUndefs; 4860 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 4861 SplatBitSize, HasAnyUndefs); 4862 if (IsSplat) { 4863 // Undef bits can contribute to a possible optimisation if set, so 4864 // set them. 4865 SplatValue |= SplatUndef; 4866 4867 // The splat value may be something like "0x00FFFFFF", which means 0 for 4868 // the first vector value and FF for the rest, repeating. We need a mask 4869 // that will apply equally to all members of the vector, so AND all the 4870 // lanes of the constant together. 4871 EVT VT = Vector->getValueType(0); 4872 unsigned BitWidth = VT.getScalarSizeInBits(); 4873 4874 // If the splat value has been compressed to a bitlength lower 4875 // than the size of the vector lane, we need to re-expand it to 4876 // the lane size. 4877 if (BitWidth > SplatBitSize) 4878 for (SplatValue = SplatValue.zextOrTrunc(BitWidth); 4879 SplatBitSize < BitWidth; 4880 SplatBitSize = SplatBitSize * 2) 4881 SplatValue |= SplatValue.shl(SplatBitSize); 4882 4883 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 4884 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 4885 if (SplatBitSize % BitWidth == 0) { 4886 Constant = APInt::getAllOnesValue(BitWidth); 4887 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i) 4888 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth); 4889 } 4890 } 4891 } 4892 4893 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 4894 // actually legal and isn't going to get expanded, else this is a false 4895 // optimisation. 4896 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 4897 Load->getValueType(0), 4898 Load->getMemoryVT()); 4899 4900 // Resize the constant to the same size as the original memory access before 4901 // extension. If it is still the AllOnesValue then this AND is completely 4902 // unneeded. 4903 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 4904 4905 bool B; 4906 switch (Load->getExtensionType()) { 4907 default: B = false; break; 4908 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 4909 case ISD::ZEXTLOAD: 4910 case ISD::NON_EXTLOAD: B = true; break; 4911 } 4912 4913 if (B && Constant.isAllOnesValue()) { 4914 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 4915 // preserve semantics once we get rid of the AND. 4916 SDValue NewLoad(Load, 0); 4917 4918 // Fold the AND away. NewLoad may get replaced immediately. 4919 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 4920 4921 if (Load->getExtensionType() == ISD::EXTLOAD) { 4922 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 4923 Load->getValueType(0), SDLoc(Load), 4924 Load->getChain(), Load->getBasePtr(), 4925 Load->getOffset(), Load->getMemoryVT(), 4926 Load->getMemOperand()); 4927 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 4928 if (Load->getNumValues() == 3) { 4929 // PRE/POST_INC loads have 3 values. 4930 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 4931 NewLoad.getValue(2) }; 4932 CombineTo(Load, To, 3, true); 4933 } else { 4934 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 4935 } 4936 } 4937 4938 return SDValue(N, 0); // Return N so it doesn't get rechecked! 4939 } 4940 } 4941 4942 // fold (and (load x), 255) -> (zextload x, i8) 4943 // fold (and (extload x, i16), 255) -> (zextload x, i8) 4944 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 4945 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 4946 (N0.getOpcode() == ISD::ANY_EXTEND && 4947 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 4948 if (SDValue Res = ReduceLoadWidth(N)) { 4949 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND 4950 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 4951 AddToWorklist(N); 4952 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 0), Res); 4953 return SDValue(N, 0); 4954 } 4955 } 4956 4957 if (Level >= AfterLegalizeTypes) { 4958 // Attempt to propagate the AND back up to the leaves which, if they're 4959 // loads, can be combined to narrow loads and the AND node can be removed. 4960 // Perform after legalization so that extend nodes will already be 4961 // combined into the loads. 4962 if (BackwardsPropagateMask(N, DAG)) { 4963 return SDValue(N, 0); 4964 } 4965 } 4966 4967 if (SDValue Combined = visitANDLike(N0, N1, N)) 4968 return Combined; 4969 4970 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 4971 if (N0.getOpcode() == N1.getOpcode()) 4972 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) 4973 return V; 4974 4975 // Masking the negated extension of a boolean is just the zero-extended 4976 // boolean: 4977 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 4978 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 4979 // 4980 // Note: the SimplifyDemandedBits fold below can make an information-losing 4981 // transform, and then we have no way to find this better fold. 4982 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 4983 if (isNullOrNullSplat(N0.getOperand(0))) { 4984 SDValue SubRHS = N0.getOperand(1); 4985 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 4986 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4987 return SubRHS; 4988 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 4989 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 4990 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 4991 } 4992 } 4993 4994 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 4995 // fold (and (sra)) -> (and (srl)) when possible. 4996 if (SimplifyDemandedBits(SDValue(N, 0))) 4997 return SDValue(N, 0); 4998 4999 // fold (zext_inreg (extload x)) -> (zextload x) 5000 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) { 5001 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5002 EVT MemVT = LN0->getMemoryVT(); 5003 // If we zero all the possible extended bits, then we can turn this into 5004 // a zextload if we are running before legalize or the operation is legal. 5005 unsigned BitWidth = N1.getScalarValueSizeInBits(); 5006 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 5007 BitWidth - MemVT.getScalarSizeInBits())) && 5008 ((!LegalOperations && !LN0->isVolatile()) || 5009 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 5010 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 5011 LN0->getChain(), LN0->getBasePtr(), 5012 MemVT, LN0->getMemOperand()); 5013 AddToWorklist(N); 5014 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5015 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5016 } 5017 } 5018 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 5019 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 5020 N0.hasOneUse()) { 5021 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5022 EVT MemVT = LN0->getMemoryVT(); 5023 // If we zero all the possible extended bits, then we can turn this into 5024 // a zextload if we are running before legalize or the operation is legal. 5025 unsigned BitWidth = N1.getScalarValueSizeInBits(); 5026 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth, 5027 BitWidth - MemVT.getScalarSizeInBits())) && 5028 ((!LegalOperations && !LN0->isVolatile()) || 5029 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 5030 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, 5031 LN0->getChain(), LN0->getBasePtr(), 5032 MemVT, LN0->getMemOperand()); 5033 AddToWorklist(N); 5034 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5035 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5036 } 5037 } 5038 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 5039 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 5040 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5041 N0.getOperand(1), false)) 5042 return BSwap; 5043 } 5044 5045 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N)) 5046 return Shifts; 5047 5048 return SDValue(); 5049 } 5050 5051 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 5052 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 5053 bool DemandHighBits) { 5054 if (!LegalOperations) 5055 return SDValue(); 5056 5057 EVT VT = N->getValueType(0); 5058 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 5059 return SDValue(); 5060 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 5061 return SDValue(); 5062 5063 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) 5064 bool LookPassAnd0 = false; 5065 bool LookPassAnd1 = false; 5066 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 5067 std::swap(N0, N1); 5068 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 5069 std::swap(N0, N1); 5070 if (N0.getOpcode() == ISD::AND) { 5071 if (!N0.getNode()->hasOneUse()) 5072 return SDValue(); 5073 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5074 // Also handle 0xffff since the LHS is guaranteed to have zeros there. 5075 // This is needed for X86. 5076 if (!N01C || (N01C->getZExtValue() != 0xFF00 && 5077 N01C->getZExtValue() != 0xFFFF)) 5078 return SDValue(); 5079 N0 = N0.getOperand(0); 5080 LookPassAnd0 = true; 5081 } 5082 5083 if (N1.getOpcode() == ISD::AND) { 5084 if (!N1.getNode()->hasOneUse()) 5085 return SDValue(); 5086 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 5087 if (!N11C || N11C->getZExtValue() != 0xFF) 5088 return SDValue(); 5089 N1 = N1.getOperand(0); 5090 LookPassAnd1 = true; 5091 } 5092 5093 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 5094 std::swap(N0, N1); 5095 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 5096 return SDValue(); 5097 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 5098 return SDValue(); 5099 5100 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5101 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 5102 if (!N01C || !N11C) 5103 return SDValue(); 5104 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 5105 return SDValue(); 5106 5107 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 5108 SDValue N00 = N0->getOperand(0); 5109 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 5110 if (!N00.getNode()->hasOneUse()) 5111 return SDValue(); 5112 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 5113 if (!N001C || N001C->getZExtValue() != 0xFF) 5114 return SDValue(); 5115 N00 = N00.getOperand(0); 5116 LookPassAnd0 = true; 5117 } 5118 5119 SDValue N10 = N1->getOperand(0); 5120 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 5121 if (!N10.getNode()->hasOneUse()) 5122 return SDValue(); 5123 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 5124 // Also allow 0xFFFF since the bits will be shifted out. This is needed 5125 // for X86. 5126 if (!N101C || (N101C->getZExtValue() != 0xFF00 && 5127 N101C->getZExtValue() != 0xFFFF)) 5128 return SDValue(); 5129 N10 = N10.getOperand(0); 5130 LookPassAnd1 = true; 5131 } 5132 5133 if (N00 != N10) 5134 return SDValue(); 5135 5136 // Make sure everything beyond the low halfword gets set to zero since the SRL 5137 // 16 will clear the top bits. 5138 unsigned OpSizeInBits = VT.getSizeInBits(); 5139 if (DemandHighBits && OpSizeInBits > 16) { 5140 // If the left-shift isn't masked out then the only way this is a bswap is 5141 // if all bits beyond the low 8 are 0. In that case the entire pattern 5142 // reduces to a left shift anyway: leave it for other parts of the combiner. 5143 if (!LookPassAnd0) 5144 return SDValue(); 5145 5146 // However, if the right shift isn't masked out then it might be because 5147 // it's not needed. See if we can spot that too. 5148 if (!LookPassAnd1 && 5149 !DAG.MaskedValueIsZero( 5150 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 5151 return SDValue(); 5152 } 5153 5154 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 5155 if (OpSizeInBits > 16) { 5156 SDLoc DL(N); 5157 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 5158 DAG.getConstant(OpSizeInBits - 16, DL, 5159 getShiftAmountTy(VT))); 5160 } 5161 return Res; 5162 } 5163 5164 /// Return true if the specified node is an element that makes up a 32-bit 5165 /// packed halfword byteswap. 5166 /// ((x & 0x000000ff) << 8) | 5167 /// ((x & 0x0000ff00) >> 8) | 5168 /// ((x & 0x00ff0000) << 8) | 5169 /// ((x & 0xff000000) >> 8) 5170 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 5171 if (!N.getNode()->hasOneUse()) 5172 return false; 5173 5174 unsigned Opc = N.getOpcode(); 5175 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 5176 return false; 5177 5178 SDValue N0 = N.getOperand(0); 5179 unsigned Opc0 = N0.getOpcode(); 5180 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 5181 return false; 5182 5183 ConstantSDNode *N1C = nullptr; 5184 // SHL or SRL: look upstream for AND mask operand 5185 if (Opc == ISD::AND) 5186 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 5187 else if (Opc0 == ISD::AND) 5188 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5189 if (!N1C) 5190 return false; 5191 5192 unsigned MaskByteOffset; 5193 switch (N1C->getZExtValue()) { 5194 default: 5195 return false; 5196 case 0xFF: MaskByteOffset = 0; break; 5197 case 0xFF00: MaskByteOffset = 1; break; 5198 case 0xFFFF: 5199 // In case demanded bits didn't clear the bits that will be shifted out. 5200 // This is needed for X86. 5201 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) { 5202 MaskByteOffset = 1; 5203 break; 5204 } 5205 return false; 5206 case 0xFF0000: MaskByteOffset = 2; break; 5207 case 0xFF000000: MaskByteOffset = 3; break; 5208 } 5209 5210 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 5211 if (Opc == ISD::AND) { 5212 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 5213 // (x >> 8) & 0xff 5214 // (x >> 8) & 0xff0000 5215 if (Opc0 != ISD::SRL) 5216 return false; 5217 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5218 if (!C || C->getZExtValue() != 8) 5219 return false; 5220 } else { 5221 // (x << 8) & 0xff00 5222 // (x << 8) & 0xff000000 5223 if (Opc0 != ISD::SHL) 5224 return false; 5225 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5226 if (!C || C->getZExtValue() != 8) 5227 return false; 5228 } 5229 } else if (Opc == ISD::SHL) { 5230 // (x & 0xff) << 8 5231 // (x & 0xff0000) << 8 5232 if (MaskByteOffset != 0 && MaskByteOffset != 2) 5233 return false; 5234 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 5235 if (!C || C->getZExtValue() != 8) 5236 return false; 5237 } else { // Opc == ISD::SRL 5238 // (x & 0xff00) >> 8 5239 // (x & 0xff000000) >> 8 5240 if (MaskByteOffset != 1 && MaskByteOffset != 3) 5241 return false; 5242 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 5243 if (!C || C->getZExtValue() != 8) 5244 return false; 5245 } 5246 5247 if (Parts[MaskByteOffset]) 5248 return false; 5249 5250 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 5251 return true; 5252 } 5253 5254 /// Match a 32-bit packed halfword bswap. That is 5255 /// ((x & 0x000000ff) << 8) | 5256 /// ((x & 0x0000ff00) >> 8) | 5257 /// ((x & 0x00ff0000) << 8) | 5258 /// ((x & 0xff000000) >> 8) 5259 /// => (rotl (bswap x), 16) 5260 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 5261 if (!LegalOperations) 5262 return SDValue(); 5263 5264 EVT VT = N->getValueType(0); 5265 if (VT != MVT::i32) 5266 return SDValue(); 5267 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 5268 return SDValue(); 5269 5270 // Look for either 5271 // (or (or (and), (and)), (or (and), (and))) 5272 // (or (or (or (and), (and)), (and)), (and)) 5273 if (N0.getOpcode() != ISD::OR) 5274 return SDValue(); 5275 SDValue N00 = N0.getOperand(0); 5276 SDValue N01 = N0.getOperand(1); 5277 SDNode *Parts[4] = {}; 5278 5279 if (N1.getOpcode() == ISD::OR && 5280 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) { 5281 // (or (or (and), (and)), (or (and), (and))) 5282 if (!isBSwapHWordElement(N00, Parts)) 5283 return SDValue(); 5284 5285 if (!isBSwapHWordElement(N01, Parts)) 5286 return SDValue(); 5287 SDValue N10 = N1.getOperand(0); 5288 if (!isBSwapHWordElement(N10, Parts)) 5289 return SDValue(); 5290 SDValue N11 = N1.getOperand(1); 5291 if (!isBSwapHWordElement(N11, Parts)) 5292 return SDValue(); 5293 } else { 5294 // (or (or (or (and), (and)), (and)), (and)) 5295 if (!isBSwapHWordElement(N1, Parts)) 5296 return SDValue(); 5297 if (!isBSwapHWordElement(N01, Parts)) 5298 return SDValue(); 5299 if (N00.getOpcode() != ISD::OR) 5300 return SDValue(); 5301 SDValue N000 = N00.getOperand(0); 5302 if (!isBSwapHWordElement(N000, Parts)) 5303 return SDValue(); 5304 SDValue N001 = N00.getOperand(1); 5305 if (!isBSwapHWordElement(N001, Parts)) 5306 return SDValue(); 5307 } 5308 5309 // Make sure the parts are all coming from the same node. 5310 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 5311 return SDValue(); 5312 5313 SDLoc DL(N); 5314 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 5315 SDValue(Parts[0], 0)); 5316 5317 // Result of the bswap should be rotated by 16. If it's not legal, then 5318 // do (x << 16) | (x >> 16). 5319 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 5320 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 5321 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 5322 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 5323 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 5324 return DAG.getNode(ISD::OR, DL, VT, 5325 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 5326 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 5327 } 5328 5329 /// This contains all DAGCombine rules which reduce two values combined by 5330 /// an Or operation to a single value \see visitANDLike(). 5331 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 5332 EVT VT = N1.getValueType(); 5333 SDLoc DL(N); 5334 5335 // fold (or x, undef) -> -1 5336 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 5337 return DAG.getAllOnesConstant(DL, VT); 5338 5339 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 5340 return V; 5341 5342 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 5343 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 5344 // Don't increase # computations. 5345 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 5346 // We can only do this xform if we know that bits from X that are set in C2 5347 // but not in C1 are already zero. Likewise for Y. 5348 if (const ConstantSDNode *N0O1C = 5349 getAsNonOpaqueConstant(N0.getOperand(1))) { 5350 if (const ConstantSDNode *N1O1C = 5351 getAsNonOpaqueConstant(N1.getOperand(1))) { 5352 // We can only do this xform if we know that bits from X that are set in 5353 // C2 but not in C1 are already zero. Likewise for Y. 5354 const APInt &LHSMask = N0O1C->getAPIntValue(); 5355 const APInt &RHSMask = N1O1C->getAPIntValue(); 5356 5357 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 5358 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 5359 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 5360 N0.getOperand(0), N1.getOperand(0)); 5361 return DAG.getNode(ISD::AND, DL, VT, X, 5362 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 5363 } 5364 } 5365 } 5366 } 5367 5368 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 5369 if (N0.getOpcode() == ISD::AND && 5370 N1.getOpcode() == ISD::AND && 5371 N0.getOperand(0) == N1.getOperand(0) && 5372 // Don't increase # computations. 5373 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 5374 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 5375 N0.getOperand(1), N1.getOperand(1)); 5376 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 5377 } 5378 5379 return SDValue(); 5380 } 5381 5382 /// OR combines for which the commuted variant will be tried as well. 5383 static SDValue visitORCommutative( 5384 SelectionDAG &DAG, SDValue N0, SDValue N1, SDNode *N) { 5385 EVT VT = N0.getValueType(); 5386 if (N0.getOpcode() == ISD::AND) { 5387 // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y) 5388 if (isBitwiseNot(N0.getOperand(1)) && N0.getOperand(1).getOperand(0) == N1) 5389 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(0), N1); 5390 5391 // fold (or (and (xor Y, -1), X), Y) -> (or X, Y) 5392 if (isBitwiseNot(N0.getOperand(0)) && N0.getOperand(0).getOperand(0) == N1) 5393 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(1), N1); 5394 } 5395 5396 return SDValue(); 5397 } 5398 5399 SDValue DAGCombiner::visitOR(SDNode *N) { 5400 SDValue N0 = N->getOperand(0); 5401 SDValue N1 = N->getOperand(1); 5402 EVT VT = N1.getValueType(); 5403 5404 // x | x --> x 5405 if (N0 == N1) 5406 return N0; 5407 5408 // fold vector ops 5409 if (VT.isVector()) { 5410 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 5411 return FoldedVOp; 5412 5413 // fold (or x, 0) -> x, vector edition 5414 if (ISD::isBuildVectorAllZeros(N0.getNode())) 5415 return N1; 5416 if (ISD::isBuildVectorAllZeros(N1.getNode())) 5417 return N0; 5418 5419 // fold (or x, -1) -> -1, vector edition 5420 if (ISD::isBuildVectorAllOnes(N0.getNode())) 5421 // do not return N0, because undef node may exist in N0 5422 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 5423 if (ISD::isBuildVectorAllOnes(N1.getNode())) 5424 // do not return N1, because undef node may exist in N1 5425 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 5426 5427 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 5428 // Do this only if the resulting shuffle is legal. 5429 if (isa<ShuffleVectorSDNode>(N0) && 5430 isa<ShuffleVectorSDNode>(N1) && 5431 // Avoid folding a node with illegal type. 5432 TLI.isTypeLegal(VT)) { 5433 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 5434 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 5435 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 5436 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 5437 // Ensure both shuffles have a zero input. 5438 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 5439 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 5440 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 5441 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 5442 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 5443 bool CanFold = true; 5444 int NumElts = VT.getVectorNumElements(); 5445 SmallVector<int, 4> Mask(NumElts); 5446 5447 for (int i = 0; i != NumElts; ++i) { 5448 int M0 = SV0->getMaskElt(i); 5449 int M1 = SV1->getMaskElt(i); 5450 5451 // Determine if either index is pointing to a zero vector. 5452 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 5453 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 5454 5455 // If one element is zero and the otherside is undef, keep undef. 5456 // This also handles the case that both are undef. 5457 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 5458 Mask[i] = -1; 5459 continue; 5460 } 5461 5462 // Make sure only one of the elements is zero. 5463 if (M0Zero == M1Zero) { 5464 CanFold = false; 5465 break; 5466 } 5467 5468 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 5469 5470 // We have a zero and non-zero element. If the non-zero came from 5471 // SV0 make the index a LHS index. If it came from SV1, make it 5472 // a RHS index. We need to mod by NumElts because we don't care 5473 // which operand it came from in the original shuffles. 5474 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 5475 } 5476 5477 if (CanFold) { 5478 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 5479 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 5480 5481 bool LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 5482 if (!LegalMask) { 5483 std::swap(NewLHS, NewRHS); 5484 ShuffleVectorSDNode::commuteMask(Mask); 5485 LegalMask = TLI.isShuffleMaskLegal(Mask, VT); 5486 } 5487 5488 if (LegalMask) 5489 return DAG.getVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, Mask); 5490 } 5491 } 5492 } 5493 } 5494 5495 // fold (or c1, c2) -> c1|c2 5496 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 5497 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 5498 if (N0C && N1C && !N1C->isOpaque()) 5499 return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C); 5500 // canonicalize constant to RHS 5501 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5502 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5503 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 5504 // fold (or x, 0) -> x 5505 if (isNullConstant(N1)) 5506 return N0; 5507 // fold (or x, -1) -> -1 5508 if (isAllOnesConstant(N1)) 5509 return N1; 5510 5511 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5512 return NewSel; 5513 5514 // fold (or x, c) -> c iff (x & ~c) == 0 5515 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 5516 return N1; 5517 5518 if (SDValue Combined = visitORLike(N0, N1, N)) 5519 return Combined; 5520 5521 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 5522 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 5523 return BSwap; 5524 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 5525 return BSwap; 5526 5527 // reassociate or 5528 if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1, N->getFlags())) 5529 return ROR; 5530 5531 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 5532 // iff (c1 & c2) != 0 or c1/c2 are undef. 5533 auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) { 5534 return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue()); 5535 }; 5536 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5537 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) { 5538 if (SDValue COR = DAG.FoldConstantArithmetic( 5539 ISD::OR, SDLoc(N1), VT, N1.getNode(), N0.getOperand(1).getNode())) { 5540 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1); 5541 AddToWorklist(IOR.getNode()); 5542 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR); 5543 } 5544 } 5545 5546 if (SDValue Combined = visitORCommutative(DAG, N0, N1, N)) 5547 return Combined; 5548 if (SDValue Combined = visitORCommutative(DAG, N1, N0, N)) 5549 return Combined; 5550 5551 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 5552 if (N0.getOpcode() == N1.getOpcode()) 5553 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) 5554 return V; 5555 5556 // See if this is some rotate idiom. 5557 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N))) 5558 return SDValue(Rot, 0); 5559 5560 if (SDValue Load = MatchLoadCombine(N)) 5561 return Load; 5562 5563 // Simplify the operands using demanded-bits information. 5564 if (SimplifyDemandedBits(SDValue(N, 0))) 5565 return SDValue(N, 0); 5566 5567 // If OR can be rewritten into ADD, try combines based on ADD. 5568 if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) && 5569 DAG.haveNoCommonBitsSet(N0, N1)) 5570 if (SDValue Combined = visitADDLike(N)) 5571 return Combined; 5572 5573 return SDValue(); 5574 } 5575 5576 static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask) { 5577 if (Op.getOpcode() == ISD::AND && 5578 DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 5579 Mask = Op.getOperand(1); 5580 return Op.getOperand(0); 5581 } 5582 return Op; 5583 } 5584 5585 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 5586 static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift, 5587 SDValue &Mask) { 5588 Op = stripConstantMask(DAG, Op, Mask); 5589 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 5590 Shift = Op; 5591 return true; 5592 } 5593 return false; 5594 } 5595 5596 /// Helper function for visitOR to extract the needed side of a rotate idiom 5597 /// from a shl/srl/mul/udiv. This is meant to handle cases where 5598 /// InstCombine merged some outside op with one of the shifts from 5599 /// the rotate pattern. 5600 /// \returns An empty \c SDValue if the needed shift couldn't be extracted. 5601 /// Otherwise, returns an expansion of \p ExtractFrom based on the following 5602 /// patterns: 5603 /// 5604 /// (or (mul v c0) (shrl (mul v c1) c2)): 5605 /// expands (mul v c0) -> (shl (mul v c1) c3) 5606 /// 5607 /// (or (udiv v c0) (shl (udiv v c1) c2)): 5608 /// expands (udiv v c0) -> (shrl (udiv v c1) c3) 5609 /// 5610 /// (or (shl v c0) (shrl (shl v c1) c2)): 5611 /// expands (shl v c0) -> (shl (shl v c1) c3) 5612 /// 5613 /// (or (shrl v c0) (shl (shrl v c1) c2)): 5614 /// expands (shrl v c0) -> (shrl (shrl v c1) c3) 5615 /// 5616 /// Such that in all cases, c3+c2==bitwidth(op v c1). 5617 static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift, 5618 SDValue ExtractFrom, SDValue &Mask, 5619 const SDLoc &DL) { 5620 assert(OppShift && ExtractFrom && "Empty SDValue"); 5621 assert( 5622 (OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && 5623 "Existing shift must be valid as a rotate half"); 5624 5625 ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask); 5626 // Preconditions: 5627 // (or (op0 v c0) (shiftl/r (op0 v c1) c2)) 5628 // 5629 // Find opcode of the needed shift to be extracted from (op0 v c0). 5630 unsigned Opcode = ISD::DELETED_NODE; 5631 bool IsMulOrDiv = false; 5632 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift 5633 // opcode or its arithmetic (mul or udiv) variant. 5634 auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) { 5635 IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant; 5636 if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift) 5637 return false; 5638 Opcode = NeededShift; 5639 return true; 5640 }; 5641 // op0 must be either the needed shift opcode or the mul/udiv equivalent 5642 // that the needed shift can be extracted from. 5643 if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) && 5644 (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV))) 5645 return SDValue(); 5646 5647 // op0 must be the same opcode on both sides, have the same LHS argument, 5648 // and produce the same value type. 5649 SDValue OppShiftLHS = OppShift.getOperand(0); 5650 EVT ShiftedVT = OppShiftLHS.getValueType(); 5651 if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() || 5652 OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) || 5653 ShiftedVT != ExtractFrom.getValueType()) 5654 return SDValue(); 5655 5656 // Amount of the existing shift. 5657 ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1)); 5658 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op. 5659 ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1)); 5660 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op. 5661 ConstantSDNode *ExtractFromCst = 5662 isConstOrConstSplat(ExtractFrom.getOperand(1)); 5663 // TODO: We should be able to handle non-uniform constant vectors for these values 5664 // Check that we have constant values. 5665 if (!OppShiftCst || !OppShiftCst->getAPIntValue() || 5666 !OppLHSCst || !OppLHSCst->getAPIntValue() || 5667 !ExtractFromCst || !ExtractFromCst->getAPIntValue()) 5668 return SDValue(); 5669 5670 // Compute the shift amount we need to extract to complete the rotate. 5671 const unsigned VTWidth = ShiftedVT.getScalarSizeInBits(); 5672 if (OppShiftCst->getAPIntValue().ugt(VTWidth)) 5673 return SDValue(); 5674 APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue(); 5675 // Normalize the bitwidth of the two mul/udiv/shift constant operands. 5676 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue(); 5677 APInt OppLHSAmt = OppLHSCst->getAPIntValue(); 5678 zeroExtendToMatch(ExtractFromAmt, OppLHSAmt); 5679 5680 // Now try extract the needed shift from the ExtractFrom op and see if the 5681 // result matches up with the existing shift's LHS op. 5682 if (IsMulOrDiv) { 5683 // Op to extract from is a mul or udiv by a constant. 5684 // Check: 5685 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0 5686 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0 5687 const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(), 5688 NeededShiftAmt.getZExtValue()); 5689 APInt ResultAmt; 5690 APInt Rem; 5691 APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem); 5692 if (Rem != 0 || ResultAmt != OppLHSAmt) 5693 return SDValue(); 5694 } else { 5695 // Op to extract from is a shift by a constant. 5696 // Check: 5697 // c2 - (bitwidth(op0 v c0) - c1) == c0 5698 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc( 5699 ExtractFromAmt.getBitWidth())) 5700 return SDValue(); 5701 } 5702 5703 // Return the expanded shift op that should allow a rotate to be formed. 5704 EVT ShiftVT = OppShift.getOperand(1).getValueType(); 5705 EVT ResVT = ExtractFrom.getValueType(); 5706 SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT); 5707 return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode); 5708 } 5709 5710 // Return true if we can prove that, whenever Neg and Pos are both in the 5711 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 5712 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 5713 // 5714 // (or (shift1 X, Neg), (shift2 X, Pos)) 5715 // 5716 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 5717 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 5718 // to consider shift amounts with defined behavior. 5719 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize, 5720 SelectionDAG &DAG) { 5721 // If EltSize is a power of 2 then: 5722 // 5723 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 5724 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 5725 // 5726 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 5727 // for the stronger condition: 5728 // 5729 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 5730 // 5731 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 5732 // we can just replace Neg with Neg' for the rest of the function. 5733 // 5734 // In other cases we check for the even stronger condition: 5735 // 5736 // Neg == EltSize - Pos [B] 5737 // 5738 // for all Neg and Pos. Note that the (or ...) then invokes undefined 5739 // behavior if Pos == 0 (and consequently Neg == EltSize). 5740 // 5741 // We could actually use [A] whenever EltSize is a power of 2, but the 5742 // only extra cases that it would match are those uninteresting ones 5743 // where Neg and Pos are never in range at the same time. E.g. for 5744 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 5745 // as well as (sub 32, Pos), but: 5746 // 5747 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 5748 // 5749 // always invokes undefined behavior for 32-bit X. 5750 // 5751 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 5752 unsigned MaskLoBits = 0; 5753 if (Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 5754 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 5755 KnownBits Known = DAG.computeKnownBits(Neg.getOperand(0)); 5756 unsigned Bits = Log2_64(EltSize); 5757 if (NegC->getAPIntValue().getActiveBits() <= Bits && 5758 ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) { 5759 Neg = Neg.getOperand(0); 5760 MaskLoBits = Bits; 5761 } 5762 } 5763 } 5764 5765 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 5766 if (Neg.getOpcode() != ISD::SUB) 5767 return false; 5768 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 5769 if (!NegC) 5770 return false; 5771 SDValue NegOp1 = Neg.getOperand(1); 5772 5773 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 5774 // Pos'. The truncation is redundant for the purpose of the equality. 5775 if (MaskLoBits && Pos.getOpcode() == ISD::AND) { 5776 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) { 5777 KnownBits Known = DAG.computeKnownBits(Pos.getOperand(0)); 5778 if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits && 5779 ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >= 5780 MaskLoBits)) 5781 Pos = Pos.getOperand(0); 5782 } 5783 } 5784 5785 // The condition we need is now: 5786 // 5787 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 5788 // 5789 // If NegOp1 == Pos then we need: 5790 // 5791 // EltSize & Mask == NegC & Mask 5792 // 5793 // (because "x & Mask" is a truncation and distributes through subtraction). 5794 APInt Width; 5795 if (Pos == NegOp1) 5796 Width = NegC->getAPIntValue(); 5797 5798 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 5799 // Then the condition we want to prove becomes: 5800 // 5801 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 5802 // 5803 // which, again because "x & Mask" is a truncation, becomes: 5804 // 5805 // NegC & Mask == (EltSize - PosC) & Mask 5806 // EltSize & Mask == (NegC + PosC) & Mask 5807 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 5808 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 5809 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 5810 else 5811 return false; 5812 } else 5813 return false; 5814 5815 // Now we just need to check that EltSize & Mask == Width & Mask. 5816 if (MaskLoBits) 5817 // EltSize & Mask is 0 since Mask is EltSize - 1. 5818 return Width.getLoBits(MaskLoBits) == 0; 5819 return Width == EltSize; 5820 } 5821 5822 // A subroutine of MatchRotate used once we have found an OR of two opposite 5823 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 5824 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 5825 // former being preferred if supported. InnerPos and InnerNeg are Pos and 5826 // Neg with outer conversions stripped away. 5827 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 5828 SDValue Neg, SDValue InnerPos, 5829 SDValue InnerNeg, unsigned PosOpcode, 5830 unsigned NegOpcode, const SDLoc &DL) { 5831 // fold (or (shl x, (*ext y)), 5832 // (srl x, (*ext (sub 32, y)))) -> 5833 // (rotl x, y) or (rotr x, (sub 32, y)) 5834 // 5835 // fold (or (shl x, (*ext (sub 32, y))), 5836 // (srl x, (*ext y))) -> 5837 // (rotr x, y) or (rotl x, (sub 32, y)) 5838 EVT VT = Shifted.getValueType(); 5839 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG)) { 5840 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 5841 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 5842 HasPos ? Pos : Neg).getNode(); 5843 } 5844 5845 return nullptr; 5846 } 5847 5848 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 5849 // idioms for rotate, and if the target supports rotation instructions, generate 5850 // a rot[lr]. 5851 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 5852 // Must be a legal type. Expanded 'n promoted things won't work with rotates. 5853 EVT VT = LHS.getValueType(); 5854 if (!TLI.isTypeLegal(VT)) return nullptr; 5855 5856 // The target must have at least one rotate flavor. 5857 bool HasROTL = hasOperation(ISD::ROTL, VT); 5858 bool HasROTR = hasOperation(ISD::ROTR, VT); 5859 if (!HasROTL && !HasROTR) return nullptr; 5860 5861 // Check for truncated rotate. 5862 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE && 5863 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) { 5864 assert(LHS.getValueType() == RHS.getValueType()); 5865 if (SDNode *Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) { 5866 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), 5867 SDValue(Rot, 0)).getNode(); 5868 } 5869 } 5870 5871 // Match "(X shl/srl V1) & V2" where V2 may not be present. 5872 SDValue LHSShift; // The shift. 5873 SDValue LHSMask; // AND value if any. 5874 matchRotateHalf(DAG, LHS, LHSShift, LHSMask); 5875 5876 SDValue RHSShift; // The shift. 5877 SDValue RHSMask; // AND value if any. 5878 matchRotateHalf(DAG, RHS, RHSShift, RHSMask); 5879 5880 // If neither side matched a rotate half, bail 5881 if (!LHSShift && !RHSShift) 5882 return nullptr; 5883 5884 // InstCombine may have combined a constant shl, srl, mul, or udiv with one 5885 // side of the rotate, so try to handle that here. In all cases we need to 5886 // pass the matched shift from the opposite side to compute the opcode and 5887 // needed shift amount to extract. We still want to do this if both sides 5888 // matched a rotate half because one half may be a potential overshift that 5889 // can be broken down (ie if InstCombine merged two shl or srl ops into a 5890 // single one). 5891 5892 // Have LHS side of the rotate, try to extract the needed shift from the RHS. 5893 if (LHSShift) 5894 if (SDValue NewRHSShift = 5895 extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL)) 5896 RHSShift = NewRHSShift; 5897 // Have RHS side of the rotate, try to extract the needed shift from the LHS. 5898 if (RHSShift) 5899 if (SDValue NewLHSShift = 5900 extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL)) 5901 LHSShift = NewLHSShift; 5902 5903 // If a side is still missing, nothing else we can do. 5904 if (!RHSShift || !LHSShift) 5905 return nullptr; 5906 5907 // At this point we've matched or extracted a shift op on each side. 5908 5909 if (LHSShift.getOperand(0) != RHSShift.getOperand(0)) 5910 return nullptr; // Not shifting the same value. 5911 5912 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 5913 return nullptr; // Shifts must disagree. 5914 5915 // Canonicalize shl to left side in a shl/srl pair. 5916 if (RHSShift.getOpcode() == ISD::SHL) { 5917 std::swap(LHS, RHS); 5918 std::swap(LHSShift, RHSShift); 5919 std::swap(LHSMask, RHSMask); 5920 } 5921 5922 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 5923 SDValue LHSShiftArg = LHSShift.getOperand(0); 5924 SDValue LHSShiftAmt = LHSShift.getOperand(1); 5925 SDValue RHSShiftArg = RHSShift.getOperand(0); 5926 SDValue RHSShiftAmt = RHSShift.getOperand(1); 5927 5928 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 5929 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 5930 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 5931 ConstantSDNode *RHS) { 5932 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 5933 }; 5934 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 5935 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, 5936 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt); 5937 5938 // If there is an AND of either shifted operand, apply it to the result. 5939 if (LHSMask.getNode() || RHSMask.getNode()) { 5940 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 5941 SDValue Mask = AllOnes; 5942 5943 if (LHSMask.getNode()) { 5944 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 5945 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 5946 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 5947 } 5948 if (RHSMask.getNode()) { 5949 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 5950 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 5951 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 5952 } 5953 5954 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, Mask); 5955 } 5956 5957 return Rot.getNode(); 5958 } 5959 5960 // If there is a mask here, and we have a variable shift, we can't be sure 5961 // that we're masking out the right stuff. 5962 if (LHSMask.getNode() || RHSMask.getNode()) 5963 return nullptr; 5964 5965 // If the shift amount is sign/zext/any-extended just peel it off. 5966 SDValue LExtOp0 = LHSShiftAmt; 5967 SDValue RExtOp0 = RHSShiftAmt; 5968 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 5969 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 5970 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 5971 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 5972 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 5973 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 5974 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 5975 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 5976 LExtOp0 = LHSShiftAmt.getOperand(0); 5977 RExtOp0 = RHSShiftAmt.getOperand(0); 5978 } 5979 5980 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, 5981 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL); 5982 if (TryL) 5983 return TryL; 5984 5985 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 5986 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL); 5987 if (TryR) 5988 return TryR; 5989 5990 return nullptr; 5991 } 5992 5993 namespace { 5994 5995 /// Represents known origin of an individual byte in load combine pattern. The 5996 /// value of the byte is either constant zero or comes from memory. 5997 struct ByteProvider { 5998 // For constant zero providers Load is set to nullptr. For memory providers 5999 // Load represents the node which loads the byte from memory. 6000 // ByteOffset is the offset of the byte in the value produced by the load. 6001 LoadSDNode *Load = nullptr; 6002 unsigned ByteOffset = 0; 6003 6004 ByteProvider() = default; 6005 6006 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 6007 return ByteProvider(Load, ByteOffset); 6008 } 6009 6010 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 6011 6012 bool isConstantZero() const { return !Load; } 6013 bool isMemory() const { return Load; } 6014 6015 bool operator==(const ByteProvider &Other) const { 6016 return Other.Load == Load && Other.ByteOffset == ByteOffset; 6017 } 6018 6019 private: 6020 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 6021 : Load(Load), ByteOffset(ByteOffset) {} 6022 }; 6023 6024 } // end anonymous namespace 6025 6026 /// Recursively traverses the expression calculating the origin of the requested 6027 /// byte of the given value. Returns None if the provider can't be calculated. 6028 /// 6029 /// For all the values except the root of the expression verifies that the value 6030 /// has exactly one use and if it's not true return None. This way if the origin 6031 /// of the byte is returned it's guaranteed that the values which contribute to 6032 /// the byte are not used outside of this expression. 6033 /// 6034 /// Because the parts of the expression are not allowed to have more than one 6035 /// use this function iterates over trees, not DAGs. So it never visits the same 6036 /// node more than once. 6037 static const Optional<ByteProvider> 6038 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, 6039 bool Root = false) { 6040 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 6041 if (Depth == 10) 6042 return None; 6043 6044 if (!Root && !Op.hasOneUse()) 6045 return None; 6046 6047 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 6048 unsigned BitWidth = Op.getValueSizeInBits(); 6049 if (BitWidth % 8 != 0) 6050 return None; 6051 unsigned ByteWidth = BitWidth / 8; 6052 assert(Index < ByteWidth && "invalid index requested"); 6053 (void) ByteWidth; 6054 6055 switch (Op.getOpcode()) { 6056 case ISD::OR: { 6057 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 6058 if (!LHS) 6059 return None; 6060 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 6061 if (!RHS) 6062 return None; 6063 6064 if (LHS->isConstantZero()) 6065 return RHS; 6066 if (RHS->isConstantZero()) 6067 return LHS; 6068 return None; 6069 } 6070 case ISD::SHL: { 6071 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 6072 if (!ShiftOp) 6073 return None; 6074 6075 uint64_t BitShift = ShiftOp->getZExtValue(); 6076 if (BitShift % 8 != 0) 6077 return None; 6078 uint64_t ByteShift = BitShift / 8; 6079 6080 return Index < ByteShift 6081 ? ByteProvider::getConstantZero() 6082 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 6083 Depth + 1); 6084 } 6085 case ISD::ANY_EXTEND: 6086 case ISD::SIGN_EXTEND: 6087 case ISD::ZERO_EXTEND: { 6088 SDValue NarrowOp = Op->getOperand(0); 6089 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 6090 if (NarrowBitWidth % 8 != 0) 6091 return None; 6092 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 6093 6094 if (Index >= NarrowByteWidth) 6095 return Op.getOpcode() == ISD::ZERO_EXTEND 6096 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 6097 : None; 6098 return calculateByteProvider(NarrowOp, Index, Depth + 1); 6099 } 6100 case ISD::BSWAP: 6101 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 6102 Depth + 1); 6103 case ISD::LOAD: { 6104 auto L = cast<LoadSDNode>(Op.getNode()); 6105 if (L->isVolatile() || L->isIndexed()) 6106 return None; 6107 6108 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 6109 if (NarrowBitWidth % 8 != 0) 6110 return None; 6111 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 6112 6113 if (Index >= NarrowByteWidth) 6114 return L->getExtensionType() == ISD::ZEXTLOAD 6115 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 6116 : None; 6117 return ByteProvider::getMemory(L, Index); 6118 } 6119 } 6120 6121 return None; 6122 } 6123 6124 /// Match a pattern where a wide type scalar value is loaded by several narrow 6125 /// loads and combined by shifts and ors. Fold it into a single load or a load 6126 /// and a BSWAP if the targets supports it. 6127 /// 6128 /// Assuming little endian target: 6129 /// i8 *a = ... 6130 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 6131 /// => 6132 /// i32 val = *((i32)a) 6133 /// 6134 /// i8 *a = ... 6135 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 6136 /// => 6137 /// i32 val = BSWAP(*((i32)a)) 6138 /// 6139 /// TODO: This rule matches complex patterns with OR node roots and doesn't 6140 /// interact well with the worklist mechanism. When a part of the pattern is 6141 /// updated (e.g. one of the loads) its direct users are put into the worklist, 6142 /// but the root node of the pattern which triggers the load combine is not 6143 /// necessarily a direct user of the changed node. For example, once the address 6144 /// of t28 load is reassociated load combine won't be triggered: 6145 /// t25: i32 = add t4, Constant:i32<2> 6146 /// t26: i64 = sign_extend t25 6147 /// t27: i64 = add t2, t26 6148 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 6149 /// t29: i32 = zero_extend t28 6150 /// t32: i32 = shl t29, Constant:i8<8> 6151 /// t33: i32 = or t23, t32 6152 /// As a possible fix visitLoad can check if the load can be a part of a load 6153 /// combine pattern and add corresponding OR roots to the worklist. 6154 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 6155 assert(N->getOpcode() == ISD::OR && 6156 "Can only match load combining against OR nodes"); 6157 6158 // Handles simple types only 6159 EVT VT = N->getValueType(0); 6160 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 6161 return SDValue(); 6162 unsigned ByteWidth = VT.getSizeInBits() / 8; 6163 6164 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 6165 // Before legalize we can introduce too wide illegal loads which will be later 6166 // split into legal sized loads. This enables us to combine i64 load by i8 6167 // patterns to a couple of i32 loads on 32 bit targets. 6168 if (LegalOperations && !TLI.isOperationLegal(ISD::LOAD, VT)) 6169 return SDValue(); 6170 6171 std::function<unsigned(unsigned, unsigned)> LittleEndianByteAt = []( 6172 unsigned BW, unsigned i) { return i; }; 6173 std::function<unsigned(unsigned, unsigned)> BigEndianByteAt = []( 6174 unsigned BW, unsigned i) { return BW - i - 1; }; 6175 6176 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 6177 auto MemoryByteOffset = [&] (ByteProvider P) { 6178 assert(P.isMemory() && "Must be a memory byte provider"); 6179 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 6180 assert(LoadBitWidth % 8 == 0 && 6181 "can only analyze providers for individual bytes not bit"); 6182 unsigned LoadByteWidth = LoadBitWidth / 8; 6183 return IsBigEndianTarget 6184 ? BigEndianByteAt(LoadByteWidth, P.ByteOffset) 6185 : LittleEndianByteAt(LoadByteWidth, P.ByteOffset); 6186 }; 6187 6188 Optional<BaseIndexOffset> Base; 6189 SDValue Chain; 6190 6191 SmallPtrSet<LoadSDNode *, 8> Loads; 6192 Optional<ByteProvider> FirstByteProvider; 6193 int64_t FirstOffset = INT64_MAX; 6194 6195 // Check if all the bytes of the OR we are looking at are loaded from the same 6196 // base address. Collect bytes offsets from Base address in ByteOffsets. 6197 SmallVector<int64_t, 4> ByteOffsets(ByteWidth); 6198 for (unsigned i = 0; i < ByteWidth; i++) { 6199 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 6200 if (!P || !P->isMemory()) // All the bytes must be loaded from memory 6201 return SDValue(); 6202 6203 LoadSDNode *L = P->Load; 6204 assert(L->hasNUsesOfValue(1, 0) && !L->isVolatile() && !L->isIndexed() && 6205 "Must be enforced by calculateByteProvider"); 6206 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 6207 6208 // All loads must share the same chain 6209 SDValue LChain = L->getChain(); 6210 if (!Chain) 6211 Chain = LChain; 6212 else if (Chain != LChain) 6213 return SDValue(); 6214 6215 // Loads must share the same base address 6216 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG); 6217 int64_t ByteOffsetFromBase = 0; 6218 if (!Base) 6219 Base = Ptr; 6220 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 6221 return SDValue(); 6222 6223 // Calculate the offset of the current byte from the base address 6224 ByteOffsetFromBase += MemoryByteOffset(*P); 6225 ByteOffsets[i] = ByteOffsetFromBase; 6226 6227 // Remember the first byte load 6228 if (ByteOffsetFromBase < FirstOffset) { 6229 FirstByteProvider = P; 6230 FirstOffset = ByteOffsetFromBase; 6231 } 6232 6233 Loads.insert(L); 6234 } 6235 assert(!Loads.empty() && "All the bytes of the value must be loaded from " 6236 "memory, so there must be at least one load which produces the value"); 6237 assert(Base && "Base address of the accessed memory location must be set"); 6238 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 6239 6240 // Check if the bytes of the OR we are looking at match with either big or 6241 // little endian value load 6242 bool BigEndian = true, LittleEndian = true; 6243 for (unsigned i = 0; i < ByteWidth; i++) { 6244 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 6245 LittleEndian &= CurrentByteOffset == LittleEndianByteAt(ByteWidth, i); 6246 BigEndian &= CurrentByteOffset == BigEndianByteAt(ByteWidth, i); 6247 if (!BigEndian && !LittleEndian) 6248 return SDValue(); 6249 } 6250 assert((BigEndian != LittleEndian) && "should be either or"); 6251 assert(FirstByteProvider && "must be set"); 6252 6253 // Ensure that the first byte is loaded from zero offset of the first load. 6254 // So the combined value can be loaded from the first load address. 6255 if (MemoryByteOffset(*FirstByteProvider) != 0) 6256 return SDValue(); 6257 LoadSDNode *FirstLoad = FirstByteProvider->Load; 6258 6259 // The node we are looking at matches with the pattern, check if we can 6260 // replace it with a single load and bswap if needed. 6261 6262 // If the load needs byte swap check if the target supports it 6263 bool NeedsBswap = IsBigEndianTarget != BigEndian; 6264 6265 // Before legalize we can introduce illegal bswaps which will be later 6266 // converted to an explicit bswap sequence. This way we end up with a single 6267 // load and byte shuffling instead of several loads and byte shuffling. 6268 if (NeedsBswap && LegalOperations && !TLI.isOperationLegal(ISD::BSWAP, VT)) 6269 return SDValue(); 6270 6271 // Check that a load of the wide type is both allowed and fast on the target 6272 bool Fast = false; 6273 bool Allowed = TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), 6274 VT, FirstLoad->getAddressSpace(), 6275 FirstLoad->getAlignment(), &Fast); 6276 if (!Allowed || !Fast) 6277 return SDValue(); 6278 6279 SDValue NewLoad = 6280 DAG.getLoad(VT, SDLoc(N), Chain, FirstLoad->getBasePtr(), 6281 FirstLoad->getPointerInfo(), FirstLoad->getAlignment()); 6282 6283 // Transfer chain users from old loads to the new load. 6284 for (LoadSDNode *L : Loads) 6285 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 6286 6287 return NeedsBswap ? DAG.getNode(ISD::BSWAP, SDLoc(N), VT, NewLoad) : NewLoad; 6288 } 6289 6290 // If the target has andn, bsl, or a similar bit-select instruction, 6291 // we want to unfold masked merge, with canonical pattern of: 6292 // | A | |B| 6293 // ((x ^ y) & m) ^ y 6294 // | D | 6295 // Into: 6296 // (x & m) | (y & ~m) 6297 // If y is a constant, and the 'andn' does not work with immediates, 6298 // we unfold into a different pattern: 6299 // ~(~x & m) & (m | y) 6300 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at 6301 // the very least that breaks andnpd / andnps patterns, and because those 6302 // patterns are simplified in IR and shouldn't be created in the DAG 6303 SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) { 6304 assert(N->getOpcode() == ISD::XOR); 6305 6306 // Don't touch 'not' (i.e. where y = -1). 6307 if (isAllOnesOrAllOnesSplat(N->getOperand(1))) 6308 return SDValue(); 6309 6310 EVT VT = N->getValueType(0); 6311 6312 // There are 3 commutable operators in the pattern, 6313 // so we have to deal with 8 possible variants of the basic pattern. 6314 SDValue X, Y, M; 6315 auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) { 6316 if (And.getOpcode() != ISD::AND || !And.hasOneUse()) 6317 return false; 6318 SDValue Xor = And.getOperand(XorIdx); 6319 if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse()) 6320 return false; 6321 SDValue Xor0 = Xor.getOperand(0); 6322 SDValue Xor1 = Xor.getOperand(1); 6323 // Don't touch 'not' (i.e. where y = -1). 6324 if (isAllOnesOrAllOnesSplat(Xor1)) 6325 return false; 6326 if (Other == Xor0) 6327 std::swap(Xor0, Xor1); 6328 if (Other != Xor1) 6329 return false; 6330 X = Xor0; 6331 Y = Xor1; 6332 M = And.getOperand(XorIdx ? 0 : 1); 6333 return true; 6334 }; 6335 6336 SDValue N0 = N->getOperand(0); 6337 SDValue N1 = N->getOperand(1); 6338 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) && 6339 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0)) 6340 return SDValue(); 6341 6342 // Don't do anything if the mask is constant. This should not be reachable. 6343 // InstCombine should have already unfolded this pattern, and DAGCombiner 6344 // probably shouldn't produce it, too. 6345 if (isa<ConstantSDNode>(M.getNode())) 6346 return SDValue(); 6347 6348 // We can transform if the target has AndNot 6349 if (!TLI.hasAndNot(M)) 6350 return SDValue(); 6351 6352 SDLoc DL(N); 6353 6354 // If Y is a constant, check that 'andn' works with immediates. 6355 if (!TLI.hasAndNot(Y)) { 6356 assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable."); 6357 // If not, we need to do a bit more work to make sure andn is still used. 6358 SDValue NotX = DAG.getNOT(DL, X, VT); 6359 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M); 6360 SDValue NotLHS = DAG.getNOT(DL, LHS, VT); 6361 SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y); 6362 return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS); 6363 } 6364 6365 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M); 6366 SDValue NotM = DAG.getNOT(DL, M, VT); 6367 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM); 6368 6369 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS); 6370 } 6371 6372 SDValue DAGCombiner::visitXOR(SDNode *N) { 6373 SDValue N0 = N->getOperand(0); 6374 SDValue N1 = N->getOperand(1); 6375 EVT VT = N0.getValueType(); 6376 6377 // fold vector ops 6378 if (VT.isVector()) { 6379 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6380 return FoldedVOp; 6381 6382 // fold (xor x, 0) -> x, vector edition 6383 if (ISD::isBuildVectorAllZeros(N0.getNode())) 6384 return N1; 6385 if (ISD::isBuildVectorAllZeros(N1.getNode())) 6386 return N0; 6387 } 6388 6389 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 6390 SDLoc DL(N); 6391 if (N0.isUndef() && N1.isUndef()) 6392 return DAG.getConstant(0, DL, VT); 6393 // fold (xor x, undef) -> undef 6394 if (N0.isUndef()) 6395 return N0; 6396 if (N1.isUndef()) 6397 return N1; 6398 // fold (xor c1, c2) -> c1^c2 6399 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6400 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 6401 if (N0C && N1C) 6402 return DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, N0C, N1C); 6403 // canonicalize constant to RHS 6404 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 6405 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 6406 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 6407 // fold (xor x, 0) -> x 6408 if (isNullConstant(N1)) 6409 return N0; 6410 6411 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6412 return NewSel; 6413 6414 // reassociate xor 6415 if (SDValue RXOR = ReassociateOps(ISD::XOR, DL, N0, N1, N->getFlags())) 6416 return RXOR; 6417 6418 // fold !(x cc y) -> (x !cc y) 6419 unsigned N0Opcode = N0.getOpcode(); 6420 SDValue LHS, RHS, CC; 6421 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) { 6422 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 6423 LHS.getValueType().isInteger()); 6424 if (!LegalOperations || 6425 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 6426 switch (N0Opcode) { 6427 default: 6428 llvm_unreachable("Unhandled SetCC Equivalent!"); 6429 case ISD::SETCC: 6430 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 6431 case ISD::SELECT_CC: 6432 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 6433 N0.getOperand(3), NotCC); 6434 } 6435 } 6436 } 6437 6438 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 6439 if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() && 6440 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 6441 SDValue V = N0.getOperand(0); 6442 SDLoc DL0(N0); 6443 V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V, 6444 DAG.getConstant(1, DL0, V.getValueType())); 6445 AddToWorklist(V.getNode()); 6446 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V); 6447 } 6448 6449 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 6450 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() && 6451 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) { 6452 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6453 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) { 6454 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND; 6455 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 6456 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 6457 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 6458 return DAG.getNode(NewOpcode, DL, VT, LHS, RHS); 6459 } 6460 } 6461 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 6462 if (isAllOnesConstant(N1) && N0.hasOneUse() && 6463 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) { 6464 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 6465 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) { 6466 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND; 6467 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS 6468 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS 6469 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode()); 6470 return DAG.getNode(NewOpcode, DL, VT, LHS, RHS); 6471 } 6472 } 6473 // fold (xor (and x, y), y) -> (and (not x), y) 6474 if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) { 6475 SDValue X = N0.getOperand(0); 6476 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 6477 AddToWorklist(NotX.getNode()); 6478 return DAG.getNode(ISD::AND, DL, VT, NotX, N1); 6479 } 6480 6481 if ((N0Opcode == ISD::SRL || N0Opcode == ISD::SHL) && N0.hasOneUse()) { 6482 ConstantSDNode *XorC = isConstOrConstSplat(N1); 6483 ConstantSDNode *ShiftC = isConstOrConstSplat(N0.getOperand(1)); 6484 unsigned BitWidth = VT.getScalarSizeInBits(); 6485 if (XorC && ShiftC) { 6486 // Don't crash on an oversized shift. We can not guarantee that a bogus 6487 // shift has been simplified to undef. 6488 uint64_t ShiftAmt = ShiftC->getLimitedValue(); 6489 if (ShiftAmt < BitWidth) { 6490 APInt Ones = APInt::getAllOnesValue(BitWidth); 6491 Ones = N0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) : Ones.lshr(ShiftAmt); 6492 if (XorC->getAPIntValue() == Ones) { 6493 // If the xor constant is a shifted -1, do a 'not' before the shift: 6494 // xor (X << ShiftC), XorC --> (not X) << ShiftC 6495 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC 6496 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT); 6497 return DAG.getNode(N0Opcode, DL, VT, Not, N0.getOperand(1)); 6498 } 6499 } 6500 } 6501 } 6502 6503 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 6504 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 6505 SDValue A = N0Opcode == ISD::ADD ? N0 : N1; 6506 SDValue S = N0Opcode == ISD::SRA ? N0 : N1; 6507 if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) { 6508 SDValue A0 = A.getOperand(0), A1 = A.getOperand(1); 6509 SDValue S0 = S.getOperand(0); 6510 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) { 6511 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6512 if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1))) 6513 if (C->getAPIntValue() == (OpSizeInBits - 1)) 6514 return DAG.getNode(ISD::ABS, DL, VT, S0); 6515 } 6516 } 6517 } 6518 6519 // fold (xor x, x) -> 0 6520 if (N0 == N1) 6521 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 6522 6523 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 6524 // Here is a concrete example of this equivalence: 6525 // i16 x == 14 6526 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 6527 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 6528 // 6529 // => 6530 // 6531 // i16 ~1 == 0b1111111111111110 6532 // i16 rol(~1, 14) == 0b1011111111111111 6533 // 6534 // Some additional tips to help conceptualize this transform: 6535 // - Try to see the operation as placing a single zero in a value of all ones. 6536 // - There exists no value for x which would allow the result to contain zero. 6537 // - Values of x larger than the bitwidth are undefined and do not require a 6538 // consistent result. 6539 // - Pushing the zero left requires shifting one bits in from the right. 6540 // A rotate left of ~1 is a nice way of achieving the desired result. 6541 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL && 6542 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 6543 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 6544 N0.getOperand(1)); 6545 } 6546 6547 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 6548 if (N0Opcode == N1.getOpcode()) 6549 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) 6550 return V; 6551 6552 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable 6553 if (SDValue MM = unfoldMaskedMerge(N)) 6554 return MM; 6555 6556 // Simplify the expression using non-local knowledge. 6557 if (SimplifyDemandedBits(SDValue(N, 0))) 6558 return SDValue(N, 0); 6559 6560 return SDValue(); 6561 } 6562 6563 /// Handle transforms common to the three shifts, when the shift amount is a 6564 /// constant. 6565 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) { 6566 // Do not turn a 'not' into a regular xor. 6567 if (isBitwiseNot(N->getOperand(0))) 6568 return SDValue(); 6569 6570 SDNode *LHS = N->getOperand(0).getNode(); 6571 if (!LHS->hasOneUse()) return SDValue(); 6572 6573 // We want to pull some binops through shifts, so that we have (and (shift)) 6574 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 6575 // thing happens with address calculations, so it's important to canonicalize 6576 // it. 6577 bool HighBitSet = false; // Can we transform this if the high bit is set? 6578 6579 switch (LHS->getOpcode()) { 6580 default: return SDValue(); 6581 case ISD::OR: 6582 case ISD::XOR: 6583 HighBitSet = false; // We can only transform sra if the high bit is clear. 6584 break; 6585 case ISD::AND: 6586 HighBitSet = true; // We can only transform sra if the high bit is set. 6587 break; 6588 case ISD::ADD: 6589 if (N->getOpcode() != ISD::SHL) 6590 return SDValue(); // only shl(add) not sr[al](add). 6591 HighBitSet = false; // We can only transform sra if the high bit is clear. 6592 break; 6593 } 6594 6595 // We require the RHS of the binop to be a constant and not opaque as well. 6596 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1)); 6597 if (!BinOpCst) return SDValue(); 6598 6599 // FIXME: disable this unless the input to the binop is a shift by a constant 6600 // or is copy/select.Enable this in other cases when figure out it's exactly profitable. 6601 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode(); 6602 bool isShift = BinOpLHSVal->getOpcode() == ISD::SHL || 6603 BinOpLHSVal->getOpcode() == ISD::SRA || 6604 BinOpLHSVal->getOpcode() == ISD::SRL; 6605 bool isCopyOrSelect = BinOpLHSVal->getOpcode() == ISD::CopyFromReg || 6606 BinOpLHSVal->getOpcode() == ISD::SELECT; 6607 6608 if ((!isShift || !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1))) && 6609 !isCopyOrSelect) 6610 return SDValue(); 6611 6612 if (isCopyOrSelect && N->hasOneUse()) 6613 return SDValue(); 6614 6615 EVT VT = N->getValueType(0); 6616 6617 // If this is a signed shift right, and the high bit is modified by the 6618 // logical operation, do not perform the transformation. The highBitSet 6619 // boolean indicates the value of the high bit of the constant which would 6620 // cause it to be modified for this operation. 6621 if (N->getOpcode() == ISD::SRA) { 6622 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative(); 6623 if (BinOpRHSSignSet != HighBitSet) 6624 return SDValue(); 6625 } 6626 6627 if (!TLI.isDesirableToCommuteWithShift(N, Level)) 6628 return SDValue(); 6629 6630 // Fold the constants, shifting the binop RHS by the shift amount. 6631 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)), 6632 N->getValueType(0), 6633 LHS->getOperand(1), N->getOperand(1)); 6634 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 6635 6636 // Create the new shift. 6637 SDValue NewShift = DAG.getNode(N->getOpcode(), 6638 SDLoc(LHS->getOperand(0)), 6639 VT, LHS->getOperand(0), N->getOperand(1)); 6640 6641 // Create the new binop. 6642 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS); 6643 } 6644 6645 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 6646 assert(N->getOpcode() == ISD::TRUNCATE); 6647 assert(N->getOperand(0).getOpcode() == ISD::AND); 6648 6649 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 6650 EVT TruncVT = N->getValueType(0); 6651 if (N->hasOneUse() && N->getOperand(0).hasOneUse() && 6652 TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) { 6653 SDValue N01 = N->getOperand(0).getOperand(1); 6654 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 6655 SDLoc DL(N); 6656 SDValue N00 = N->getOperand(0).getOperand(0); 6657 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 6658 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 6659 AddToWorklist(Trunc00.getNode()); 6660 AddToWorklist(Trunc01.getNode()); 6661 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 6662 } 6663 } 6664 6665 return SDValue(); 6666 } 6667 6668 SDValue DAGCombiner::visitRotate(SDNode *N) { 6669 SDLoc dl(N); 6670 SDValue N0 = N->getOperand(0); 6671 SDValue N1 = N->getOperand(1); 6672 EVT VT = N->getValueType(0); 6673 unsigned Bitsize = VT.getScalarSizeInBits(); 6674 6675 // fold (rot x, 0) -> x 6676 if (isNullOrNullSplat(N1)) 6677 return N0; 6678 6679 // fold (rot x, c) -> x iff (c % BitSize) == 0 6680 if (isPowerOf2_32(Bitsize) && Bitsize > 1) { 6681 APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1); 6682 if (DAG.MaskedValueIsZero(N1, ModuloMask)) 6683 return N0; 6684 } 6685 6686 // fold (rot x, c) -> (rot x, c % BitSize) 6687 if (ConstantSDNode *Cst = isConstOrConstSplat(N1)) { 6688 if (Cst->getAPIntValue().uge(Bitsize)) { 6689 uint64_t RotAmt = Cst->getAPIntValue().urem(Bitsize); 6690 return DAG.getNode(N->getOpcode(), dl, VT, N0, 6691 DAG.getConstant(RotAmt, dl, N1.getValueType())); 6692 } 6693 } 6694 6695 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 6696 if (N1.getOpcode() == ISD::TRUNCATE && 6697 N1.getOperand(0).getOpcode() == ISD::AND) { 6698 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6699 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 6700 } 6701 6702 unsigned NextOp = N0.getOpcode(); 6703 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 6704 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 6705 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 6706 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 6707 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 6708 EVT ShiftVT = C1->getValueType(0); 6709 bool SameSide = (N->getOpcode() == NextOp); 6710 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 6711 if (SDValue CombinedShift = 6712 DAG.FoldConstantArithmetic(CombineOp, dl, ShiftVT, C1, C2)) { 6713 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 6714 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 6715 ISD::SREM, dl, ShiftVT, CombinedShift.getNode(), 6716 BitsizeC.getNode()); 6717 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 6718 CombinedShiftNorm); 6719 } 6720 } 6721 } 6722 return SDValue(); 6723 } 6724 6725 SDValue DAGCombiner::visitSHL(SDNode *N) { 6726 SDValue N0 = N->getOperand(0); 6727 SDValue N1 = N->getOperand(1); 6728 if (SDValue V = DAG.simplifyShift(N0, N1)) 6729 return V; 6730 6731 EVT VT = N0.getValueType(); 6732 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6733 6734 // fold vector ops 6735 if (VT.isVector()) { 6736 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6737 return FoldedVOp; 6738 6739 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 6740 // If setcc produces all-one true value then: 6741 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 6742 if (N1CV && N1CV->isConstant()) { 6743 if (N0.getOpcode() == ISD::AND) { 6744 SDValue N00 = N0->getOperand(0); 6745 SDValue N01 = N0->getOperand(1); 6746 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 6747 6748 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 6749 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 6750 TargetLowering::ZeroOrNegativeOneBooleanContent) { 6751 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, 6752 N01CV, N1CV)) 6753 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 6754 } 6755 } 6756 } 6757 } 6758 6759 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6760 6761 // fold (shl c1, c2) -> c1<<c2 6762 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6763 if (N0C && N1C && !N1C->isOpaque()) 6764 return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C); 6765 6766 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6767 return NewSel; 6768 6769 // if (shl x, c) is known to be zero, return 0 6770 if (DAG.MaskedValueIsZero(SDValue(N, 0), 6771 APInt::getAllOnesValue(OpSizeInBits))) 6772 return DAG.getConstant(0, SDLoc(N), VT); 6773 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 6774 if (N1.getOpcode() == ISD::TRUNCATE && 6775 N1.getOperand(0).getOpcode() == ISD::AND) { 6776 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 6777 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 6778 } 6779 6780 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 6781 return SDValue(N, 0); 6782 6783 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 6784 if (N0.getOpcode() == ISD::SHL) { 6785 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 6786 ConstantSDNode *RHS) { 6787 APInt c1 = LHS->getAPIntValue(); 6788 APInt c2 = RHS->getAPIntValue(); 6789 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6790 return (c1 + c2).uge(OpSizeInBits); 6791 }; 6792 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 6793 return DAG.getConstant(0, SDLoc(N), VT); 6794 6795 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 6796 ConstantSDNode *RHS) { 6797 APInt c1 = LHS->getAPIntValue(); 6798 APInt c2 = RHS->getAPIntValue(); 6799 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6800 return (c1 + c2).ult(OpSizeInBits); 6801 }; 6802 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 6803 SDLoc DL(N); 6804 EVT ShiftVT = N1.getValueType(); 6805 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 6806 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 6807 } 6808 } 6809 6810 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2))) 6811 // For this to be valid, the second form must not preserve any of the bits 6812 // that are shifted out by the inner shift in the first form. This means 6813 // the outer shift size must be >= the number of bits added by the ext. 6814 // As a corollary, we don't care what kind of ext it is. 6815 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND || 6816 N0.getOpcode() == ISD::ANY_EXTEND || 6817 N0.getOpcode() == ISD::SIGN_EXTEND) && 6818 N0.getOperand(0).getOpcode() == ISD::SHL) { 6819 SDValue N0Op0 = N0.getOperand(0); 6820 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 6821 APInt c1 = N0Op0C1->getAPIntValue(); 6822 APInt c2 = N1C->getAPIntValue(); 6823 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 6824 6825 EVT InnerShiftVT = N0Op0.getValueType(); 6826 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 6827 if (c2.uge(OpSizeInBits - InnerShiftSize)) { 6828 SDLoc DL(N0); 6829 APInt Sum = c1 + c2; 6830 if (Sum.uge(OpSizeInBits)) 6831 return DAG.getConstant(0, DL, VT); 6832 6833 return DAG.getNode( 6834 ISD::SHL, DL, VT, 6835 DAG.getNode(N0.getOpcode(), DL, VT, N0Op0->getOperand(0)), 6836 DAG.getConstant(Sum.getZExtValue(), DL, N1.getValueType())); 6837 } 6838 } 6839 } 6840 6841 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 6842 // Only fold this if the inner zext has no other uses to avoid increasing 6843 // the total number of instructions. 6844 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 6845 N0.getOperand(0).getOpcode() == ISD::SRL) { 6846 SDValue N0Op0 = N0.getOperand(0); 6847 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) { 6848 if (N0Op0C1->getAPIntValue().ult(VT.getScalarSizeInBits())) { 6849 uint64_t c1 = N0Op0C1->getZExtValue(); 6850 uint64_t c2 = N1C->getZExtValue(); 6851 if (c1 == c2) { 6852 SDValue NewOp0 = N0.getOperand(0); 6853 EVT CountVT = NewOp0.getOperand(1).getValueType(); 6854 SDLoc DL(N); 6855 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(), 6856 NewOp0, 6857 DAG.getConstant(c2, DL, CountVT)); 6858 AddToWorklist(NewSHL.getNode()); 6859 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 6860 } 6861 } 6862 } 6863 } 6864 6865 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 6866 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 6867 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 6868 N0->getFlags().hasExact()) { 6869 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 6870 uint64_t C1 = N0C1->getZExtValue(); 6871 uint64_t C2 = N1C->getZExtValue(); 6872 SDLoc DL(N); 6873 if (C1 <= C2) 6874 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 6875 DAG.getConstant(C2 - C1, DL, N1.getValueType())); 6876 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 6877 DAG.getConstant(C1 - C2, DL, N1.getValueType())); 6878 } 6879 } 6880 6881 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 6882 // (and (srl x, (sub c1, c2), MASK) 6883 // Only fold this if the inner shift has no other uses -- if it does, folding 6884 // this will increase the total number of instructions. 6885 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && 6886 TLI.shouldFoldConstantShiftPairToMask(N, Level)) { 6887 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 6888 if (N0C1->getAPIntValue().ult(OpSizeInBits)) { 6889 uint64_t c1 = N0C1->getZExtValue(); 6890 uint64_t c2 = N1C->getZExtValue(); 6891 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 6892 SDValue Shift; 6893 if (c2 > c1) { 6894 Mask <<= c2 - c1; 6895 SDLoc DL(N); 6896 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 6897 DAG.getConstant(c2 - c1, DL, N1.getValueType())); 6898 } else { 6899 Mask.lshrInPlace(c1 - c2); 6900 SDLoc DL(N); 6901 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 6902 DAG.getConstant(c1 - c2, DL, N1.getValueType())); 6903 } 6904 SDLoc DL(N0); 6905 return DAG.getNode(ISD::AND, DL, VT, Shift, 6906 DAG.getConstant(Mask, DL, VT)); 6907 } 6908 } 6909 } 6910 6911 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 6912 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 6913 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 6914 SDLoc DL(N); 6915 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 6916 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 6917 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 6918 } 6919 6920 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 6921 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 6922 // Variant of version done on multiply, except mul by a power of 2 is turned 6923 // into a shift. 6924 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && 6925 N0.getNode()->hasOneUse() && 6926 isConstantOrConstantVector(N1, /* No Opaques */ true) && 6927 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) && 6928 TLI.isDesirableToCommuteWithShift(N, Level)) { 6929 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 6930 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 6931 AddToWorklist(Shl0.getNode()); 6932 AddToWorklist(Shl1.getNode()); 6933 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); 6934 } 6935 6936 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 6937 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 6938 isConstantOrConstantVector(N1, /* No Opaques */ true) && 6939 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 6940 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 6941 if (isConstantOrConstantVector(Shl)) 6942 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 6943 } 6944 6945 if (N1C && !N1C->isOpaque()) 6946 if (SDValue NewSHL = visitShiftByConstant(N, N1C)) 6947 return NewSHL; 6948 6949 return SDValue(); 6950 } 6951 6952 SDValue DAGCombiner::visitSRA(SDNode *N) { 6953 SDValue N0 = N->getOperand(0); 6954 SDValue N1 = N->getOperand(1); 6955 if (SDValue V = DAG.simplifyShift(N0, N1)) 6956 return V; 6957 6958 EVT VT = N0.getValueType(); 6959 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 6960 6961 // Arithmetic shifting an all-sign-bit value is a no-op. 6962 // fold (sra 0, x) -> 0 6963 // fold (sra -1, x) -> -1 6964 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 6965 return N0; 6966 6967 // fold vector ops 6968 if (VT.isVector()) 6969 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 6970 return FoldedVOp; 6971 6972 ConstantSDNode *N1C = isConstOrConstSplat(N1); 6973 6974 // fold (sra c1, c2) -> (sra c1, c2) 6975 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 6976 if (N0C && N1C && !N1C->isOpaque()) 6977 return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C); 6978 6979 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6980 return NewSel; 6981 6982 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 6983 // sext_inreg. 6984 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 6985 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 6986 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 6987 if (VT.isVector()) 6988 ExtVT = EVT::getVectorVT(*DAG.getContext(), 6989 ExtVT, VT.getVectorNumElements()); 6990 if ((!LegalOperations || 6991 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT))) 6992 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 6993 N0.getOperand(0), DAG.getValueType(ExtVT)); 6994 } 6995 6996 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 6997 // clamp (add c1, c2) to max shift. 6998 if (N0.getOpcode() == ISD::SRA) { 6999 SDLoc DL(N); 7000 EVT ShiftVT = N1.getValueType(); 7001 EVT ShiftSVT = ShiftVT.getScalarType(); 7002 SmallVector<SDValue, 16> ShiftValues; 7003 7004 auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) { 7005 APInt c1 = LHS->getAPIntValue(); 7006 APInt c2 = RHS->getAPIntValue(); 7007 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 7008 APInt Sum = c1 + c2; 7009 unsigned ShiftSum = 7010 Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue(); 7011 ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT)); 7012 return true; 7013 }; 7014 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) { 7015 SDValue ShiftValue; 7016 if (VT.isVector()) 7017 ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues); 7018 else 7019 ShiftValue = ShiftValues[0]; 7020 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue); 7021 } 7022 } 7023 7024 // fold (sra (shl X, m), (sub result_size, n)) 7025 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 7026 // result_size - n != m. 7027 // If truncate is free for the target sext(shl) is likely to result in better 7028 // code. 7029 if (N0.getOpcode() == ISD::SHL && N1C) { 7030 // Get the two constanst of the shifts, CN0 = m, CN = n. 7031 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 7032 if (N01C) { 7033 LLVMContext &Ctx = *DAG.getContext(); 7034 // Determine what the truncate's result bitsize and type would be. 7035 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 7036 7037 if (VT.isVector()) 7038 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements()); 7039 7040 // Determine the residual right-shift amount. 7041 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 7042 7043 // If the shift is not a no-op (in which case this should be just a sign 7044 // extend already), the truncated to type is legal, sign_extend is legal 7045 // on that type, and the truncate to that type is both legal and free, 7046 // perform the transform. 7047 if ((ShiftAmt > 0) && 7048 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 7049 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 7050 TLI.isTruncateFree(VT, TruncVT)) { 7051 SDLoc DL(N); 7052 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 7053 getShiftAmountTy(N0.getOperand(0).getValueType())); 7054 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 7055 N0.getOperand(0), Amt); 7056 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 7057 Shift); 7058 return DAG.getNode(ISD::SIGN_EXTEND, DL, 7059 N->getValueType(0), Trunc); 7060 } 7061 } 7062 } 7063 7064 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 7065 if (N1.getOpcode() == ISD::TRUNCATE && 7066 N1.getOperand(0).getOpcode() == ISD::AND) { 7067 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 7068 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 7069 } 7070 7071 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 7072 // if c1 is equal to the number of bits the trunc removes 7073 if (N0.getOpcode() == ISD::TRUNCATE && 7074 (N0.getOperand(0).getOpcode() == ISD::SRL || 7075 N0.getOperand(0).getOpcode() == ISD::SRA) && 7076 N0.getOperand(0).hasOneUse() && 7077 N0.getOperand(0).getOperand(1).hasOneUse() && 7078 N1C) { 7079 SDValue N0Op0 = N0.getOperand(0); 7080 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 7081 unsigned LargeShiftVal = LargeShift->getZExtValue(); 7082 EVT LargeVT = N0Op0.getValueType(); 7083 7084 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) { 7085 SDLoc DL(N); 7086 SDValue Amt = 7087 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL, 7088 getShiftAmountTy(N0Op0.getOperand(0).getValueType())); 7089 SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT, 7090 N0Op0.getOperand(0), Amt); 7091 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 7092 } 7093 } 7094 } 7095 7096 // Simplify, based on bits shifted out of the LHS. 7097 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 7098 return SDValue(N, 0); 7099 7100 // If the sign bit is known to be zero, switch this to a SRL. 7101 if (DAG.SignBitIsZero(N0)) 7102 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 7103 7104 if (N1C && !N1C->isOpaque()) 7105 if (SDValue NewSRA = visitShiftByConstant(N, N1C)) 7106 return NewSRA; 7107 7108 return SDValue(); 7109 } 7110 7111 SDValue DAGCombiner::visitSRL(SDNode *N) { 7112 SDValue N0 = N->getOperand(0); 7113 SDValue N1 = N->getOperand(1); 7114 if (SDValue V = DAG.simplifyShift(N0, N1)) 7115 return V; 7116 7117 EVT VT = N0.getValueType(); 7118 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 7119 7120 // fold vector ops 7121 if (VT.isVector()) 7122 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 7123 return FoldedVOp; 7124 7125 ConstantSDNode *N1C = isConstOrConstSplat(N1); 7126 7127 // fold (srl c1, c2) -> c1 >>u c2 7128 ConstantSDNode *N0C = getAsNonOpaqueConstant(N0); 7129 if (N0C && N1C && !N1C->isOpaque()) 7130 return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C); 7131 7132 if (SDValue NewSel = foldBinOpIntoSelect(N)) 7133 return NewSel; 7134 7135 // if (srl x, c) is known to be zero, return 0 7136 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), 7137 APInt::getAllOnesValue(OpSizeInBits))) 7138 return DAG.getConstant(0, SDLoc(N), VT); 7139 7140 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 7141 if (N0.getOpcode() == ISD::SRL) { 7142 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 7143 ConstantSDNode *RHS) { 7144 APInt c1 = LHS->getAPIntValue(); 7145 APInt c2 = RHS->getAPIntValue(); 7146 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 7147 return (c1 + c2).uge(OpSizeInBits); 7148 }; 7149 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 7150 return DAG.getConstant(0, SDLoc(N), VT); 7151 7152 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 7153 ConstantSDNode *RHS) { 7154 APInt c1 = LHS->getAPIntValue(); 7155 APInt c2 = RHS->getAPIntValue(); 7156 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 7157 return (c1 + c2).ult(OpSizeInBits); 7158 }; 7159 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 7160 SDLoc DL(N); 7161 EVT ShiftVT = N1.getValueType(); 7162 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 7163 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 7164 } 7165 } 7166 7167 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2))) 7168 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 7169 N0.getOperand(0).getOpcode() == ISD::SRL) { 7170 if (auto N001C = isConstOrConstSplat(N0.getOperand(0).getOperand(1))) { 7171 uint64_t c1 = N001C->getZExtValue(); 7172 uint64_t c2 = N1C->getZExtValue(); 7173 EVT InnerShiftVT = N0.getOperand(0).getValueType(); 7174 EVT ShiftCountVT = N0.getOperand(0).getOperand(1).getValueType(); 7175 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 7176 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 7177 if (c1 + OpSizeInBits == InnerShiftSize) { 7178 SDLoc DL(N0); 7179 if (c1 + c2 >= InnerShiftSize) 7180 return DAG.getConstant(0, DL, VT); 7181 return DAG.getNode(ISD::TRUNCATE, DL, VT, 7182 DAG.getNode(ISD::SRL, DL, InnerShiftVT, 7183 N0.getOperand(0).getOperand(0), 7184 DAG.getConstant(c1 + c2, DL, 7185 ShiftCountVT))); 7186 } 7187 } 7188 } 7189 7190 // fold (srl (shl x, c), c) -> (and x, cst2) 7191 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 7192 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 7193 SDLoc DL(N); 7194 SDValue Mask = 7195 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 7196 AddToWorklist(Mask.getNode()); 7197 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 7198 } 7199 7200 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 7201 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 7202 // Shifting in all undef bits? 7203 EVT SmallVT = N0.getOperand(0).getValueType(); 7204 unsigned BitSize = SmallVT.getScalarSizeInBits(); 7205 if (N1C->getZExtValue() >= BitSize) 7206 return DAG.getUNDEF(VT); 7207 7208 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 7209 uint64_t ShiftAmt = N1C->getZExtValue(); 7210 SDLoc DL0(N0); 7211 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 7212 N0.getOperand(0), 7213 DAG.getConstant(ShiftAmt, DL0, 7214 getShiftAmountTy(SmallVT))); 7215 AddToWorklist(SmallShift.getNode()); 7216 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 7217 SDLoc DL(N); 7218 return DAG.getNode(ISD::AND, DL, VT, 7219 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 7220 DAG.getConstant(Mask, DL, VT)); 7221 } 7222 } 7223 7224 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 7225 // bit, which is unmodified by sra. 7226 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) { 7227 if (N0.getOpcode() == ISD::SRA) 7228 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 7229 } 7230 7231 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 7232 if (N1C && N0.getOpcode() == ISD::CTLZ && 7233 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 7234 KnownBits Known = DAG.computeKnownBits(N0.getOperand(0)); 7235 7236 // If any of the input bits are KnownOne, then the input couldn't be all 7237 // zeros, thus the result of the srl will always be zero. 7238 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 7239 7240 // If all of the bits input the to ctlz node are known to be zero, then 7241 // the result of the ctlz is "32" and the result of the shift is one. 7242 APInt UnknownBits = ~Known.Zero; 7243 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 7244 7245 // Otherwise, check to see if there is exactly one bit input to the ctlz. 7246 if (UnknownBits.isPowerOf2()) { 7247 // Okay, we know that only that the single bit specified by UnknownBits 7248 // could be set on input to the CTLZ node. If this bit is set, the SRL 7249 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 7250 // to an SRL/XOR pair, which is likely to simplify more. 7251 unsigned ShAmt = UnknownBits.countTrailingZeros(); 7252 SDValue Op = N0.getOperand(0); 7253 7254 if (ShAmt) { 7255 SDLoc DL(N0); 7256 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 7257 DAG.getConstant(ShAmt, DL, 7258 getShiftAmountTy(Op.getValueType()))); 7259 AddToWorklist(Op.getNode()); 7260 } 7261 7262 SDLoc DL(N); 7263 return DAG.getNode(ISD::XOR, DL, VT, 7264 Op, DAG.getConstant(1, DL, VT)); 7265 } 7266 } 7267 7268 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 7269 if (N1.getOpcode() == ISD::TRUNCATE && 7270 N1.getOperand(0).getOpcode() == ISD::AND) { 7271 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 7272 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 7273 } 7274 7275 // fold operands of srl based on knowledge that the low bits are not 7276 // demanded. 7277 if (N1C && SimplifyDemandedBits(SDValue(N, 0))) 7278 return SDValue(N, 0); 7279 7280 if (N1C && !N1C->isOpaque()) 7281 if (SDValue NewSRL = visitShiftByConstant(N, N1C)) 7282 return NewSRL; 7283 7284 // Attempt to convert a srl of a load into a narrower zero-extending load. 7285 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 7286 return NarrowLoad; 7287 7288 // Here is a common situation. We want to optimize: 7289 // 7290 // %a = ... 7291 // %b = and i32 %a, 2 7292 // %c = srl i32 %b, 1 7293 // brcond i32 %c ... 7294 // 7295 // into 7296 // 7297 // %a = ... 7298 // %b = and %a, 2 7299 // %c = setcc eq %b, 0 7300 // brcond %c ... 7301 // 7302 // However when after the source operand of SRL is optimized into AND, the SRL 7303 // itself may not be optimized further. Look for it and add the BRCOND into 7304 // the worklist. 7305 if (N->hasOneUse()) { 7306 SDNode *Use = *N->use_begin(); 7307 if (Use->getOpcode() == ISD::BRCOND) 7308 AddToWorklist(Use); 7309 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 7310 // Also look pass the truncate. 7311 Use = *Use->use_begin(); 7312 if (Use->getOpcode() == ISD::BRCOND) 7313 AddToWorklist(Use); 7314 } 7315 } 7316 7317 return SDValue(); 7318 } 7319 7320 SDValue DAGCombiner::visitFunnelShift(SDNode *N) { 7321 EVT VT = N->getValueType(0); 7322 SDValue N0 = N->getOperand(0); 7323 SDValue N1 = N->getOperand(1); 7324 SDValue N2 = N->getOperand(2); 7325 bool IsFSHL = N->getOpcode() == ISD::FSHL; 7326 unsigned BitWidth = VT.getScalarSizeInBits(); 7327 7328 // fold (fshl N0, N1, 0) -> N0 7329 // fold (fshr N0, N1, 0) -> N1 7330 if (isPowerOf2_32(BitWidth)) 7331 if (DAG.MaskedValueIsZero( 7332 N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1))) 7333 return IsFSHL ? N0 : N1; 7334 7335 auto IsUndefOrZero = [](SDValue V) { 7336 return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true); 7337 }; 7338 7339 if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) { 7340 EVT ShAmtTy = N2.getValueType(); 7341 7342 // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth) 7343 if (Cst->getAPIntValue().uge(BitWidth)) { 7344 uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth); 7345 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N0, N1, 7346 DAG.getConstant(RotAmt, SDLoc(N), ShAmtTy)); 7347 } 7348 7349 unsigned ShAmt = Cst->getZExtValue(); 7350 if (ShAmt == 0) 7351 return IsFSHL ? N0 : N1; 7352 7353 // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C) 7354 // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C) 7355 // fold fshl(N0, undef_or_zero, C) -> shl(N0, C) 7356 // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C) 7357 if (IsUndefOrZero(N0)) 7358 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, 7359 DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt, 7360 SDLoc(N), ShAmtTy)); 7361 if (IsUndefOrZero(N1)) 7362 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 7363 DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt, 7364 SDLoc(N), ShAmtTy)); 7365 } 7366 7367 // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2) 7368 // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2) 7369 // iff We know the shift amount is in range. 7370 // TODO: when is it worth doing SUB(BW, N2) as well? 7371 if (isPowerOf2_32(BitWidth)) { 7372 APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1); 7373 if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits)) 7374 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, N2); 7375 if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits)) 7376 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N2); 7377 } 7378 7379 // fold (fshl N0, N0, N2) -> (rotl N0, N2) 7380 // fold (fshr N0, N0, N2) -> (rotr N0, N2) 7381 // TODO: Investigate flipping this rotate if only one is legal, if funnel shift 7382 // is legal as well we might be better off avoiding non-constant (BW - N2). 7383 unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR; 7384 if (N0 == N1 && hasOperation(RotOpc, VT)) 7385 return DAG.getNode(RotOpc, SDLoc(N), VT, N0, N2); 7386 7387 // Simplify, based on bits shifted out of N0/N1. 7388 if (SimplifyDemandedBits(SDValue(N, 0))) 7389 return SDValue(N, 0); 7390 7391 return SDValue(); 7392 } 7393 7394 SDValue DAGCombiner::visitABS(SDNode *N) { 7395 SDValue N0 = N->getOperand(0); 7396 EVT VT = N->getValueType(0); 7397 7398 // fold (abs c1) -> c2 7399 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7400 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 7401 // fold (abs (abs x)) -> (abs x) 7402 if (N0.getOpcode() == ISD::ABS) 7403 return N0; 7404 // fold (abs x) -> x iff not-negative 7405 if (DAG.SignBitIsZero(N0)) 7406 return N0; 7407 return SDValue(); 7408 } 7409 7410 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 7411 SDValue N0 = N->getOperand(0); 7412 EVT VT = N->getValueType(0); 7413 7414 // fold (bswap c1) -> c2 7415 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7416 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 7417 // fold (bswap (bswap x)) -> x 7418 if (N0.getOpcode() == ISD::BSWAP) 7419 return N0->getOperand(0); 7420 return SDValue(); 7421 } 7422 7423 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 7424 SDValue N0 = N->getOperand(0); 7425 EVT VT = N->getValueType(0); 7426 7427 // fold (bitreverse c1) -> c2 7428 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7429 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 7430 // fold (bitreverse (bitreverse x)) -> x 7431 if (N0.getOpcode() == ISD::BITREVERSE) 7432 return N0.getOperand(0); 7433 return SDValue(); 7434 } 7435 7436 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 7437 SDValue N0 = N->getOperand(0); 7438 EVT VT = N->getValueType(0); 7439 7440 // fold (ctlz c1) -> c2 7441 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7442 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 7443 7444 // If the value is known never to be zero, switch to the undef version. 7445 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) { 7446 if (DAG.isKnownNeverZero(N0)) 7447 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7448 } 7449 7450 return SDValue(); 7451 } 7452 7453 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 7454 SDValue N0 = N->getOperand(0); 7455 EVT VT = N->getValueType(0); 7456 7457 // fold (ctlz_zero_undef c1) -> c2 7458 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7459 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7460 return SDValue(); 7461 } 7462 7463 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 7464 SDValue N0 = N->getOperand(0); 7465 EVT VT = N->getValueType(0); 7466 7467 // fold (cttz c1) -> c2 7468 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7469 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 7470 7471 // If the value is known never to be zero, switch to the undef version. 7472 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) { 7473 if (DAG.isKnownNeverZero(N0)) 7474 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7475 } 7476 7477 return SDValue(); 7478 } 7479 7480 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 7481 SDValue N0 = N->getOperand(0); 7482 EVT VT = N->getValueType(0); 7483 7484 // fold (cttz_zero_undef c1) -> c2 7485 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7486 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 7487 return SDValue(); 7488 } 7489 7490 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 7491 SDValue N0 = N->getOperand(0); 7492 EVT VT = N->getValueType(0); 7493 7494 // fold (ctpop c1) -> c2 7495 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 7496 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 7497 return SDValue(); 7498 } 7499 7500 // FIXME: This should be checking for no signed zeros on individual operands, as 7501 // well as no nans. 7502 static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS, 7503 SDValue RHS, 7504 const TargetLowering &TLI) { 7505 const TargetOptions &Options = DAG.getTarget().Options; 7506 EVT VT = LHS.getValueType(); 7507 7508 return Options.NoSignedZerosFPMath && VT.isFloatingPoint() && 7509 TLI.isProfitableToCombineMinNumMaxNum(VT) && 7510 DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS); 7511 } 7512 7513 /// Generate Min/Max node 7514 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 7515 SDValue RHS, SDValue True, SDValue False, 7516 ISD::CondCode CC, const TargetLowering &TLI, 7517 SelectionDAG &DAG) { 7518 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 7519 return SDValue(); 7520 7521 EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 7522 switch (CC) { 7523 case ISD::SETOLT: 7524 case ISD::SETOLE: 7525 case ISD::SETLT: 7526 case ISD::SETLE: 7527 case ISD::SETULT: 7528 case ISD::SETULE: { 7529 // Since it's known never nan to get here already, either fminnum or 7530 // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is 7531 // expanded in terms of it. 7532 unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 7533 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT)) 7534 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS); 7535 7536 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 7537 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) 7538 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 7539 return SDValue(); 7540 } 7541 case ISD::SETOGT: 7542 case ISD::SETOGE: 7543 case ISD::SETGT: 7544 case ISD::SETGE: 7545 case ISD::SETUGT: 7546 case ISD::SETUGE: { 7547 unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE; 7548 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT)) 7549 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS); 7550 7551 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 7552 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) 7553 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 7554 return SDValue(); 7555 } 7556 default: 7557 return SDValue(); 7558 } 7559 } 7560 7561 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 7562 SDValue Cond = N->getOperand(0); 7563 SDValue N1 = N->getOperand(1); 7564 SDValue N2 = N->getOperand(2); 7565 EVT VT = N->getValueType(0); 7566 EVT CondVT = Cond.getValueType(); 7567 SDLoc DL(N); 7568 7569 if (!VT.isInteger()) 7570 return SDValue(); 7571 7572 auto *C1 = dyn_cast<ConstantSDNode>(N1); 7573 auto *C2 = dyn_cast<ConstantSDNode>(N2); 7574 if (!C1 || !C2) 7575 return SDValue(); 7576 7577 // Only do this before legalization to avoid conflicting with target-specific 7578 // transforms in the other direction (create a select from a zext/sext). There 7579 // is also a target-independent combine here in DAGCombiner in the other 7580 // direction for (select Cond, -1, 0) when the condition is not i1. 7581 if (CondVT == MVT::i1 && !LegalOperations) { 7582 if (C1->isNullValue() && C2->isOne()) { 7583 // select Cond, 0, 1 --> zext (!Cond) 7584 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 7585 if (VT != MVT::i1) 7586 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 7587 return NotCond; 7588 } 7589 if (C1->isNullValue() && C2->isAllOnesValue()) { 7590 // select Cond, 0, -1 --> sext (!Cond) 7591 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 7592 if (VT != MVT::i1) 7593 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 7594 return NotCond; 7595 } 7596 if (C1->isOne() && C2->isNullValue()) { 7597 // select Cond, 1, 0 --> zext (Cond) 7598 if (VT != MVT::i1) 7599 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 7600 return Cond; 7601 } 7602 if (C1->isAllOnesValue() && C2->isNullValue()) { 7603 // select Cond, -1, 0 --> sext (Cond) 7604 if (VT != MVT::i1) 7605 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 7606 return Cond; 7607 } 7608 7609 // For any constants that differ by 1, we can transform the select into an 7610 // extend and add. Use a target hook because some targets may prefer to 7611 // transform in the other direction. 7612 if (TLI.convertSelectOfConstantsToMath(VT)) { 7613 if (C1->getAPIntValue() - 1 == C2->getAPIntValue()) { 7614 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 7615 if (VT != MVT::i1) 7616 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 7617 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 7618 } 7619 if (C1->getAPIntValue() + 1 == C2->getAPIntValue()) { 7620 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 7621 if (VT != MVT::i1) 7622 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 7623 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 7624 } 7625 } 7626 7627 return SDValue(); 7628 } 7629 7630 // fold (select Cond, 0, 1) -> (xor Cond, 1) 7631 // We can't do this reliably if integer based booleans have different contents 7632 // to floating point based booleans. This is because we can't tell whether we 7633 // have an integer-based boolean or a floating-point-based boolean unless we 7634 // can find the SETCC that produced it and inspect its operands. This is 7635 // fairly easy if C is the SETCC node, but it can potentially be 7636 // undiscoverable (or not reasonably discoverable). For example, it could be 7637 // in another basic block or it could require searching a complicated 7638 // expression. 7639 if (CondVT.isInteger() && 7640 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) == 7641 TargetLowering::ZeroOrOneBooleanContent && 7642 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) == 7643 TargetLowering::ZeroOrOneBooleanContent && 7644 C1->isNullValue() && C2->isOne()) { 7645 SDValue NotCond = 7646 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 7647 if (VT.bitsEq(CondVT)) 7648 return NotCond; 7649 return DAG.getZExtOrTrunc(NotCond, DL, VT); 7650 } 7651 7652 return SDValue(); 7653 } 7654 7655 SDValue DAGCombiner::visitSELECT(SDNode *N) { 7656 SDValue N0 = N->getOperand(0); 7657 SDValue N1 = N->getOperand(1); 7658 SDValue N2 = N->getOperand(2); 7659 EVT VT = N->getValueType(0); 7660 EVT VT0 = N0.getValueType(); 7661 SDLoc DL(N); 7662 7663 if (SDValue V = DAG.simplifySelect(N0, N1, N2)) 7664 return V; 7665 7666 // fold (select X, X, Y) -> (or X, Y) 7667 // fold (select X, 1, Y) -> (or C, Y) 7668 if (VT == VT0 && VT == MVT::i1 && (N0 == N1 || isOneConstant(N1))) 7669 return DAG.getNode(ISD::OR, DL, VT, N0, N2); 7670 7671 if (SDValue V = foldSelectOfConstants(N)) 7672 return V; 7673 7674 // fold (select C, 0, X) -> (and (not C), X) 7675 if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) { 7676 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 7677 AddToWorklist(NOTNode.getNode()); 7678 return DAG.getNode(ISD::AND, DL, VT, NOTNode, N2); 7679 } 7680 // fold (select C, X, 1) -> (or (not C), X) 7681 if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) { 7682 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT); 7683 AddToWorklist(NOTNode.getNode()); 7684 return DAG.getNode(ISD::OR, DL, VT, NOTNode, N1); 7685 } 7686 // fold (select X, Y, X) -> (and X, Y) 7687 // fold (select X, Y, 0) -> (and X, Y) 7688 if (VT == VT0 && VT == MVT::i1 && (N0 == N2 || isNullConstant(N2))) 7689 return DAG.getNode(ISD::AND, DL, VT, N0, N1); 7690 7691 // If we can fold this based on the true/false value, do so. 7692 if (SimplifySelectOps(N, N1, N2)) 7693 return SDValue(N, 0); // Don't revisit N. 7694 7695 if (VT0 == MVT::i1) { 7696 // The code in this block deals with the following 2 equivalences: 7697 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 7698 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 7699 // The target can specify its preferred form with the 7700 // shouldNormalizeToSelectSequence() callback. However we always transform 7701 // to the right anyway if we find the inner select exists in the DAG anyway 7702 // and we always transform to the left side if we know that we can further 7703 // optimize the combination of the conditions. 7704 bool normalizeToSequence = 7705 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 7706 // select (and Cond0, Cond1), X, Y 7707 // -> select Cond0, (select Cond1, X, Y), Y 7708 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 7709 SDValue Cond0 = N0->getOperand(0); 7710 SDValue Cond1 = N0->getOperand(1); 7711 SDValue InnerSelect = 7712 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 7713 if (normalizeToSequence || !InnerSelect.use_empty()) 7714 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 7715 InnerSelect, N2); 7716 // Cleanup on failure. 7717 if (InnerSelect.use_empty()) 7718 recursivelyDeleteUnusedNodes(InnerSelect.getNode()); 7719 } 7720 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 7721 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 7722 SDValue Cond0 = N0->getOperand(0); 7723 SDValue Cond1 = N0->getOperand(1); 7724 SDValue InnerSelect = 7725 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2); 7726 if (normalizeToSequence || !InnerSelect.use_empty()) 7727 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 7728 InnerSelect); 7729 // Cleanup on failure. 7730 if (InnerSelect.use_empty()) 7731 recursivelyDeleteUnusedNodes(InnerSelect.getNode()); 7732 } 7733 7734 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 7735 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 7736 SDValue N1_0 = N1->getOperand(0); 7737 SDValue N1_1 = N1->getOperand(1); 7738 SDValue N1_2 = N1->getOperand(2); 7739 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 7740 // Create the actual and node if we can generate good code for it. 7741 if (!normalizeToSequence) { 7742 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 7743 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, N2); 7744 } 7745 // Otherwise see if we can optimize the "and" to a better pattern. 7746 if (SDValue Combined = visitANDLike(N0, N1_0, N)) 7747 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 7748 N2); 7749 } 7750 } 7751 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 7752 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 7753 SDValue N2_0 = N2->getOperand(0); 7754 SDValue N2_1 = N2->getOperand(1); 7755 SDValue N2_2 = N2->getOperand(2); 7756 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 7757 // Create the actual or node if we can generate good code for it. 7758 if (!normalizeToSequence) { 7759 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 7760 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, N2_2); 7761 } 7762 // Otherwise see if we can optimize to a better pattern. 7763 if (SDValue Combined = visitORLike(N0, N2_0, N)) 7764 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 7765 N2_2); 7766 } 7767 } 7768 } 7769 7770 // select (not Cond), N1, N2 -> select Cond, N2, N1 7771 if (SDValue F = extractBooleanFlip(N0, TLI)) 7772 return DAG.getSelect(DL, VT, F, N2, N1); 7773 7774 // Fold selects based on a setcc into other things, such as min/max/abs. 7775 if (N0.getOpcode() == ISD::SETCC) { 7776 SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1); 7777 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 7778 7779 // select (fcmp lt x, y), x, y -> fminnum x, y 7780 // select (fcmp gt x, y), x, y -> fmaxnum x, y 7781 // 7782 // This is OK if we don't care what happens if either operand is a NaN. 7783 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2, TLI)) 7784 if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2, 7785 CC, TLI, DAG)) 7786 return FMinMax; 7787 7788 // Use 'unsigned add with overflow' to optimize an unsigned saturating add. 7789 // This is conservatively limited to pre-legal-operations to give targets 7790 // a chance to reverse the transform if they want to do that. Also, it is 7791 // unlikely that the pattern would be formed late, so it's probably not 7792 // worth going through the other checks. 7793 if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) && 7794 CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) && 7795 N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) { 7796 auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1)); 7797 auto *NotC = dyn_cast<ConstantSDNode>(Cond1); 7798 if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) { 7799 // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) --> 7800 // uaddo Cond0, C; select uaddo.1, -1, uaddo.0 7801 // 7802 // The IR equivalent of this transform would have this form: 7803 // %a = add %x, C 7804 // %c = icmp ugt %x, ~C 7805 // %r = select %c, -1, %a 7806 // => 7807 // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C) 7808 // %u0 = extractvalue %u, 0 7809 // %u1 = extractvalue %u, 1 7810 // %r = select %u1, -1, %u0 7811 SDVTList VTs = DAG.getVTList(VT, VT0); 7812 SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1)); 7813 return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0)); 7814 } 7815 } 7816 7817 if (TLI.isOperationLegal(ISD::SELECT_CC, VT) || 7818 (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))) 7819 return DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1, N2, 7820 N0.getOperand(2)); 7821 7822 return SimplifySelect(DL, N0, N1, N2); 7823 } 7824 7825 return SDValue(); 7826 } 7827 7828 static 7829 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) { 7830 SDLoc DL(N); 7831 EVT LoVT, HiVT; 7832 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 7833 7834 // Split the inputs. 7835 SDValue Lo, Hi, LL, LH, RL, RH; 7836 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0); 7837 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1); 7838 7839 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); 7840 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); 7841 7842 return std::make_pair(Lo, Hi); 7843 } 7844 7845 // This function assumes all the vselect's arguments are CONCAT_VECTOR 7846 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 7847 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 7848 SDLoc DL(N); 7849 SDValue Cond = N->getOperand(0); 7850 SDValue LHS = N->getOperand(1); 7851 SDValue RHS = N->getOperand(2); 7852 EVT VT = N->getValueType(0); 7853 int NumElems = VT.getVectorNumElements(); 7854 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 7855 RHS.getOpcode() == ISD::CONCAT_VECTORS && 7856 Cond.getOpcode() == ISD::BUILD_VECTOR); 7857 7858 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 7859 // binary ones here. 7860 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 7861 return SDValue(); 7862 7863 // We're sure we have an even number of elements due to the 7864 // concat_vectors we have as arguments to vselect. 7865 // Skip BV elements until we find one that's not an UNDEF 7866 // After we find an UNDEF element, keep looping until we get to half the 7867 // length of the BV and see if all the non-undef nodes are the same. 7868 ConstantSDNode *BottomHalf = nullptr; 7869 for (int i = 0; i < NumElems / 2; ++i) { 7870 if (Cond->getOperand(i)->isUndef()) 7871 continue; 7872 7873 if (BottomHalf == nullptr) 7874 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 7875 else if (Cond->getOperand(i).getNode() != BottomHalf) 7876 return SDValue(); 7877 } 7878 7879 // Do the same for the second half of the BuildVector 7880 ConstantSDNode *TopHalf = nullptr; 7881 for (int i = NumElems / 2; i < NumElems; ++i) { 7882 if (Cond->getOperand(i)->isUndef()) 7883 continue; 7884 7885 if (TopHalf == nullptr) 7886 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 7887 else if (Cond->getOperand(i).getNode() != TopHalf) 7888 return SDValue(); 7889 } 7890 7891 assert(TopHalf && BottomHalf && 7892 "One half of the selector was all UNDEFs and the other was all the " 7893 "same value. This should have been addressed before this function."); 7894 return DAG.getNode( 7895 ISD::CONCAT_VECTORS, DL, VT, 7896 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0), 7897 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1)); 7898 } 7899 7900 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 7901 if (Level >= AfterLegalizeTypes) 7902 return SDValue(); 7903 7904 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 7905 SDValue Mask = MSC->getMask(); 7906 SDValue Data = MSC->getValue(); 7907 SDLoc DL(N); 7908 7909 // If the MSCATTER data type requires splitting and the mask is provided by a 7910 // SETCC, then split both nodes and its operands before legalization. This 7911 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7912 // and enables future optimizations (e.g. min/max pattern matching on X86). 7913 if (Mask.getOpcode() != ISD::SETCC) 7914 return SDValue(); 7915 7916 // Check if any splitting is required. 7917 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) != 7918 TargetLowering::TypeSplitVector) 7919 return SDValue(); 7920 SDValue MaskLo, MaskHi; 7921 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7922 7923 EVT LoVT, HiVT; 7924 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0)); 7925 7926 SDValue Chain = MSC->getChain(); 7927 7928 EVT MemoryVT = MSC->getMemoryVT(); 7929 unsigned Alignment = MSC->getOriginalAlignment(); 7930 7931 EVT LoMemVT, HiMemVT; 7932 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7933 7934 SDValue DataLo, DataHi; 7935 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 7936 7937 SDValue Scale = MSC->getScale(); 7938 SDValue BasePtr = MSC->getBasePtr(); 7939 SDValue IndexLo, IndexHi; 7940 std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL); 7941 7942 MachineMemOperand *MMO = DAG.getMachineFunction(). 7943 getMachineMemOperand(MSC->getPointerInfo(), 7944 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 7945 Alignment, MSC->getAAInfo(), MSC->getRanges()); 7946 7947 SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo, Scale }; 7948 SDValue Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), 7949 DataLo.getValueType(), DL, OpsLo, MMO); 7950 7951 // The order of the Scatter operation after split is well defined. The "Hi" 7952 // part comes after the "Lo". So these two operations should be chained one 7953 // after another. 7954 SDValue OpsHi[] = { Lo, DataHi, MaskHi, BasePtr, IndexHi, Scale }; 7955 return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(), 7956 DL, OpsHi, MMO); 7957 } 7958 7959 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 7960 if (Level >= AfterLegalizeTypes) 7961 return SDValue(); 7962 7963 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N); 7964 SDValue Mask = MST->getMask(); 7965 SDValue Data = MST->getValue(); 7966 EVT VT = Data.getValueType(); 7967 SDLoc DL(N); 7968 7969 // If the MSTORE data type requires splitting and the mask is provided by a 7970 // SETCC, then split both nodes and its operands before legalization. This 7971 // prevents the type legalizer from unrolling SETCC into scalar comparisons 7972 // and enables future optimizations (e.g. min/max pattern matching on X86). 7973 if (Mask.getOpcode() == ISD::SETCC) { 7974 // Check if any splitting is required. 7975 if (TLI.getTypeAction(*DAG.getContext(), VT) != 7976 TargetLowering::TypeSplitVector) 7977 return SDValue(); 7978 7979 SDValue MaskLo, MaskHi, Lo, Hi; 7980 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 7981 7982 SDValue Chain = MST->getChain(); 7983 SDValue Ptr = MST->getBasePtr(); 7984 7985 EVT MemoryVT = MST->getMemoryVT(); 7986 unsigned Alignment = MST->getOriginalAlignment(); 7987 7988 // if Alignment is equal to the vector size, 7989 // take the half of it for the second part 7990 unsigned SecondHalfAlignment = 7991 (Alignment == VT.getSizeInBits() / 8) ? Alignment / 2 : Alignment; 7992 7993 EVT LoMemVT, HiMemVT; 7994 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 7995 7996 SDValue DataLo, DataHi; 7997 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL); 7998 7999 MachineMemOperand *MMO = DAG.getMachineFunction(). 8000 getMachineMemOperand(MST->getPointerInfo(), 8001 MachineMemOperand::MOStore, LoMemVT.getStoreSize(), 8002 Alignment, MST->getAAInfo(), MST->getRanges()); 8003 8004 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO, 8005 MST->isTruncatingStore(), 8006 MST->isCompressingStore()); 8007 8008 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 8009 MST->isCompressingStore()); 8010 unsigned HiOffset = LoMemVT.getStoreSize(); 8011 8012 MMO = DAG.getMachineFunction().getMachineMemOperand( 8013 MST->getPointerInfo().getWithOffset(HiOffset), 8014 MachineMemOperand::MOStore, HiMemVT.getStoreSize(), SecondHalfAlignment, 8015 MST->getAAInfo(), MST->getRanges()); 8016 8017 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO, 8018 MST->isTruncatingStore(), 8019 MST->isCompressingStore()); 8020 8021 AddToWorklist(Lo.getNode()); 8022 AddToWorklist(Hi.getNode()); 8023 8024 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); 8025 } 8026 return SDValue(); 8027 } 8028 8029 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 8030 if (Level >= AfterLegalizeTypes) 8031 return SDValue(); 8032 8033 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); 8034 SDValue Mask = MGT->getMask(); 8035 SDLoc DL(N); 8036 8037 // If the MGATHER result requires splitting and the mask is provided by a 8038 // SETCC, then split both nodes and its operands before legalization. This 8039 // prevents the type legalizer from unrolling SETCC into scalar comparisons 8040 // and enables future optimizations (e.g. min/max pattern matching on X86). 8041 8042 if (Mask.getOpcode() != ISD::SETCC) 8043 return SDValue(); 8044 8045 EVT VT = N->getValueType(0); 8046 8047 // Check if any splitting is required. 8048 if (TLI.getTypeAction(*DAG.getContext(), VT) != 8049 TargetLowering::TypeSplitVector) 8050 return SDValue(); 8051 8052 SDValue MaskLo, MaskHi, Lo, Hi; 8053 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 8054 8055 SDValue PassThru = MGT->getPassThru(); 8056 SDValue PassThruLo, PassThruHi; 8057 std::tie(PassThruLo, PassThruHi) = DAG.SplitVector(PassThru, DL); 8058 8059 EVT LoVT, HiVT; 8060 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT); 8061 8062 SDValue Chain = MGT->getChain(); 8063 EVT MemoryVT = MGT->getMemoryVT(); 8064 unsigned Alignment = MGT->getOriginalAlignment(); 8065 8066 EVT LoMemVT, HiMemVT; 8067 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 8068 8069 SDValue Scale = MGT->getScale(); 8070 SDValue BasePtr = MGT->getBasePtr(); 8071 SDValue Index = MGT->getIndex(); 8072 SDValue IndexLo, IndexHi; 8073 std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL); 8074 8075 MachineMemOperand *MMO = DAG.getMachineFunction(). 8076 getMachineMemOperand(MGT->getPointerInfo(), 8077 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 8078 Alignment, MGT->getAAInfo(), MGT->getRanges()); 8079 8080 SDValue OpsLo[] = { Chain, PassThruLo, MaskLo, BasePtr, IndexLo, Scale }; 8081 Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo, 8082 MMO); 8083 8084 SDValue OpsHi[] = { Chain, PassThruHi, MaskHi, BasePtr, IndexHi, Scale }; 8085 Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi, 8086 MMO); 8087 8088 AddToWorklist(Lo.getNode()); 8089 AddToWorklist(Hi.getNode()); 8090 8091 // Build a factor node to remember that this load is independent of the 8092 // other one. 8093 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 8094 Hi.getValue(1)); 8095 8096 // Legalized the chain result - switch anything that used the old chain to 8097 // use the new one. 8098 DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain); 8099 8100 SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 8101 8102 SDValue RetOps[] = { GatherRes, Chain }; 8103 return DAG.getMergeValues(RetOps, DL); 8104 } 8105 8106 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 8107 if (Level >= AfterLegalizeTypes) 8108 return SDValue(); 8109 8110 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N); 8111 SDValue Mask = MLD->getMask(); 8112 SDLoc DL(N); 8113 8114 // If the MLOAD result requires splitting and the mask is provided by a 8115 // SETCC, then split both nodes and its operands before legalization. This 8116 // prevents the type legalizer from unrolling SETCC into scalar comparisons 8117 // and enables future optimizations (e.g. min/max pattern matching on X86). 8118 if (Mask.getOpcode() == ISD::SETCC) { 8119 EVT VT = N->getValueType(0); 8120 8121 // Check if any splitting is required. 8122 if (TLI.getTypeAction(*DAG.getContext(), VT) != 8123 TargetLowering::TypeSplitVector) 8124 return SDValue(); 8125 8126 SDValue MaskLo, MaskHi, Lo, Hi; 8127 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG); 8128 8129 SDValue PassThru = MLD->getPassThru(); 8130 SDValue PassThruLo, PassThruHi; 8131 std::tie(PassThruLo, PassThruHi) = DAG.SplitVector(PassThru, DL); 8132 8133 EVT LoVT, HiVT; 8134 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0)); 8135 8136 SDValue Chain = MLD->getChain(); 8137 SDValue Ptr = MLD->getBasePtr(); 8138 EVT MemoryVT = MLD->getMemoryVT(); 8139 unsigned Alignment = MLD->getOriginalAlignment(); 8140 8141 // if Alignment is equal to the vector size, 8142 // take the half of it for the second part 8143 unsigned SecondHalfAlignment = 8144 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ? 8145 Alignment/2 : Alignment; 8146 8147 EVT LoMemVT, HiMemVT; 8148 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT); 8149 8150 MachineMemOperand *MMO = DAG.getMachineFunction(). 8151 getMachineMemOperand(MLD->getPointerInfo(), 8152 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(), 8153 Alignment, MLD->getAAInfo(), MLD->getRanges()); 8154 8155 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, PassThruLo, LoMemVT, 8156 MMO, ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 8157 8158 Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG, 8159 MLD->isExpandingLoad()); 8160 unsigned HiOffset = LoMemVT.getStoreSize(); 8161 8162 MMO = DAG.getMachineFunction().getMachineMemOperand( 8163 MLD->getPointerInfo().getWithOffset(HiOffset), 8164 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(), SecondHalfAlignment, 8165 MLD->getAAInfo(), MLD->getRanges()); 8166 8167 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, PassThruHi, HiMemVT, 8168 MMO, ISD::NON_EXTLOAD, MLD->isExpandingLoad()); 8169 8170 AddToWorklist(Lo.getNode()); 8171 AddToWorklist(Hi.getNode()); 8172 8173 // Build a factor node to remember that this load is independent of the 8174 // other one. 8175 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1), 8176 Hi.getValue(1)); 8177 8178 // Legalized the chain result - switch anything that used the old chain to 8179 // use the new one. 8180 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain); 8181 8182 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi); 8183 8184 SDValue RetOps[] = { LoadRes, Chain }; 8185 return DAG.getMergeValues(RetOps, DL); 8186 } 8187 return SDValue(); 8188 } 8189 8190 /// A vector select of 2 constant vectors can be simplified to math/logic to 8191 /// avoid a variable select instruction and possibly avoid constant loads. 8192 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { 8193 SDValue Cond = N->getOperand(0); 8194 SDValue N1 = N->getOperand(1); 8195 SDValue N2 = N->getOperand(2); 8196 EVT VT = N->getValueType(0); 8197 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || 8198 !TLI.convertSelectOfConstantsToMath(VT) || 8199 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || 8200 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) 8201 return SDValue(); 8202 8203 // Check if we can use the condition value to increment/decrement a single 8204 // constant value. This simplifies a select to an add and removes a constant 8205 // load/materialization from the general case. 8206 bool AllAddOne = true; 8207 bool AllSubOne = true; 8208 unsigned Elts = VT.getVectorNumElements(); 8209 for (unsigned i = 0; i != Elts; ++i) { 8210 SDValue N1Elt = N1.getOperand(i); 8211 SDValue N2Elt = N2.getOperand(i); 8212 if (N1Elt.isUndef() || N2Elt.isUndef()) 8213 continue; 8214 8215 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); 8216 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); 8217 if (C1 != C2 + 1) 8218 AllAddOne = false; 8219 if (C1 != C2 - 1) 8220 AllSubOne = false; 8221 } 8222 8223 // Further simplifications for the extra-special cases where the constants are 8224 // all 0 or all -1 should be implemented as folds of these patterns. 8225 SDLoc DL(N); 8226 if (AllAddOne || AllSubOne) { 8227 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C 8228 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C 8229 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 8230 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); 8231 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); 8232 } 8233 8234 // The general case for select-of-constants: 8235 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 8236 // ...but that only makes sense if a vselect is slower than 2 logic ops, so 8237 // leave that to a machine-specific pass. 8238 return SDValue(); 8239 } 8240 8241 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 8242 SDValue N0 = N->getOperand(0); 8243 SDValue N1 = N->getOperand(1); 8244 SDValue N2 = N->getOperand(2); 8245 EVT VT = N->getValueType(0); 8246 SDLoc DL(N); 8247 8248 if (SDValue V = DAG.simplifySelect(N0, N1, N2)) 8249 return V; 8250 8251 // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1 8252 if (SDValue F = extractBooleanFlip(N0, TLI)) 8253 return DAG.getSelect(DL, VT, F, N2, N1); 8254 8255 // Canonicalize integer abs. 8256 // vselect (setg[te] X, 0), X, -X -> 8257 // vselect (setgt X, -1), X, -X -> 8258 // vselect (setl[te] X, 0), -X, X -> 8259 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 8260 if (N0.getOpcode() == ISD::SETCC) { 8261 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 8262 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 8263 bool isAbs = false; 8264 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 8265 8266 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 8267 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 8268 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 8269 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 8270 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 8271 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 8272 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 8273 8274 if (isAbs) { 8275 EVT VT = LHS.getValueType(); 8276 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 8277 return DAG.getNode(ISD::ABS, DL, VT, LHS); 8278 8279 SDValue Shift = DAG.getNode( 8280 ISD::SRA, DL, VT, LHS, 8281 DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT)); 8282 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 8283 AddToWorklist(Shift.getNode()); 8284 AddToWorklist(Add.getNode()); 8285 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 8286 } 8287 8288 // vselect x, y (fcmp lt x, y) -> fminnum x, y 8289 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y 8290 // 8291 // This is OK if we don't care about what happens if either operand is a 8292 // NaN. 8293 // 8294 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum( 8295 DAG, N0.getOperand(0), N0.getOperand(1), TLI)) { 8296 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 8297 if (SDValue FMinMax = combineMinNumMaxNum( 8298 DL, VT, N0.getOperand(0), N0.getOperand(1), N1, N2, CC, TLI, DAG)) 8299 return FMinMax; 8300 } 8301 8302 // If this select has a condition (setcc) with narrower operands than the 8303 // select, try to widen the compare to match the select width. 8304 // TODO: This should be extended to handle any constant. 8305 // TODO: This could be extended to handle non-loading patterns, but that 8306 // requires thorough testing to avoid regressions. 8307 if (isNullOrNullSplat(RHS)) { 8308 EVT NarrowVT = LHS.getValueType(); 8309 EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger(); 8310 EVT SetCCVT = getSetCCResultType(LHS.getValueType()); 8311 unsigned SetCCWidth = SetCCVT.getScalarSizeInBits(); 8312 unsigned WideWidth = WideVT.getScalarSizeInBits(); 8313 bool IsSigned = isSignedIntSetCC(CC); 8314 auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 8315 if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() && 8316 SetCCWidth != 1 && SetCCWidth < WideWidth && 8317 TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) && 8318 TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) { 8319 // Both compare operands can be widened for free. The LHS can use an 8320 // extended load, and the RHS is a constant: 8321 // vselect (ext (setcc load(X), C)), N1, N2 --> 8322 // vselect (setcc extload(X), C'), N1, N2 8323 auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8324 SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS); 8325 SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS); 8326 EVT WideSetCCVT = getSetCCResultType(WideVT); 8327 SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC); 8328 return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2); 8329 } 8330 } 8331 } 8332 8333 if (SimplifySelectOps(N, N1, N2)) 8334 return SDValue(N, 0); // Don't revisit N. 8335 8336 // Fold (vselect (build_vector all_ones), N1, N2) -> N1 8337 if (ISD::isBuildVectorAllOnes(N0.getNode())) 8338 return N1; 8339 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2 8340 if (ISD::isBuildVectorAllZeros(N0.getNode())) 8341 return N2; 8342 8343 // The ConvertSelectToConcatVector function is assuming both the above 8344 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 8345 // and addressed. 8346 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 8347 N2.getOpcode() == ISD::CONCAT_VECTORS && 8348 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 8349 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 8350 return CV; 8351 } 8352 8353 if (SDValue V = foldVSelectOfConstants(N)) 8354 return V; 8355 8356 return SDValue(); 8357 } 8358 8359 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 8360 SDValue N0 = N->getOperand(0); 8361 SDValue N1 = N->getOperand(1); 8362 SDValue N2 = N->getOperand(2); 8363 SDValue N3 = N->getOperand(3); 8364 SDValue N4 = N->getOperand(4); 8365 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 8366 8367 // fold select_cc lhs, rhs, x, x, cc -> x 8368 if (N2 == N3) 8369 return N2; 8370 8371 // Determine if the condition we're dealing with is constant 8372 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 8373 CC, SDLoc(N), false)) { 8374 AddToWorklist(SCC.getNode()); 8375 8376 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 8377 if (!SCCC->isNullValue()) 8378 return N2; // cond always true -> true val 8379 else 8380 return N3; // cond always false -> false val 8381 } else if (SCC->isUndef()) { 8382 // When the condition is UNDEF, just return the first operand. This is 8383 // coherent the DAG creation, no setcc node is created in this case 8384 return N2; 8385 } else if (SCC.getOpcode() == ISD::SETCC) { 8386 // Fold to a simpler select_cc 8387 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(), 8388 SCC.getOperand(0), SCC.getOperand(1), N2, N3, 8389 SCC.getOperand(2)); 8390 } 8391 } 8392 8393 // If we can fold this based on the true/false value, do so. 8394 if (SimplifySelectOps(N, N2, N3)) 8395 return SDValue(N, 0); // Don't revisit N. 8396 8397 // fold select_cc into other things, such as min/max/abs 8398 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 8399 } 8400 8401 SDValue DAGCombiner::visitSETCC(SDNode *N) { 8402 // setcc is very commonly used as an argument to brcond. This pattern 8403 // also lend itself to numerous combines and, as a result, it is desired 8404 // we keep the argument to a brcond as a setcc as much as possible. 8405 bool PreferSetCC = 8406 N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND; 8407 8408 SDValue Combined = SimplifySetCC( 8409 N->getValueType(0), N->getOperand(0), N->getOperand(1), 8410 cast<CondCodeSDNode>(N->getOperand(2))->get(), SDLoc(N), !PreferSetCC); 8411 8412 if (!Combined) 8413 return SDValue(); 8414 8415 // If we prefer to have a setcc, and we don't, we'll try our best to 8416 // recreate one using rebuildSetCC. 8417 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) { 8418 SDValue NewSetCC = rebuildSetCC(Combined); 8419 8420 // We don't have anything interesting to combine to. 8421 if (NewSetCC.getNode() == N) 8422 return SDValue(); 8423 8424 if (NewSetCC) 8425 return NewSetCC; 8426 } 8427 8428 return Combined; 8429 } 8430 8431 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 8432 SDValue LHS = N->getOperand(0); 8433 SDValue RHS = N->getOperand(1); 8434 SDValue Carry = N->getOperand(2); 8435 SDValue Cond = N->getOperand(3); 8436 8437 // If Carry is false, fold to a regular SETCC. 8438 if (isNullConstant(Carry)) 8439 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 8440 8441 return SDValue(); 8442 } 8443 8444 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 8445 /// a build_vector of constants. 8446 /// This function is called by the DAGCombiner when visiting sext/zext/aext 8447 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 8448 /// Vector extends are not folded if operations are legal; this is to 8449 /// avoid introducing illegal build_vector dag nodes. 8450 static SDValue tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 8451 SelectionDAG &DAG, bool LegalTypes) { 8452 unsigned Opcode = N->getOpcode(); 8453 SDValue N0 = N->getOperand(0); 8454 EVT VT = N->getValueType(0); 8455 8456 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 8457 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 8458 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 8459 && "Expected EXTEND dag node in input!"); 8460 8461 // fold (sext c1) -> c1 8462 // fold (zext c1) -> c1 8463 // fold (aext c1) -> c1 8464 if (isa<ConstantSDNode>(N0)) 8465 return DAG.getNode(Opcode, SDLoc(N), VT, N0); 8466 8467 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 8468 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 8469 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 8470 EVT SVT = VT.getScalarType(); 8471 if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) && 8472 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 8473 return SDValue(); 8474 8475 // We can fold this node into a build_vector. 8476 unsigned VTBits = SVT.getSizeInBits(); 8477 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 8478 SmallVector<SDValue, 8> Elts; 8479 unsigned NumElts = VT.getVectorNumElements(); 8480 SDLoc DL(N); 8481 8482 // For zero-extensions, UNDEF elements still guarantee to have the upper 8483 // bits set to zero. 8484 bool IsZext = 8485 Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG; 8486 8487 for (unsigned i = 0; i != NumElts; ++i) { 8488 SDValue Op = N0.getOperand(i); 8489 if (Op.isUndef()) { 8490 Elts.push_back(IsZext ? DAG.getConstant(0, DL, SVT) : DAG.getUNDEF(SVT)); 8491 continue; 8492 } 8493 8494 SDLoc DL(Op); 8495 // Get the constant value and if needed trunc it to the size of the type. 8496 // Nodes like build_vector might have constants wider than the scalar type. 8497 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 8498 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 8499 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 8500 else 8501 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 8502 } 8503 8504 return DAG.getBuildVector(VT, DL, Elts); 8505 } 8506 8507 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 8508 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 8509 // transformation. Returns true if extension are possible and the above 8510 // mentioned transformation is profitable. 8511 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0, 8512 unsigned ExtOpc, 8513 SmallVectorImpl<SDNode *> &ExtendNodes, 8514 const TargetLowering &TLI) { 8515 bool HasCopyToRegUses = false; 8516 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType()); 8517 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 8518 UE = N0.getNode()->use_end(); 8519 UI != UE; ++UI) { 8520 SDNode *User = *UI; 8521 if (User == N) 8522 continue; 8523 if (UI.getUse().getResNo() != N0.getResNo()) 8524 continue; 8525 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 8526 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 8527 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 8528 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 8529 // Sign bits will be lost after a zext. 8530 return false; 8531 bool Add = false; 8532 for (unsigned i = 0; i != 2; ++i) { 8533 SDValue UseOp = User->getOperand(i); 8534 if (UseOp == N0) 8535 continue; 8536 if (!isa<ConstantSDNode>(UseOp)) 8537 return false; 8538 Add = true; 8539 } 8540 if (Add) 8541 ExtendNodes.push_back(User); 8542 continue; 8543 } 8544 // If truncates aren't free and there are users we can't 8545 // extend, it isn't worthwhile. 8546 if (!isTruncFree) 8547 return false; 8548 // Remember if this value is live-out. 8549 if (User->getOpcode() == ISD::CopyToReg) 8550 HasCopyToRegUses = true; 8551 } 8552 8553 if (HasCopyToRegUses) { 8554 bool BothLiveOut = false; 8555 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 8556 UI != UE; ++UI) { 8557 SDUse &Use = UI.getUse(); 8558 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 8559 BothLiveOut = true; 8560 break; 8561 } 8562 } 8563 if (BothLiveOut) 8564 // Both unextended and extended values are live out. There had better be 8565 // a good reason for the transformation. 8566 return ExtendNodes.size(); 8567 } 8568 return true; 8569 } 8570 8571 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 8572 SDValue OrigLoad, SDValue ExtLoad, 8573 ISD::NodeType ExtType) { 8574 // Extend SetCC uses if necessary. 8575 SDLoc DL(ExtLoad); 8576 for (SDNode *SetCC : SetCCs) { 8577 SmallVector<SDValue, 4> Ops; 8578 8579 for (unsigned j = 0; j != 2; ++j) { 8580 SDValue SOp = SetCC->getOperand(j); 8581 if (SOp == OrigLoad) 8582 Ops.push_back(ExtLoad); 8583 else 8584 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 8585 } 8586 8587 Ops.push_back(SetCC->getOperand(2)); 8588 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 8589 } 8590 } 8591 8592 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 8593 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 8594 SDValue N0 = N->getOperand(0); 8595 EVT DstVT = N->getValueType(0); 8596 EVT SrcVT = N0.getValueType(); 8597 8598 assert((N->getOpcode() == ISD::SIGN_EXTEND || 8599 N->getOpcode() == ISD::ZERO_EXTEND) && 8600 "Unexpected node type (not an extend)!"); 8601 8602 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 8603 // For example, on a target with legal v4i32, but illegal v8i32, turn: 8604 // (v8i32 (sext (v8i16 (load x)))) 8605 // into: 8606 // (v8i32 (concat_vectors (v4i32 (sextload x)), 8607 // (v4i32 (sextload (x + 16))))) 8608 // Where uses of the original load, i.e.: 8609 // (v8i16 (load x)) 8610 // are replaced with: 8611 // (v8i16 (truncate 8612 // (v8i32 (concat_vectors (v4i32 (sextload x)), 8613 // (v4i32 (sextload (x + 16))))))) 8614 // 8615 // This combine is only applicable to illegal, but splittable, vectors. 8616 // All legal types, and illegal non-vector types, are handled elsewhere. 8617 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 8618 // 8619 if (N0->getOpcode() != ISD::LOAD) 8620 return SDValue(); 8621 8622 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8623 8624 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 8625 !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() || 8626 !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 8627 return SDValue(); 8628 8629 SmallVector<SDNode *, 4> SetCCs; 8630 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI)) 8631 return SDValue(); 8632 8633 ISD::LoadExtType ExtType = 8634 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 8635 8636 // Try to split the vector types to get down to legal types. 8637 EVT SplitSrcVT = SrcVT; 8638 EVT SplitDstVT = DstVT; 8639 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 8640 SplitSrcVT.getVectorNumElements() > 1) { 8641 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 8642 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 8643 } 8644 8645 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 8646 return SDValue(); 8647 8648 SDLoc DL(N); 8649 const unsigned NumSplits = 8650 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 8651 const unsigned Stride = SplitSrcVT.getStoreSize(); 8652 SmallVector<SDValue, 4> Loads; 8653 SmallVector<SDValue, 4> Chains; 8654 8655 SDValue BasePtr = LN0->getBasePtr(); 8656 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 8657 const unsigned Offset = Idx * Stride; 8658 const unsigned Align = MinAlign(LN0->getAlignment(), Offset); 8659 8660 SDValue SplitLoad = DAG.getExtLoad( 8661 ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr, 8662 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 8663 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 8664 8665 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, 8666 DAG.getConstant(Stride, DL, BasePtr.getValueType())); 8667 8668 Loads.push_back(SplitLoad.getValue(0)); 8669 Chains.push_back(SplitLoad.getValue(1)); 8670 } 8671 8672 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 8673 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 8674 8675 // Simplify TF. 8676 AddToWorklist(NewChain.getNode()); 8677 8678 CombineTo(N, NewValue); 8679 8680 // Replace uses of the original load (before extension) 8681 // with a truncate of the concatenated sextloaded vectors. 8682 SDValue Trunc = 8683 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 8684 ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode()); 8685 CombineTo(N0.getNode(), Trunc, NewChain); 8686 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8687 } 8688 8689 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 8690 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 8691 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) { 8692 assert(N->getOpcode() == ISD::ZERO_EXTEND); 8693 EVT VT = N->getValueType(0); 8694 EVT OrigVT = N->getOperand(0).getValueType(); 8695 if (TLI.isZExtFree(OrigVT, VT)) 8696 return SDValue(); 8697 8698 // and/or/xor 8699 SDValue N0 = N->getOperand(0); 8700 if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8701 N0.getOpcode() == ISD::XOR) || 8702 N0.getOperand(1).getOpcode() != ISD::Constant || 8703 (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT))) 8704 return SDValue(); 8705 8706 // shl/shr 8707 SDValue N1 = N0->getOperand(0); 8708 if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) || 8709 N1.getOperand(1).getOpcode() != ISD::Constant || 8710 (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT))) 8711 return SDValue(); 8712 8713 // load 8714 if (!isa<LoadSDNode>(N1.getOperand(0))) 8715 return SDValue(); 8716 LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0)); 8717 EVT MemVT = Load->getMemoryVT(); 8718 if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) || 8719 Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed()) 8720 return SDValue(); 8721 8722 8723 // If the shift op is SHL, the logic op must be AND, otherwise the result 8724 // will be wrong. 8725 if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND) 8726 return SDValue(); 8727 8728 if (!N0.hasOneUse() || !N1.hasOneUse()) 8729 return SDValue(); 8730 8731 SmallVector<SDNode*, 4> SetCCs; 8732 if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0), 8733 ISD::ZERO_EXTEND, SetCCs, TLI)) 8734 return SDValue(); 8735 8736 // Actually do the transformation. 8737 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT, 8738 Load->getChain(), Load->getBasePtr(), 8739 Load->getMemoryVT(), Load->getMemOperand()); 8740 8741 SDLoc DL1(N1); 8742 SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad, 8743 N1.getOperand(1)); 8744 8745 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 8746 Mask = Mask.zext(VT.getSizeInBits()); 8747 SDLoc DL0(N0); 8748 SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift, 8749 DAG.getConstant(Mask, DL0, VT)); 8750 8751 ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 8752 CombineTo(N, And); 8753 if (SDValue(Load, 0).hasOneUse()) { 8754 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1)); 8755 } else { 8756 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load), 8757 Load->getValueType(0), ExtLoad); 8758 CombineTo(Load, Trunc, ExtLoad.getValue(1)); 8759 } 8760 8761 // N0 is dead at this point. 8762 recursivelyDeleteUnusedNodes(N0.getNode()); 8763 8764 return SDValue(N,0); // Return N so it doesn't get rechecked! 8765 } 8766 8767 /// If we're narrowing or widening the result of a vector select and the final 8768 /// size is the same size as a setcc (compare) feeding the select, then try to 8769 /// apply the cast operation to the select's operands because matching vector 8770 /// sizes for a select condition and other operands should be more efficient. 8771 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 8772 unsigned CastOpcode = Cast->getOpcode(); 8773 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 8774 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 8775 CastOpcode == ISD::FP_ROUND) && 8776 "Unexpected opcode for vector select narrowing/widening"); 8777 8778 // We only do this transform before legal ops because the pattern may be 8779 // obfuscated by target-specific operations after legalization. Do not create 8780 // an illegal select op, however, because that may be difficult to lower. 8781 EVT VT = Cast->getValueType(0); 8782 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 8783 return SDValue(); 8784 8785 SDValue VSel = Cast->getOperand(0); 8786 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 8787 VSel.getOperand(0).getOpcode() != ISD::SETCC) 8788 return SDValue(); 8789 8790 // Does the setcc have the same vector size as the casted select? 8791 SDValue SetCC = VSel.getOperand(0); 8792 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 8793 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 8794 return SDValue(); 8795 8796 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 8797 SDValue A = VSel.getOperand(1); 8798 SDValue B = VSel.getOperand(2); 8799 SDValue CastA, CastB; 8800 SDLoc DL(Cast); 8801 if (CastOpcode == ISD::FP_ROUND) { 8802 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 8803 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 8804 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 8805 } else { 8806 CastA = DAG.getNode(CastOpcode, DL, VT, A); 8807 CastB = DAG.getNode(CastOpcode, DL, VT, B); 8808 } 8809 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 8810 } 8811 8812 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8813 // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8814 static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner, 8815 const TargetLowering &TLI, EVT VT, 8816 bool LegalOperations, SDNode *N, 8817 SDValue N0, ISD::LoadExtType ExtLoadType) { 8818 SDNode *N0Node = N0.getNode(); 8819 bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node) 8820 : ISD::isZEXTLoad(N0Node); 8821 if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) || 8822 !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse()) 8823 return SDValue(); 8824 8825 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8826 EVT MemVT = LN0->getMemoryVT(); 8827 if ((LegalOperations || LN0->isVolatile() || VT.isVector()) && 8828 !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT)) 8829 return SDValue(); 8830 8831 SDValue ExtLoad = 8832 DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 8833 LN0->getBasePtr(), MemVT, LN0->getMemOperand()); 8834 Combiner.CombineTo(N, ExtLoad); 8835 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8836 if (LN0->use_empty()) 8837 Combiner.recursivelyDeleteUnusedNodes(LN0); 8838 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8839 } 8840 8841 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x))) 8842 // Only generate vector extloads when 1) they're legal, and 2) they are 8843 // deemed desirable by the target. 8844 static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner, 8845 const TargetLowering &TLI, EVT VT, 8846 bool LegalOperations, SDNode *N, SDValue N0, 8847 ISD::LoadExtType ExtLoadType, 8848 ISD::NodeType ExtOpc) { 8849 if (!ISD::isNON_EXTLoad(N0.getNode()) || 8850 !ISD::isUNINDEXEDLoad(N0.getNode()) || 8851 ((LegalOperations || VT.isVector() || 8852 cast<LoadSDNode>(N0)->isVolatile()) && 8853 !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType()))) 8854 return {}; 8855 8856 bool DoXform = true; 8857 SmallVector<SDNode *, 4> SetCCs; 8858 if (!N0.hasOneUse()) 8859 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI); 8860 if (VT.isVector()) 8861 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 8862 if (!DoXform) 8863 return {}; 8864 8865 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 8866 SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 8867 LN0->getBasePtr(), N0.getValueType(), 8868 LN0->getMemOperand()); 8869 Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc); 8870 // If the load value is used only by N, replace it via CombineTo N. 8871 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 8872 Combiner.CombineTo(N, ExtLoad); 8873 if (NoReplaceTrunc) { 8874 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 8875 Combiner.recursivelyDeleteUnusedNodes(LN0); 8876 } else { 8877 SDValue Trunc = 8878 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad); 8879 Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 8880 } 8881 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8882 } 8883 8884 static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG, 8885 bool LegalOperations) { 8886 assert((N->getOpcode() == ISD::SIGN_EXTEND || 8887 N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext"); 8888 8889 SDValue SetCC = N->getOperand(0); 8890 if (LegalOperations || SetCC.getOpcode() != ISD::SETCC || 8891 !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1) 8892 return SDValue(); 8893 8894 SDValue X = SetCC.getOperand(0); 8895 SDValue Ones = SetCC.getOperand(1); 8896 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); 8897 EVT VT = N->getValueType(0); 8898 EVT XVT = X.getValueType(); 8899 // setge X, C is canonicalized to setgt, so we do not need to match that 8900 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does 8901 // not require the 'not' op. 8902 if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) { 8903 // Invert and smear/shift the sign bit: 8904 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1) 8905 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1) 8906 SDLoc DL(N); 8907 SDValue NotX = DAG.getNOT(DL, X, VT); 8908 SDValue ShiftAmount = DAG.getConstant(VT.getSizeInBits() - 1, DL, VT); 8909 auto ShiftOpcode = N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL; 8910 return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount); 8911 } 8912 return SDValue(); 8913 } 8914 8915 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 8916 SDValue N0 = N->getOperand(0); 8917 EVT VT = N->getValueType(0); 8918 SDLoc DL(N); 8919 8920 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 8921 return Res; 8922 8923 // fold (sext (sext x)) -> (sext x) 8924 // fold (sext (aext x)) -> (sext x) 8925 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 8926 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 8927 8928 if (N0.getOpcode() == ISD::TRUNCATE) { 8929 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 8930 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 8931 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 8932 SDNode *oye = N0.getOperand(0).getNode(); 8933 if (NarrowLoad.getNode() != N0.getNode()) { 8934 CombineTo(N0.getNode(), NarrowLoad); 8935 // CombineTo deleted the truncate, if needed, but not what's under it. 8936 AddToWorklist(oye); 8937 } 8938 return SDValue(N, 0); // Return N so it doesn't get rechecked! 8939 } 8940 8941 // See if the value being truncated is already sign extended. If so, just 8942 // eliminate the trunc/sext pair. 8943 SDValue Op = N0.getOperand(0); 8944 unsigned OpBits = Op.getScalarValueSizeInBits(); 8945 unsigned MidBits = N0.getScalarValueSizeInBits(); 8946 unsigned DestBits = VT.getScalarSizeInBits(); 8947 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 8948 8949 if (OpBits == DestBits) { 8950 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 8951 // bits, it is already ready. 8952 if (NumSignBits > DestBits-MidBits) 8953 return Op; 8954 } else if (OpBits < DestBits) { 8955 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 8956 // bits, just sext from i32. 8957 if (NumSignBits > OpBits-MidBits) 8958 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 8959 } else { 8960 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 8961 // bits, just truncate to i32. 8962 if (NumSignBits > OpBits-MidBits) 8963 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 8964 } 8965 8966 // fold (sext (truncate x)) -> (sextinreg x). 8967 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 8968 N0.getValueType())) { 8969 if (OpBits < DestBits) 8970 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 8971 else if (OpBits > DestBits) 8972 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 8973 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 8974 DAG.getValueType(N0.getValueType())); 8975 } 8976 } 8977 8978 // Try to simplify (sext (load x)). 8979 if (SDValue foldedExt = 8980 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 8981 ISD::SEXTLOAD, ISD::SIGN_EXTEND)) 8982 return foldedExt; 8983 8984 // fold (sext (load x)) to multiple smaller sextloads. 8985 // Only on illegal but splittable vectors. 8986 if (SDValue ExtLoad = CombineExtLoad(N)) 8987 return ExtLoad; 8988 8989 // Try to simplify (sext (sextload x)). 8990 if (SDValue foldedExt = tryToFoldExtOfExtload( 8991 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD)) 8992 return foldedExt; 8993 8994 // fold (sext (and/or/xor (load x), cst)) -> 8995 // (and/or/xor (sextload x), (sext cst)) 8996 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 8997 N0.getOpcode() == ISD::XOR) && 8998 isa<LoadSDNode>(N0.getOperand(0)) && 8999 N0.getOperand(1).getOpcode() == ISD::Constant && 9000 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 9001 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 9002 EVT MemVT = LN00->getMemoryVT(); 9003 if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) && 9004 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) { 9005 SmallVector<SDNode*, 4> SetCCs; 9006 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 9007 ISD::SIGN_EXTEND, SetCCs, TLI); 9008 if (DoXform) { 9009 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT, 9010 LN00->getChain(), LN00->getBasePtr(), 9011 LN00->getMemoryVT(), 9012 LN00->getMemOperand()); 9013 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 9014 Mask = Mask.sext(VT.getSizeInBits()); 9015 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 9016 ExtLoad, DAG.getConstant(Mask, DL, VT)); 9017 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND); 9018 bool NoReplaceTruncAnd = !N0.hasOneUse(); 9019 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 9020 CombineTo(N, And); 9021 // If N0 has multiple uses, change other uses as well. 9022 if (NoReplaceTruncAnd) { 9023 SDValue TruncAnd = 9024 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 9025 CombineTo(N0.getNode(), TruncAnd); 9026 } 9027 if (NoReplaceTrunc) { 9028 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 9029 } else { 9030 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 9031 LN00->getValueType(0), ExtLoad); 9032 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 9033 } 9034 return SDValue(N,0); // Return N so it doesn't get rechecked! 9035 } 9036 } 9037 } 9038 9039 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 9040 return V; 9041 9042 if (N0.getOpcode() == ISD::SETCC) { 9043 SDValue N00 = N0.getOperand(0); 9044 SDValue N01 = N0.getOperand(1); 9045 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 9046 EVT N00VT = N0.getOperand(0).getValueType(); 9047 9048 // sext(setcc) -> sext_in_reg(vsetcc) for vectors. 9049 // Only do this before legalize for now. 9050 if (VT.isVector() && !LegalOperations && 9051 TLI.getBooleanContents(N00VT) == 9052 TargetLowering::ZeroOrNegativeOneBooleanContent) { 9053 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 9054 // of the same size as the compared operands. Only optimize sext(setcc()) 9055 // if this is the case. 9056 EVT SVT = getSetCCResultType(N00VT); 9057 9058 // If we already have the desired type, don't change it. 9059 if (SVT != N0.getValueType()) { 9060 // We know that the # elements of the results is the same as the 9061 // # elements of the compare (and the # elements of the compare result 9062 // for that matter). Check to see that they are the same size. If so, 9063 // we know that the element size of the sext'd result matches the 9064 // element size of the compare operands. 9065 if (VT.getSizeInBits() == SVT.getSizeInBits()) 9066 return DAG.getSetCC(DL, VT, N00, N01, CC); 9067 9068 // If the desired elements are smaller or larger than the source 9069 // elements, we can use a matching integer vector type and then 9070 // truncate/sign extend. 9071 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 9072 if (SVT == MatchingVecType) { 9073 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 9074 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 9075 } 9076 } 9077 } 9078 9079 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 9080 // Here, T can be 1 or -1, depending on the type of the setcc and 9081 // getBooleanContents(). 9082 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 9083 9084 // To determine the "true" side of the select, we need to know the high bit 9085 // of the value returned by the setcc if it evaluates to true. 9086 // If the type of the setcc is i1, then the true case of the select is just 9087 // sext(i1 1), that is, -1. 9088 // If the type of the setcc is larger (say, i8) then the value of the high 9089 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 9090 // of the appropriate width. 9091 SDValue ExtTrueVal = (SetCCWidth == 1) 9092 ? DAG.getAllOnesConstant(DL, VT) 9093 : DAG.getBoolConstant(true, DL, VT, N00VT); 9094 SDValue Zero = DAG.getConstant(0, DL, VT); 9095 if (SDValue SCC = 9096 SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 9097 return SCC; 9098 9099 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { 9100 EVT SetCCVT = getSetCCResultType(N00VT); 9101 // Don't do this transform for i1 because there's a select transform 9102 // that would reverse it. 9103 // TODO: We should not do this transform at all without a target hook 9104 // because a sext is likely cheaper than a select? 9105 if (SetCCVT.getScalarSizeInBits() != 1 && 9106 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 9107 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 9108 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 9109 } 9110 } 9111 } 9112 9113 // fold (sext x) -> (zext x) if the sign bit is known zero. 9114 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 9115 DAG.SignBitIsZero(N0)) 9116 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 9117 9118 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 9119 return NewVSel; 9120 9121 // Eliminate this sign extend by doing a negation in the destination type: 9122 // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64) 9123 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() && 9124 isNullOrNullSplat(N0.getOperand(0)) && 9125 N0.getOperand(1).getOpcode() == ISD::ZERO_EXTEND && 9126 TLI.isOperationLegalOrCustom(ISD::SUB, VT)) { 9127 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT); 9128 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Zext); 9129 } 9130 // Eliminate this sign extend by doing a decrement in the destination type: 9131 // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1) 9132 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && 9133 isAllOnesOrAllOnesSplat(N0.getOperand(1)) && 9134 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 9135 TLI.isOperationLegalOrCustom(ISD::ADD, VT)) { 9136 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT); 9137 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT)); 9138 } 9139 9140 return SDValue(); 9141 } 9142 9143 // isTruncateOf - If N is a truncate of some other value, return true, record 9144 // the value being truncated in Op and which of Op's bits are zero/one in Known. 9145 // This function computes KnownBits to avoid a duplicated call to 9146 // computeKnownBits in the caller. 9147 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 9148 KnownBits &Known) { 9149 if (N->getOpcode() == ISD::TRUNCATE) { 9150 Op = N->getOperand(0); 9151 Known = DAG.computeKnownBits(Op); 9152 return true; 9153 } 9154 9155 if (N.getOpcode() != ISD::SETCC || 9156 N.getValueType().getScalarType() != MVT::i1 || 9157 cast<CondCodeSDNode>(N.getOperand(2))->get() != ISD::SETNE) 9158 return false; 9159 9160 SDValue Op0 = N->getOperand(0); 9161 SDValue Op1 = N->getOperand(1); 9162 assert(Op0.getValueType() == Op1.getValueType()); 9163 9164 if (isNullOrNullSplat(Op0)) 9165 Op = Op1; 9166 else if (isNullOrNullSplat(Op1)) 9167 Op = Op0; 9168 else 9169 return false; 9170 9171 Known = DAG.computeKnownBits(Op); 9172 9173 return (Known.Zero | 1).isAllOnesValue(); 9174 } 9175 9176 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 9177 SDValue N0 = N->getOperand(0); 9178 EVT VT = N->getValueType(0); 9179 9180 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 9181 return Res; 9182 9183 // fold (zext (zext x)) -> (zext x) 9184 // fold (zext (aext x)) -> (zext x) 9185 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 9186 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 9187 N0.getOperand(0)); 9188 9189 // fold (zext (truncate x)) -> (zext x) or 9190 // (zext (truncate x)) -> (truncate x) 9191 // This is valid when the truncated bits of x are already zero. 9192 SDValue Op; 9193 KnownBits Known; 9194 if (isTruncateOf(DAG, N0, Op, Known)) { 9195 APInt TruncatedBits = 9196 (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ? 9197 APInt(Op.getScalarValueSizeInBits(), 0) : 9198 APInt::getBitsSet(Op.getScalarValueSizeInBits(), 9199 N0.getScalarValueSizeInBits(), 9200 std::min(Op.getScalarValueSizeInBits(), 9201 VT.getScalarSizeInBits())); 9202 if (TruncatedBits.isSubsetOf(Known.Zero)) 9203 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 9204 } 9205 9206 // fold (zext (truncate x)) -> (and x, mask) 9207 if (N0.getOpcode() == ISD::TRUNCATE) { 9208 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 9209 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 9210 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 9211 SDNode *oye = N0.getOperand(0).getNode(); 9212 if (NarrowLoad.getNode() != N0.getNode()) { 9213 CombineTo(N0.getNode(), NarrowLoad); 9214 // CombineTo deleted the truncate, if needed, but not what's under it. 9215 AddToWorklist(oye); 9216 } 9217 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9218 } 9219 9220 EVT SrcVT = N0.getOperand(0).getValueType(); 9221 EVT MinVT = N0.getValueType(); 9222 9223 // Try to mask before the extension to avoid having to generate a larger mask, 9224 // possibly over several sub-vectors. 9225 if (SrcVT.bitsLT(VT) && VT.isVector()) { 9226 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 9227 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 9228 SDValue Op = N0.getOperand(0); 9229 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 9230 AddToWorklist(Op.getNode()); 9231 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 9232 // Transfer the debug info; the new node is equivalent to N0. 9233 DAG.transferDbgValues(N0, ZExtOrTrunc); 9234 return ZExtOrTrunc; 9235 } 9236 } 9237 9238 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 9239 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 9240 AddToWorklist(Op.getNode()); 9241 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType()); 9242 // We may safely transfer the debug info describing the truncate node over 9243 // to the equivalent and operation. 9244 DAG.transferDbgValues(N0, And); 9245 return And; 9246 } 9247 } 9248 9249 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 9250 // if either of the casts is not free. 9251 if (N0.getOpcode() == ISD::AND && 9252 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 9253 N0.getOperand(1).getOpcode() == ISD::Constant && 9254 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 9255 N0.getValueType()) || 9256 !TLI.isZExtFree(N0.getValueType(), VT))) { 9257 SDValue X = N0.getOperand(0).getOperand(0); 9258 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 9259 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 9260 Mask = Mask.zext(VT.getSizeInBits()); 9261 SDLoc DL(N); 9262 return DAG.getNode(ISD::AND, DL, VT, 9263 X, DAG.getConstant(Mask, DL, VT)); 9264 } 9265 9266 // Try to simplify (zext (load x)). 9267 if (SDValue foldedExt = 9268 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 9269 ISD::ZEXTLOAD, ISD::ZERO_EXTEND)) 9270 return foldedExt; 9271 9272 // fold (zext (load x)) to multiple smaller zextloads. 9273 // Only on illegal but splittable vectors. 9274 if (SDValue ExtLoad = CombineExtLoad(N)) 9275 return ExtLoad; 9276 9277 // fold (zext (and/or/xor (load x), cst)) -> 9278 // (and/or/xor (zextload x), (zext cst)) 9279 // Unless (and (load x) cst) will match as a zextload already and has 9280 // additional users. 9281 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 9282 N0.getOpcode() == ISD::XOR) && 9283 isa<LoadSDNode>(N0.getOperand(0)) && 9284 N0.getOperand(1).getOpcode() == ISD::Constant && 9285 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 9286 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 9287 EVT MemVT = LN00->getMemoryVT(); 9288 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) && 9289 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) { 9290 bool DoXform = true; 9291 SmallVector<SDNode*, 4> SetCCs; 9292 if (!N0.hasOneUse()) { 9293 if (N0.getOpcode() == ISD::AND) { 9294 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 9295 EVT LoadResultTy = AndC->getValueType(0); 9296 EVT ExtVT; 9297 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT)) 9298 DoXform = false; 9299 } 9300 } 9301 if (DoXform) 9302 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 9303 ISD::ZERO_EXTEND, SetCCs, TLI); 9304 if (DoXform) { 9305 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT, 9306 LN00->getChain(), LN00->getBasePtr(), 9307 LN00->getMemoryVT(), 9308 LN00->getMemOperand()); 9309 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 9310 Mask = Mask.zext(VT.getSizeInBits()); 9311 SDLoc DL(N); 9312 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 9313 ExtLoad, DAG.getConstant(Mask, DL, VT)); 9314 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 9315 bool NoReplaceTruncAnd = !N0.hasOneUse(); 9316 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 9317 CombineTo(N, And); 9318 // If N0 has multiple uses, change other uses as well. 9319 if (NoReplaceTruncAnd) { 9320 SDValue TruncAnd = 9321 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 9322 CombineTo(N0.getNode(), TruncAnd); 9323 } 9324 if (NoReplaceTrunc) { 9325 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 9326 } else { 9327 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 9328 LN00->getValueType(0), ExtLoad); 9329 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 9330 } 9331 return SDValue(N,0); // Return N so it doesn't get rechecked! 9332 } 9333 } 9334 } 9335 9336 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 9337 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 9338 if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N)) 9339 return ZExtLoad; 9340 9341 // Try to simplify (zext (zextload x)). 9342 if (SDValue foldedExt = tryToFoldExtOfExtload( 9343 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD)) 9344 return foldedExt; 9345 9346 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 9347 return V; 9348 9349 if (N0.getOpcode() == ISD::SETCC) { 9350 // Only do this before legalize for now. 9351 if (!LegalOperations && VT.isVector() && 9352 N0.getValueType().getVectorElementType() == MVT::i1) { 9353 EVT N00VT = N0.getOperand(0).getValueType(); 9354 if (getSetCCResultType(N00VT) == N0.getValueType()) 9355 return SDValue(); 9356 9357 // We know that the # elements of the results is the same as the # 9358 // elements of the compare (and the # elements of the compare result for 9359 // that matter). Check to see that they are the same size. If so, we know 9360 // that the element size of the sext'd result matches the element size of 9361 // the compare operands. 9362 SDLoc DL(N); 9363 SDValue VecOnes = DAG.getConstant(1, DL, VT); 9364 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 9365 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors. 9366 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 9367 N0.getOperand(1), N0.getOperand(2)); 9368 return DAG.getNode(ISD::AND, DL, VT, VSetCC, VecOnes); 9369 } 9370 9371 // If the desired elements are smaller or larger than the source 9372 // elements we can use a matching integer vector type and then 9373 // truncate/sign extend. 9374 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 9375 SDValue VsetCC = 9376 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 9377 N0.getOperand(1), N0.getOperand(2)); 9378 return DAG.getNode(ISD::AND, DL, VT, DAG.getSExtOrTrunc(VsetCC, DL, VT), 9379 VecOnes); 9380 } 9381 9382 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 9383 SDLoc DL(N); 9384 if (SDValue SCC = SimplifySelectCC( 9385 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 9386 DAG.getConstant(0, DL, VT), 9387 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 9388 return SCC; 9389 } 9390 9391 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 9392 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 9393 isa<ConstantSDNode>(N0.getOperand(1)) && 9394 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 9395 N0.hasOneUse()) { 9396 SDValue ShAmt = N0.getOperand(1); 9397 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue(); 9398 if (N0.getOpcode() == ISD::SHL) { 9399 SDValue InnerZExt = N0.getOperand(0); 9400 // If the original shl may be shifting out bits, do not perform this 9401 // transformation. 9402 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 9403 InnerZExt.getOperand(0).getValueSizeInBits(); 9404 if (ShAmtVal > KnownZeroBits) 9405 return SDValue(); 9406 } 9407 9408 SDLoc DL(N); 9409 9410 // Ensure that the shift amount is wide enough for the shifted value. 9411 if (VT.getSizeInBits() >= 256) 9412 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 9413 9414 return DAG.getNode(N0.getOpcode(), DL, VT, 9415 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 9416 ShAmt); 9417 } 9418 9419 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 9420 return NewVSel; 9421 9422 return SDValue(); 9423 } 9424 9425 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 9426 SDValue N0 = N->getOperand(0); 9427 EVT VT = N->getValueType(0); 9428 9429 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 9430 return Res; 9431 9432 // fold (aext (aext x)) -> (aext x) 9433 // fold (aext (zext x)) -> (zext x) 9434 // fold (aext (sext x)) -> (sext x) 9435 if (N0.getOpcode() == ISD::ANY_EXTEND || 9436 N0.getOpcode() == ISD::ZERO_EXTEND || 9437 N0.getOpcode() == ISD::SIGN_EXTEND) 9438 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 9439 9440 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 9441 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 9442 if (N0.getOpcode() == ISD::TRUNCATE) { 9443 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 9444 SDNode *oye = N0.getOperand(0).getNode(); 9445 if (NarrowLoad.getNode() != N0.getNode()) { 9446 CombineTo(N0.getNode(), NarrowLoad); 9447 // CombineTo deleted the truncate, if needed, but not what's under it. 9448 AddToWorklist(oye); 9449 } 9450 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9451 } 9452 } 9453 9454 // fold (aext (truncate x)) 9455 if (N0.getOpcode() == ISD::TRUNCATE) 9456 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 9457 9458 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 9459 // if the trunc is not free. 9460 if (N0.getOpcode() == ISD::AND && 9461 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 9462 N0.getOperand(1).getOpcode() == ISD::Constant && 9463 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 9464 N0.getValueType())) { 9465 SDLoc DL(N); 9466 SDValue X = N0.getOperand(0).getOperand(0); 9467 X = DAG.getAnyExtOrTrunc(X, DL, VT); 9468 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue(); 9469 Mask = Mask.zext(VT.getSizeInBits()); 9470 return DAG.getNode(ISD::AND, DL, VT, 9471 X, DAG.getConstant(Mask, DL, VT)); 9472 } 9473 9474 // fold (aext (load x)) -> (aext (truncate (extload x))) 9475 // None of the supported targets knows how to perform load and any_ext 9476 // on vectors in one instruction. We only perform this transformation on 9477 // scalars. 9478 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() && 9479 ISD::isUNINDEXEDLoad(N0.getNode()) && 9480 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 9481 bool DoXform = true; 9482 SmallVector<SDNode*, 4> SetCCs; 9483 if (!N0.hasOneUse()) 9484 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, 9485 TLI); 9486 if (DoXform) { 9487 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9488 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 9489 LN0->getChain(), 9490 LN0->getBasePtr(), N0.getValueType(), 9491 LN0->getMemOperand()); 9492 ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND); 9493 // If the load value is used only by N, replace it via CombineTo N. 9494 bool NoReplaceTrunc = N0.hasOneUse(); 9495 CombineTo(N, ExtLoad); 9496 if (NoReplaceTrunc) { 9497 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 9498 recursivelyDeleteUnusedNodes(LN0); 9499 } else { 9500 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), 9501 N0.getValueType(), ExtLoad); 9502 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 9503 } 9504 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9505 } 9506 } 9507 9508 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 9509 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 9510 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 9511 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) && 9512 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 9513 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9514 ISD::LoadExtType ExtType = LN0->getExtensionType(); 9515 EVT MemVT = LN0->getMemoryVT(); 9516 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 9517 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 9518 VT, LN0->getChain(), LN0->getBasePtr(), 9519 MemVT, LN0->getMemOperand()); 9520 CombineTo(N, ExtLoad); 9521 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 9522 recursivelyDeleteUnusedNodes(LN0); 9523 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9524 } 9525 } 9526 9527 if (N0.getOpcode() == ISD::SETCC) { 9528 // For vectors: 9529 // aext(setcc) -> vsetcc 9530 // aext(setcc) -> truncate(vsetcc) 9531 // aext(setcc) -> aext(vsetcc) 9532 // Only do this before legalize for now. 9533 if (VT.isVector() && !LegalOperations) { 9534 EVT N00VT = N0.getOperand(0).getValueType(); 9535 if (getSetCCResultType(N00VT) == N0.getValueType()) 9536 return SDValue(); 9537 9538 // We know that the # elements of the results is the same as the 9539 // # elements of the compare (and the # elements of the compare result 9540 // for that matter). Check to see that they are the same size. If so, 9541 // we know that the element size of the sext'd result matches the 9542 // element size of the compare operands. 9543 if (VT.getSizeInBits() == N00VT.getSizeInBits()) 9544 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 9545 N0.getOperand(1), 9546 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 9547 9548 // If the desired elements are smaller or larger than the source 9549 // elements we can use a matching integer vector type and then 9550 // truncate/any extend 9551 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 9552 SDValue VsetCC = 9553 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 9554 N0.getOperand(1), 9555 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 9556 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 9557 } 9558 9559 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 9560 SDLoc DL(N); 9561 if (SDValue SCC = SimplifySelectCC( 9562 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 9563 DAG.getConstant(0, DL, VT), 9564 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 9565 return SCC; 9566 } 9567 9568 return SDValue(); 9569 } 9570 9571 SDValue DAGCombiner::visitAssertExt(SDNode *N) { 9572 unsigned Opcode = N->getOpcode(); 9573 SDValue N0 = N->getOperand(0); 9574 SDValue N1 = N->getOperand(1); 9575 EVT AssertVT = cast<VTSDNode>(N1)->getVT(); 9576 9577 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) 9578 if (N0.getOpcode() == Opcode && 9579 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 9580 return N0; 9581 9582 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 9583 N0.getOperand(0).getOpcode() == Opcode) { 9584 // We have an assert, truncate, assert sandwich. Make one stronger assert 9585 // by asserting on the smallest asserted type to the larger source type. 9586 // This eliminates the later assert: 9587 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN 9588 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN 9589 SDValue BigA = N0.getOperand(0); 9590 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 9591 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 9592 "Asserting zero/sign-extended bits to a type larger than the " 9593 "truncated destination does not provide information"); 9594 9595 SDLoc DL(N); 9596 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; 9597 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); 9598 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 9599 BigA.getOperand(0), MinAssertVTVal); 9600 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 9601 } 9602 9603 // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller 9604 // than X. Just move the AssertZext in front of the truncate and drop the 9605 // AssertSExt. 9606 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 9607 N0.getOperand(0).getOpcode() == ISD::AssertSext && 9608 Opcode == ISD::AssertZext) { 9609 SDValue BigA = N0.getOperand(0); 9610 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 9611 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 9612 "Asserting zero/sign-extended bits to a type larger than the " 9613 "truncated destination does not provide information"); 9614 9615 if (AssertVT.bitsLT(BigA_AssertVT)) { 9616 SDLoc DL(N); 9617 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 9618 BigA.getOperand(0), N1); 9619 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 9620 } 9621 } 9622 9623 return SDValue(); 9624 } 9625 9626 /// If the result of a wider load is shifted to right of N bits and then 9627 /// truncated to a narrower type and where N is a multiple of number of bits of 9628 /// the narrower type, transform it to a narrower load from address + N / num of 9629 /// bits of new type. Also narrow the load if the result is masked with an AND 9630 /// to effectively produce a smaller type. If the result is to be extended, also 9631 /// fold the extension to form a extending load. 9632 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 9633 unsigned Opc = N->getOpcode(); 9634 9635 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 9636 SDValue N0 = N->getOperand(0); 9637 EVT VT = N->getValueType(0); 9638 EVT ExtVT = VT; 9639 9640 // This transformation isn't valid for vector loads. 9641 if (VT.isVector()) 9642 return SDValue(); 9643 9644 unsigned ShAmt = 0; 9645 bool HasShiftedOffset = false; 9646 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 9647 // extended to VT. 9648 if (Opc == ISD::SIGN_EXTEND_INREG) { 9649 ExtType = ISD::SEXTLOAD; 9650 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 9651 } else if (Opc == ISD::SRL) { 9652 // Another special-case: SRL is basically zero-extending a narrower value, 9653 // or it maybe shifting a higher subword, half or byte into the lowest 9654 // bits. 9655 ExtType = ISD::ZEXTLOAD; 9656 N0 = SDValue(N, 0); 9657 9658 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); 9659 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 9660 if (!N01 || !LN0) 9661 return SDValue(); 9662 9663 uint64_t ShiftAmt = N01->getZExtValue(); 9664 uint64_t MemoryWidth = LN0->getMemoryVT().getSizeInBits(); 9665 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) 9666 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); 9667 else 9668 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 9669 VT.getSizeInBits() - ShiftAmt); 9670 } else if (Opc == ISD::AND) { 9671 // An AND with a constant mask is the same as a truncate + zero-extend. 9672 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9673 if (!AndC) 9674 return SDValue(); 9675 9676 const APInt &Mask = AndC->getAPIntValue(); 9677 unsigned ActiveBits = 0; 9678 if (Mask.isMask()) { 9679 ActiveBits = Mask.countTrailingOnes(); 9680 } else if (Mask.isShiftedMask()) { 9681 ShAmt = Mask.countTrailingZeros(); 9682 APInt ShiftedMask = Mask.lshr(ShAmt); 9683 ActiveBits = ShiftedMask.countTrailingOnes(); 9684 HasShiftedOffset = true; 9685 } else 9686 return SDValue(); 9687 9688 ExtType = ISD::ZEXTLOAD; 9689 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 9690 } 9691 9692 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 9693 SDValue SRL = N0; 9694 if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) { 9695 ShAmt = ConstShift->getZExtValue(); 9696 unsigned EVTBits = ExtVT.getSizeInBits(); 9697 // Is the shift amount a multiple of size of VT? 9698 if ((ShAmt & (EVTBits-1)) == 0) { 9699 N0 = N0.getOperand(0); 9700 // Is the load width a multiple of size of VT? 9701 if ((N0.getValueSizeInBits() & (EVTBits-1)) != 0) 9702 return SDValue(); 9703 } 9704 9705 // At this point, we must have a load or else we can't do the transform. 9706 if (!isa<LoadSDNode>(N0)) return SDValue(); 9707 9708 auto *LN0 = cast<LoadSDNode>(N0); 9709 9710 // Because a SRL must be assumed to *need* to zero-extend the high bits 9711 // (as opposed to anyext the high bits), we can't combine the zextload 9712 // lowering of SRL and an sextload. 9713 if (LN0->getExtensionType() == ISD::SEXTLOAD) 9714 return SDValue(); 9715 9716 // If the shift amount is larger than the input type then we're not 9717 // accessing any of the loaded bytes. If the load was a zextload/extload 9718 // then the result of the shift+trunc is zero/undef (handled elsewhere). 9719 if (ShAmt >= LN0->getMemoryVT().getSizeInBits()) 9720 return SDValue(); 9721 9722 // If the SRL is only used by a masking AND, we may be able to adjust 9723 // the ExtVT to make the AND redundant. 9724 SDNode *Mask = *(SRL->use_begin()); 9725 if (Mask->getOpcode() == ISD::AND && 9726 isa<ConstantSDNode>(Mask->getOperand(1))) { 9727 const APInt &ShiftMask = 9728 cast<ConstantSDNode>(Mask->getOperand(1))->getAPIntValue(); 9729 if (ShiftMask.isMask()) { 9730 EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(), 9731 ShiftMask.countTrailingOnes()); 9732 // If the mask is smaller, recompute the type. 9733 if ((ExtVT.getSizeInBits() > MaskedVT.getSizeInBits()) && 9734 TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT)) 9735 ExtVT = MaskedVT; 9736 } 9737 } 9738 } 9739 } 9740 9741 // If the load is shifted left (and the result isn't shifted back right), 9742 // we can fold the truncate through the shift. 9743 unsigned ShLeftAmt = 0; 9744 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 9745 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 9746 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 9747 ShLeftAmt = N01->getZExtValue(); 9748 N0 = N0.getOperand(0); 9749 } 9750 } 9751 9752 // If we haven't found a load, we can't narrow it. 9753 if (!isa<LoadSDNode>(N0)) 9754 return SDValue(); 9755 9756 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9757 if (!isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt)) 9758 return SDValue(); 9759 9760 auto AdjustBigEndianShift = [&](unsigned ShAmt) { 9761 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits(); 9762 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits(); 9763 return LVTStoreBits - EVTStoreBits - ShAmt; 9764 }; 9765 9766 // For big endian targets, we need to adjust the offset to the pointer to 9767 // load the correct bytes. 9768 if (DAG.getDataLayout().isBigEndian()) 9769 ShAmt = AdjustBigEndianShift(ShAmt); 9770 9771 EVT PtrType = N0.getOperand(1).getValueType(); 9772 uint64_t PtrOff = ShAmt / 8; 9773 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff); 9774 SDLoc DL(LN0); 9775 // The original load itself didn't wrap, so an offset within it doesn't. 9776 SDNodeFlags Flags; 9777 Flags.setNoUnsignedWrap(true); 9778 SDValue NewPtr = DAG.getNode(ISD::ADD, DL, 9779 PtrType, LN0->getBasePtr(), 9780 DAG.getConstant(PtrOff, DL, PtrType), 9781 Flags); 9782 AddToWorklist(NewPtr.getNode()); 9783 9784 SDValue Load; 9785 if (ExtType == ISD::NON_EXTLOAD) 9786 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr, 9787 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 9788 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 9789 else 9790 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(), NewPtr, 9791 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 9792 NewAlign, LN0->getMemOperand()->getFlags(), 9793 LN0->getAAInfo()); 9794 9795 // Replace the old load's chain with the new load's chain. 9796 WorklistRemover DeadNodes(*this); 9797 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 9798 9799 // Shift the result left, if we've swallowed a left shift. 9800 SDValue Result = Load; 9801 if (ShLeftAmt != 0) { 9802 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 9803 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt)) 9804 ShImmTy = VT; 9805 // If the shift amount is as large as the result size (but, presumably, 9806 // no larger than the source) then the useful bits of the result are 9807 // zero; we can't simply return the shortened shift, because the result 9808 // of that operation is undefined. 9809 SDLoc DL(N0); 9810 if (ShLeftAmt >= VT.getSizeInBits()) 9811 Result = DAG.getConstant(0, DL, VT); 9812 else 9813 Result = DAG.getNode(ISD::SHL, DL, VT, 9814 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 9815 } 9816 9817 if (HasShiftedOffset) { 9818 // Recalculate the shift amount after it has been altered to calculate 9819 // the offset. 9820 if (DAG.getDataLayout().isBigEndian()) 9821 ShAmt = AdjustBigEndianShift(ShAmt); 9822 9823 // We're using a shifted mask, so the load now has an offset. This means 9824 // that data has been loaded into the lower bytes than it would have been 9825 // before, so we need to shl the loaded data into the correct position in the 9826 // register. 9827 SDValue ShiftC = DAG.getConstant(ShAmt, DL, VT); 9828 Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC); 9829 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 9830 } 9831 9832 // Return the new loaded value. 9833 return Result; 9834 } 9835 9836 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 9837 SDValue N0 = N->getOperand(0); 9838 SDValue N1 = N->getOperand(1); 9839 EVT VT = N->getValueType(0); 9840 EVT EVT = cast<VTSDNode>(N1)->getVT(); 9841 unsigned VTBits = VT.getScalarSizeInBits(); 9842 unsigned EVTBits = EVT.getScalarSizeInBits(); 9843 9844 if (N0.isUndef()) 9845 return DAG.getUNDEF(VT); 9846 9847 // fold (sext_in_reg c1) -> c1 9848 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9849 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 9850 9851 // If the input is already sign extended, just drop the extension. 9852 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1) 9853 return N0; 9854 9855 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 9856 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 9857 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 9858 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 9859 N0.getOperand(0), N1); 9860 9861 // fold (sext_in_reg (sext x)) -> (sext x) 9862 // fold (sext_in_reg (aext x)) -> (sext x) 9863 // if x is small enough or if we know that x has more than 1 sign bit and the 9864 // sign_extend_inreg is extending from one of them. 9865 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 9866 SDValue N00 = N0.getOperand(0); 9867 unsigned N00Bits = N00.getScalarValueSizeInBits(); 9868 if ((N00Bits <= EVTBits || 9869 (N00Bits - DAG.ComputeNumSignBits(N00)) < EVTBits) && 9870 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 9871 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00); 9872 } 9873 9874 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x) 9875 if ((N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 9876 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 9877 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) && 9878 N0.getOperand(0).getScalarValueSizeInBits() == EVTBits) { 9879 if (!LegalOperations || 9880 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)) 9881 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT, 9882 N0.getOperand(0)); 9883 } 9884 9885 // fold (sext_in_reg (zext x)) -> (sext x) 9886 // iff we are extending the source sign bit. 9887 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 9888 SDValue N00 = N0.getOperand(0); 9889 if (N00.getScalarValueSizeInBits() == EVTBits && 9890 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 9891 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 9892 } 9893 9894 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 9895 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, EVTBits - 1))) 9896 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT.getScalarType()); 9897 9898 // fold operands of sext_in_reg based on knowledge that the top bits are not 9899 // demanded. 9900 if (SimplifyDemandedBits(SDValue(N, 0))) 9901 return SDValue(N, 0); 9902 9903 // fold (sext_in_reg (load x)) -> (smaller sextload x) 9904 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 9905 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 9906 return NarrowLoad; 9907 9908 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 9909 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 9910 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 9911 if (N0.getOpcode() == ISD::SRL) { 9912 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 9913 if (ShAmt->getZExtValue()+EVTBits <= VTBits) { 9914 // We can turn this into an SRA iff the input to the SRL is already sign 9915 // extended enough. 9916 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 9917 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits) 9918 return DAG.getNode(ISD::SRA, SDLoc(N), VT, 9919 N0.getOperand(0), N0.getOperand(1)); 9920 } 9921 } 9922 9923 // fold (sext_inreg (extload x)) -> (sextload x) 9924 // If sextload is not supported by target, we can only do the combine when 9925 // load has one use. Doing otherwise can block folding the extload with other 9926 // extends that the target does support. 9927 if (ISD::isEXTLoad(N0.getNode()) && 9928 ISD::isUNINDEXEDLoad(N0.getNode()) && 9929 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 9930 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile() && 9931 N0.hasOneUse()) || 9932 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 9933 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9934 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 9935 LN0->getChain(), 9936 LN0->getBasePtr(), EVT, 9937 LN0->getMemOperand()); 9938 CombineTo(N, ExtLoad); 9939 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 9940 AddToWorklist(ExtLoad.getNode()); 9941 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9942 } 9943 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 9944 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 9945 N0.hasOneUse() && 9946 EVT == cast<LoadSDNode>(N0)->getMemoryVT() && 9947 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 9948 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) { 9949 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9950 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 9951 LN0->getChain(), 9952 LN0->getBasePtr(), EVT, 9953 LN0->getMemOperand()); 9954 CombineTo(N, ExtLoad); 9955 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 9956 return SDValue(N, 0); // Return N so it doesn't get rechecked! 9957 } 9958 9959 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 9960 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) { 9961 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 9962 N0.getOperand(1), false)) 9963 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 9964 BSwap, N1); 9965 } 9966 9967 return SDValue(); 9968 } 9969 9970 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) { 9971 SDValue N0 = N->getOperand(0); 9972 EVT VT = N->getValueType(0); 9973 9974 if (N0.isUndef()) 9975 return DAG.getUNDEF(VT); 9976 9977 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 9978 return Res; 9979 9980 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 9981 return SDValue(N, 0); 9982 9983 return SDValue(); 9984 } 9985 9986 SDValue DAGCombiner::visitZERO_EXTEND_VECTOR_INREG(SDNode *N) { 9987 SDValue N0 = N->getOperand(0); 9988 EVT VT = N->getValueType(0); 9989 9990 if (N0.isUndef()) 9991 return DAG.getUNDEF(VT); 9992 9993 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 9994 return Res; 9995 9996 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 9997 return SDValue(N, 0); 9998 9999 return SDValue(); 10000 } 10001 10002 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 10003 SDValue N0 = N->getOperand(0); 10004 EVT VT = N->getValueType(0); 10005 EVT SrcVT = N0.getValueType(); 10006 bool isLE = DAG.getDataLayout().isLittleEndian(); 10007 10008 // noop truncate 10009 if (SrcVT == VT) 10010 return N0; 10011 10012 // fold (truncate (truncate x)) -> (truncate x) 10013 if (N0.getOpcode() == ISD::TRUNCATE) 10014 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 10015 10016 // fold (truncate c1) -> c1 10017 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 10018 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 10019 if (C.getNode() != N) 10020 return C; 10021 } 10022 10023 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 10024 if (N0.getOpcode() == ISD::ZERO_EXTEND || 10025 N0.getOpcode() == ISD::SIGN_EXTEND || 10026 N0.getOpcode() == ISD::ANY_EXTEND) { 10027 // if the source is smaller than the dest, we still need an extend. 10028 if (N0.getOperand(0).getValueType().bitsLT(VT)) 10029 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 10030 // if the source is larger than the dest, than we just need the truncate. 10031 if (N0.getOperand(0).getValueType().bitsGT(VT)) 10032 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 10033 // if the source and dest are the same type, we can drop both the extend 10034 // and the truncate. 10035 return N0.getOperand(0); 10036 } 10037 10038 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 10039 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 10040 return SDValue(); 10041 10042 // Fold extract-and-trunc into a narrow extract. For example: 10043 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 10044 // i32 y = TRUNCATE(i64 x) 10045 // -- becomes -- 10046 // v16i8 b = BITCAST (v2i64 val) 10047 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 10048 // 10049 // Note: We only run this optimization after type legalization (which often 10050 // creates this pattern) and before operation legalization after which 10051 // we need to be more careful about the vector instructions that we generate. 10052 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 10053 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 10054 EVT VecTy = N0.getOperand(0).getValueType(); 10055 EVT ExTy = N0.getValueType(); 10056 EVT TrTy = N->getValueType(0); 10057 10058 unsigned NumElem = VecTy.getVectorNumElements(); 10059 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 10060 10061 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem); 10062 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 10063 10064 SDValue EltNo = N0->getOperand(1); 10065 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 10066 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 10067 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 10068 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 10069 10070 SDLoc DL(N); 10071 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 10072 DAG.getBitcast(NVT, N0.getOperand(0)), 10073 DAG.getConstant(Index, DL, IndexTy)); 10074 } 10075 } 10076 10077 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 10078 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 10079 EVT SrcVT = N0.getValueType(); 10080 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 10081 TLI.isTruncateFree(SrcVT, VT)) { 10082 SDLoc SL(N0); 10083 SDValue Cond = N0.getOperand(0); 10084 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 10085 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 10086 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 10087 } 10088 } 10089 10090 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 10091 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 10092 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::SHL, VT)) && 10093 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 10094 SDValue Amt = N0.getOperand(1); 10095 KnownBits Known = DAG.computeKnownBits(Amt); 10096 unsigned Size = VT.getScalarSizeInBits(); 10097 if (Known.getBitWidth() - Known.countMinLeadingZeros() <= Log2_32(Size)) { 10098 SDLoc SL(N); 10099 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 10100 10101 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 10102 if (AmtVT != Amt.getValueType()) { 10103 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 10104 AddToWorklist(Amt.getNode()); 10105 } 10106 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 10107 } 10108 } 10109 10110 // Attempt to pre-truncate BUILD_VECTOR sources. 10111 if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations && 10112 TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType())) { 10113 SDLoc DL(N); 10114 EVT SVT = VT.getScalarType(); 10115 SmallVector<SDValue, 8> TruncOps; 10116 for (const SDValue &Op : N0->op_values()) { 10117 SDValue TruncOp = DAG.getNode(ISD::TRUNCATE, DL, SVT, Op); 10118 TruncOps.push_back(TruncOp); 10119 } 10120 return DAG.getBuildVector(VT, DL, TruncOps); 10121 } 10122 10123 // Fold a series of buildvector, bitcast, and truncate if possible. 10124 // For example fold 10125 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 10126 // (2xi32 (buildvector x, y)). 10127 if (Level == AfterLegalizeVectorOps && VT.isVector() && 10128 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 10129 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 10130 N0.getOperand(0).hasOneUse()) { 10131 SDValue BuildVect = N0.getOperand(0); 10132 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 10133 EVT TruncVecEltTy = VT.getVectorElementType(); 10134 10135 // Check that the element types match. 10136 if (BuildVectEltTy == TruncVecEltTy) { 10137 // Now we only need to compute the offset of the truncated elements. 10138 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 10139 unsigned TruncVecNumElts = VT.getVectorNumElements(); 10140 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 10141 10142 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 10143 "Invalid number of elements"); 10144 10145 SmallVector<SDValue, 8> Opnds; 10146 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 10147 Opnds.push_back(BuildVect.getOperand(i)); 10148 10149 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 10150 } 10151 } 10152 10153 // See if we can simplify the input to this truncate through knowledge that 10154 // only the low bits are being used. 10155 // For example "trunc (or (shl x, 8), y)" // -> trunc y 10156 // Currently we only perform this optimization on scalars because vectors 10157 // may have different active low bits. 10158 if (!VT.isVector()) { 10159 APInt Mask = 10160 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); 10161 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) 10162 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 10163 } 10164 10165 // fold (truncate (load x)) -> (smaller load x) 10166 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 10167 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 10168 if (SDValue Reduced = ReduceLoadWidth(N)) 10169 return Reduced; 10170 10171 // Handle the case where the load remains an extending load even 10172 // after truncation. 10173 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 10174 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10175 if (!LN0->isVolatile() && 10176 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) { 10177 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 10178 VT, LN0->getChain(), LN0->getBasePtr(), 10179 LN0->getMemoryVT(), 10180 LN0->getMemOperand()); 10181 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 10182 return NewLoad; 10183 } 10184 } 10185 } 10186 10187 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 10188 // where ... are all 'undef'. 10189 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 10190 SmallVector<EVT, 8> VTs; 10191 SDValue V; 10192 unsigned Idx = 0; 10193 unsigned NumDefs = 0; 10194 10195 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 10196 SDValue X = N0.getOperand(i); 10197 if (!X.isUndef()) { 10198 V = X; 10199 Idx = i; 10200 NumDefs++; 10201 } 10202 // Stop if more than one members are non-undef. 10203 if (NumDefs > 1) 10204 break; 10205 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 10206 VT.getVectorElementType(), 10207 X.getValueType().getVectorNumElements())); 10208 } 10209 10210 if (NumDefs == 0) 10211 return DAG.getUNDEF(VT); 10212 10213 if (NumDefs == 1) { 10214 assert(V.getNode() && "The single defined operand is empty!"); 10215 SmallVector<SDValue, 8> Opnds; 10216 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 10217 if (i != Idx) { 10218 Opnds.push_back(DAG.getUNDEF(VTs[i])); 10219 continue; 10220 } 10221 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 10222 AddToWorklist(NV.getNode()); 10223 Opnds.push_back(NV); 10224 } 10225 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 10226 } 10227 } 10228 10229 // Fold truncate of a bitcast of a vector to an extract of the low vector 10230 // element. 10231 // 10232 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx 10233 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 10234 SDValue VecSrc = N0.getOperand(0); 10235 EVT SrcVT = VecSrc.getValueType(); 10236 if (SrcVT.isVector() && SrcVT.getScalarType() == VT && 10237 (!LegalOperations || 10238 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, SrcVT))) { 10239 SDLoc SL(N); 10240 10241 EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout()); 10242 unsigned Idx = isLE ? 0 : SrcVT.getVectorNumElements() - 1; 10243 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, 10244 VecSrc, DAG.getConstant(Idx, SL, IdxVT)); 10245 } 10246 } 10247 10248 // Simplify the operands using demanded-bits information. 10249 if (!VT.isVector() && 10250 SimplifyDemandedBits(SDValue(N, 0))) 10251 return SDValue(N, 0); 10252 10253 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 10254 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 10255 // When the adde's carry is not used. 10256 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 10257 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 10258 (!LegalOperations || TLI.isOperationLegal(N0.getOpcode(), VT))) { 10259 SDLoc SL(N); 10260 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 10261 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 10262 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 10263 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 10264 } 10265 10266 // fold (truncate (extract_subvector(ext x))) -> 10267 // (extract_subvector x) 10268 // TODO: This can be generalized to cover cases where the truncate and extract 10269 // do not fully cancel each other out. 10270 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 10271 SDValue N00 = N0.getOperand(0); 10272 if (N00.getOpcode() == ISD::SIGN_EXTEND || 10273 N00.getOpcode() == ISD::ZERO_EXTEND || 10274 N00.getOpcode() == ISD::ANY_EXTEND) { 10275 if (N00.getOperand(0)->getValueType(0).getVectorElementType() == 10276 VT.getVectorElementType()) 10277 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT, 10278 N00.getOperand(0), N0.getOperand(1)); 10279 } 10280 } 10281 10282 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 10283 return NewVSel; 10284 10285 // Narrow a suitable binary operation with a non-opaque constant operand by 10286 // moving it ahead of the truncate. This is limited to pre-legalization 10287 // because targets may prefer a wider type during later combines and invert 10288 // this transform. 10289 switch (N0.getOpcode()) { 10290 case ISD::ADD: 10291 case ISD::SUB: 10292 case ISD::MUL: 10293 case ISD::AND: 10294 case ISD::OR: 10295 case ISD::XOR: 10296 if (!LegalOperations && N0.hasOneUse() && 10297 (isConstantOrConstantVector(N0.getOperand(0), true) || 10298 isConstantOrConstantVector(N0.getOperand(1), true))) { 10299 // TODO: We already restricted this to pre-legalization, but for vectors 10300 // we are extra cautious to not create an unsupported operation. 10301 // Target-specific changes are likely needed to avoid regressions here. 10302 if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) { 10303 SDLoc DL(N); 10304 SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0)); 10305 SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1)); 10306 return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR); 10307 } 10308 } 10309 } 10310 10311 return SDValue(); 10312 } 10313 10314 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 10315 SDValue Elt = N->getOperand(i); 10316 if (Elt.getOpcode() != ISD::MERGE_VALUES) 10317 return Elt.getNode(); 10318 return Elt.getOperand(Elt.getResNo()).getNode(); 10319 } 10320 10321 /// build_pair (load, load) -> load 10322 /// if load locations are consecutive. 10323 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 10324 assert(N->getOpcode() == ISD::BUILD_PAIR); 10325 10326 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 10327 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 10328 10329 // A BUILD_PAIR is always having the least significant part in elt 0 and the 10330 // most significant part in elt 1. So when combining into one large load, we 10331 // need to consider the endianness. 10332 if (DAG.getDataLayout().isBigEndian()) 10333 std::swap(LD1, LD2); 10334 10335 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() || 10336 LD1->getAddressSpace() != LD2->getAddressSpace()) 10337 return SDValue(); 10338 EVT LD1VT = LD1->getValueType(0); 10339 unsigned LD1Bytes = LD1VT.getStoreSize(); 10340 if (ISD::isNON_EXTLoad(LD2) && LD2->hasOneUse() && 10341 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1)) { 10342 unsigned Align = LD1->getAlignment(); 10343 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 10344 VT.getTypeForEVT(*DAG.getContext())); 10345 10346 if (NewAlign <= Align && 10347 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) 10348 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 10349 LD1->getPointerInfo(), Align); 10350 } 10351 10352 return SDValue(); 10353 } 10354 10355 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 10356 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 10357 // and Lo parts; on big-endian machines it doesn't. 10358 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 10359 } 10360 10361 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 10362 const TargetLowering &TLI) { 10363 // If this is not a bitcast to an FP type or if the target doesn't have 10364 // IEEE754-compliant FP logic, we're done. 10365 EVT VT = N->getValueType(0); 10366 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 10367 return SDValue(); 10368 10369 // TODO: Handle cases where the integer constant is a different scalar 10370 // bitwidth to the FP. 10371 SDValue N0 = N->getOperand(0); 10372 EVT SourceVT = N0.getValueType(); 10373 if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits()) 10374 return SDValue(); 10375 10376 unsigned FPOpcode; 10377 APInt SignMask; 10378 switch (N0.getOpcode()) { 10379 case ISD::AND: 10380 FPOpcode = ISD::FABS; 10381 SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits()); 10382 break; 10383 case ISD::XOR: 10384 FPOpcode = ISD::FNEG; 10385 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits()); 10386 break; 10387 case ISD::OR: 10388 FPOpcode = ISD::FABS; 10389 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits()); 10390 break; 10391 default: 10392 return SDValue(); 10393 } 10394 10395 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 10396 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 10397 // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) -> 10398 // fneg (fabs X) 10399 SDValue LogicOp0 = N0.getOperand(0); 10400 ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true); 10401 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 10402 LogicOp0.getOpcode() == ISD::BITCAST && 10403 LogicOp0.getOperand(0).getValueType() == VT) { 10404 SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0.getOperand(0)); 10405 NumFPLogicOpsConv++; 10406 if (N0.getOpcode() == ISD::OR) 10407 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp); 10408 return FPOp; 10409 } 10410 10411 return SDValue(); 10412 } 10413 10414 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 10415 SDValue N0 = N->getOperand(0); 10416 EVT VT = N->getValueType(0); 10417 10418 if (N0.isUndef()) 10419 return DAG.getUNDEF(VT); 10420 10421 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 10422 // Only do this before legalize types, unless both types are integer and the 10423 // scalar type is legal. Only do this before legalize ops, since the target 10424 // maybe depending on the bitcast. 10425 // First check to see if this is all constant. 10426 // TODO: Support FP bitcasts after legalize types. 10427 if (VT.isVector() && 10428 (!LegalTypes || 10429 (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() && 10430 TLI.isTypeLegal(VT.getVectorElementType()))) && 10431 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 10432 cast<BuildVectorSDNode>(N0)->isConstant()) 10433 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), 10434 VT.getVectorElementType()); 10435 10436 // If the input is a constant, let getNode fold it. 10437 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) { 10438 // If we can't allow illegal operations, we need to check that this is just 10439 // a fp -> int or int -> conversion and that the resulting operation will 10440 // be legal. 10441 if (!LegalOperations || 10442 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 10443 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 10444 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 10445 TLI.isOperationLegal(ISD::Constant, VT))) { 10446 SDValue C = DAG.getBitcast(VT, N0); 10447 if (C.getNode() != N) 10448 return C; 10449 } 10450 } 10451 10452 // (conv (conv x, t1), t2) -> (conv x, t2) 10453 if (N0.getOpcode() == ISD::BITCAST) 10454 return DAG.getBitcast(VT, N0.getOperand(0)); 10455 10456 // fold (conv (load x)) -> (load (conv*)x) 10457 // If the resultant load doesn't need a higher alignment than the original! 10458 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10459 // Do not remove the cast if the types differ in endian layout. 10460 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 10461 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 10462 // If the load is volatile, we only want to change the load type if the 10463 // resulting load is legal. Otherwise we might increase the number of 10464 // memory accesses. We don't care if the original type was legal or not 10465 // as we assume software couldn't rely on the number of accesses of an 10466 // illegal type. 10467 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) || 10468 TLI.isOperationLegal(ISD::LOAD, VT)) && 10469 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) { 10470 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10471 unsigned OrigAlign = LN0->getAlignment(); 10472 10473 bool Fast = false; 10474 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 10475 LN0->getAddressSpace(), OrigAlign, &Fast) && 10476 Fast) { 10477 SDValue Load = 10478 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 10479 LN0->getPointerInfo(), OrigAlign, 10480 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 10481 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 10482 return Load; 10483 } 10484 } 10485 10486 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 10487 return V; 10488 10489 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 10490 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 10491 // 10492 // For ppc_fp128: 10493 // fold (bitcast (fneg x)) -> 10494 // flipbit = signbit 10495 // (xor (bitcast x) (build_pair flipbit, flipbit)) 10496 // 10497 // fold (bitcast (fabs x)) -> 10498 // flipbit = (and (extract_element (bitcast x), 0), signbit) 10499 // (xor (bitcast x) (build_pair flipbit, flipbit)) 10500 // This often reduces constant pool loads. 10501 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 10502 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 10503 N0.getNode()->hasOneUse() && VT.isInteger() && 10504 !VT.isVector() && !N0.getValueType().isVector()) { 10505 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 10506 AddToWorklist(NewConv.getNode()); 10507 10508 SDLoc DL(N); 10509 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 10510 assert(VT.getSizeInBits() == 128); 10511 SDValue SignBit = DAG.getConstant( 10512 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 10513 SDValue FlipBit; 10514 if (N0.getOpcode() == ISD::FNEG) { 10515 FlipBit = SignBit; 10516 AddToWorklist(FlipBit.getNode()); 10517 } else { 10518 assert(N0.getOpcode() == ISD::FABS); 10519 SDValue Hi = 10520 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 10521 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 10522 SDLoc(NewConv))); 10523 AddToWorklist(Hi.getNode()); 10524 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 10525 AddToWorklist(FlipBit.getNode()); 10526 } 10527 SDValue FlipBits = 10528 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 10529 AddToWorklist(FlipBits.getNode()); 10530 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 10531 } 10532 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 10533 if (N0.getOpcode() == ISD::FNEG) 10534 return DAG.getNode(ISD::XOR, DL, VT, 10535 NewConv, DAG.getConstant(SignBit, DL, VT)); 10536 assert(N0.getOpcode() == ISD::FABS); 10537 return DAG.getNode(ISD::AND, DL, VT, 10538 NewConv, DAG.getConstant(~SignBit, DL, VT)); 10539 } 10540 10541 // fold (bitconvert (fcopysign cst, x)) -> 10542 // (or (and (bitconvert x), sign), (and cst, (not sign))) 10543 // Note that we don't handle (copysign x, cst) because this can always be 10544 // folded to an fneg or fabs. 10545 // 10546 // For ppc_fp128: 10547 // fold (bitcast (fcopysign cst, x)) -> 10548 // flipbit = (and (extract_element 10549 // (xor (bitcast cst), (bitcast x)), 0), 10550 // signbit) 10551 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 10552 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 10553 isa<ConstantFPSDNode>(N0.getOperand(0)) && 10554 VT.isInteger() && !VT.isVector()) { 10555 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 10556 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 10557 if (isTypeLegal(IntXVT)) { 10558 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 10559 AddToWorklist(X.getNode()); 10560 10561 // If X has a different width than the result/lhs, sext it or truncate it. 10562 unsigned VTWidth = VT.getSizeInBits(); 10563 if (OrigXWidth < VTWidth) { 10564 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 10565 AddToWorklist(X.getNode()); 10566 } else if (OrigXWidth > VTWidth) { 10567 // To get the sign bit in the right place, we have to shift it right 10568 // before truncating. 10569 SDLoc DL(X); 10570 X = DAG.getNode(ISD::SRL, DL, 10571 X.getValueType(), X, 10572 DAG.getConstant(OrigXWidth-VTWidth, DL, 10573 X.getValueType())); 10574 AddToWorklist(X.getNode()); 10575 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 10576 AddToWorklist(X.getNode()); 10577 } 10578 10579 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 10580 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 10581 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 10582 AddToWorklist(Cst.getNode()); 10583 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 10584 AddToWorklist(X.getNode()); 10585 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 10586 AddToWorklist(XorResult.getNode()); 10587 SDValue XorResult64 = DAG.getNode( 10588 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 10589 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 10590 SDLoc(XorResult))); 10591 AddToWorklist(XorResult64.getNode()); 10592 SDValue FlipBit = 10593 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 10594 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 10595 AddToWorklist(FlipBit.getNode()); 10596 SDValue FlipBits = 10597 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 10598 AddToWorklist(FlipBits.getNode()); 10599 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 10600 } 10601 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 10602 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 10603 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 10604 AddToWorklist(X.getNode()); 10605 10606 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 10607 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 10608 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 10609 AddToWorklist(Cst.getNode()); 10610 10611 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 10612 } 10613 } 10614 10615 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 10616 if (N0.getOpcode() == ISD::BUILD_PAIR) 10617 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 10618 return CombineLD; 10619 10620 // Remove double bitcasts from shuffles - this is often a legacy of 10621 // XformToShuffleWithZero being used to combine bitmaskings (of 10622 // float vectors bitcast to integer vectors) into shuffles. 10623 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 10624 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 10625 N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() && 10626 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 10627 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 10628 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 10629 10630 // If operands are a bitcast, peek through if it casts the original VT. 10631 // If operands are a constant, just bitcast back to original VT. 10632 auto PeekThroughBitcast = [&](SDValue Op) { 10633 if (Op.getOpcode() == ISD::BITCAST && 10634 Op.getOperand(0).getValueType() == VT) 10635 return SDValue(Op.getOperand(0)); 10636 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 10637 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 10638 return DAG.getBitcast(VT, Op); 10639 return SDValue(); 10640 }; 10641 10642 // FIXME: If either input vector is bitcast, try to convert the shuffle to 10643 // the result type of this bitcast. This would eliminate at least one 10644 // bitcast. See the transform in InstCombine. 10645 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 10646 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 10647 if (!(SV0 && SV1)) 10648 return SDValue(); 10649 10650 int MaskScale = 10651 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 10652 SmallVector<int, 8> NewMask; 10653 for (int M : SVN->getMask()) 10654 for (int i = 0; i != MaskScale; ++i) 10655 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 10656 10657 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 10658 if (!LegalMask) { 10659 std::swap(SV0, SV1); 10660 ShuffleVectorSDNode::commuteMask(NewMask); 10661 LegalMask = TLI.isShuffleMaskLegal(NewMask, VT); 10662 } 10663 10664 if (LegalMask) 10665 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask); 10666 } 10667 10668 return SDValue(); 10669 } 10670 10671 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 10672 EVT VT = N->getValueType(0); 10673 return CombineConsecutiveLoads(N, VT); 10674 } 10675 10676 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 10677 /// operands. DstEltVT indicates the destination element value type. 10678 SDValue DAGCombiner:: 10679 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 10680 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 10681 10682 // If this is already the right type, we're done. 10683 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 10684 10685 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 10686 unsigned DstBitSize = DstEltVT.getSizeInBits(); 10687 10688 // If this is a conversion of N elements of one type to N elements of another 10689 // type, convert each element. This handles FP<->INT cases. 10690 if (SrcBitSize == DstBitSize) { 10691 SmallVector<SDValue, 8> Ops; 10692 for (SDValue Op : BV->op_values()) { 10693 // If the vector element type is not legal, the BUILD_VECTOR operands 10694 // are promoted and implicitly truncated. Make that explicit here. 10695 if (Op.getValueType() != SrcEltVT) 10696 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 10697 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 10698 AddToWorklist(Ops.back().getNode()); 10699 } 10700 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 10701 BV->getValueType(0).getVectorNumElements()); 10702 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 10703 } 10704 10705 // Otherwise, we're growing or shrinking the elements. To avoid having to 10706 // handle annoying details of growing/shrinking FP values, we convert them to 10707 // int first. 10708 if (SrcEltVT.isFloatingPoint()) { 10709 // Convert the input float vector to a int vector where the elements are the 10710 // same sizes. 10711 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 10712 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 10713 SrcEltVT = IntVT; 10714 } 10715 10716 // Now we know the input is an integer vector. If the output is a FP type, 10717 // convert to integer first, then to FP of the right size. 10718 if (DstEltVT.isFloatingPoint()) { 10719 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 10720 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 10721 10722 // Next, convert to FP elements of the same size. 10723 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 10724 } 10725 10726 SDLoc DL(BV); 10727 10728 // Okay, we know the src/dst types are both integers of differing types. 10729 // Handling growing first. 10730 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 10731 if (SrcBitSize < DstBitSize) { 10732 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize; 10733 10734 SmallVector<SDValue, 8> Ops; 10735 for (unsigned i = 0, e = BV->getNumOperands(); i != e; 10736 i += NumInputsPerOutput) { 10737 bool isLE = DAG.getDataLayout().isLittleEndian(); 10738 APInt NewBits = APInt(DstBitSize, 0); 10739 bool EltIsUndef = true; 10740 for (unsigned j = 0; j != NumInputsPerOutput; ++j) { 10741 // Shift the previously computed bits over. 10742 NewBits <<= SrcBitSize; 10743 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j)); 10744 if (Op.isUndef()) continue; 10745 EltIsUndef = false; 10746 10747 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue(). 10748 zextOrTrunc(SrcBitSize).zext(DstBitSize); 10749 } 10750 10751 if (EltIsUndef) 10752 Ops.push_back(DAG.getUNDEF(DstEltVT)); 10753 else 10754 Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT)); 10755 } 10756 10757 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 10758 return DAG.getBuildVector(VT, DL, Ops); 10759 } 10760 10761 // Finally, this must be the case where we are shrinking elements: each input 10762 // turns into multiple outputs. 10763 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize; 10764 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 10765 NumOutputsPerInput*BV->getNumOperands()); 10766 SmallVector<SDValue, 8> Ops; 10767 10768 for (const SDValue &Op : BV->op_values()) { 10769 if (Op.isUndef()) { 10770 Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT)); 10771 continue; 10772 } 10773 10774 APInt OpVal = cast<ConstantSDNode>(Op)-> 10775 getAPIntValue().zextOrTrunc(SrcBitSize); 10776 10777 for (unsigned j = 0; j != NumOutputsPerInput; ++j) { 10778 APInt ThisVal = OpVal.trunc(DstBitSize); 10779 Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT)); 10780 OpVal.lshrInPlace(DstBitSize); 10781 } 10782 10783 // For big endian targets, swap the order of the pieces of each element. 10784 if (DAG.getDataLayout().isBigEndian()) 10785 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end()); 10786 } 10787 10788 return DAG.getBuildVector(VT, DL, Ops); 10789 } 10790 10791 static bool isContractable(SDNode *N) { 10792 SDNodeFlags F = N->getFlags(); 10793 return F.hasAllowContract() || F.hasAllowReassociation(); 10794 } 10795 10796 /// Try to perform FMA combining on a given FADD node. 10797 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 10798 SDValue N0 = N->getOperand(0); 10799 SDValue N1 = N->getOperand(1); 10800 EVT VT = N->getValueType(0); 10801 SDLoc SL(N); 10802 10803 const TargetOptions &Options = DAG.getTarget().Options; 10804 10805 // Floating-point multiply-add with intermediate rounding. 10806 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 10807 10808 // Floating-point multiply-add without intermediate rounding. 10809 bool HasFMA = 10810 TLI.isFMAFasterThanFMulAndFAdd(VT) && 10811 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 10812 10813 // No valid opcode, do not combine. 10814 if (!HasFMAD && !HasFMA) 10815 return SDValue(); 10816 10817 SDNodeFlags Flags = N->getFlags(); 10818 bool CanFuse = Options.UnsafeFPMath || isContractable(N); 10819 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 10820 CanFuse || HasFMAD); 10821 // If the addition is not contractable, do not combine. 10822 if (!AllowFusionGlobally && !isContractable(N)) 10823 return SDValue(); 10824 10825 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 10826 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 10827 return SDValue(); 10828 10829 // Always prefer FMAD to FMA for precision. 10830 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 10831 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 10832 10833 // Is the node an FMUL and contractable either due to global flags or 10834 // SDNodeFlags. 10835 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 10836 if (N.getOpcode() != ISD::FMUL) 10837 return false; 10838 return AllowFusionGlobally || isContractable(N.getNode()); 10839 }; 10840 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 10841 // prefer to fold the multiply with fewer uses. 10842 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 10843 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 10844 std::swap(N0, N1); 10845 } 10846 10847 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 10848 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 10849 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10850 N0.getOperand(0), N0.getOperand(1), N1, Flags); 10851 } 10852 10853 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 10854 // Note: Commutes FADD operands. 10855 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 10856 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10857 N1.getOperand(0), N1.getOperand(1), N0, Flags); 10858 } 10859 10860 // Look through FP_EXTEND nodes to do more combining. 10861 10862 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 10863 if (N0.getOpcode() == ISD::FP_EXTEND) { 10864 SDValue N00 = N0.getOperand(0); 10865 if (isContractableFMUL(N00) && 10866 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10867 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10868 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10869 N00.getOperand(0)), 10870 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10871 N00.getOperand(1)), N1, Flags); 10872 } 10873 } 10874 10875 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 10876 // Note: Commutes FADD operands. 10877 if (N1.getOpcode() == ISD::FP_EXTEND) { 10878 SDValue N10 = N1.getOperand(0); 10879 if (isContractableFMUL(N10) && 10880 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10881 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10882 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10883 N10.getOperand(0)), 10884 DAG.getNode(ISD::FP_EXTEND, SL, VT, 10885 N10.getOperand(1)), N0, Flags); 10886 } 10887 } 10888 10889 // More folding opportunities when target permits. 10890 if (Aggressive) { 10891 // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z)) 10892 if (CanFuse && 10893 N0.getOpcode() == PreferredFusedOpcode && 10894 N0.getOperand(2).getOpcode() == ISD::FMUL && 10895 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 10896 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10897 N0.getOperand(0), N0.getOperand(1), 10898 DAG.getNode(PreferredFusedOpcode, SL, VT, 10899 N0.getOperand(2).getOperand(0), 10900 N0.getOperand(2).getOperand(1), 10901 N1, Flags), Flags); 10902 } 10903 10904 // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x)) 10905 if (CanFuse && 10906 N1->getOpcode() == PreferredFusedOpcode && 10907 N1.getOperand(2).getOpcode() == ISD::FMUL && 10908 N1->hasOneUse() && N1.getOperand(2)->hasOneUse()) { 10909 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10910 N1.getOperand(0), N1.getOperand(1), 10911 DAG.getNode(PreferredFusedOpcode, SL, VT, 10912 N1.getOperand(2).getOperand(0), 10913 N1.getOperand(2).getOperand(1), 10914 N0, Flags), Flags); 10915 } 10916 10917 10918 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 10919 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 10920 auto FoldFAddFMAFPExtFMul = [&] ( 10921 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z, 10922 SDNodeFlags Flags) { 10923 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 10924 DAG.getNode(PreferredFusedOpcode, SL, VT, 10925 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 10926 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 10927 Z, Flags), Flags); 10928 }; 10929 if (N0.getOpcode() == PreferredFusedOpcode) { 10930 SDValue N02 = N0.getOperand(2); 10931 if (N02.getOpcode() == ISD::FP_EXTEND) { 10932 SDValue N020 = N02.getOperand(0); 10933 if (isContractableFMUL(N020) && 10934 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 10935 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 10936 N020.getOperand(0), N020.getOperand(1), 10937 N1, Flags); 10938 } 10939 } 10940 } 10941 10942 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 10943 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 10944 // FIXME: This turns two single-precision and one double-precision 10945 // operation into two double-precision operations, which might not be 10946 // interesting for all targets, especially GPUs. 10947 auto FoldFAddFPExtFMAFMul = [&] ( 10948 SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z, 10949 SDNodeFlags Flags) { 10950 return DAG.getNode(PreferredFusedOpcode, SL, VT, 10951 DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 10952 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 10953 DAG.getNode(PreferredFusedOpcode, SL, VT, 10954 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 10955 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 10956 Z, Flags), Flags); 10957 }; 10958 if (N0.getOpcode() == ISD::FP_EXTEND) { 10959 SDValue N00 = N0.getOperand(0); 10960 if (N00.getOpcode() == PreferredFusedOpcode) { 10961 SDValue N002 = N00.getOperand(2); 10962 if (isContractableFMUL(N002) && 10963 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 10964 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 10965 N002.getOperand(0), N002.getOperand(1), 10966 N1, Flags); 10967 } 10968 } 10969 } 10970 10971 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 10972 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 10973 if (N1.getOpcode() == PreferredFusedOpcode) { 10974 SDValue N12 = N1.getOperand(2); 10975 if (N12.getOpcode() == ISD::FP_EXTEND) { 10976 SDValue N120 = N12.getOperand(0); 10977 if (isContractableFMUL(N120) && 10978 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 10979 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 10980 N120.getOperand(0), N120.getOperand(1), 10981 N0, Flags); 10982 } 10983 } 10984 } 10985 10986 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 10987 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 10988 // FIXME: This turns two single-precision and one double-precision 10989 // operation into two double-precision operations, which might not be 10990 // interesting for all targets, especially GPUs. 10991 if (N1.getOpcode() == ISD::FP_EXTEND) { 10992 SDValue N10 = N1.getOperand(0); 10993 if (N10.getOpcode() == PreferredFusedOpcode) { 10994 SDValue N102 = N10.getOperand(2); 10995 if (isContractableFMUL(N102) && 10996 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 10997 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 10998 N102.getOperand(0), N102.getOperand(1), 10999 N0, Flags); 11000 } 11001 } 11002 } 11003 } 11004 11005 return SDValue(); 11006 } 11007 11008 /// Try to perform FMA combining on a given FSUB node. 11009 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 11010 SDValue N0 = N->getOperand(0); 11011 SDValue N1 = N->getOperand(1); 11012 EVT VT = N->getValueType(0); 11013 SDLoc SL(N); 11014 11015 const TargetOptions &Options = DAG.getTarget().Options; 11016 // Floating-point multiply-add with intermediate rounding. 11017 bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 11018 11019 // Floating-point multiply-add without intermediate rounding. 11020 bool HasFMA = 11021 TLI.isFMAFasterThanFMulAndFAdd(VT) && 11022 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 11023 11024 // No valid opcode, do not combine. 11025 if (!HasFMAD && !HasFMA) 11026 return SDValue(); 11027 11028 const SDNodeFlags Flags = N->getFlags(); 11029 bool CanFuse = Options.UnsafeFPMath || isContractable(N); 11030 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 11031 CanFuse || HasFMAD); 11032 11033 // If the subtraction is not contractable, do not combine. 11034 if (!AllowFusionGlobally && !isContractable(N)) 11035 return SDValue(); 11036 11037 const SelectionDAGTargetInfo *STI = DAG.getSubtarget().getSelectionDAGInfo(); 11038 if (STI && STI->generateFMAsInMachineCombiner(OptLevel)) 11039 return SDValue(); 11040 11041 // Always prefer FMAD to FMA for precision. 11042 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 11043 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 11044 11045 // Is the node an FMUL and contractable either due to global flags or 11046 // SDNodeFlags. 11047 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 11048 if (N.getOpcode() != ISD::FMUL) 11049 return false; 11050 return AllowFusionGlobally || isContractable(N.getNode()); 11051 }; 11052 11053 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 11054 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 11055 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11056 N0.getOperand(0), N0.getOperand(1), 11057 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 11058 } 11059 11060 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 11061 // Note: Commutes FSUB operands. 11062 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 11063 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11064 DAG.getNode(ISD::FNEG, SL, VT, 11065 N1.getOperand(0)), 11066 N1.getOperand(1), N0, Flags); 11067 } 11068 11069 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 11070 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 11071 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 11072 SDValue N00 = N0.getOperand(0).getOperand(0); 11073 SDValue N01 = N0.getOperand(0).getOperand(1); 11074 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11075 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 11076 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 11077 } 11078 11079 // Look through FP_EXTEND nodes to do more combining. 11080 11081 // fold (fsub (fpext (fmul x, y)), z) 11082 // -> (fma (fpext x), (fpext y), (fneg z)) 11083 if (N0.getOpcode() == ISD::FP_EXTEND) { 11084 SDValue N00 = N0.getOperand(0); 11085 if (isContractableFMUL(N00) && 11086 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 11087 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11088 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11089 N00.getOperand(0)), 11090 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11091 N00.getOperand(1)), 11092 DAG.getNode(ISD::FNEG, SL, VT, N1), Flags); 11093 } 11094 } 11095 11096 // fold (fsub x, (fpext (fmul y, z))) 11097 // -> (fma (fneg (fpext y)), (fpext z), x) 11098 // Note: Commutes FSUB operands. 11099 if (N1.getOpcode() == ISD::FP_EXTEND) { 11100 SDValue N10 = N1.getOperand(0); 11101 if (isContractableFMUL(N10) && 11102 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N10.getValueType())) { 11103 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11104 DAG.getNode(ISD::FNEG, SL, VT, 11105 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11106 N10.getOperand(0))), 11107 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11108 N10.getOperand(1)), 11109 N0, Flags); 11110 } 11111 } 11112 11113 // fold (fsub (fpext (fneg (fmul, x, y))), z) 11114 // -> (fneg (fma (fpext x), (fpext y), z)) 11115 // Note: This could be removed with appropriate canonicalization of the 11116 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 11117 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 11118 // from implementing the canonicalization in visitFSUB. 11119 if (N0.getOpcode() == ISD::FP_EXTEND) { 11120 SDValue N00 = N0.getOperand(0); 11121 if (N00.getOpcode() == ISD::FNEG) { 11122 SDValue N000 = N00.getOperand(0); 11123 if (isContractableFMUL(N000) && 11124 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 11125 return DAG.getNode(ISD::FNEG, SL, VT, 11126 DAG.getNode(PreferredFusedOpcode, SL, VT, 11127 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11128 N000.getOperand(0)), 11129 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11130 N000.getOperand(1)), 11131 N1, Flags)); 11132 } 11133 } 11134 } 11135 11136 // fold (fsub (fneg (fpext (fmul, x, y))), z) 11137 // -> (fneg (fma (fpext x)), (fpext y), z) 11138 // Note: This could be removed with appropriate canonicalization of the 11139 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 11140 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 11141 // from implementing the canonicalization in visitFSUB. 11142 if (N0.getOpcode() == ISD::FNEG) { 11143 SDValue N00 = N0.getOperand(0); 11144 if (N00.getOpcode() == ISD::FP_EXTEND) { 11145 SDValue N000 = N00.getOperand(0); 11146 if (isContractableFMUL(N000) && 11147 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N000.getValueType())) { 11148 return DAG.getNode(ISD::FNEG, SL, VT, 11149 DAG.getNode(PreferredFusedOpcode, SL, VT, 11150 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11151 N000.getOperand(0)), 11152 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11153 N000.getOperand(1)), 11154 N1, Flags)); 11155 } 11156 } 11157 } 11158 11159 // More folding opportunities when target permits. 11160 if (Aggressive) { 11161 // fold (fsub (fma x, y, (fmul u, v)), z) 11162 // -> (fma x, y (fma u, v, (fneg z))) 11163 if (CanFuse && N0.getOpcode() == PreferredFusedOpcode && 11164 isContractableFMUL(N0.getOperand(2)) && N0->hasOneUse() && 11165 N0.getOperand(2)->hasOneUse()) { 11166 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11167 N0.getOperand(0), N0.getOperand(1), 11168 DAG.getNode(PreferredFusedOpcode, SL, VT, 11169 N0.getOperand(2).getOperand(0), 11170 N0.getOperand(2).getOperand(1), 11171 DAG.getNode(ISD::FNEG, SL, VT, 11172 N1), Flags), Flags); 11173 } 11174 11175 // fold (fsub x, (fma y, z, (fmul u, v))) 11176 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 11177 if (CanFuse && N1.getOpcode() == PreferredFusedOpcode && 11178 isContractableFMUL(N1.getOperand(2))) { 11179 SDValue N20 = N1.getOperand(2).getOperand(0); 11180 SDValue N21 = N1.getOperand(2).getOperand(1); 11181 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11182 DAG.getNode(ISD::FNEG, SL, VT, 11183 N1.getOperand(0)), 11184 N1.getOperand(1), 11185 DAG.getNode(PreferredFusedOpcode, SL, VT, 11186 DAG.getNode(ISD::FNEG, SL, VT, N20), 11187 N21, N0, Flags), Flags); 11188 } 11189 11190 11191 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 11192 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 11193 if (N0.getOpcode() == PreferredFusedOpcode) { 11194 SDValue N02 = N0.getOperand(2); 11195 if (N02.getOpcode() == ISD::FP_EXTEND) { 11196 SDValue N020 = N02.getOperand(0); 11197 if (isContractableFMUL(N020) && 11198 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N020.getValueType())) { 11199 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11200 N0.getOperand(0), N0.getOperand(1), 11201 DAG.getNode(PreferredFusedOpcode, SL, VT, 11202 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11203 N020.getOperand(0)), 11204 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11205 N020.getOperand(1)), 11206 DAG.getNode(ISD::FNEG, SL, VT, 11207 N1), Flags), Flags); 11208 } 11209 } 11210 } 11211 11212 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 11213 // -> (fma (fpext x), (fpext y), 11214 // (fma (fpext u), (fpext v), (fneg z))) 11215 // FIXME: This turns two single-precision and one double-precision 11216 // operation into two double-precision operations, which might not be 11217 // interesting for all targets, especially GPUs. 11218 if (N0.getOpcode() == ISD::FP_EXTEND) { 11219 SDValue N00 = N0.getOperand(0); 11220 if (N00.getOpcode() == PreferredFusedOpcode) { 11221 SDValue N002 = N00.getOperand(2); 11222 if (isContractableFMUL(N002) && 11223 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N00.getValueType())) { 11224 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11225 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11226 N00.getOperand(0)), 11227 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11228 N00.getOperand(1)), 11229 DAG.getNode(PreferredFusedOpcode, SL, VT, 11230 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11231 N002.getOperand(0)), 11232 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11233 N002.getOperand(1)), 11234 DAG.getNode(ISD::FNEG, SL, VT, 11235 N1), Flags), Flags); 11236 } 11237 } 11238 } 11239 11240 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 11241 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 11242 if (N1.getOpcode() == PreferredFusedOpcode && 11243 N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) { 11244 SDValue N120 = N1.getOperand(2).getOperand(0); 11245 if (isContractableFMUL(N120) && 11246 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, N120.getValueType())) { 11247 SDValue N1200 = N120.getOperand(0); 11248 SDValue N1201 = N120.getOperand(1); 11249 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11250 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), 11251 N1.getOperand(1), 11252 DAG.getNode(PreferredFusedOpcode, SL, VT, 11253 DAG.getNode(ISD::FNEG, SL, VT, 11254 DAG.getNode(ISD::FP_EXTEND, SL, 11255 VT, N1200)), 11256 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11257 N1201), 11258 N0, Flags), Flags); 11259 } 11260 } 11261 11262 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 11263 // -> (fma (fneg (fpext y)), (fpext z), 11264 // (fma (fneg (fpext u)), (fpext v), x)) 11265 // FIXME: This turns two single-precision and one double-precision 11266 // operation into two double-precision operations, which might not be 11267 // interesting for all targets, especially GPUs. 11268 if (N1.getOpcode() == ISD::FP_EXTEND && 11269 N1.getOperand(0).getOpcode() == PreferredFusedOpcode) { 11270 SDValue CvtSrc = N1.getOperand(0); 11271 SDValue N100 = CvtSrc.getOperand(0); 11272 SDValue N101 = CvtSrc.getOperand(1); 11273 SDValue N102 = CvtSrc.getOperand(2); 11274 if (isContractableFMUL(N102) && 11275 TLI.isFPExtFoldable(PreferredFusedOpcode, VT, CvtSrc.getValueType())) { 11276 SDValue N1020 = N102.getOperand(0); 11277 SDValue N1021 = N102.getOperand(1); 11278 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11279 DAG.getNode(ISD::FNEG, SL, VT, 11280 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11281 N100)), 11282 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 11283 DAG.getNode(PreferredFusedOpcode, SL, VT, 11284 DAG.getNode(ISD::FNEG, SL, VT, 11285 DAG.getNode(ISD::FP_EXTEND, SL, 11286 VT, N1020)), 11287 DAG.getNode(ISD::FP_EXTEND, SL, VT, 11288 N1021), 11289 N0, Flags), Flags); 11290 } 11291 } 11292 } 11293 11294 return SDValue(); 11295 } 11296 11297 /// Try to perform FMA combining on a given FMUL node based on the distributive 11298 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 11299 /// subtraction instead of addition). 11300 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 11301 SDValue N0 = N->getOperand(0); 11302 SDValue N1 = N->getOperand(1); 11303 EVT VT = N->getValueType(0); 11304 SDLoc SL(N); 11305 const SDNodeFlags Flags = N->getFlags(); 11306 11307 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 11308 11309 const TargetOptions &Options = DAG.getTarget().Options; 11310 11311 // The transforms below are incorrect when x == 0 and y == inf, because the 11312 // intermediate multiplication produces a nan. 11313 if (!Options.NoInfsFPMath) 11314 return SDValue(); 11315 11316 // Floating-point multiply-add without intermediate rounding. 11317 bool HasFMA = 11318 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) && 11319 TLI.isFMAFasterThanFMulAndFAdd(VT) && 11320 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 11321 11322 // Floating-point multiply-add with intermediate rounding. This can result 11323 // in a less precise result due to the changed rounding order. 11324 bool HasFMAD = Options.UnsafeFPMath && 11325 (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT)); 11326 11327 // No valid opcode, do not combine. 11328 if (!HasFMAD && !HasFMA) 11329 return SDValue(); 11330 11331 // Always prefer FMAD to FMA for precision. 11332 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 11333 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 11334 11335 // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y) 11336 // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y)) 11337 auto FuseFADD = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) { 11338 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 11339 if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) { 11340 if (C->isExactlyValue(+1.0)) 11341 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 11342 Y, Flags); 11343 if (C->isExactlyValue(-1.0)) 11344 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 11345 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 11346 } 11347 } 11348 return SDValue(); 11349 }; 11350 11351 if (SDValue FMA = FuseFADD(N0, N1, Flags)) 11352 return FMA; 11353 if (SDValue FMA = FuseFADD(N1, N0, Flags)) 11354 return FMA; 11355 11356 // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y) 11357 // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y)) 11358 // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y)) 11359 // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y) 11360 auto FuseFSUB = [&](SDValue X, SDValue Y, const SDNodeFlags Flags) { 11361 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 11362 if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) { 11363 if (C0->isExactlyValue(+1.0)) 11364 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11365 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 11366 Y, Flags); 11367 if (C0->isExactlyValue(-1.0)) 11368 return DAG.getNode(PreferredFusedOpcode, SL, VT, 11369 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 11370 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 11371 } 11372 if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) { 11373 if (C1->isExactlyValue(+1.0)) 11374 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 11375 DAG.getNode(ISD::FNEG, SL, VT, Y), Flags); 11376 if (C1->isExactlyValue(-1.0)) 11377 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 11378 Y, Flags); 11379 } 11380 } 11381 return SDValue(); 11382 }; 11383 11384 if (SDValue FMA = FuseFSUB(N0, N1, Flags)) 11385 return FMA; 11386 if (SDValue FMA = FuseFSUB(N1, N0, Flags)) 11387 return FMA; 11388 11389 return SDValue(); 11390 } 11391 11392 SDValue DAGCombiner::visitFADD(SDNode *N) { 11393 SDValue N0 = N->getOperand(0); 11394 SDValue N1 = N->getOperand(1); 11395 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 11396 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 11397 EVT VT = N->getValueType(0); 11398 SDLoc DL(N); 11399 const TargetOptions &Options = DAG.getTarget().Options; 11400 const SDNodeFlags Flags = N->getFlags(); 11401 11402 // fold vector ops 11403 if (VT.isVector()) 11404 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 11405 return FoldedVOp; 11406 11407 // fold (fadd c1, c2) -> c1 + c2 11408 if (N0CFP && N1CFP) 11409 return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags); 11410 11411 // canonicalize constant to RHS 11412 if (N0CFP && !N1CFP) 11413 return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags); 11414 11415 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math) 11416 ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true); 11417 if (N1C && N1C->isZero()) 11418 if (N1C->isNegative() || Options.UnsafeFPMath || Flags.hasNoSignedZeros()) 11419 return N0; 11420 11421 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11422 return NewSel; 11423 11424 // fold (fadd A, (fneg B)) -> (fsub A, B) 11425 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 11426 isNegatibleForFree(N1, LegalOperations, TLI, &Options, ForCodeSize) == 2) 11427 return DAG.getNode(ISD::FSUB, DL, VT, N0, 11428 GetNegatedExpression(N1, DAG, LegalOperations, 11429 ForCodeSize), Flags); 11430 11431 // fold (fadd (fneg A), B) -> (fsub B, A) 11432 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) && 11433 isNegatibleForFree(N0, LegalOperations, TLI, &Options, ForCodeSize) == 2) 11434 return DAG.getNode(ISD::FSUB, DL, VT, N1, 11435 GetNegatedExpression(N0, DAG, LegalOperations, 11436 ForCodeSize), Flags); 11437 11438 auto isFMulNegTwo = [](SDValue FMul) { 11439 if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL) 11440 return false; 11441 auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true); 11442 return C && C->isExactlyValue(-2.0); 11443 }; 11444 11445 // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B) 11446 if (isFMulNegTwo(N0)) { 11447 SDValue B = N0.getOperand(0); 11448 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B, Flags); 11449 return DAG.getNode(ISD::FSUB, DL, VT, N1, Add, Flags); 11450 } 11451 // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B) 11452 if (isFMulNegTwo(N1)) { 11453 SDValue B = N1.getOperand(0); 11454 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B, Flags); 11455 return DAG.getNode(ISD::FSUB, DL, VT, N0, Add, Flags); 11456 } 11457 11458 // No FP constant should be created after legalization as Instruction 11459 // Selection pass has a hard time dealing with FP constants. 11460 bool AllowNewConst = (Level < AfterLegalizeDAG); 11461 11462 // If 'unsafe math' or nnan is enabled, fold lots of things. 11463 if ((Options.UnsafeFPMath || Flags.hasNoNaNs()) && AllowNewConst) { 11464 // If allowed, fold (fadd (fneg x), x) -> 0.0 11465 if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 11466 return DAG.getConstantFP(0.0, DL, VT); 11467 11468 // If allowed, fold (fadd x, (fneg x)) -> 0.0 11469 if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 11470 return DAG.getConstantFP(0.0, DL, VT); 11471 } 11472 11473 // If 'unsafe math' or reassoc and nsz, fold lots of things. 11474 // TODO: break out portions of the transformations below for which Unsafe is 11475 // considered and which do not require both nsz and reassoc 11476 if ((Options.UnsafeFPMath || 11477 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) && 11478 AllowNewConst) { 11479 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2 11480 if (N1CFP && N0.getOpcode() == ISD::FADD && 11481 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 11482 SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1, Flags); 11483 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC, Flags); 11484 } 11485 11486 // We can fold chains of FADD's of the same value into multiplications. 11487 // This transform is not safe in general because we are reducing the number 11488 // of rounding steps. 11489 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 11490 if (N0.getOpcode() == ISD::FMUL) { 11491 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 11492 bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 11493 11494 // (fadd (fmul x, c), x) -> (fmul x, c+1) 11495 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 11496 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 11497 DAG.getConstantFP(1.0, DL, VT), Flags); 11498 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags); 11499 } 11500 11501 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 11502 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 11503 N1.getOperand(0) == N1.getOperand(1) && 11504 N0.getOperand(0) == N1.getOperand(0)) { 11505 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 11506 DAG.getConstantFP(2.0, DL, VT), Flags); 11507 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags); 11508 } 11509 } 11510 11511 if (N1.getOpcode() == ISD::FMUL) { 11512 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 11513 bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 11514 11515 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 11516 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 11517 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 11518 DAG.getConstantFP(1.0, DL, VT), Flags); 11519 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags); 11520 } 11521 11522 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 11523 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 11524 N0.getOperand(0) == N0.getOperand(1) && 11525 N1.getOperand(0) == N0.getOperand(0)) { 11526 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 11527 DAG.getConstantFP(2.0, DL, VT), Flags); 11528 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags); 11529 } 11530 } 11531 11532 if (N0.getOpcode() == ISD::FADD) { 11533 bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 11534 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 11535 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 11536 (N0.getOperand(0) == N1)) { 11537 return DAG.getNode(ISD::FMUL, DL, VT, 11538 N1, DAG.getConstantFP(3.0, DL, VT), Flags); 11539 } 11540 } 11541 11542 if (N1.getOpcode() == ISD::FADD) { 11543 bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 11544 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 11545 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 11546 N1.getOperand(0) == N0) { 11547 return DAG.getNode(ISD::FMUL, DL, VT, 11548 N0, DAG.getConstantFP(3.0, DL, VT), Flags); 11549 } 11550 } 11551 11552 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 11553 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 11554 N0.getOperand(0) == N0.getOperand(1) && 11555 N1.getOperand(0) == N1.getOperand(1) && 11556 N0.getOperand(0) == N1.getOperand(0)) { 11557 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 11558 DAG.getConstantFP(4.0, DL, VT), Flags); 11559 } 11560 } 11561 } // enable-unsafe-fp-math 11562 11563 // FADD -> FMA combines: 11564 if (SDValue Fused = visitFADDForFMACombine(N)) { 11565 AddToWorklist(Fused.getNode()); 11566 return Fused; 11567 } 11568 return SDValue(); 11569 } 11570 11571 SDValue DAGCombiner::visitFSUB(SDNode *N) { 11572 SDValue N0 = N->getOperand(0); 11573 SDValue N1 = N->getOperand(1); 11574 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true); 11575 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true); 11576 EVT VT = N->getValueType(0); 11577 SDLoc DL(N); 11578 const TargetOptions &Options = DAG.getTarget().Options; 11579 const SDNodeFlags Flags = N->getFlags(); 11580 11581 // fold vector ops 11582 if (VT.isVector()) 11583 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 11584 return FoldedVOp; 11585 11586 // fold (fsub c1, c2) -> c1-c2 11587 if (N0CFP && N1CFP) 11588 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1, Flags); 11589 11590 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11591 return NewSel; 11592 11593 // (fsub A, 0) -> A 11594 if (N1CFP && N1CFP->isZero()) { 11595 if (!N1CFP->isNegative() || Options.UnsafeFPMath || 11596 Flags.hasNoSignedZeros()) { 11597 return N0; 11598 } 11599 } 11600 11601 if (N0 == N1) { 11602 // (fsub x, x) -> 0.0 11603 if (Options.UnsafeFPMath || Flags.hasNoNaNs()) 11604 return DAG.getConstantFP(0.0f, DL, VT); 11605 } 11606 11607 // (fsub -0.0, N1) -> -N1 11608 if (N0CFP && N0CFP->isZero()) { 11609 if (N0CFP->isNegative() || 11610 (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())) { 11611 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options, ForCodeSize)) 11612 return GetNegatedExpression(N1, DAG, LegalOperations, ForCodeSize); 11613 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 11614 return DAG.getNode(ISD::FNEG, DL, VT, N1, Flags); 11615 } 11616 } 11617 11618 if ((Options.UnsafeFPMath || 11619 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) 11620 && N1.getOpcode() == ISD::FADD) { 11621 // X - (X + Y) -> -Y 11622 if (N0 == N1->getOperand(0)) 11623 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1), Flags); 11624 // X - (Y + X) -> -Y 11625 if (N0 == N1->getOperand(1)) 11626 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0), Flags); 11627 } 11628 11629 // fold (fsub A, (fneg B)) -> (fadd A, B) 11630 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options, ForCodeSize)) 11631 return DAG.getNode(ISD::FADD, DL, VT, N0, 11632 GetNegatedExpression(N1, DAG, LegalOperations, 11633 ForCodeSize), Flags); 11634 11635 // FSUB -> FMA combines: 11636 if (SDValue Fused = visitFSUBForFMACombine(N)) { 11637 AddToWorklist(Fused.getNode()); 11638 return Fused; 11639 } 11640 11641 return SDValue(); 11642 } 11643 11644 SDValue DAGCombiner::visitFMUL(SDNode *N) { 11645 SDValue N0 = N->getOperand(0); 11646 SDValue N1 = N->getOperand(1); 11647 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true); 11648 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true); 11649 EVT VT = N->getValueType(0); 11650 SDLoc DL(N); 11651 const TargetOptions &Options = DAG.getTarget().Options; 11652 const SDNodeFlags Flags = N->getFlags(); 11653 11654 // fold vector ops 11655 if (VT.isVector()) { 11656 // This just handles C1 * C2 for vectors. Other vector folds are below. 11657 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 11658 return FoldedVOp; 11659 } 11660 11661 // fold (fmul c1, c2) -> c1*c2 11662 if (N0CFP && N1CFP) 11663 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags); 11664 11665 // canonicalize constant to RHS 11666 if (isConstantFPBuildVectorOrConstantFP(N0) && 11667 !isConstantFPBuildVectorOrConstantFP(N1)) 11668 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags); 11669 11670 // fold (fmul A, 1.0) -> A 11671 if (N1CFP && N1CFP->isExactlyValue(1.0)) 11672 return N0; 11673 11674 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11675 return NewSel; 11676 11677 if (Options.UnsafeFPMath || 11678 (Flags.hasNoNaNs() && Flags.hasNoSignedZeros())) { 11679 // fold (fmul A, 0) -> 0 11680 if (N1CFP && N1CFP->isZero()) 11681 return N1; 11682 } 11683 11684 if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) { 11685 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2 11686 if (isConstantFPBuildVectorOrConstantFP(N1) && 11687 N0.getOpcode() == ISD::FMUL) { 11688 SDValue N00 = N0.getOperand(0); 11689 SDValue N01 = N0.getOperand(1); 11690 // Avoid an infinite loop by making sure that N00 is not a constant 11691 // (the inner multiply has not been constant folded yet). 11692 if (isConstantFPBuildVectorOrConstantFP(N01) && 11693 !isConstantFPBuildVectorOrConstantFP(N00)) { 11694 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags); 11695 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags); 11696 } 11697 } 11698 11699 // Match a special-case: we convert X * 2.0 into fadd. 11700 // fmul (fadd X, X), C -> fmul X, 2.0 * C 11701 if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() && 11702 N0.getOperand(0) == N0.getOperand(1)) { 11703 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 11704 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags); 11705 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags); 11706 } 11707 } 11708 11709 // fold (fmul X, 2.0) -> (fadd X, X) 11710 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 11711 return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags); 11712 11713 // fold (fmul X, -1.0) -> (fneg X) 11714 if (N1CFP && N1CFP->isExactlyValue(-1.0)) 11715 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 11716 return DAG.getNode(ISD::FNEG, DL, VT, N0); 11717 11718 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y) 11719 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options, 11720 ForCodeSize)) { 11721 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options, 11722 ForCodeSize)) { 11723 // Both can be negated for free, check to see if at least one is cheaper 11724 // negated. 11725 if (LHSNeg == 2 || RHSNeg == 2) 11726 return DAG.getNode(ISD::FMUL, DL, VT, 11727 GetNegatedExpression(N0, DAG, LegalOperations, 11728 ForCodeSize), 11729 GetNegatedExpression(N1, DAG, LegalOperations, 11730 ForCodeSize), 11731 Flags); 11732 } 11733 } 11734 11735 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 11736 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 11737 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 11738 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 11739 TLI.isOperationLegal(ISD::FABS, VT)) { 11740 SDValue Select = N0, X = N1; 11741 if (Select.getOpcode() != ISD::SELECT) 11742 std::swap(Select, X); 11743 11744 SDValue Cond = Select.getOperand(0); 11745 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 11746 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 11747 11748 if (TrueOpnd && FalseOpnd && 11749 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 11750 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 11751 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 11752 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 11753 switch (CC) { 11754 default: break; 11755 case ISD::SETOLT: 11756 case ISD::SETULT: 11757 case ISD::SETOLE: 11758 case ISD::SETULE: 11759 case ISD::SETLT: 11760 case ISD::SETLE: 11761 std::swap(TrueOpnd, FalseOpnd); 11762 LLVM_FALLTHROUGH; 11763 case ISD::SETOGT: 11764 case ISD::SETUGT: 11765 case ISD::SETOGE: 11766 case ISD::SETUGE: 11767 case ISD::SETGT: 11768 case ISD::SETGE: 11769 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 11770 TLI.isOperationLegal(ISD::FNEG, VT)) 11771 return DAG.getNode(ISD::FNEG, DL, VT, 11772 DAG.getNode(ISD::FABS, DL, VT, X)); 11773 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 11774 return DAG.getNode(ISD::FABS, DL, VT, X); 11775 11776 break; 11777 } 11778 } 11779 } 11780 11781 // FMUL -> FMA combines: 11782 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 11783 AddToWorklist(Fused.getNode()); 11784 return Fused; 11785 } 11786 11787 return SDValue(); 11788 } 11789 11790 SDValue DAGCombiner::visitFMA(SDNode *N) { 11791 SDValue N0 = N->getOperand(0); 11792 SDValue N1 = N->getOperand(1); 11793 SDValue N2 = N->getOperand(2); 11794 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11795 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11796 EVT VT = N->getValueType(0); 11797 SDLoc DL(N); 11798 const TargetOptions &Options = DAG.getTarget().Options; 11799 11800 // FMA nodes have flags that propagate to the created nodes. 11801 const SDNodeFlags Flags = N->getFlags(); 11802 bool UnsafeFPMath = Options.UnsafeFPMath || isContractable(N); 11803 11804 // Constant fold FMA. 11805 if (isa<ConstantFPSDNode>(N0) && 11806 isa<ConstantFPSDNode>(N1) && 11807 isa<ConstantFPSDNode>(N2)) { 11808 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 11809 } 11810 11811 if (UnsafeFPMath) { 11812 if (N0CFP && N0CFP->isZero()) 11813 return N2; 11814 if (N1CFP && N1CFP->isZero()) 11815 return N2; 11816 } 11817 // TODO: The FMA node should have flags that propagate to these nodes. 11818 if (N0CFP && N0CFP->isExactlyValue(1.0)) 11819 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 11820 if (N1CFP && N1CFP->isExactlyValue(1.0)) 11821 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 11822 11823 // Canonicalize (fma c, x, y) -> (fma x, c, y) 11824 if (isConstantFPBuildVectorOrConstantFP(N0) && 11825 !isConstantFPBuildVectorOrConstantFP(N1)) 11826 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 11827 11828 if (UnsafeFPMath) { 11829 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 11830 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 11831 isConstantFPBuildVectorOrConstantFP(N1) && 11832 isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 11833 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11834 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1), 11835 Flags), Flags); 11836 } 11837 11838 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 11839 if (N0.getOpcode() == ISD::FMUL && 11840 isConstantFPBuildVectorOrConstantFP(N1) && 11841 isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 11842 return DAG.getNode(ISD::FMA, DL, VT, 11843 N0.getOperand(0), 11844 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1), 11845 Flags), 11846 N2); 11847 } 11848 } 11849 11850 // (fma x, 1, y) -> (fadd x, y) 11851 // (fma x, -1, y) -> (fadd (fneg x), y) 11852 if (N1CFP) { 11853 if (N1CFP->isExactlyValue(1.0)) 11854 // TODO: The FMA node should have flags that propagate to this node. 11855 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 11856 11857 if (N1CFP->isExactlyValue(-1.0) && 11858 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 11859 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 11860 AddToWorklist(RHSNeg.getNode()); 11861 // TODO: The FMA node should have flags that propagate to this node. 11862 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 11863 } 11864 11865 // fma (fneg x), K, y -> fma x -K, y 11866 if (N0.getOpcode() == ISD::FNEG && 11867 (TLI.isOperationLegal(ISD::ConstantFP, VT) || 11868 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT, 11869 ForCodeSize)))) { 11870 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 11871 DAG.getNode(ISD::FNEG, DL, VT, N1, Flags), N2); 11872 } 11873 } 11874 11875 if (UnsafeFPMath) { 11876 // (fma x, c, x) -> (fmul x, (c+1)) 11877 if (N1CFP && N0 == N2) { 11878 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11879 DAG.getNode(ISD::FADD, DL, VT, N1, 11880 DAG.getConstantFP(1.0, DL, VT), Flags), 11881 Flags); 11882 } 11883 11884 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 11885 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 11886 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11887 DAG.getNode(ISD::FADD, DL, VT, N1, 11888 DAG.getConstantFP(-1.0, DL, VT), Flags), 11889 Flags); 11890 } 11891 } 11892 11893 return SDValue(); 11894 } 11895 11896 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11897 // reciprocal. 11898 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 11899 // Notice that this is not always beneficial. One reason is different targets 11900 // may have different costs for FDIV and FMUL, so sometimes the cost of two 11901 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 11902 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 11903 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 11904 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 11905 const SDNodeFlags Flags = N->getFlags(); 11906 if (!UnsafeMath && !Flags.hasAllowReciprocal()) 11907 return SDValue(); 11908 11909 // Skip if current node is a reciprocal. 11910 SDValue N0 = N->getOperand(0); 11911 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11912 if (N0CFP && N0CFP->isExactlyValue(1.0)) 11913 return SDValue(); 11914 11915 // Exit early if the target does not want this transform or if there can't 11916 // possibly be enough uses of the divisor to make the transform worthwhile. 11917 SDValue N1 = N->getOperand(1); 11918 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 11919 if (!MinUses || N1->use_size() < MinUses) 11920 return SDValue(); 11921 11922 // Find all FDIV users of the same divisor. 11923 // Use a set because duplicates may be present in the user list. 11924 SetVector<SDNode *> Users; 11925 for (auto *U : N1->uses()) { 11926 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 11927 // This division is eligible for optimization only if global unsafe math 11928 // is enabled or if this division allows reciprocal formation. 11929 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 11930 Users.insert(U); 11931 } 11932 } 11933 11934 // Now that we have the actual number of divisor uses, make sure it meets 11935 // the minimum threshold specified by the target. 11936 if (Users.size() < MinUses) 11937 return SDValue(); 11938 11939 EVT VT = N->getValueType(0); 11940 SDLoc DL(N); 11941 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 11942 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 11943 11944 // Dividend / Divisor -> Dividend * Reciprocal 11945 for (auto *U : Users) { 11946 SDValue Dividend = U->getOperand(0); 11947 if (Dividend != FPOne) { 11948 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 11949 Reciprocal, Flags); 11950 CombineTo(U, NewNode); 11951 } else if (U != Reciprocal.getNode()) { 11952 // In the absence of fast-math-flags, this user node is always the 11953 // same node as Reciprocal, but with FMF they may be different nodes. 11954 CombineTo(U, Reciprocal); 11955 } 11956 } 11957 return SDValue(N, 0); // N was replaced. 11958 } 11959 11960 SDValue DAGCombiner::visitFDIV(SDNode *N) { 11961 SDValue N0 = N->getOperand(0); 11962 SDValue N1 = N->getOperand(1); 11963 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 11964 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 11965 EVT VT = N->getValueType(0); 11966 SDLoc DL(N); 11967 const TargetOptions &Options = DAG.getTarget().Options; 11968 SDNodeFlags Flags = N->getFlags(); 11969 11970 // fold vector ops 11971 if (VT.isVector()) 11972 if (SDValue FoldedVOp = SimplifyVBinOp(N)) 11973 return FoldedVOp; 11974 11975 // fold (fdiv c1, c2) -> c1/c2 11976 if (N0CFP && N1CFP) 11977 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags); 11978 11979 if (SDValue NewSel = foldBinOpIntoSelect(N)) 11980 return NewSel; 11981 11982 if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) { 11983 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 11984 if (N1CFP) { 11985 // Compute the reciprocal 1.0 / c2. 11986 const APFloat &N1APF = N1CFP->getValueAPF(); 11987 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 11988 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 11989 // Only do the transform if the reciprocal is a legal fp immediate that 11990 // isn't too nasty (eg NaN, denormal, ...). 11991 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 11992 (!LegalOperations || 11993 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 11994 // backend)... we should handle this gracefully after Legalize. 11995 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || 11996 TLI.isOperationLegal(ISD::ConstantFP, VT) || 11997 TLI.isFPImmLegal(Recip, VT, ForCodeSize))) 11998 return DAG.getNode(ISD::FMUL, DL, VT, N0, 11999 DAG.getConstantFP(Recip, DL, VT), Flags); 12000 } 12001 12002 // If this FDIV is part of a reciprocal square root, it may be folded 12003 // into a target-specific square root estimate instruction. 12004 if (N1.getOpcode() == ISD::FSQRT) { 12005 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) { 12006 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 12007 } 12008 } else if (N1.getOpcode() == ISD::FP_EXTEND && 12009 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 12010 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 12011 Flags)) { 12012 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 12013 AddToWorklist(RV.getNode()); 12014 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 12015 } 12016 } else if (N1.getOpcode() == ISD::FP_ROUND && 12017 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 12018 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0).getOperand(0), 12019 Flags)) { 12020 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 12021 AddToWorklist(RV.getNode()); 12022 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 12023 } 12024 } else if (N1.getOpcode() == ISD::FMUL) { 12025 // Look through an FMUL. Even though this won't remove the FDIV directly, 12026 // it's still worthwhile to get rid of the FSQRT if possible. 12027 SDValue SqrtOp; 12028 SDValue OtherOp; 12029 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 12030 SqrtOp = N1.getOperand(0); 12031 OtherOp = N1.getOperand(1); 12032 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 12033 SqrtOp = N1.getOperand(1); 12034 OtherOp = N1.getOperand(0); 12035 } 12036 if (SqrtOp.getNode()) { 12037 // We found a FSQRT, so try to make this fold: 12038 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y) 12039 if (SDValue RV = buildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) { 12040 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags); 12041 AddToWorklist(RV.getNode()); 12042 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 12043 } 12044 } 12045 } 12046 12047 // Fold into a reciprocal estimate and multiply instead of a real divide. 12048 if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) { 12049 AddToWorklist(RV.getNode()); 12050 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags); 12051 } 12052 } 12053 12054 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 12055 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options, 12056 ForCodeSize)) { 12057 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options, 12058 ForCodeSize)) { 12059 // Both can be negated for free, check to see if at least one is cheaper 12060 // negated. 12061 if (LHSNeg == 2 || RHSNeg == 2) 12062 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, 12063 GetNegatedExpression(N0, DAG, LegalOperations, 12064 ForCodeSize), 12065 GetNegatedExpression(N1, DAG, LegalOperations, 12066 ForCodeSize), 12067 Flags); 12068 } 12069 } 12070 12071 if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N)) 12072 return CombineRepeatedDivisors; 12073 12074 return SDValue(); 12075 } 12076 12077 SDValue DAGCombiner::visitFREM(SDNode *N) { 12078 SDValue N0 = N->getOperand(0); 12079 SDValue N1 = N->getOperand(1); 12080 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 12081 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 12082 EVT VT = N->getValueType(0); 12083 12084 // fold (frem c1, c2) -> fmod(c1,c2) 12085 if (N0CFP && N1CFP) 12086 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1, N->getFlags()); 12087 12088 if (SDValue NewSel = foldBinOpIntoSelect(N)) 12089 return NewSel; 12090 12091 return SDValue(); 12092 } 12093 12094 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 12095 SDNodeFlags Flags = N->getFlags(); 12096 if (!DAG.getTarget().Options.UnsafeFPMath && 12097 !Flags.hasApproximateFuncs()) 12098 return SDValue(); 12099 12100 SDValue N0 = N->getOperand(0); 12101 if (TLI.isFsqrtCheap(N0, DAG)) 12102 return SDValue(); 12103 12104 // FSQRT nodes have flags that propagate to the created nodes. 12105 return buildSqrtEstimate(N0, Flags); 12106 } 12107 12108 /// copysign(x, fp_extend(y)) -> copysign(x, y) 12109 /// copysign(x, fp_round(y)) -> copysign(x, y) 12110 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 12111 SDValue N1 = N->getOperand(1); 12112 if ((N1.getOpcode() == ISD::FP_EXTEND || 12113 N1.getOpcode() == ISD::FP_ROUND)) { 12114 // Do not optimize out type conversion of f128 type yet. 12115 // For some targets like x86_64, configuration is changed to keep one f128 12116 // value in one SSE register, but instruction selection cannot handle 12117 // FCOPYSIGN on SSE registers yet. 12118 EVT N1VT = N1->getValueType(0); 12119 EVT N1Op0VT = N1->getOperand(0).getValueType(); 12120 return (N1VT == N1Op0VT || N1Op0VT != MVT::f128); 12121 } 12122 return false; 12123 } 12124 12125 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 12126 SDValue N0 = N->getOperand(0); 12127 SDValue N1 = N->getOperand(1); 12128 bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0); 12129 bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1); 12130 EVT VT = N->getValueType(0); 12131 12132 if (N0CFP && N1CFP) // Constant fold 12133 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 12134 12135 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N->getOperand(1))) { 12136 const APFloat &V = N1C->getValueAPF(); 12137 // copysign(x, c1) -> fabs(x) iff ispos(c1) 12138 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 12139 if (!V.isNegative()) { 12140 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 12141 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 12142 } else { 12143 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 12144 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 12145 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 12146 } 12147 } 12148 12149 // copysign(fabs(x), y) -> copysign(x, y) 12150 // copysign(fneg(x), y) -> copysign(x, y) 12151 // copysign(copysign(x,z), y) -> copysign(x, y) 12152 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 12153 N0.getOpcode() == ISD::FCOPYSIGN) 12154 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 12155 12156 // copysign(x, abs(y)) -> abs(x) 12157 if (N1.getOpcode() == ISD::FABS) 12158 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 12159 12160 // copysign(x, copysign(y,z)) -> copysign(x, z) 12161 if (N1.getOpcode() == ISD::FCOPYSIGN) 12162 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 12163 12164 // copysign(x, fp_extend(y)) -> copysign(x, y) 12165 // copysign(x, fp_round(y)) -> copysign(x, y) 12166 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 12167 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 12168 12169 return SDValue(); 12170 } 12171 12172 SDValue DAGCombiner::visitFPOW(SDNode *N) { 12173 ConstantFPSDNode *ExponentC = isConstOrConstSplatFP(N->getOperand(1)); 12174 if (!ExponentC) 12175 return SDValue(); 12176 12177 // Try to convert x ** (1/3) into cube root. 12178 // TODO: Handle the various flavors of long double. 12179 // TODO: Since we're approximating, we don't need an exact 1/3 exponent. 12180 // Some range near 1/3 should be fine. 12181 EVT VT = N->getValueType(0); 12182 if ((VT == MVT::f32 && ExponentC->getValueAPF().isExactlyValue(1.0f/3.0f)) || 12183 (VT == MVT::f64 && ExponentC->getValueAPF().isExactlyValue(1.0/3.0))) { 12184 // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0. 12185 // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf. 12186 // pow(-val, 1/3) = nan; cbrt(-val) = -num. 12187 // For regular numbers, rounding may cause the results to differ. 12188 // Therefore, we require { nsz ninf nnan afn } for this transform. 12189 // TODO: We could select out the special cases if we don't have nsz/ninf. 12190 SDNodeFlags Flags = N->getFlags(); 12191 if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || !Flags.hasNoNaNs() || 12192 !Flags.hasApproximateFuncs()) 12193 return SDValue(); 12194 12195 // Do not create a cbrt() libcall if the target does not have it, and do not 12196 // turn a pow that has lowering support into a cbrt() libcall. 12197 if (!DAG.getLibInfo().has(LibFunc_cbrt) || 12198 (!DAG.getTargetLoweringInfo().isOperationExpand(ISD::FPOW, VT) && 12199 DAG.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT, VT))) 12200 return SDValue(); 12201 12202 return DAG.getNode(ISD::FCBRT, SDLoc(N), VT, N->getOperand(0), Flags); 12203 } 12204 12205 // Try to convert x ** (1/4) and x ** (3/4) into square roots. 12206 // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case. 12207 // TODO: This could be extended (using a target hook) to handle smaller 12208 // power-of-2 fractional exponents. 12209 bool ExponentIs025 = ExponentC->getValueAPF().isExactlyValue(0.25); 12210 bool ExponentIs075 = ExponentC->getValueAPF().isExactlyValue(0.75); 12211 if (ExponentIs025 || ExponentIs075) { 12212 // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0. 12213 // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN. 12214 // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0. 12215 // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) = NaN. 12216 // For regular numbers, rounding may cause the results to differ. 12217 // Therefore, we require { nsz ninf afn } for this transform. 12218 // TODO: We could select out the special cases if we don't have nsz/ninf. 12219 SDNodeFlags Flags = N->getFlags(); 12220 12221 // We only need no signed zeros for the 0.25 case. 12222 if ((!Flags.hasNoSignedZeros() && ExponentIs025) || !Flags.hasNoInfs() || 12223 !Flags.hasApproximateFuncs()) 12224 return SDValue(); 12225 12226 // Don't double the number of libcalls. We are trying to inline fast code. 12227 if (!DAG.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT, VT)) 12228 return SDValue(); 12229 12230 // Assume that libcalls are the smallest code. 12231 // TODO: This restriction should probably be lifted for vectors. 12232 if (DAG.getMachineFunction().getFunction().hasOptSize()) 12233 return SDValue(); 12234 12235 // pow(X, 0.25) --> sqrt(sqrt(X)) 12236 SDLoc DL(N); 12237 SDValue Sqrt = DAG.getNode(ISD::FSQRT, DL, VT, N->getOperand(0), Flags); 12238 SDValue SqrtSqrt = DAG.getNode(ISD::FSQRT, DL, VT, Sqrt, Flags); 12239 if (ExponentIs025) 12240 return SqrtSqrt; 12241 // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X)) 12242 return DAG.getNode(ISD::FMUL, DL, VT, Sqrt, SqrtSqrt, Flags); 12243 } 12244 12245 return SDValue(); 12246 } 12247 12248 static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG, 12249 const TargetLowering &TLI) { 12250 // This optimization is guarded by a function attribute because it may produce 12251 // unexpected results. Ie, programs may be relying on the platform-specific 12252 // undefined behavior when the float-to-int conversion overflows. 12253 const Function &F = DAG.getMachineFunction().getFunction(); 12254 Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow"); 12255 if (StrictOverflow.getValueAsString().equals("false")) 12256 return SDValue(); 12257 12258 // We only do this if the target has legal ftrunc. Otherwise, we'd likely be 12259 // replacing casts with a libcall. We also must be allowed to ignore -0.0 12260 // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer 12261 // conversions would return +0.0. 12262 // FIXME: We should be able to use node-level FMF here. 12263 // TODO: If strict math, should we use FABS (+ range check for signed cast)? 12264 EVT VT = N->getValueType(0); 12265 if (!TLI.isOperationLegal(ISD::FTRUNC, VT) || 12266 !DAG.getTarget().Options.NoSignedZerosFPMath) 12267 return SDValue(); 12268 12269 // fptosi/fptoui round towards zero, so converting from FP to integer and 12270 // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X 12271 SDValue N0 = N->getOperand(0); 12272 if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT && 12273 N0.getOperand(0).getValueType() == VT) 12274 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 12275 12276 if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT && 12277 N0.getOperand(0).getValueType() == VT) 12278 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 12279 12280 return SDValue(); 12281 } 12282 12283 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 12284 SDValue N0 = N->getOperand(0); 12285 EVT VT = N->getValueType(0); 12286 EVT OpVT = N0.getValueType(); 12287 12288 // fold (sint_to_fp c1) -> c1fp 12289 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 12290 // ...but only if the target supports immediate floating-point values 12291 (!LegalOperations || 12292 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 12293 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 12294 12295 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 12296 // but UINT_TO_FP is legal on this target, try to convert. 12297 if (!hasOperation(ISD::SINT_TO_FP, OpVT) && 12298 hasOperation(ISD::UINT_TO_FP, OpVT)) { 12299 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 12300 if (DAG.SignBitIsZero(N0)) 12301 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 12302 } 12303 12304 // The next optimizations are desirable only if SELECT_CC can be lowered. 12305 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 12306 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 12307 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 12308 !VT.isVector() && 12309 (!LegalOperations || 12310 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 12311 SDLoc DL(N); 12312 SDValue Ops[] = 12313 { N0.getOperand(0), N0.getOperand(1), 12314 DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 12315 N0.getOperand(2) }; 12316 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 12317 } 12318 12319 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 12320 // (select_cc x, y, 1.0, 0.0,, cc) 12321 if (N0.getOpcode() == ISD::ZERO_EXTEND && 12322 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() && 12323 (!LegalOperations || 12324 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 12325 SDLoc DL(N); 12326 SDValue Ops[] = 12327 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1), 12328 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 12329 N0.getOperand(0).getOperand(2) }; 12330 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 12331 } 12332 } 12333 12334 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 12335 return FTrunc; 12336 12337 return SDValue(); 12338 } 12339 12340 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 12341 SDValue N0 = N->getOperand(0); 12342 EVT VT = N->getValueType(0); 12343 EVT OpVT = N0.getValueType(); 12344 12345 // fold (uint_to_fp c1) -> c1fp 12346 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 12347 // ...but only if the target supports immediate floating-point values 12348 (!LegalOperations || 12349 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 12350 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 12351 12352 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 12353 // but SINT_TO_FP is legal on this target, try to convert. 12354 if (!hasOperation(ISD::UINT_TO_FP, OpVT) && 12355 hasOperation(ISD::SINT_TO_FP, OpVT)) { 12356 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 12357 if (DAG.SignBitIsZero(N0)) 12358 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 12359 } 12360 12361 // The next optimizations are desirable only if SELECT_CC can be lowered. 12362 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) { 12363 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc) 12364 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 12365 (!LegalOperations || 12366 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 12367 SDLoc DL(N); 12368 SDValue Ops[] = 12369 { N0.getOperand(0), N0.getOperand(1), 12370 DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT), 12371 N0.getOperand(2) }; 12372 return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops); 12373 } 12374 } 12375 12376 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 12377 return FTrunc; 12378 12379 return SDValue(); 12380 } 12381 12382 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 12383 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 12384 SDValue N0 = N->getOperand(0); 12385 EVT VT = N->getValueType(0); 12386 12387 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 12388 return SDValue(); 12389 12390 SDValue Src = N0.getOperand(0); 12391 EVT SrcVT = Src.getValueType(); 12392 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 12393 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 12394 12395 // We can safely assume the conversion won't overflow the output range, 12396 // because (for example) (uint8_t)18293.f is undefined behavior. 12397 12398 // Since we can assume the conversion won't overflow, our decision as to 12399 // whether the input will fit in the float should depend on the minimum 12400 // of the input range and output range. 12401 12402 // This means this is also safe for a signed input and unsigned output, since 12403 // a negative input would lead to undefined behavior. 12404 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 12405 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 12406 unsigned ActualSize = std::min(InputSize, OutputSize); 12407 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 12408 12409 // We can only fold away the float conversion if the input range can be 12410 // represented exactly in the float range. 12411 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 12412 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 12413 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 12414 : ISD::ZERO_EXTEND; 12415 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 12416 } 12417 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 12418 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 12419 return DAG.getBitcast(VT, Src); 12420 } 12421 return SDValue(); 12422 } 12423 12424 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 12425 SDValue N0 = N->getOperand(0); 12426 EVT VT = N->getValueType(0); 12427 12428 // fold (fp_to_sint c1fp) -> c1 12429 if (isConstantFPBuildVectorOrConstantFP(N0)) 12430 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 12431 12432 return FoldIntToFPToInt(N, DAG); 12433 } 12434 12435 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 12436 SDValue N0 = N->getOperand(0); 12437 EVT VT = N->getValueType(0); 12438 12439 // fold (fp_to_uint c1fp) -> c1 12440 if (isConstantFPBuildVectorOrConstantFP(N0)) 12441 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 12442 12443 return FoldIntToFPToInt(N, DAG); 12444 } 12445 12446 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 12447 SDValue N0 = N->getOperand(0); 12448 SDValue N1 = N->getOperand(1); 12449 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 12450 EVT VT = N->getValueType(0); 12451 12452 // fold (fp_round c1fp) -> c1fp 12453 if (N0CFP) 12454 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 12455 12456 // fold (fp_round (fp_extend x)) -> x 12457 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 12458 return N0.getOperand(0); 12459 12460 // fold (fp_round (fp_round x)) -> (fp_round x) 12461 if (N0.getOpcode() == ISD::FP_ROUND) { 12462 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 12463 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 12464 12465 // Skip this folding if it results in an fp_round from f80 to f16. 12466 // 12467 // f80 to f16 always generates an expensive (and as yet, unimplemented) 12468 // libcall to __truncxfhf2 instead of selecting native f16 conversion 12469 // instructions from f32 or f64. Moreover, the first (value-preserving) 12470 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 12471 // x86. 12472 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 12473 return SDValue(); 12474 12475 // If the first fp_round isn't a value preserving truncation, it might 12476 // introduce a tie in the second fp_round, that wouldn't occur in the 12477 // single-step fp_round we want to fold to. 12478 // In other words, double rounding isn't the same as rounding. 12479 // Also, this is a value preserving truncation iff both fp_round's are. 12480 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 12481 SDLoc DL(N); 12482 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 12483 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 12484 } 12485 } 12486 12487 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 12488 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 12489 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 12490 N0.getOperand(0), N1); 12491 AddToWorklist(Tmp.getNode()); 12492 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 12493 Tmp, N0.getOperand(1)); 12494 } 12495 12496 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 12497 return NewVSel; 12498 12499 return SDValue(); 12500 } 12501 12502 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) { 12503 SDValue N0 = N->getOperand(0); 12504 EVT VT = N->getValueType(0); 12505 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 12506 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 12507 12508 // fold (fp_round_inreg c1fp) -> c1fp 12509 if (N0CFP && isTypeLegal(EVT)) { 12510 SDLoc DL(N); 12511 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT); 12512 return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round); 12513 } 12514 12515 return SDValue(); 12516 } 12517 12518 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 12519 SDValue N0 = N->getOperand(0); 12520 EVT VT = N->getValueType(0); 12521 12522 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 12523 if (N->hasOneUse() && 12524 N->use_begin()->getOpcode() == ISD::FP_ROUND) 12525 return SDValue(); 12526 12527 // fold (fp_extend c1fp) -> c1fp 12528 if (isConstantFPBuildVectorOrConstantFP(N0)) 12529 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 12530 12531 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 12532 if (N0.getOpcode() == ISD::FP16_TO_FP && 12533 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 12534 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 12535 12536 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 12537 // value of X. 12538 if (N0.getOpcode() == ISD::FP_ROUND 12539 && N0.getConstantOperandVal(1) == 1) { 12540 SDValue In = N0.getOperand(0); 12541 if (In.getValueType() == VT) return In; 12542 if (VT.bitsLT(In.getValueType())) 12543 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 12544 In, N0.getOperand(1)); 12545 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 12546 } 12547 12548 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 12549 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12550 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 12551 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12552 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 12553 LN0->getChain(), 12554 LN0->getBasePtr(), N0.getValueType(), 12555 LN0->getMemOperand()); 12556 CombineTo(N, ExtLoad); 12557 CombineTo(N0.getNode(), 12558 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 12559 N0.getValueType(), ExtLoad, 12560 DAG.getIntPtrConstant(1, SDLoc(N0))), 12561 ExtLoad.getValue(1)); 12562 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12563 } 12564 12565 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 12566 return NewVSel; 12567 12568 return SDValue(); 12569 } 12570 12571 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 12572 SDValue N0 = N->getOperand(0); 12573 EVT VT = N->getValueType(0); 12574 12575 // fold (fceil c1) -> fceil(c1) 12576 if (isConstantFPBuildVectorOrConstantFP(N0)) 12577 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 12578 12579 return SDValue(); 12580 } 12581 12582 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 12583 SDValue N0 = N->getOperand(0); 12584 EVT VT = N->getValueType(0); 12585 12586 // fold (ftrunc c1) -> ftrunc(c1) 12587 if (isConstantFPBuildVectorOrConstantFP(N0)) 12588 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 12589 12590 // fold ftrunc (known rounded int x) -> x 12591 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is 12592 // likely to be generated to extract integer from a rounded floating value. 12593 switch (N0.getOpcode()) { 12594 default: break; 12595 case ISD::FRINT: 12596 case ISD::FTRUNC: 12597 case ISD::FNEARBYINT: 12598 case ISD::FFLOOR: 12599 case ISD::FCEIL: 12600 return N0; 12601 } 12602 12603 return SDValue(); 12604 } 12605 12606 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 12607 SDValue N0 = N->getOperand(0); 12608 EVT VT = N->getValueType(0); 12609 12610 // fold (ffloor c1) -> ffloor(c1) 12611 if (isConstantFPBuildVectorOrConstantFP(N0)) 12612 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 12613 12614 return SDValue(); 12615 } 12616 12617 // FIXME: FNEG and FABS have a lot in common; refactor. 12618 SDValue DAGCombiner::visitFNEG(SDNode *N) { 12619 SDValue N0 = N->getOperand(0); 12620 EVT VT = N->getValueType(0); 12621 12622 // Constant fold FNEG. 12623 if (isConstantFPBuildVectorOrConstantFP(N0)) 12624 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 12625 12626 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(), 12627 &DAG.getTarget().Options, ForCodeSize)) 12628 return GetNegatedExpression(N0, DAG, LegalOperations, ForCodeSize); 12629 12630 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading 12631 // constant pool values. 12632 if (!TLI.isFNegFree(VT) && 12633 N0.getOpcode() == ISD::BITCAST && 12634 N0.getNode()->hasOneUse()) { 12635 SDValue Int = N0.getOperand(0); 12636 EVT IntVT = Int.getValueType(); 12637 if (IntVT.isInteger() && !IntVT.isVector()) { 12638 APInt SignMask; 12639 if (N0.getValueType().isVector()) { 12640 // For a vector, get a mask such as 0x80... per scalar element 12641 // and splat it. 12642 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 12643 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 12644 } else { 12645 // For a scalar, just generate 0x80... 12646 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 12647 } 12648 SDLoc DL0(N0); 12649 Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int, 12650 DAG.getConstant(SignMask, DL0, IntVT)); 12651 AddToWorklist(Int.getNode()); 12652 return DAG.getBitcast(VT, Int); 12653 } 12654 } 12655 12656 // (fneg (fmul c, x)) -> (fmul -c, x) 12657 if (N0.getOpcode() == ISD::FMUL && 12658 (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) { 12659 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 12660 if (CFP1) { 12661 APFloat CVal = CFP1->getValueAPF(); 12662 CVal.changeSign(); 12663 if (Level >= AfterLegalizeDAG && 12664 (TLI.isFPImmLegal(CVal, VT, ForCodeSize) || 12665 TLI.isOperationLegal(ISD::ConstantFP, VT))) 12666 return DAG.getNode( 12667 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), 12668 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)), 12669 N0->getFlags()); 12670 } 12671 } 12672 12673 return SDValue(); 12674 } 12675 12676 static SDValue visitFMinMax(SelectionDAG &DAG, SDNode *N, 12677 APFloat (*Op)(const APFloat &, const APFloat &)) { 12678 SDValue N0 = N->getOperand(0); 12679 SDValue N1 = N->getOperand(1); 12680 EVT VT = N->getValueType(0); 12681 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 12682 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 12683 12684 if (N0CFP && N1CFP) { 12685 const APFloat &C0 = N0CFP->getValueAPF(); 12686 const APFloat &C1 = N1CFP->getValueAPF(); 12687 return DAG.getConstantFP(Op(C0, C1), SDLoc(N), VT); 12688 } 12689 12690 // Canonicalize to constant on RHS. 12691 if (isConstantFPBuildVectorOrConstantFP(N0) && 12692 !isConstantFPBuildVectorOrConstantFP(N1)) 12693 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 12694 12695 return SDValue(); 12696 } 12697 12698 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 12699 return visitFMinMax(DAG, N, minnum); 12700 } 12701 12702 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 12703 return visitFMinMax(DAG, N, maxnum); 12704 } 12705 12706 SDValue DAGCombiner::visitFMINIMUM(SDNode *N) { 12707 return visitFMinMax(DAG, N, minimum); 12708 } 12709 12710 SDValue DAGCombiner::visitFMAXIMUM(SDNode *N) { 12711 return visitFMinMax(DAG, N, maximum); 12712 } 12713 12714 SDValue DAGCombiner::visitFABS(SDNode *N) { 12715 SDValue N0 = N->getOperand(0); 12716 EVT VT = N->getValueType(0); 12717 12718 // fold (fabs c1) -> fabs(c1) 12719 if (isConstantFPBuildVectorOrConstantFP(N0)) 12720 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 12721 12722 // fold (fabs (fabs x)) -> (fabs x) 12723 if (N0.getOpcode() == ISD::FABS) 12724 return N->getOperand(0); 12725 12726 // fold (fabs (fneg x)) -> (fabs x) 12727 // fold (fabs (fcopysign x, y)) -> (fabs x) 12728 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 12729 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 12730 12731 // fabs(bitcast(x)) -> bitcast(x & ~sign) to avoid constant pool loads. 12732 if (!TLI.isFAbsFree(VT) && N0.getOpcode() == ISD::BITCAST && N0.hasOneUse()) { 12733 SDValue Int = N0.getOperand(0); 12734 EVT IntVT = Int.getValueType(); 12735 if (IntVT.isInteger() && !IntVT.isVector()) { 12736 APInt SignMask; 12737 if (N0.getValueType().isVector()) { 12738 // For a vector, get a mask such as 0x7f... per scalar element 12739 // and splat it. 12740 SignMask = ~APInt::getSignMask(N0.getScalarValueSizeInBits()); 12741 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 12742 } else { 12743 // For a scalar, just generate 0x7f... 12744 SignMask = ~APInt::getSignMask(IntVT.getSizeInBits()); 12745 } 12746 SDLoc DL(N0); 12747 Int = DAG.getNode(ISD::AND, DL, IntVT, Int, 12748 DAG.getConstant(SignMask, DL, IntVT)); 12749 AddToWorklist(Int.getNode()); 12750 return DAG.getBitcast(N->getValueType(0), Int); 12751 } 12752 } 12753 12754 return SDValue(); 12755 } 12756 12757 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 12758 SDValue Chain = N->getOperand(0); 12759 SDValue N1 = N->getOperand(1); 12760 SDValue N2 = N->getOperand(2); 12761 12762 // If N is a constant we could fold this into a fallthrough or unconditional 12763 // branch. However that doesn't happen very often in normal code, because 12764 // Instcombine/SimplifyCFG should have handled the available opportunities. 12765 // If we did this folding here, it would be necessary to update the 12766 // MachineBasicBlock CFG, which is awkward. 12767 12768 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 12769 // on the target. 12770 if (N1.getOpcode() == ISD::SETCC && 12771 TLI.isOperationLegalOrCustom(ISD::BR_CC, 12772 N1.getOperand(0).getValueType())) { 12773 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 12774 Chain, N1.getOperand(2), 12775 N1.getOperand(0), N1.getOperand(1), N2); 12776 } 12777 12778 if (N1.hasOneUse()) { 12779 if (SDValue NewN1 = rebuildSetCC(N1)) 12780 return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, NewN1, N2); 12781 } 12782 12783 return SDValue(); 12784 } 12785 12786 SDValue DAGCombiner::rebuildSetCC(SDValue N) { 12787 if (N.getOpcode() == ISD::SRL || 12788 (N.getOpcode() == ISD::TRUNCATE && 12789 (N.getOperand(0).hasOneUse() && 12790 N.getOperand(0).getOpcode() == ISD::SRL))) { 12791 // Look pass the truncate. 12792 if (N.getOpcode() == ISD::TRUNCATE) 12793 N = N.getOperand(0); 12794 12795 // Match this pattern so that we can generate simpler code: 12796 // 12797 // %a = ... 12798 // %b = and i32 %a, 2 12799 // %c = srl i32 %b, 1 12800 // brcond i32 %c ... 12801 // 12802 // into 12803 // 12804 // %a = ... 12805 // %b = and i32 %a, 2 12806 // %c = setcc eq %b, 0 12807 // brcond %c ... 12808 // 12809 // This applies only when the AND constant value has one bit set and the 12810 // SRL constant is equal to the log2 of the AND constant. The back-end is 12811 // smart enough to convert the result into a TEST/JMP sequence. 12812 SDValue Op0 = N.getOperand(0); 12813 SDValue Op1 = N.getOperand(1); 12814 12815 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) { 12816 SDValue AndOp1 = Op0.getOperand(1); 12817 12818 if (AndOp1.getOpcode() == ISD::Constant) { 12819 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 12820 12821 if (AndConst.isPowerOf2() && 12822 cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) { 12823 SDLoc DL(N); 12824 return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()), 12825 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 12826 ISD::SETNE); 12827 } 12828 } 12829 } 12830 } 12831 12832 // Transform br(xor(x, y)) -> br(x != y) 12833 // Transform br(xor(xor(x,y), 1)) -> br (x == y) 12834 if (N.getOpcode() == ISD::XOR) { 12835 // Because we may call this on a speculatively constructed 12836 // SimplifiedSetCC Node, we need to simplify this node first. 12837 // Ideally this should be folded into SimplifySetCC and not 12838 // here. For now, grab a handle to N so we don't lose it from 12839 // replacements interal to the visit. 12840 HandleSDNode XORHandle(N); 12841 while (N.getOpcode() == ISD::XOR) { 12842 SDValue Tmp = visitXOR(N.getNode()); 12843 // No simplification done. 12844 if (!Tmp.getNode()) 12845 break; 12846 // Returning N is form in-visit replacement that may invalidated 12847 // N. Grab value from Handle. 12848 if (Tmp.getNode() == N.getNode()) 12849 N = XORHandle.getValue(); 12850 else // Node simplified. Try simplifying again. 12851 N = Tmp; 12852 } 12853 12854 if (N.getOpcode() != ISD::XOR) 12855 return N; 12856 12857 SDNode *TheXor = N.getNode(); 12858 12859 SDValue Op0 = TheXor->getOperand(0); 12860 SDValue Op1 = TheXor->getOperand(1); 12861 12862 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 12863 bool Equal = false; 12864 if (isOneConstant(Op0) && Op0.hasOneUse() && 12865 Op0.getOpcode() == ISD::XOR) { 12866 TheXor = Op0.getNode(); 12867 Equal = true; 12868 } 12869 12870 EVT SetCCVT = N.getValueType(); 12871 if (LegalTypes) 12872 SetCCVT = getSetCCResultType(SetCCVT); 12873 // Replace the uses of XOR with SETCC 12874 return DAG.getSetCC(SDLoc(TheXor), SetCCVT, Op0, Op1, 12875 Equal ? ISD::SETEQ : ISD::SETNE); 12876 } 12877 } 12878 12879 return SDValue(); 12880 } 12881 12882 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 12883 // 12884 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 12885 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 12886 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 12887 12888 // If N is a constant we could fold this into a fallthrough or unconditional 12889 // branch. However that doesn't happen very often in normal code, because 12890 // Instcombine/SimplifyCFG should have handled the available opportunities. 12891 // If we did this folding here, it would be necessary to update the 12892 // MachineBasicBlock CFG, which is awkward. 12893 12894 // Use SimplifySetCC to simplify SETCC's. 12895 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 12896 CondLHS, CondRHS, CC->get(), SDLoc(N), 12897 false); 12898 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 12899 12900 // fold to a simpler setcc 12901 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 12902 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 12903 N->getOperand(0), Simp.getOperand(2), 12904 Simp.getOperand(0), Simp.getOperand(1), 12905 N->getOperand(4)); 12906 12907 return SDValue(); 12908 } 12909 12910 /// Return true if 'Use' is a load or a store that uses N as its base pointer 12911 /// and that N may be folded in the load / store addressing mode. 12912 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, 12913 SelectionDAG &DAG, 12914 const TargetLowering &TLI) { 12915 EVT VT; 12916 unsigned AS; 12917 12918 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 12919 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 12920 return false; 12921 VT = LD->getMemoryVT(); 12922 AS = LD->getAddressSpace(); 12923 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 12924 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 12925 return false; 12926 VT = ST->getMemoryVT(); 12927 AS = ST->getAddressSpace(); 12928 } else 12929 return false; 12930 12931 TargetLowering::AddrMode AM; 12932 if (N->getOpcode() == ISD::ADD) { 12933 AM.HasBaseReg = true; 12934 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12935 if (Offset) 12936 // [reg +/- imm] 12937 AM.BaseOffs = Offset->getSExtValue(); 12938 else 12939 // [reg +/- reg] 12940 AM.Scale = 1; 12941 } else if (N->getOpcode() == ISD::SUB) { 12942 AM.HasBaseReg = true; 12943 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12944 if (Offset) 12945 // [reg +/- imm] 12946 AM.BaseOffs = -Offset->getSExtValue(); 12947 else 12948 // [reg +/- reg] 12949 AM.Scale = 1; 12950 } else 12951 return false; 12952 12953 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 12954 VT.getTypeForEVT(*DAG.getContext()), AS); 12955 } 12956 12957 /// Try turning a load/store into a pre-indexed load/store when the base 12958 /// pointer is an add or subtract and it has other uses besides the load/store. 12959 /// After the transformation, the new indexed load/store has effectively folded 12960 /// the add/subtract in and all of its other uses are redirected to the 12961 /// new load/store. 12962 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 12963 if (Level < AfterLegalizeDAG) 12964 return false; 12965 12966 bool isLoad = true; 12967 SDValue Ptr; 12968 EVT VT; 12969 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 12970 if (LD->isIndexed()) 12971 return false; 12972 VT = LD->getMemoryVT(); 12973 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) && 12974 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT)) 12975 return false; 12976 Ptr = LD->getBasePtr(); 12977 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 12978 if (ST->isIndexed()) 12979 return false; 12980 VT = ST->getMemoryVT(); 12981 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) && 12982 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT)) 12983 return false; 12984 Ptr = ST->getBasePtr(); 12985 isLoad = false; 12986 } else { 12987 return false; 12988 } 12989 12990 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 12991 // out. There is no reason to make this a preinc/predec. 12992 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 12993 Ptr.getNode()->hasOneUse()) 12994 return false; 12995 12996 // Ask the target to do addressing mode selection. 12997 SDValue BasePtr; 12998 SDValue Offset; 12999 ISD::MemIndexedMode AM = ISD::UNINDEXED; 13000 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 13001 return false; 13002 13003 // Backends without true r+i pre-indexed forms may need to pass a 13004 // constant base with a variable offset so that constant coercion 13005 // will work with the patterns in canonical form. 13006 bool Swapped = false; 13007 if (isa<ConstantSDNode>(BasePtr)) { 13008 std::swap(BasePtr, Offset); 13009 Swapped = true; 13010 } 13011 13012 // Don't create a indexed load / store with zero offset. 13013 if (isNullConstant(Offset)) 13014 return false; 13015 13016 // Try turning it into a pre-indexed load / store except when: 13017 // 1) The new base ptr is a frame index. 13018 // 2) If N is a store and the new base ptr is either the same as or is a 13019 // predecessor of the value being stored. 13020 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 13021 // that would create a cycle. 13022 // 4) All uses are load / store ops that use it as old base ptr. 13023 13024 // Check #1. Preinc'ing a frame index would require copying the stack pointer 13025 // (plus the implicit offset) to a register to preinc anyway. 13026 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 13027 return false; 13028 13029 // Check #2. 13030 if (!isLoad) { 13031 SDValue Val = cast<StoreSDNode>(N)->getValue(); 13032 13033 // Would require a copy. 13034 if (Val == BasePtr) 13035 return false; 13036 13037 // Would create a cycle. 13038 if (Val == Ptr || Ptr->isPredecessorOf(Val.getNode())) 13039 return false; 13040 } 13041 13042 // Caches for hasPredecessorHelper. 13043 SmallPtrSet<const SDNode *, 32> Visited; 13044 SmallVector<const SDNode *, 16> Worklist; 13045 Worklist.push_back(N); 13046 13047 // If the offset is a constant, there may be other adds of constants that 13048 // can be folded with this one. We should do this to avoid having to keep 13049 // a copy of the original base pointer. 13050 SmallVector<SDNode *, 16> OtherUses; 13051 if (isa<ConstantSDNode>(Offset)) 13052 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 13053 UE = BasePtr.getNode()->use_end(); 13054 UI != UE; ++UI) { 13055 SDUse &Use = UI.getUse(); 13056 // Skip the use that is Ptr and uses of other results from BasePtr's 13057 // node (important for nodes that return multiple results). 13058 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 13059 continue; 13060 13061 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 13062 continue; 13063 13064 if (Use.getUser()->getOpcode() != ISD::ADD && 13065 Use.getUser()->getOpcode() != ISD::SUB) { 13066 OtherUses.clear(); 13067 break; 13068 } 13069 13070 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 13071 if (!isa<ConstantSDNode>(Op1)) { 13072 OtherUses.clear(); 13073 break; 13074 } 13075 13076 // FIXME: In some cases, we can be smarter about this. 13077 if (Op1.getValueType() != Offset.getValueType()) { 13078 OtherUses.clear(); 13079 break; 13080 } 13081 13082 OtherUses.push_back(Use.getUser()); 13083 } 13084 13085 if (Swapped) 13086 std::swap(BasePtr, Offset); 13087 13088 // Now check for #3 and #4. 13089 bool RealUse = false; 13090 13091 for (SDNode *Use : Ptr.getNode()->uses()) { 13092 if (Use == N) 13093 continue; 13094 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 13095 return false; 13096 13097 // If Ptr may be folded in addressing mode of other use, then it's 13098 // not profitable to do this transformation. 13099 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 13100 RealUse = true; 13101 } 13102 13103 if (!RealUse) 13104 return false; 13105 13106 SDValue Result; 13107 if (isLoad) 13108 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 13109 BasePtr, Offset, AM); 13110 else 13111 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 13112 BasePtr, Offset, AM); 13113 ++PreIndexedNodes; 13114 ++NodesCombined; 13115 LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: "; 13116 Result.getNode()->dump(&DAG); dbgs() << '\n'); 13117 WorklistRemover DeadNodes(*this); 13118 if (isLoad) { 13119 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 13120 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 13121 } else { 13122 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 13123 } 13124 13125 // Finally, since the node is now dead, remove it from the graph. 13126 deleteAndRecombine(N); 13127 13128 if (Swapped) 13129 std::swap(BasePtr, Offset); 13130 13131 // Replace other uses of BasePtr that can be updated to use Ptr 13132 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 13133 unsigned OffsetIdx = 1; 13134 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 13135 OffsetIdx = 0; 13136 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 13137 BasePtr.getNode() && "Expected BasePtr operand"); 13138 13139 // We need to replace ptr0 in the following expression: 13140 // x0 * offset0 + y0 * ptr0 = t0 13141 // knowing that 13142 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 13143 // 13144 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 13145 // indexed load/store and the expression that needs to be re-written. 13146 // 13147 // Therefore, we have: 13148 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 13149 13150 ConstantSDNode *CN = 13151 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 13152 int X0, X1, Y0, Y1; 13153 const APInt &Offset0 = CN->getAPIntValue(); 13154 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 13155 13156 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 13157 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 13158 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 13159 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 13160 13161 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 13162 13163 APInt CNV = Offset0; 13164 if (X0 < 0) CNV = -CNV; 13165 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 13166 else CNV = CNV - Offset1; 13167 13168 SDLoc DL(OtherUses[i]); 13169 13170 // We can now generate the new expression. 13171 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 13172 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0); 13173 13174 SDValue NewUse = DAG.getNode(Opcode, 13175 DL, 13176 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 13177 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 13178 deleteAndRecombine(OtherUses[i]); 13179 } 13180 13181 // Replace the uses of Ptr with uses of the updated base value. 13182 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0)); 13183 deleteAndRecombine(Ptr.getNode()); 13184 AddToWorklist(Result.getNode()); 13185 13186 return true; 13187 } 13188 13189 /// Try to combine a load/store with a add/sub of the base pointer node into a 13190 /// post-indexed load/store. The transformation folded the add/subtract into the 13191 /// new indexed load/store effectively and all of its uses are redirected to the 13192 /// new load/store. 13193 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 13194 if (Level < AfterLegalizeDAG) 13195 return false; 13196 13197 bool isLoad = true; 13198 SDValue Ptr; 13199 EVT VT; 13200 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13201 if (LD->isIndexed()) 13202 return false; 13203 VT = LD->getMemoryVT(); 13204 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) && 13205 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT)) 13206 return false; 13207 Ptr = LD->getBasePtr(); 13208 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13209 if (ST->isIndexed()) 13210 return false; 13211 VT = ST->getMemoryVT(); 13212 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) && 13213 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT)) 13214 return false; 13215 Ptr = ST->getBasePtr(); 13216 isLoad = false; 13217 } else { 13218 return false; 13219 } 13220 13221 if (Ptr.getNode()->hasOneUse()) 13222 return false; 13223 13224 for (SDNode *Op : Ptr.getNode()->uses()) { 13225 if (Op == N || 13226 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)) 13227 continue; 13228 13229 SDValue BasePtr; 13230 SDValue Offset; 13231 ISD::MemIndexedMode AM = ISD::UNINDEXED; 13232 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) { 13233 // Don't create a indexed load / store with zero offset. 13234 if (isNullConstant(Offset)) 13235 continue; 13236 13237 // Try turning it into a post-indexed load / store except when 13238 // 1) All uses are load / store ops that use it as base ptr (and 13239 // it may be folded as addressing mmode). 13240 // 2) Op must be independent of N, i.e. Op is neither a predecessor 13241 // nor a successor of N. Otherwise, if Op is folded that would 13242 // create a cycle. 13243 13244 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 13245 continue; 13246 13247 // Check for #1. 13248 bool TryNext = false; 13249 for (SDNode *Use : BasePtr.getNode()->uses()) { 13250 if (Use == Ptr.getNode()) 13251 continue; 13252 13253 // If all the uses are load / store addresses, then don't do the 13254 // transformation. 13255 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){ 13256 bool RealUse = false; 13257 for (SDNode *UseUse : Use->uses()) { 13258 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 13259 RealUse = true; 13260 } 13261 13262 if (!RealUse) { 13263 TryNext = true; 13264 break; 13265 } 13266 } 13267 } 13268 13269 if (TryNext) 13270 continue; 13271 13272 // Check for #2. 13273 SmallPtrSet<const SDNode *, 32> Visited; 13274 SmallVector<const SDNode *, 8> Worklist; 13275 // Ptr is predecessor to both N and Op. 13276 Visited.insert(Ptr.getNode()); 13277 Worklist.push_back(N); 13278 Worklist.push_back(Op); 13279 if (!SDNode::hasPredecessorHelper(N, Visited, Worklist) && 13280 !SDNode::hasPredecessorHelper(Op, Visited, Worklist)) { 13281 SDValue Result = isLoad 13282 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N), 13283 BasePtr, Offset, AM) 13284 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N), 13285 BasePtr, Offset, AM); 13286 ++PostIndexedNodes; 13287 ++NodesCombined; 13288 LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG); 13289 dbgs() << "\nWith: "; Result.getNode()->dump(&DAG); 13290 dbgs() << '\n'); 13291 WorklistRemover DeadNodes(*this); 13292 if (isLoad) { 13293 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 13294 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 13295 } else { 13296 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 13297 } 13298 13299 // Finally, since the node is now dead, remove it from the graph. 13300 deleteAndRecombine(N); 13301 13302 // Replace the uses of Use with uses of the updated base value. 13303 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 13304 Result.getValue(isLoad ? 1 : 0)); 13305 deleteAndRecombine(Op); 13306 return true; 13307 } 13308 } 13309 } 13310 13311 return false; 13312 } 13313 13314 /// Return the base-pointer arithmetic from an indexed \p LD. 13315 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 13316 ISD::MemIndexedMode AM = LD->getAddressingMode(); 13317 assert(AM != ISD::UNINDEXED); 13318 SDValue BP = LD->getOperand(1); 13319 SDValue Inc = LD->getOperand(2); 13320 13321 // Some backends use TargetConstants for load offsets, but don't expect 13322 // TargetConstants in general ADD nodes. We can convert these constants into 13323 // regular Constants (if the constant is not opaque). 13324 assert((Inc.getOpcode() != ISD::TargetConstant || 13325 !cast<ConstantSDNode>(Inc)->isOpaque()) && 13326 "Cannot split out indexing using opaque target constants"); 13327 if (Inc.getOpcode() == ISD::TargetConstant) { 13328 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 13329 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 13330 ConstInc->getValueType(0)); 13331 } 13332 13333 unsigned Opc = 13334 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 13335 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 13336 } 13337 13338 static inline int numVectorEltsOrZero(EVT T) { 13339 return T.isVector() ? T.getVectorNumElements() : 0; 13340 } 13341 13342 bool DAGCombiner::getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val) { 13343 Val = ST->getValue(); 13344 EVT STType = Val.getValueType(); 13345 EVT STMemType = ST->getMemoryVT(); 13346 if (STType == STMemType) 13347 return true; 13348 if (isTypeLegal(STMemType)) 13349 return false; // fail. 13350 if (STType.isFloatingPoint() && STMemType.isFloatingPoint() && 13351 TLI.isOperationLegal(ISD::FTRUNC, STMemType)) { 13352 Val = DAG.getNode(ISD::FTRUNC, SDLoc(ST), STMemType, Val); 13353 return true; 13354 } 13355 if (numVectorEltsOrZero(STType) == numVectorEltsOrZero(STMemType) && 13356 STType.isInteger() && STMemType.isInteger()) { 13357 Val = DAG.getNode(ISD::TRUNCATE, SDLoc(ST), STMemType, Val); 13358 return true; 13359 } 13360 if (STType.getSizeInBits() == STMemType.getSizeInBits()) { 13361 Val = DAG.getBitcast(STMemType, Val); 13362 return true; 13363 } 13364 return false; // fail. 13365 } 13366 13367 bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val) { 13368 EVT LDMemType = LD->getMemoryVT(); 13369 EVT LDType = LD->getValueType(0); 13370 assert(Val.getValueType() == LDMemType && 13371 "Attempting to extend value of non-matching type"); 13372 if (LDType == LDMemType) 13373 return true; 13374 if (LDMemType.isInteger() && LDType.isInteger()) { 13375 switch (LD->getExtensionType()) { 13376 case ISD::NON_EXTLOAD: 13377 Val = DAG.getBitcast(LDType, Val); 13378 return true; 13379 case ISD::EXTLOAD: 13380 Val = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LD), LDType, Val); 13381 return true; 13382 case ISD::SEXTLOAD: 13383 Val = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(LD), LDType, Val); 13384 return true; 13385 case ISD::ZEXTLOAD: 13386 Val = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(LD), LDType, Val); 13387 return true; 13388 } 13389 } 13390 return false; 13391 } 13392 13393 SDValue DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode *LD) { 13394 if (OptLevel == CodeGenOpt::None || LD->isVolatile()) 13395 return SDValue(); 13396 SDValue Chain = LD->getOperand(0); 13397 StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain.getNode()); 13398 if (!ST || ST->isVolatile()) 13399 return SDValue(); 13400 13401 EVT LDType = LD->getValueType(0); 13402 EVT LDMemType = LD->getMemoryVT(); 13403 EVT STMemType = ST->getMemoryVT(); 13404 EVT STType = ST->getValue().getValueType(); 13405 13406 BaseIndexOffset BasePtrLD = BaseIndexOffset::match(LD, DAG); 13407 BaseIndexOffset BasePtrST = BaseIndexOffset::match(ST, DAG); 13408 int64_t Offset; 13409 if (!BasePtrST.equalBaseIndex(BasePtrLD, DAG, Offset)) 13410 return SDValue(); 13411 13412 // Normalize for Endianness. After this Offset=0 will denote that the least 13413 // significant bit in the loaded value maps to the least significant bit in 13414 // the stored value). With Offset=n (for n > 0) the loaded value starts at the 13415 // n:th least significant byte of the stored value. 13416 if (DAG.getDataLayout().isBigEndian()) 13417 Offset = (STMemType.getStoreSizeInBits() - 13418 LDMemType.getStoreSizeInBits()) / 8 - Offset; 13419 13420 // Check that the stored value cover all bits that are loaded. 13421 bool STCoversLD = 13422 (Offset >= 0) && 13423 (Offset * 8 + LDMemType.getSizeInBits() <= STMemType.getSizeInBits()); 13424 13425 auto ReplaceLd = [&](LoadSDNode *LD, SDValue Val, SDValue Chain) -> SDValue { 13426 if (LD->isIndexed()) { 13427 bool IsSub = (LD->getAddressingMode() == ISD::PRE_DEC || 13428 LD->getAddressingMode() == ISD::POST_DEC); 13429 unsigned Opc = IsSub ? ISD::SUB : ISD::ADD; 13430 SDValue Idx = DAG.getNode(Opc, SDLoc(LD), LD->getOperand(1).getValueType(), 13431 LD->getOperand(1), LD->getOperand(2)); 13432 SDValue Ops[] = {Val, Idx, Chain}; 13433 return CombineTo(LD, Ops, 3); 13434 } 13435 return CombineTo(LD, Val, Chain); 13436 }; 13437 13438 if (!STCoversLD) 13439 return SDValue(); 13440 13441 // Memory as copy space (potentially masked). 13442 if (Offset == 0 && LDType == STType && STMemType == LDMemType) { 13443 // Simple case: Direct non-truncating forwarding 13444 if (LDType.getSizeInBits() == LDMemType.getSizeInBits()) 13445 return ReplaceLd(LD, ST->getValue(), Chain); 13446 // Can we model the truncate and extension with an and mask? 13447 if (STType.isInteger() && LDMemType.isInteger() && !STType.isVector() && 13448 !LDMemType.isVector() && LD->getExtensionType() != ISD::SEXTLOAD) { 13449 // Mask to size of LDMemType 13450 auto Mask = 13451 DAG.getConstant(APInt::getLowBitsSet(STType.getSizeInBits(), 13452 STMemType.getSizeInBits()), 13453 SDLoc(ST), STType); 13454 auto Val = DAG.getNode(ISD::AND, SDLoc(LD), LDType, ST->getValue(), Mask); 13455 return ReplaceLd(LD, Val, Chain); 13456 } 13457 } 13458 13459 // TODO: Deal with nonzero offset. 13460 if (LD->getBasePtr().isUndef() || Offset != 0) 13461 return SDValue(); 13462 // Model necessary truncations / extenstions. 13463 SDValue Val; 13464 // Truncate Value To Stored Memory Size. 13465 do { 13466 if (!getTruncatedStoreValue(ST, Val)) 13467 continue; 13468 if (!isTypeLegal(LDMemType)) 13469 continue; 13470 if (STMemType != LDMemType) { 13471 // TODO: Support vectors? This requires extract_subvector/bitcast. 13472 if (!STMemType.isVector() && !LDMemType.isVector() && 13473 STMemType.isInteger() && LDMemType.isInteger()) 13474 Val = DAG.getNode(ISD::TRUNCATE, SDLoc(LD), LDMemType, Val); 13475 else 13476 continue; 13477 } 13478 if (!extendLoadedValueToExtension(LD, Val)) 13479 continue; 13480 return ReplaceLd(LD, Val, Chain); 13481 } while (false); 13482 13483 // On failure, cleanup dead nodes we may have created. 13484 if (Val->use_empty()) 13485 deleteAndRecombine(Val.getNode()); 13486 return SDValue(); 13487 } 13488 13489 SDValue DAGCombiner::visitLOAD(SDNode *N) { 13490 LoadSDNode *LD = cast<LoadSDNode>(N); 13491 SDValue Chain = LD->getChain(); 13492 SDValue Ptr = LD->getBasePtr(); 13493 13494 // If load is not volatile and there are no uses of the loaded value (and 13495 // the updated indexed value in case of indexed loads), change uses of the 13496 // chain value into uses of the chain input (i.e. delete the dead load). 13497 if (!LD->isVolatile()) { 13498 if (N->getValueType(1) == MVT::Other) { 13499 // Unindexed loads. 13500 if (!N->hasAnyUseOfValue(0)) { 13501 // It's not safe to use the two value CombineTo variant here. e.g. 13502 // v1, chain2 = load chain1, loc 13503 // v2, chain3 = load chain2, loc 13504 // v3 = add v2, c 13505 // Now we replace use of chain2 with chain1. This makes the second load 13506 // isomorphic to the one we are deleting, and thus makes this load live. 13507 LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG); 13508 dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG); 13509 dbgs() << "\n"); 13510 WorklistRemover DeadNodes(*this); 13511 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 13512 AddUsersToWorklist(Chain.getNode()); 13513 if (N->use_empty()) 13514 deleteAndRecombine(N); 13515 13516 return SDValue(N, 0); // Return N so it doesn't get rechecked! 13517 } 13518 } else { 13519 // Indexed loads. 13520 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 13521 13522 // If this load has an opaque TargetConstant offset, then we cannot split 13523 // the indexing into an add/sub directly (that TargetConstant may not be 13524 // valid for a different type of node, and we cannot convert an opaque 13525 // target constant into a regular constant). 13526 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant && 13527 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque(); 13528 13529 if (!N->hasAnyUseOfValue(0) && 13530 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) { 13531 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 13532 SDValue Index; 13533 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) { 13534 Index = SplitIndexingFromLoad(LD); 13535 // Try to fold the base pointer arithmetic into subsequent loads and 13536 // stores. 13537 AddUsersToWorklist(N); 13538 } else 13539 Index = DAG.getUNDEF(N->getValueType(1)); 13540 LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG); 13541 dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG); 13542 dbgs() << " and 2 other values\n"); 13543 WorklistRemover DeadNodes(*this); 13544 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 13545 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 13546 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 13547 deleteAndRecombine(N); 13548 return SDValue(N, 0); // Return N so it doesn't get rechecked! 13549 } 13550 } 13551 } 13552 13553 // If this load is directly stored, replace the load value with the stored 13554 // value. 13555 if (auto V = ForwardStoreValueToDirectLoad(LD)) 13556 return V; 13557 13558 // Try to infer better alignment information than the load already has. 13559 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) { 13560 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 13561 if (Align > LD->getAlignment() && LD->getSrcValueOffset() % Align == 0) { 13562 SDValue NewLoad = DAG.getExtLoad( 13563 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 13564 LD->getPointerInfo(), LD->getMemoryVT(), Align, 13565 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 13566 // NewLoad will always be N as we are only refining the alignment 13567 assert(NewLoad.getNode() == N); 13568 (void)NewLoad; 13569 } 13570 } 13571 } 13572 13573 if (LD->isUnindexed()) { 13574 // Walk up chain skipping non-aliasing memory nodes. 13575 SDValue BetterChain = FindBetterChain(LD, Chain); 13576 13577 // If there is a better chain. 13578 if (Chain != BetterChain) { 13579 SDValue ReplLoad; 13580 13581 // Replace the chain to void dependency. 13582 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 13583 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 13584 BetterChain, Ptr, LD->getMemOperand()); 13585 } else { 13586 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 13587 LD->getValueType(0), 13588 BetterChain, Ptr, LD->getMemoryVT(), 13589 LD->getMemOperand()); 13590 } 13591 13592 // Create token factor to keep old chain connected. 13593 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 13594 MVT::Other, Chain, ReplLoad.getValue(1)); 13595 13596 // Replace uses with load result and token factor 13597 return CombineTo(N, ReplLoad.getValue(0), Token); 13598 } 13599 } 13600 13601 // Try transforming N to an indexed load. 13602 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 13603 return SDValue(N, 0); 13604 13605 // Try to slice up N to more direct loads if the slices are mapped to 13606 // different register banks or pairing can take place. 13607 if (SliceUpLoad(N)) 13608 return SDValue(N, 0); 13609 13610 return SDValue(); 13611 } 13612 13613 namespace { 13614 13615 /// Helper structure used to slice a load in smaller loads. 13616 /// Basically a slice is obtained from the following sequence: 13617 /// Origin = load Ty1, Base 13618 /// Shift = srl Ty1 Origin, CstTy Amount 13619 /// Inst = trunc Shift to Ty2 13620 /// 13621 /// Then, it will be rewritten into: 13622 /// Slice = load SliceTy, Base + SliceOffset 13623 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 13624 /// 13625 /// SliceTy is deduced from the number of bits that are actually used to 13626 /// build Inst. 13627 struct LoadedSlice { 13628 /// Helper structure used to compute the cost of a slice. 13629 struct Cost { 13630 /// Are we optimizing for code size. 13631 bool ForCodeSize; 13632 13633 /// Various cost. 13634 unsigned Loads = 0; 13635 unsigned Truncates = 0; 13636 unsigned CrossRegisterBanksCopies = 0; 13637 unsigned ZExts = 0; 13638 unsigned Shift = 0; 13639 13640 Cost(bool ForCodeSize = false) : ForCodeSize(ForCodeSize) {} 13641 13642 /// Get the cost of one isolated slice. 13643 Cost(const LoadedSlice &LS, bool ForCodeSize = false) 13644 : ForCodeSize(ForCodeSize), Loads(1) { 13645 EVT TruncType = LS.Inst->getValueType(0); 13646 EVT LoadedType = LS.getLoadedType(); 13647 if (TruncType != LoadedType && 13648 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 13649 ZExts = 1; 13650 } 13651 13652 /// Account for slicing gain in the current cost. 13653 /// Slicing provide a few gains like removing a shift or a 13654 /// truncate. This method allows to grow the cost of the original 13655 /// load with the gain from this slice. 13656 void addSliceGain(const LoadedSlice &LS) { 13657 // Each slice saves a truncate. 13658 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 13659 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 13660 LS.Inst->getValueType(0))) 13661 ++Truncates; 13662 // If there is a shift amount, this slice gets rid of it. 13663 if (LS.Shift) 13664 ++Shift; 13665 // If this slice can merge a cross register bank copy, account for it. 13666 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 13667 ++CrossRegisterBanksCopies; 13668 } 13669 13670 Cost &operator+=(const Cost &RHS) { 13671 Loads += RHS.Loads; 13672 Truncates += RHS.Truncates; 13673 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 13674 ZExts += RHS.ZExts; 13675 Shift += RHS.Shift; 13676 return *this; 13677 } 13678 13679 bool operator==(const Cost &RHS) const { 13680 return Loads == RHS.Loads && Truncates == RHS.Truncates && 13681 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 13682 ZExts == RHS.ZExts && Shift == RHS.Shift; 13683 } 13684 13685 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 13686 13687 bool operator<(const Cost &RHS) const { 13688 // Assume cross register banks copies are as expensive as loads. 13689 // FIXME: Do we want some more target hooks? 13690 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 13691 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 13692 // Unless we are optimizing for code size, consider the 13693 // expensive operation first. 13694 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 13695 return ExpensiveOpsLHS < ExpensiveOpsRHS; 13696 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 13697 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 13698 } 13699 13700 bool operator>(const Cost &RHS) const { return RHS < *this; } 13701 13702 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 13703 13704 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 13705 }; 13706 13707 // The last instruction that represent the slice. This should be a 13708 // truncate instruction. 13709 SDNode *Inst; 13710 13711 // The original load instruction. 13712 LoadSDNode *Origin; 13713 13714 // The right shift amount in bits from the original load. 13715 unsigned Shift; 13716 13717 // The DAG from which Origin came from. 13718 // This is used to get some contextual information about legal types, etc. 13719 SelectionDAG *DAG; 13720 13721 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 13722 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 13723 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 13724 13725 /// Get the bits used in a chunk of bits \p BitWidth large. 13726 /// \return Result is \p BitWidth and has used bits set to 1 and 13727 /// not used bits set to 0. 13728 APInt getUsedBits() const { 13729 // Reproduce the trunc(lshr) sequence: 13730 // - Start from the truncated value. 13731 // - Zero extend to the desired bit width. 13732 // - Shift left. 13733 assert(Origin && "No original load to compare against."); 13734 unsigned BitWidth = Origin->getValueSizeInBits(0); 13735 assert(Inst && "This slice is not bound to an instruction"); 13736 assert(Inst->getValueSizeInBits(0) <= BitWidth && 13737 "Extracted slice is bigger than the whole type!"); 13738 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 13739 UsedBits.setAllBits(); 13740 UsedBits = UsedBits.zext(BitWidth); 13741 UsedBits <<= Shift; 13742 return UsedBits; 13743 } 13744 13745 /// Get the size of the slice to be loaded in bytes. 13746 unsigned getLoadedSize() const { 13747 unsigned SliceSize = getUsedBits().countPopulation(); 13748 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 13749 return SliceSize / 8; 13750 } 13751 13752 /// Get the type that will be loaded for this slice. 13753 /// Note: This may not be the final type for the slice. 13754 EVT getLoadedType() const { 13755 assert(DAG && "Missing context"); 13756 LLVMContext &Ctxt = *DAG->getContext(); 13757 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 13758 } 13759 13760 /// Get the alignment of the load used for this slice. 13761 unsigned getAlignment() const { 13762 unsigned Alignment = Origin->getAlignment(); 13763 unsigned Offset = getOffsetFromBase(); 13764 if (Offset != 0) 13765 Alignment = MinAlign(Alignment, Alignment + Offset); 13766 return Alignment; 13767 } 13768 13769 /// Check if this slice can be rewritten with legal operations. 13770 bool isLegal() const { 13771 // An invalid slice is not legal. 13772 if (!Origin || !Inst || !DAG) 13773 return false; 13774 13775 // Offsets are for indexed load only, we do not handle that. 13776 if (!Origin->getOffset().isUndef()) 13777 return false; 13778 13779 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 13780 13781 // Check that the type is legal. 13782 EVT SliceType = getLoadedType(); 13783 if (!TLI.isTypeLegal(SliceType)) 13784 return false; 13785 13786 // Check that the load is legal for this type. 13787 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 13788 return false; 13789 13790 // Check that the offset can be computed. 13791 // 1. Check its type. 13792 EVT PtrType = Origin->getBasePtr().getValueType(); 13793 if (PtrType == MVT::Untyped || PtrType.isExtended()) 13794 return false; 13795 13796 // 2. Check that it fits in the immediate. 13797 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 13798 return false; 13799 13800 // 3. Check that the computation is legal. 13801 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 13802 return false; 13803 13804 // Check that the zext is legal if it needs one. 13805 EVT TruncateType = Inst->getValueType(0); 13806 if (TruncateType != SliceType && 13807 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 13808 return false; 13809 13810 return true; 13811 } 13812 13813 /// Get the offset in bytes of this slice in the original chunk of 13814 /// bits. 13815 /// \pre DAG != nullptr. 13816 uint64_t getOffsetFromBase() const { 13817 assert(DAG && "Missing context."); 13818 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 13819 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 13820 uint64_t Offset = Shift / 8; 13821 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 13822 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 13823 "The size of the original loaded type is not a multiple of a" 13824 " byte."); 13825 // If Offset is bigger than TySizeInBytes, it means we are loading all 13826 // zeros. This should have been optimized before in the process. 13827 assert(TySizeInBytes > Offset && 13828 "Invalid shift amount for given loaded size"); 13829 if (IsBigEndian) 13830 Offset = TySizeInBytes - Offset - getLoadedSize(); 13831 return Offset; 13832 } 13833 13834 /// Generate the sequence of instructions to load the slice 13835 /// represented by this object and redirect the uses of this slice to 13836 /// this new sequence of instructions. 13837 /// \pre this->Inst && this->Origin are valid Instructions and this 13838 /// object passed the legal check: LoadedSlice::isLegal returned true. 13839 /// \return The last instruction of the sequence used to load the slice. 13840 SDValue loadSlice() const { 13841 assert(Inst && Origin && "Unable to replace a non-existing slice."); 13842 const SDValue &OldBaseAddr = Origin->getBasePtr(); 13843 SDValue BaseAddr = OldBaseAddr; 13844 // Get the offset in that chunk of bytes w.r.t. the endianness. 13845 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 13846 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 13847 if (Offset) { 13848 // BaseAddr = BaseAddr + Offset. 13849 EVT ArithType = BaseAddr.getValueType(); 13850 SDLoc DL(Origin); 13851 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 13852 DAG->getConstant(Offset, DL, ArithType)); 13853 } 13854 13855 // Create the type of the loaded slice according to its size. 13856 EVT SliceType = getLoadedType(); 13857 13858 // Create the load for the slice. 13859 SDValue LastInst = 13860 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 13861 Origin->getPointerInfo().getWithOffset(Offset), 13862 getAlignment(), Origin->getMemOperand()->getFlags()); 13863 // If the final type is not the same as the loaded type, this means that 13864 // we have to pad with zero. Create a zero extend for that. 13865 EVT FinalType = Inst->getValueType(0); 13866 if (SliceType != FinalType) 13867 LastInst = 13868 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 13869 return LastInst; 13870 } 13871 13872 /// Check if this slice can be merged with an expensive cross register 13873 /// bank copy. E.g., 13874 /// i = load i32 13875 /// f = bitcast i32 i to float 13876 bool canMergeExpensiveCrossRegisterBankCopy() const { 13877 if (!Inst || !Inst->hasOneUse()) 13878 return false; 13879 SDNode *Use = *Inst->use_begin(); 13880 if (Use->getOpcode() != ISD::BITCAST) 13881 return false; 13882 assert(DAG && "Missing context"); 13883 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 13884 EVT ResVT = Use->getValueType(0); 13885 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT()); 13886 const TargetRegisterClass *ArgRC = 13887 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT()); 13888 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 13889 return false; 13890 13891 // At this point, we know that we perform a cross-register-bank copy. 13892 // Check if it is expensive. 13893 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 13894 // Assume bitcasts are cheap, unless both register classes do not 13895 // explicitly share a common sub class. 13896 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 13897 return false; 13898 13899 // Check if it will be merged with the load. 13900 // 1. Check the alignment constraint. 13901 unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment( 13902 ResVT.getTypeForEVT(*DAG->getContext())); 13903 13904 if (RequiredAlignment > getAlignment()) 13905 return false; 13906 13907 // 2. Check that the load is a legal operation for that type. 13908 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 13909 return false; 13910 13911 // 3. Check that we do not have a zext in the way. 13912 if (Inst->getValueType(0) != getLoadedType()) 13913 return false; 13914 13915 return true; 13916 } 13917 }; 13918 13919 } // end anonymous namespace 13920 13921 /// Check that all bits set in \p UsedBits form a dense region, i.e., 13922 /// \p UsedBits looks like 0..0 1..1 0..0. 13923 static bool areUsedBitsDense(const APInt &UsedBits) { 13924 // If all the bits are one, this is dense! 13925 if (UsedBits.isAllOnesValue()) 13926 return true; 13927 13928 // Get rid of the unused bits on the right. 13929 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 13930 // Get rid of the unused bits on the left. 13931 if (NarrowedUsedBits.countLeadingZeros()) 13932 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 13933 // Check that the chunk of bits is completely used. 13934 return NarrowedUsedBits.isAllOnesValue(); 13935 } 13936 13937 /// Check whether or not \p First and \p Second are next to each other 13938 /// in memory. This means that there is no hole between the bits loaded 13939 /// by \p First and the bits loaded by \p Second. 13940 static bool areSlicesNextToEachOther(const LoadedSlice &First, 13941 const LoadedSlice &Second) { 13942 assert(First.Origin == Second.Origin && First.Origin && 13943 "Unable to match different memory origins."); 13944 APInt UsedBits = First.getUsedBits(); 13945 assert((UsedBits & Second.getUsedBits()) == 0 && 13946 "Slices are not supposed to overlap."); 13947 UsedBits |= Second.getUsedBits(); 13948 return areUsedBitsDense(UsedBits); 13949 } 13950 13951 /// Adjust the \p GlobalLSCost according to the target 13952 /// paring capabilities and the layout of the slices. 13953 /// \pre \p GlobalLSCost should account for at least as many loads as 13954 /// there is in the slices in \p LoadedSlices. 13955 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 13956 LoadedSlice::Cost &GlobalLSCost) { 13957 unsigned NumberOfSlices = LoadedSlices.size(); 13958 // If there is less than 2 elements, no pairing is possible. 13959 if (NumberOfSlices < 2) 13960 return; 13961 13962 // Sort the slices so that elements that are likely to be next to each 13963 // other in memory are next to each other in the list. 13964 llvm::sort(LoadedSlices, [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 13965 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 13966 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 13967 }); 13968 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 13969 // First (resp. Second) is the first (resp. Second) potentially candidate 13970 // to be placed in a paired load. 13971 const LoadedSlice *First = nullptr; 13972 const LoadedSlice *Second = nullptr; 13973 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 13974 // Set the beginning of the pair. 13975 First = Second) { 13976 Second = &LoadedSlices[CurrSlice]; 13977 13978 // If First is NULL, it means we start a new pair. 13979 // Get to the next slice. 13980 if (!First) 13981 continue; 13982 13983 EVT LoadedType = First->getLoadedType(); 13984 13985 // If the types of the slices are different, we cannot pair them. 13986 if (LoadedType != Second->getLoadedType()) 13987 continue; 13988 13989 // Check if the target supplies paired loads for this type. 13990 unsigned RequiredAlignment = 0; 13991 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 13992 // move to the next pair, this type is hopeless. 13993 Second = nullptr; 13994 continue; 13995 } 13996 // Check if we meet the alignment requirement. 13997 if (RequiredAlignment > First->getAlignment()) 13998 continue; 13999 14000 // Check that both loads are next to each other in memory. 14001 if (!areSlicesNextToEachOther(*First, *Second)) 14002 continue; 14003 14004 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 14005 --GlobalLSCost.Loads; 14006 // Move to the next pair. 14007 Second = nullptr; 14008 } 14009 } 14010 14011 /// Check the profitability of all involved LoadedSlice. 14012 /// Currently, it is considered profitable if there is exactly two 14013 /// involved slices (1) which are (2) next to each other in memory, and 14014 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 14015 /// 14016 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 14017 /// the elements themselves. 14018 /// 14019 /// FIXME: When the cost model will be mature enough, we can relax 14020 /// constraints (1) and (2). 14021 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 14022 const APInt &UsedBits, bool ForCodeSize) { 14023 unsigned NumberOfSlices = LoadedSlices.size(); 14024 if (StressLoadSlicing) 14025 return NumberOfSlices > 1; 14026 14027 // Check (1). 14028 if (NumberOfSlices != 2) 14029 return false; 14030 14031 // Check (2). 14032 if (!areUsedBitsDense(UsedBits)) 14033 return false; 14034 14035 // Check (3). 14036 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 14037 // The original code has one big load. 14038 OrigCost.Loads = 1; 14039 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 14040 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 14041 // Accumulate the cost of all the slices. 14042 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 14043 GlobalSlicingCost += SliceCost; 14044 14045 // Account as cost in the original configuration the gain obtained 14046 // with the current slices. 14047 OrigCost.addSliceGain(LS); 14048 } 14049 14050 // If the target supports paired load, adjust the cost accordingly. 14051 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 14052 return OrigCost > GlobalSlicingCost; 14053 } 14054 14055 /// If the given load, \p LI, is used only by trunc or trunc(lshr) 14056 /// operations, split it in the various pieces being extracted. 14057 /// 14058 /// This sort of thing is introduced by SROA. 14059 /// This slicing takes care not to insert overlapping loads. 14060 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 14061 bool DAGCombiner::SliceUpLoad(SDNode *N) { 14062 if (Level < AfterLegalizeDAG) 14063 return false; 14064 14065 LoadSDNode *LD = cast<LoadSDNode>(N); 14066 if (LD->isVolatile() || !ISD::isNormalLoad(LD) || 14067 !LD->getValueType(0).isInteger()) 14068 return false; 14069 14070 // Keep track of already used bits to detect overlapping values. 14071 // In that case, we will just abort the transformation. 14072 APInt UsedBits(LD->getValueSizeInBits(0), 0); 14073 14074 SmallVector<LoadedSlice, 4> LoadedSlices; 14075 14076 // Check if this load is used as several smaller chunks of bits. 14077 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 14078 // of computation for each trunc. 14079 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 14080 UI != UIEnd; ++UI) { 14081 // Skip the uses of the chain. 14082 if (UI.getUse().getResNo() != 0) 14083 continue; 14084 14085 SDNode *User = *UI; 14086 unsigned Shift = 0; 14087 14088 // Check if this is a trunc(lshr). 14089 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 14090 isa<ConstantSDNode>(User->getOperand(1))) { 14091 Shift = User->getConstantOperandVal(1); 14092 User = *User->use_begin(); 14093 } 14094 14095 // At this point, User is a Truncate, iff we encountered, trunc or 14096 // trunc(lshr). 14097 if (User->getOpcode() != ISD::TRUNCATE) 14098 return false; 14099 14100 // The width of the type must be a power of 2 and greater than 8-bits. 14101 // Otherwise the load cannot be represented in LLVM IR. 14102 // Moreover, if we shifted with a non-8-bits multiple, the slice 14103 // will be across several bytes. We do not support that. 14104 unsigned Width = User->getValueSizeInBits(0); 14105 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 14106 return false; 14107 14108 // Build the slice for this chain of computations. 14109 LoadedSlice LS(User, LD, Shift, &DAG); 14110 APInt CurrentUsedBits = LS.getUsedBits(); 14111 14112 // Check if this slice overlaps with another. 14113 if ((CurrentUsedBits & UsedBits) != 0) 14114 return false; 14115 // Update the bits used globally. 14116 UsedBits |= CurrentUsedBits; 14117 14118 // Check if the new slice would be legal. 14119 if (!LS.isLegal()) 14120 return false; 14121 14122 // Record the slice. 14123 LoadedSlices.push_back(LS); 14124 } 14125 14126 // Abort slicing if it does not seem to be profitable. 14127 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 14128 return false; 14129 14130 ++SlicedLoads; 14131 14132 // Rewrite each chain to use an independent load. 14133 // By construction, each chain can be represented by a unique load. 14134 14135 // Prepare the argument for the new token factor for all the slices. 14136 SmallVector<SDValue, 8> ArgChains; 14137 for (SmallVectorImpl<LoadedSlice>::const_iterator 14138 LSIt = LoadedSlices.begin(), 14139 LSItEnd = LoadedSlices.end(); 14140 LSIt != LSItEnd; ++LSIt) { 14141 SDValue SliceInst = LSIt->loadSlice(); 14142 CombineTo(LSIt->Inst, SliceInst, true); 14143 if (SliceInst.getOpcode() != ISD::LOAD) 14144 SliceInst = SliceInst.getOperand(0); 14145 assert(SliceInst->getOpcode() == ISD::LOAD && 14146 "It takes more than a zext to get to the loaded slice!!"); 14147 ArgChains.push_back(SliceInst.getValue(1)); 14148 } 14149 14150 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 14151 ArgChains); 14152 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 14153 AddToWorklist(Chain.getNode()); 14154 return true; 14155 } 14156 14157 /// Check to see if V is (and load (ptr), imm), where the load is having 14158 /// specific bytes cleared out. If so, return the byte size being masked out 14159 /// and the shift amount. 14160 static std::pair<unsigned, unsigned> 14161 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 14162 std::pair<unsigned, unsigned> Result(0, 0); 14163 14164 // Check for the structure we're looking for. 14165 if (V->getOpcode() != ISD::AND || 14166 !isa<ConstantSDNode>(V->getOperand(1)) || 14167 !ISD::isNormalLoad(V->getOperand(0).getNode())) 14168 return Result; 14169 14170 // Check the chain and pointer. 14171 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 14172 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 14173 14174 // This only handles simple types. 14175 if (V.getValueType() != MVT::i16 && 14176 V.getValueType() != MVT::i32 && 14177 V.getValueType() != MVT::i64) 14178 return Result; 14179 14180 // Check the constant mask. Invert it so that the bits being masked out are 14181 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 14182 // follow the sign bit for uniformity. 14183 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 14184 unsigned NotMaskLZ = countLeadingZeros(NotMask); 14185 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 14186 unsigned NotMaskTZ = countTrailingZeros(NotMask); 14187 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 14188 if (NotMaskLZ == 64) return Result; // All zero mask. 14189 14190 // See if we have a continuous run of bits. If so, we have 0*1+0* 14191 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 14192 return Result; 14193 14194 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 14195 if (V.getValueType() != MVT::i64 && NotMaskLZ) 14196 NotMaskLZ -= 64-V.getValueSizeInBits(); 14197 14198 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 14199 switch (MaskedBytes) { 14200 case 1: 14201 case 2: 14202 case 4: break; 14203 default: return Result; // All one mask, or 5-byte mask. 14204 } 14205 14206 // Verify that the first bit starts at a multiple of mask so that the access 14207 // is aligned the same as the access width. 14208 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 14209 14210 // For narrowing to be valid, it must be the case that the load the 14211 // immediately preceding memory operation before the store. 14212 if (LD == Chain.getNode()) 14213 ; // ok. 14214 else if (Chain->getOpcode() == ISD::TokenFactor && 14215 SDValue(LD, 1).hasOneUse()) { 14216 // LD has only 1 chain use so they are no indirect dependencies. 14217 bool isOk = false; 14218 for (const SDValue &ChainOp : Chain->op_values()) 14219 if (ChainOp.getNode() == LD) { 14220 isOk = true; 14221 break; 14222 } 14223 if (!isOk) 14224 return Result; 14225 } else 14226 return Result; // Fail. 14227 14228 Result.first = MaskedBytes; 14229 Result.second = NotMaskTZ/8; 14230 return Result; 14231 } 14232 14233 /// Check to see if IVal is something that provides a value as specified by 14234 /// MaskInfo. If so, replace the specified store with a narrower store of 14235 /// truncated IVal. 14236 static SDNode * 14237 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 14238 SDValue IVal, StoreSDNode *St, 14239 DAGCombiner *DC) { 14240 unsigned NumBytes = MaskInfo.first; 14241 unsigned ByteShift = MaskInfo.second; 14242 SelectionDAG &DAG = DC->getDAG(); 14243 14244 // Check to see if IVal is all zeros in the part being masked in by the 'or' 14245 // that uses this. If not, this is not a replacement. 14246 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 14247 ByteShift*8, (ByteShift+NumBytes)*8); 14248 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr; 14249 14250 // Check that it is legal on the target to do this. It is legal if the new 14251 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 14252 // legalization. 14253 MVT VT = MVT::getIntegerVT(NumBytes*8); 14254 if (!DC->isTypeLegal(VT)) 14255 return nullptr; 14256 14257 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 14258 // shifted by ByteShift and truncated down to NumBytes. 14259 if (ByteShift) { 14260 SDLoc DL(IVal); 14261 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 14262 DAG.getConstant(ByteShift*8, DL, 14263 DC->getShiftAmountTy(IVal.getValueType()))); 14264 } 14265 14266 // Figure out the offset for the store and the alignment of the access. 14267 unsigned StOffset; 14268 unsigned NewAlign = St->getAlignment(); 14269 14270 if (DAG.getDataLayout().isLittleEndian()) 14271 StOffset = ByteShift; 14272 else 14273 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 14274 14275 SDValue Ptr = St->getBasePtr(); 14276 if (StOffset) { 14277 SDLoc DL(IVal); 14278 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), 14279 Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType())); 14280 NewAlign = MinAlign(NewAlign, StOffset); 14281 } 14282 14283 // Truncate down to the new size. 14284 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 14285 14286 ++OpsNarrowed; 14287 return DAG 14288 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 14289 St->getPointerInfo().getWithOffset(StOffset), NewAlign) 14290 .getNode(); 14291 } 14292 14293 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 14294 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 14295 /// narrowing the load and store if it would end up being a win for performance 14296 /// or code size. 14297 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 14298 StoreSDNode *ST = cast<StoreSDNode>(N); 14299 if (ST->isVolatile()) 14300 return SDValue(); 14301 14302 SDValue Chain = ST->getChain(); 14303 SDValue Value = ST->getValue(); 14304 SDValue Ptr = ST->getBasePtr(); 14305 EVT VT = Value.getValueType(); 14306 14307 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 14308 return SDValue(); 14309 14310 unsigned Opc = Value.getOpcode(); 14311 14312 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 14313 // is a byte mask indicating a consecutive number of bytes, check to see if 14314 // Y is known to provide just those bytes. If so, we try to replace the 14315 // load + replace + store sequence with a single (narrower) store, which makes 14316 // the load dead. 14317 if (Opc == ISD::OR) { 14318 std::pair<unsigned, unsigned> MaskedLoad; 14319 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 14320 if (MaskedLoad.first) 14321 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 14322 Value.getOperand(1), ST,this)) 14323 return SDValue(NewST, 0); 14324 14325 // Or is commutative, so try swapping X and Y. 14326 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 14327 if (MaskedLoad.first) 14328 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 14329 Value.getOperand(0), ST,this)) 14330 return SDValue(NewST, 0); 14331 } 14332 14333 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 14334 Value.getOperand(1).getOpcode() != ISD::Constant) 14335 return SDValue(); 14336 14337 SDValue N0 = Value.getOperand(0); 14338 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 14339 Chain == SDValue(N0.getNode(), 1)) { 14340 LoadSDNode *LD = cast<LoadSDNode>(N0); 14341 if (LD->getBasePtr() != Ptr || 14342 LD->getPointerInfo().getAddrSpace() != 14343 ST->getPointerInfo().getAddrSpace()) 14344 return SDValue(); 14345 14346 // Find the type to narrow it the load / op / store to. 14347 SDValue N1 = Value.getOperand(1); 14348 unsigned BitWidth = N1.getValueSizeInBits(); 14349 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 14350 if (Opc == ISD::AND) 14351 Imm ^= APInt::getAllOnesValue(BitWidth); 14352 if (Imm == 0 || Imm.isAllOnesValue()) 14353 return SDValue(); 14354 unsigned ShAmt = Imm.countTrailingZeros(); 14355 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 14356 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 14357 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 14358 // The narrowing should be profitable, the load/store operation should be 14359 // legal (or custom) and the store size should be equal to the NewVT width. 14360 while (NewBW < BitWidth && 14361 (NewVT.getStoreSizeInBits() != NewBW || 14362 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 14363 !TLI.isNarrowingProfitable(VT, NewVT))) { 14364 NewBW = NextPowerOf2(NewBW); 14365 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 14366 } 14367 if (NewBW >= BitWidth) 14368 return SDValue(); 14369 14370 // If the lsb changed does not start at the type bitwidth boundary, 14371 // start at the previous one. 14372 if (ShAmt % NewBW) 14373 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 14374 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 14375 std::min(BitWidth, ShAmt + NewBW)); 14376 if ((Imm & Mask) == Imm) { 14377 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 14378 if (Opc == ISD::AND) 14379 NewImm ^= APInt::getAllOnesValue(NewBW); 14380 uint64_t PtrOff = ShAmt / 8; 14381 // For big endian targets, we need to adjust the offset to the pointer to 14382 // load the correct bytes. 14383 if (DAG.getDataLayout().isBigEndian()) 14384 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 14385 14386 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff); 14387 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext()); 14388 if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy)) 14389 return SDValue(); 14390 14391 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD), 14392 Ptr.getValueType(), Ptr, 14393 DAG.getConstant(PtrOff, SDLoc(LD), 14394 Ptr.getValueType())); 14395 SDValue NewLD = 14396 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 14397 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 14398 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 14399 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 14400 DAG.getConstant(NewImm, SDLoc(Value), 14401 NewVT)); 14402 SDValue NewST = 14403 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 14404 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 14405 14406 AddToWorklist(NewPtr.getNode()); 14407 AddToWorklist(NewLD.getNode()); 14408 AddToWorklist(NewVal.getNode()); 14409 WorklistRemover DeadNodes(*this); 14410 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 14411 ++OpsNarrowed; 14412 return NewST; 14413 } 14414 } 14415 14416 return SDValue(); 14417 } 14418 14419 /// For a given floating point load / store pair, if the load value isn't used 14420 /// by any other operations, then consider transforming the pair to integer 14421 /// load / store operations if the target deems the transformation profitable. 14422 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 14423 StoreSDNode *ST = cast<StoreSDNode>(N); 14424 SDValue Chain = ST->getChain(); 14425 SDValue Value = ST->getValue(); 14426 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 14427 Value.hasOneUse() && 14428 Chain == SDValue(Value.getNode(), 1)) { 14429 LoadSDNode *LD = cast<LoadSDNode>(Value); 14430 EVT VT = LD->getMemoryVT(); 14431 if (!VT.isFloatingPoint() || 14432 VT != ST->getMemoryVT() || 14433 LD->isNonTemporal() || 14434 ST->isNonTemporal() || 14435 LD->getPointerInfo().getAddrSpace() != 0 || 14436 ST->getPointerInfo().getAddrSpace() != 0) 14437 return SDValue(); 14438 14439 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 14440 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 14441 !TLI.isOperationLegal(ISD::STORE, IntVT) || 14442 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 14443 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT)) 14444 return SDValue(); 14445 14446 unsigned LDAlign = LD->getAlignment(); 14447 unsigned STAlign = ST->getAlignment(); 14448 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext()); 14449 unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy); 14450 if (LDAlign < ABIAlign || STAlign < ABIAlign) 14451 return SDValue(); 14452 14453 SDValue NewLD = 14454 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 14455 LD->getPointerInfo(), LDAlign); 14456 14457 SDValue NewST = 14458 DAG.getStore(NewLD.getValue(1), SDLoc(N), NewLD, ST->getBasePtr(), 14459 ST->getPointerInfo(), STAlign); 14460 14461 AddToWorklist(NewLD.getNode()); 14462 AddToWorklist(NewST.getNode()); 14463 WorklistRemover DeadNodes(*this); 14464 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 14465 ++LdStFP2Int; 14466 return NewST; 14467 } 14468 14469 return SDValue(); 14470 } 14471 14472 // This is a helper function for visitMUL to check the profitability 14473 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 14474 // MulNode is the original multiply, AddNode is (add x, c1), 14475 // and ConstNode is c2. 14476 // 14477 // If the (add x, c1) has multiple uses, we could increase 14478 // the number of adds if we make this transformation. 14479 // It would only be worth doing this if we can remove a 14480 // multiply in the process. Check for that here. 14481 // To illustrate: 14482 // (A + c1) * c3 14483 // (A + c2) * c3 14484 // We're checking for cases where we have common "c3 * A" expressions. 14485 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 14486 SDValue &AddNode, 14487 SDValue &ConstNode) { 14488 APInt Val; 14489 14490 // If the add only has one use, this would be OK to do. 14491 if (AddNode.getNode()->hasOneUse()) 14492 return true; 14493 14494 // Walk all the users of the constant with which we're multiplying. 14495 for (SDNode *Use : ConstNode->uses()) { 14496 if (Use == MulNode) // This use is the one we're on right now. Skip it. 14497 continue; 14498 14499 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 14500 SDNode *OtherOp; 14501 SDNode *MulVar = AddNode.getOperand(0).getNode(); 14502 14503 // OtherOp is what we're multiplying against the constant. 14504 if (Use->getOperand(0) == ConstNode) 14505 OtherOp = Use->getOperand(1).getNode(); 14506 else 14507 OtherOp = Use->getOperand(0).getNode(); 14508 14509 // Check to see if multiply is with the same operand of our "add". 14510 // 14511 // ConstNode = CONST 14512 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 14513 // ... 14514 // AddNode = (A + c1) <-- MulVar is A. 14515 // = AddNode * ConstNode <-- current visiting instruction. 14516 // 14517 // If we make this transformation, we will have a common 14518 // multiply (ConstNode * A) that we can save. 14519 if (OtherOp == MulVar) 14520 return true; 14521 14522 // Now check to see if a future expansion will give us a common 14523 // multiply. 14524 // 14525 // ConstNode = CONST 14526 // AddNode = (A + c1) 14527 // ... = AddNode * ConstNode <-- current visiting instruction. 14528 // ... 14529 // OtherOp = (A + c2) 14530 // Use = OtherOp * ConstNode <-- visiting Use. 14531 // 14532 // If we make this transformation, we will have a common 14533 // multiply (CONST * A) after we also do the same transformation 14534 // to the "t2" instruction. 14535 if (OtherOp->getOpcode() == ISD::ADD && 14536 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 14537 OtherOp->getOperand(0).getNode() == MulVar) 14538 return true; 14539 } 14540 } 14541 14542 // Didn't find a case where this would be profitable. 14543 return false; 14544 } 14545 14546 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 14547 unsigned NumStores) { 14548 SmallVector<SDValue, 8> Chains; 14549 SmallPtrSet<const SDNode *, 8> Visited; 14550 SDLoc StoreDL(StoreNodes[0].MemNode); 14551 14552 for (unsigned i = 0; i < NumStores; ++i) { 14553 Visited.insert(StoreNodes[i].MemNode); 14554 } 14555 14556 // don't include nodes that are children or repeated nodes. 14557 for (unsigned i = 0; i < NumStores; ++i) { 14558 if (Visited.insert(StoreNodes[i].MemNode->getChain().getNode()).second) 14559 Chains.push_back(StoreNodes[i].MemNode->getChain()); 14560 } 14561 14562 assert(Chains.size() > 0 && "Chain should have generated a chain"); 14563 return DAG.getTokenFactor(StoreDL, Chains); 14564 } 14565 14566 bool DAGCombiner::MergeStoresOfConstantsOrVecElts( 14567 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 14568 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 14569 // Make sure we have something to merge. 14570 if (NumStores < 2) 14571 return false; 14572 14573 // The latest Node in the DAG. 14574 SDLoc DL(StoreNodes[0].MemNode); 14575 14576 int64_t ElementSizeBits = MemVT.getStoreSizeInBits(); 14577 unsigned SizeInBits = NumStores * ElementSizeBits; 14578 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 14579 14580 EVT StoreTy; 14581 if (UseVector) { 14582 unsigned Elts = NumStores * NumMemElts; 14583 // Get the type for the merged vector store. 14584 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 14585 } else 14586 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 14587 14588 SDValue StoredVal; 14589 if (UseVector) { 14590 if (IsConstantSrc) { 14591 SmallVector<SDValue, 8> BuildVector; 14592 for (unsigned I = 0; I != NumStores; ++I) { 14593 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 14594 SDValue Val = St->getValue(); 14595 // If constant is of the wrong type, convert it now. 14596 if (MemVT != Val.getValueType()) { 14597 Val = peekThroughBitcasts(Val); 14598 // Deal with constants of wrong size. 14599 if (ElementSizeBits != Val.getValueSizeInBits()) { 14600 EVT IntMemVT = 14601 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 14602 if (isa<ConstantFPSDNode>(Val)) { 14603 // Not clear how to truncate FP values. 14604 return false; 14605 } else if (auto *C = dyn_cast<ConstantSDNode>(Val)) 14606 Val = DAG.getConstant(C->getAPIntValue() 14607 .zextOrTrunc(Val.getValueSizeInBits()) 14608 .zextOrTrunc(ElementSizeBits), 14609 SDLoc(C), IntMemVT); 14610 } 14611 // Make sure correctly size type is the correct type. 14612 Val = DAG.getBitcast(MemVT, Val); 14613 } 14614 BuildVector.push_back(Val); 14615 } 14616 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 14617 : ISD::BUILD_VECTOR, 14618 DL, StoreTy, BuildVector); 14619 } else { 14620 SmallVector<SDValue, 8> Ops; 14621 for (unsigned i = 0; i < NumStores; ++i) { 14622 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 14623 SDValue Val = peekThroughBitcasts(St->getValue()); 14624 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of 14625 // type MemVT. If the underlying value is not the correct 14626 // type, but it is an extraction of an appropriate vector we 14627 // can recast Val to be of the correct type. This may require 14628 // converting between EXTRACT_VECTOR_ELT and 14629 // EXTRACT_SUBVECTOR. 14630 if ((MemVT != Val.getValueType()) && 14631 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 14632 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { 14633 EVT MemVTScalarTy = MemVT.getScalarType(); 14634 // We may need to add a bitcast here to get types to line up. 14635 if (MemVTScalarTy != Val.getValueType().getScalarType()) { 14636 Val = DAG.getBitcast(MemVT, Val); 14637 } else { 14638 unsigned OpC = MemVT.isVector() ? ISD::EXTRACT_SUBVECTOR 14639 : ISD::EXTRACT_VECTOR_ELT; 14640 SDValue Vec = Val.getOperand(0); 14641 SDValue Idx = Val.getOperand(1); 14642 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Idx); 14643 } 14644 } 14645 Ops.push_back(Val); 14646 } 14647 14648 // Build the extracted vector elements back into a vector. 14649 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 14650 : ISD::BUILD_VECTOR, 14651 DL, StoreTy, Ops); 14652 } 14653 } else { 14654 // We should always use a vector store when merging extracted vector 14655 // elements, so this path implies a store of constants. 14656 assert(IsConstantSrc && "Merged vector elements should use vector store"); 14657 14658 APInt StoreInt(SizeInBits, 0); 14659 14660 // Construct a single integer constant which is made of the smaller 14661 // constant inputs. 14662 bool IsLE = DAG.getDataLayout().isLittleEndian(); 14663 for (unsigned i = 0; i < NumStores; ++i) { 14664 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 14665 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 14666 14667 SDValue Val = St->getValue(); 14668 Val = peekThroughBitcasts(Val); 14669 StoreInt <<= ElementSizeBits; 14670 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 14671 StoreInt |= C->getAPIntValue() 14672 .zextOrTrunc(ElementSizeBits) 14673 .zextOrTrunc(SizeInBits); 14674 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 14675 StoreInt |= C->getValueAPF() 14676 .bitcastToAPInt() 14677 .zextOrTrunc(ElementSizeBits) 14678 .zextOrTrunc(SizeInBits); 14679 // If fp truncation is necessary give up for now. 14680 if (MemVT.getSizeInBits() != ElementSizeBits) 14681 return false; 14682 } else { 14683 llvm_unreachable("Invalid constant element type"); 14684 } 14685 } 14686 14687 // Create the new Load and Store operations. 14688 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 14689 } 14690 14691 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 14692 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 14693 14694 // make sure we use trunc store if it's necessary to be legal. 14695 SDValue NewStore; 14696 if (!UseTrunc) { 14697 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 14698 FirstInChain->getPointerInfo(), 14699 FirstInChain->getAlignment()); 14700 } else { // Must be realized as a trunc store 14701 EVT LegalizedStoredValTy = 14702 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 14703 unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits(); 14704 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 14705 SDValue ExtendedStoreVal = 14706 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 14707 LegalizedStoredValTy); 14708 NewStore = DAG.getTruncStore( 14709 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 14710 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 14711 FirstInChain->getAlignment(), 14712 FirstInChain->getMemOperand()->getFlags()); 14713 } 14714 14715 // Replace all merged stores with the new store. 14716 for (unsigned i = 0; i < NumStores; ++i) 14717 CombineTo(StoreNodes[i].MemNode, NewStore); 14718 14719 AddToWorklist(NewChain.getNode()); 14720 return true; 14721 } 14722 14723 void DAGCombiner::getStoreMergeCandidates( 14724 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes, 14725 SDNode *&RootNode) { 14726 // This holds the base pointer, index, and the offset in bytes from the base 14727 // pointer. 14728 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 14729 EVT MemVT = St->getMemoryVT(); 14730 14731 SDValue Val = peekThroughBitcasts(St->getValue()); 14732 // We must have a base and an offset. 14733 if (!BasePtr.getBase().getNode()) 14734 return; 14735 14736 // Do not handle stores to undef base pointers. 14737 if (BasePtr.getBase().isUndef()) 14738 return; 14739 14740 bool IsConstantSrc = isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val); 14741 bool IsExtractVecSrc = (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 14742 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR); 14743 bool IsLoadSrc = isa<LoadSDNode>(Val); 14744 BaseIndexOffset LBasePtr; 14745 // Match on loadbaseptr if relevant. 14746 EVT LoadVT; 14747 if (IsLoadSrc) { 14748 auto *Ld = cast<LoadSDNode>(Val); 14749 LBasePtr = BaseIndexOffset::match(Ld, DAG); 14750 LoadVT = Ld->getMemoryVT(); 14751 // Load and store should be the same type. 14752 if (MemVT != LoadVT) 14753 return; 14754 // Loads must only have one use. 14755 if (!Ld->hasNUsesOfValue(1, 0)) 14756 return; 14757 // The memory operands must not be volatile. 14758 if (Ld->isVolatile() || Ld->isIndexed()) 14759 return; 14760 } 14761 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 14762 int64_t &Offset) -> bool { 14763 if (Other->isVolatile() || Other->isIndexed()) 14764 return false; 14765 SDValue Val = peekThroughBitcasts(Other->getValue()); 14766 // Allow merging constants of different types as integers. 14767 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) 14768 : Other->getMemoryVT() != MemVT; 14769 if (IsLoadSrc) { 14770 if (NoTypeMatch) 14771 return false; 14772 // The Load's Base Ptr must also match 14773 if (LoadSDNode *OtherLd = dyn_cast<LoadSDNode>(Val)) { 14774 auto LPtr = BaseIndexOffset::match(OtherLd, DAG); 14775 if (LoadVT != OtherLd->getMemoryVT()) 14776 return false; 14777 // Loads must only have one use. 14778 if (!OtherLd->hasNUsesOfValue(1, 0)) 14779 return false; 14780 // The memory operands must not be volatile. 14781 if (OtherLd->isVolatile() || OtherLd->isIndexed()) 14782 return false; 14783 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 14784 return false; 14785 } else 14786 return false; 14787 } 14788 if (IsConstantSrc) { 14789 if (NoTypeMatch) 14790 return false; 14791 if (!(isa<ConstantSDNode>(Val) || isa<ConstantFPSDNode>(Val))) 14792 return false; 14793 } 14794 if (IsExtractVecSrc) { 14795 // Do not merge truncated stores here. 14796 if (Other->isTruncatingStore()) 14797 return false; 14798 if (!MemVT.bitsEq(Val.getValueType())) 14799 return false; 14800 if (Val.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 14801 Val.getOpcode() != ISD::EXTRACT_SUBVECTOR) 14802 return false; 14803 } 14804 Ptr = BaseIndexOffset::match(Other, DAG); 14805 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 14806 }; 14807 14808 // We looking for a root node which is an ancestor to all mergable 14809 // stores. We search up through a load, to our root and then down 14810 // through all children. For instance we will find Store{1,2,3} if 14811 // St is Store1, Store2. or Store3 where the root is not a load 14812 // which always true for nonvolatile ops. TODO: Expand 14813 // the search to find all valid candidates through multiple layers of loads. 14814 // 14815 // Root 14816 // |-------|-------| 14817 // Load Load Store3 14818 // | | 14819 // Store1 Store2 14820 // 14821 // FIXME: We should be able to climb and 14822 // descend TokenFactors to find candidates as well. 14823 14824 RootNode = St->getChain().getNode(); 14825 14826 if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 14827 RootNode = Ldn->getChain().getNode(); 14828 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 14829 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) // walk down chain 14830 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 14831 if (I2.getOperandNo() == 0) 14832 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I2)) { 14833 BaseIndexOffset Ptr; 14834 int64_t PtrDiff; 14835 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 14836 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 14837 } 14838 } else 14839 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); I != E; ++I) 14840 if (I.getOperandNo() == 0) 14841 if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) { 14842 BaseIndexOffset Ptr; 14843 int64_t PtrDiff; 14844 if (CandidateMatch(OtherST, Ptr, PtrDiff)) 14845 StoreNodes.push_back(MemOpLink(OtherST, PtrDiff)); 14846 } 14847 } 14848 14849 // We need to check that merging these stores does not cause a loop in 14850 // the DAG. Any store candidate may depend on another candidate 14851 // indirectly through its operand (we already consider dependencies 14852 // through the chain). Check in parallel by searching up from 14853 // non-chain operands of candidates. 14854 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 14855 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 14856 SDNode *RootNode) { 14857 // FIXME: We should be able to truncate a full search of 14858 // predecessors by doing a BFS and keeping tabs the originating 14859 // stores from which worklist nodes come from in a similar way to 14860 // TokenFactor simplfication. 14861 14862 SmallPtrSet<const SDNode *, 32> Visited; 14863 SmallVector<const SDNode *, 8> Worklist; 14864 14865 // RootNode is a predecessor to all candidates so we need not search 14866 // past it. Add RootNode (peeking through TokenFactors). Do not count 14867 // these towards size check. 14868 14869 Worklist.push_back(RootNode); 14870 while (!Worklist.empty()) { 14871 auto N = Worklist.pop_back_val(); 14872 if (!Visited.insert(N).second) 14873 continue; // Already present in Visited. 14874 if (N->getOpcode() == ISD::TokenFactor) { 14875 for (SDValue Op : N->ops()) 14876 Worklist.push_back(Op.getNode()); 14877 } 14878 } 14879 14880 // Don't count pruning nodes towards max. 14881 unsigned int Max = 1024 + Visited.size(); 14882 // Search Ops of store candidates. 14883 for (unsigned i = 0; i < NumStores; ++i) { 14884 SDNode *N = StoreNodes[i].MemNode; 14885 // Of the 4 Store Operands: 14886 // * Chain (Op 0) -> We have already considered these 14887 // in candidate selection and can be 14888 // safely ignored 14889 // * Value (Op 1) -> Cycles may happen (e.g. through load chains) 14890 // * Address (Op 2) -> Merged addresses may only vary by a fixed constant, 14891 // but aren't necessarily fromt the same base node, so 14892 // cycles possible (e.g. via indexed store). 14893 // * (Op 3) -> Represents the pre or post-indexing offset (or undef for 14894 // non-indexed stores). Not constant on all targets (e.g. ARM) 14895 // and so can participate in a cycle. 14896 for (unsigned j = 1; j < N->getNumOperands(); ++j) 14897 Worklist.push_back(N->getOperand(j).getNode()); 14898 } 14899 // Search through DAG. We can stop early if we find a store node. 14900 for (unsigned i = 0; i < NumStores; ++i) 14901 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, 14902 Max)) 14903 return false; 14904 return true; 14905 } 14906 14907 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode *St) { 14908 if (OptLevel == CodeGenOpt::None) 14909 return false; 14910 14911 EVT MemVT = St->getMemoryVT(); 14912 int64_t ElementSizeBytes = MemVT.getStoreSize(); 14913 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 14914 14915 if (MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 14916 return false; 14917 14918 bool NoVectors = DAG.getMachineFunction().getFunction().hasFnAttribute( 14919 Attribute::NoImplicitFloat); 14920 14921 // This function cannot currently deal with non-byte-sized memory sizes. 14922 if (ElementSizeBytes * 8 != MemVT.getSizeInBits()) 14923 return false; 14924 14925 if (!MemVT.isSimple()) 14926 return false; 14927 14928 // Perform an early exit check. Do not bother looking at stored values that 14929 // are not constants, loads, or extracted vector elements. 14930 SDValue StoredVal = peekThroughBitcasts(St->getValue()); 14931 bool IsLoadSrc = isa<LoadSDNode>(StoredVal); 14932 bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) || 14933 isa<ConstantFPSDNode>(StoredVal); 14934 bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 14935 StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR); 14936 14937 if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc) 14938 return false; 14939 14940 SmallVector<MemOpLink, 8> StoreNodes; 14941 SDNode *RootNode; 14942 // Find potential store merge candidates by searching through chain sub-DAG 14943 getStoreMergeCandidates(St, StoreNodes, RootNode); 14944 14945 // Check if there is anything to merge. 14946 if (StoreNodes.size() < 2) 14947 return false; 14948 14949 // Sort the memory operands according to their distance from the 14950 // base pointer. 14951 llvm::sort(StoreNodes, [](MemOpLink LHS, MemOpLink RHS) { 14952 return LHS.OffsetFromBase < RHS.OffsetFromBase; 14953 }); 14954 14955 // Store Merge attempts to merge the lowest stores. This generally 14956 // works out as if successful, as the remaining stores are checked 14957 // after the first collection of stores is merged. However, in the 14958 // case that a non-mergeable store is found first, e.g., {p[-2], 14959 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 14960 // mergeable cases. To prevent this, we prune such stores from the 14961 // front of StoreNodes here. 14962 14963 bool RV = false; 14964 while (StoreNodes.size() > 1) { 14965 unsigned StartIdx = 0; 14966 while ((StartIdx + 1 < StoreNodes.size()) && 14967 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 14968 StoreNodes[StartIdx + 1].OffsetFromBase) 14969 ++StartIdx; 14970 14971 // Bail if we don't have enough candidates to merge. 14972 if (StartIdx + 1 >= StoreNodes.size()) 14973 return RV; 14974 14975 if (StartIdx) 14976 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 14977 14978 // Scan the memory operations on the chain and find the first 14979 // non-consecutive store memory address. 14980 unsigned NumConsecutiveStores = 1; 14981 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 14982 // Check that the addresses are consecutive starting from the second 14983 // element in the list of stores. 14984 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 14985 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 14986 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 14987 break; 14988 NumConsecutiveStores = i + 1; 14989 } 14990 14991 if (NumConsecutiveStores < 2) { 14992 StoreNodes.erase(StoreNodes.begin(), 14993 StoreNodes.begin() + NumConsecutiveStores); 14994 continue; 14995 } 14996 14997 // The node with the lowest store address. 14998 LLVMContext &Context = *DAG.getContext(); 14999 const DataLayout &DL = DAG.getDataLayout(); 15000 15001 // Store the constants into memory as one consecutive store. 15002 if (IsConstantSrc) { 15003 while (NumConsecutiveStores >= 2) { 15004 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 15005 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 15006 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 15007 unsigned LastLegalType = 1; 15008 unsigned LastLegalVectorType = 1; 15009 bool LastIntegerTrunc = false; 15010 bool NonZero = false; 15011 unsigned FirstZeroAfterNonZero = NumConsecutiveStores; 15012 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 15013 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 15014 SDValue StoredVal = ST->getValue(); 15015 bool IsElementZero = false; 15016 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) 15017 IsElementZero = C->isNullValue(); 15018 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) 15019 IsElementZero = C->getConstantFPValue()->isNullValue(); 15020 if (IsElementZero) { 15021 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) 15022 FirstZeroAfterNonZero = i; 15023 } 15024 NonZero |= !IsElementZero; 15025 15026 // Find a legal type for the constant store. 15027 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 15028 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 15029 bool IsFast = false; 15030 15031 // Break early when size is too large to be legal. 15032 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 15033 break; 15034 15035 if (TLI.isTypeLegal(StoreTy) && 15036 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 15037 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 15038 FirstStoreAlign, &IsFast) && 15039 IsFast) { 15040 LastIntegerTrunc = false; 15041 LastLegalType = i + 1; 15042 // Or check whether a truncstore is legal. 15043 } else if (TLI.getTypeAction(Context, StoreTy) == 15044 TargetLowering::TypePromoteInteger) { 15045 EVT LegalizedStoredValTy = 15046 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 15047 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 15048 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && 15049 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 15050 FirstStoreAlign, &IsFast) && 15051 IsFast) { 15052 LastIntegerTrunc = true; 15053 LastLegalType = i + 1; 15054 } 15055 } 15056 15057 // We only use vectors if the constant is known to be zero or the 15058 // target allows it and the function is not marked with the 15059 // noimplicitfloat attribute. 15060 if ((!NonZero || 15061 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 15062 !NoVectors) { 15063 // Find a legal type for the vector store. 15064 unsigned Elts = (i + 1) * NumMemElts; 15065 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 15066 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) && 15067 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 15068 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 15069 FirstStoreAlign, &IsFast) && 15070 IsFast) 15071 LastLegalVectorType = i + 1; 15072 } 15073 } 15074 15075 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors; 15076 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 15077 15078 // Check if we found a legal integer type that creates a meaningful 15079 // merge. 15080 if (NumElem < 2) { 15081 // We know that candidate stores are in order and of correct 15082 // shape. While there is no mergeable sequence from the 15083 // beginning one may start later in the sequence. The only 15084 // reason a merge of size N could have failed where another of 15085 // the same size would not have, is if the alignment has 15086 // improved or we've dropped a non-zero value. Drop as many 15087 // candidates as we can here. 15088 unsigned NumSkip = 1; 15089 while ( 15090 (NumSkip < NumConsecutiveStores) && 15091 (NumSkip < FirstZeroAfterNonZero) && 15092 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 15093 NumSkip++; 15094 15095 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 15096 NumConsecutiveStores -= NumSkip; 15097 continue; 15098 } 15099 15100 // Check that we can merge these candidates without causing a cycle. 15101 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 15102 RootNode)) { 15103 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 15104 NumConsecutiveStores -= NumElem; 15105 continue; 15106 } 15107 15108 RV |= MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, true, 15109 UseVector, LastIntegerTrunc); 15110 15111 // Remove merged stores for next iteration. 15112 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 15113 NumConsecutiveStores -= NumElem; 15114 } 15115 continue; 15116 } 15117 15118 // When extracting multiple vector elements, try to store them 15119 // in one vector store rather than a sequence of scalar stores. 15120 if (IsExtractVecSrc) { 15121 // Loop on Consecutive Stores on success. 15122 while (NumConsecutiveStores >= 2) { 15123 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 15124 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 15125 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 15126 unsigned NumStoresToMerge = 1; 15127 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 15128 // Find a legal type for the vector store. 15129 unsigned Elts = (i + 1) * NumMemElts; 15130 EVT Ty = 15131 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 15132 bool IsFast; 15133 15134 // Break early when size is too large to be legal. 15135 if (Ty.getSizeInBits() > MaximumLegalStoreInBits) 15136 break; 15137 15138 if (TLI.isTypeLegal(Ty) && 15139 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG) && 15140 TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS, 15141 FirstStoreAlign, &IsFast) && 15142 IsFast) 15143 NumStoresToMerge = i + 1; 15144 } 15145 15146 // Check if we found a legal integer type creating a meaningful 15147 // merge. 15148 if (NumStoresToMerge < 2) { 15149 // We know that candidate stores are in order and of correct 15150 // shape. While there is no mergeable sequence from the 15151 // beginning one may start later in the sequence. The only 15152 // reason a merge of size N could have failed where another of 15153 // the same size would not have, is if the alignment has 15154 // improved. Drop as many candidates as we can here. 15155 unsigned NumSkip = 1; 15156 while ( 15157 (NumSkip < NumConsecutiveStores) && 15158 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 15159 NumSkip++; 15160 15161 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 15162 NumConsecutiveStores -= NumSkip; 15163 continue; 15164 } 15165 15166 // Check that we can merge these candidates without causing a cycle. 15167 if (!checkMergeStoreCandidatesForDependencies( 15168 StoreNodes, NumStoresToMerge, RootNode)) { 15169 StoreNodes.erase(StoreNodes.begin(), 15170 StoreNodes.begin() + NumStoresToMerge); 15171 NumConsecutiveStores -= NumStoresToMerge; 15172 continue; 15173 } 15174 15175 RV |= MergeStoresOfConstantsOrVecElts( 15176 StoreNodes, MemVT, NumStoresToMerge, false, true, false); 15177 15178 StoreNodes.erase(StoreNodes.begin(), 15179 StoreNodes.begin() + NumStoresToMerge); 15180 NumConsecutiveStores -= NumStoresToMerge; 15181 } 15182 continue; 15183 } 15184 15185 // Below we handle the case of multiple consecutive stores that 15186 // come from multiple consecutive loads. We merge them into a single 15187 // wide load and a single wide store. 15188 15189 // Look for load nodes which are used by the stored values. 15190 SmallVector<MemOpLink, 8> LoadNodes; 15191 15192 // Find acceptable loads. Loads need to have the same chain (token factor), 15193 // must not be zext, volatile, indexed, and they must be consecutive. 15194 BaseIndexOffset LdBasePtr; 15195 15196 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 15197 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 15198 SDValue Val = peekThroughBitcasts(St->getValue()); 15199 LoadSDNode *Ld = cast<LoadSDNode>(Val); 15200 15201 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG); 15202 // If this is not the first ptr that we check. 15203 int64_t LdOffset = 0; 15204 if (LdBasePtr.getBase().getNode()) { 15205 // The base ptr must be the same. 15206 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 15207 break; 15208 } else { 15209 // Check that all other base pointers are the same as this one. 15210 LdBasePtr = LdPtr; 15211 } 15212 15213 // We found a potential memory operand to merge. 15214 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 15215 } 15216 15217 while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) { 15218 // If we have load/store pair instructions and we only have two values, 15219 // don't bother merging. 15220 unsigned RequiredAlignment; 15221 if (LoadNodes.size() == 2 && 15222 TLI.hasPairedLoad(MemVT, RequiredAlignment) && 15223 StoreNodes[0].MemNode->getAlignment() >= RequiredAlignment) { 15224 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 15225 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2); 15226 break; 15227 } 15228 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 15229 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 15230 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 15231 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 15232 unsigned FirstLoadAS = FirstLoad->getAddressSpace(); 15233 unsigned FirstLoadAlign = FirstLoad->getAlignment(); 15234 15235 // Scan the memory operations on the chain and find the first 15236 // non-consecutive load memory address. These variables hold the index in 15237 // the store node array. 15238 15239 unsigned LastConsecutiveLoad = 1; 15240 15241 // This variable refers to the size and not index in the array. 15242 unsigned LastLegalVectorType = 1; 15243 unsigned LastLegalIntegerType = 1; 15244 bool isDereferenceable = true; 15245 bool DoIntegerTruncate = false; 15246 StartAddress = LoadNodes[0].OffsetFromBase; 15247 SDValue FirstChain = FirstLoad->getChain(); 15248 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 15249 // All loads must share the same chain. 15250 if (LoadNodes[i].MemNode->getChain() != FirstChain) 15251 break; 15252 15253 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 15254 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 15255 break; 15256 LastConsecutiveLoad = i; 15257 15258 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 15259 isDereferenceable = false; 15260 15261 // Find a legal type for the vector store. 15262 unsigned Elts = (i + 1) * NumMemElts; 15263 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 15264 15265 // Break early when size is too large to be legal. 15266 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 15267 break; 15268 15269 bool IsFastSt, IsFastLd; 15270 if (TLI.isTypeLegal(StoreTy) && 15271 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 15272 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 15273 FirstStoreAlign, &IsFastSt) && 15274 IsFastSt && 15275 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 15276 FirstLoadAlign, &IsFastLd) && 15277 IsFastLd) { 15278 LastLegalVectorType = i + 1; 15279 } 15280 15281 // Find a legal type for the integer store. 15282 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 15283 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 15284 if (TLI.isTypeLegal(StoreTy) && 15285 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, DAG) && 15286 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 15287 FirstStoreAlign, &IsFastSt) && 15288 IsFastSt && 15289 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 15290 FirstLoadAlign, &IsFastLd) && 15291 IsFastLd) { 15292 LastLegalIntegerType = i + 1; 15293 DoIntegerTruncate = false; 15294 // Or check whether a truncstore and extload is legal. 15295 } else if (TLI.getTypeAction(Context, StoreTy) == 15296 TargetLowering::TypePromoteInteger) { 15297 EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy); 15298 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 15299 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, DAG) && 15300 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy, 15301 StoreTy) && 15302 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy, 15303 StoreTy) && 15304 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) && 15305 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS, 15306 FirstStoreAlign, &IsFastSt) && 15307 IsFastSt && 15308 TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS, 15309 FirstLoadAlign, &IsFastLd) && 15310 IsFastLd) { 15311 LastLegalIntegerType = i + 1; 15312 DoIntegerTruncate = true; 15313 } 15314 } 15315 } 15316 15317 // Only use vector types if the vector type is larger than the integer 15318 // type. If they are the same, use integers. 15319 bool UseVectorTy = 15320 LastLegalVectorType > LastLegalIntegerType && !NoVectors; 15321 unsigned LastLegalType = 15322 std::max(LastLegalVectorType, LastLegalIntegerType); 15323 15324 // We add +1 here because the LastXXX variables refer to location while 15325 // the NumElem refers to array/index size. 15326 unsigned NumElem = 15327 std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 15328 NumElem = std::min(LastLegalType, NumElem); 15329 15330 if (NumElem < 2) { 15331 // We know that candidate stores are in order and of correct 15332 // shape. While there is no mergeable sequence from the 15333 // beginning one may start later in the sequence. The only 15334 // reason a merge of size N could have failed where another of 15335 // the same size would not have is if the alignment or either 15336 // the load or store has improved. Drop as many candidates as we 15337 // can here. 15338 unsigned NumSkip = 1; 15339 while ((NumSkip < LoadNodes.size()) && 15340 (LoadNodes[NumSkip].MemNode->getAlignment() <= FirstLoadAlign) && 15341 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 15342 NumSkip++; 15343 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 15344 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip); 15345 NumConsecutiveStores -= NumSkip; 15346 continue; 15347 } 15348 15349 // Check that we can merge these candidates without causing a cycle. 15350 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 15351 RootNode)) { 15352 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 15353 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 15354 NumConsecutiveStores -= NumElem; 15355 continue; 15356 } 15357 15358 // Find if it is better to use vectors or integers to load and store 15359 // to memory. 15360 EVT JointMemOpVT; 15361 if (UseVectorTy) { 15362 // Find a legal type for the vector store. 15363 unsigned Elts = NumElem * NumMemElts; 15364 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 15365 } else { 15366 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 15367 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 15368 } 15369 15370 SDLoc LoadDL(LoadNodes[0].MemNode); 15371 SDLoc StoreDL(StoreNodes[0].MemNode); 15372 15373 // The merged loads are required to have the same incoming chain, so 15374 // using the first's chain is acceptable. 15375 15376 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 15377 AddToWorklist(NewStoreChain.getNode()); 15378 15379 MachineMemOperand::Flags MMOFlags = 15380 isDereferenceable ? MachineMemOperand::MODereferenceable 15381 : MachineMemOperand::MONone; 15382 15383 SDValue NewLoad, NewStore; 15384 if (UseVectorTy || !DoIntegerTruncate) { 15385 NewLoad = 15386 DAG.getLoad(JointMemOpVT, LoadDL, FirstLoad->getChain(), 15387 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(), 15388 FirstLoadAlign, MMOFlags); 15389 NewStore = DAG.getStore( 15390 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 15391 FirstInChain->getPointerInfo(), FirstStoreAlign); 15392 } else { // This must be the truncstore/extload case 15393 EVT ExtendedTy = 15394 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 15395 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, 15396 FirstLoad->getChain(), FirstLoad->getBasePtr(), 15397 FirstLoad->getPointerInfo(), JointMemOpVT, 15398 FirstLoadAlign, MMOFlags); 15399 NewStore = DAG.getTruncStore(NewStoreChain, StoreDL, NewLoad, 15400 FirstInChain->getBasePtr(), 15401 FirstInChain->getPointerInfo(), 15402 JointMemOpVT, FirstInChain->getAlignment(), 15403 FirstInChain->getMemOperand()->getFlags()); 15404 } 15405 15406 // Transfer chain users from old loads to the new load. 15407 for (unsigned i = 0; i < NumElem; ++i) { 15408 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 15409 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 15410 SDValue(NewLoad.getNode(), 1)); 15411 } 15412 15413 // Replace the all stores with the new store. Recursively remove 15414 // corresponding value if its no longer used. 15415 for (unsigned i = 0; i < NumElem; ++i) { 15416 SDValue Val = StoreNodes[i].MemNode->getOperand(1); 15417 CombineTo(StoreNodes[i].MemNode, NewStore); 15418 if (Val.getNode()->use_empty()) 15419 recursivelyDeleteUnusedNodes(Val.getNode()); 15420 } 15421 15422 RV = true; 15423 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 15424 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 15425 NumConsecutiveStores -= NumElem; 15426 } 15427 } 15428 return RV; 15429 } 15430 15431 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 15432 SDLoc SL(ST); 15433 SDValue ReplStore; 15434 15435 // Replace the chain to avoid dependency. 15436 if (ST->isTruncatingStore()) { 15437 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 15438 ST->getBasePtr(), ST->getMemoryVT(), 15439 ST->getMemOperand()); 15440 } else { 15441 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 15442 ST->getMemOperand()); 15443 } 15444 15445 // Create token to keep both nodes around. 15446 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 15447 MVT::Other, ST->getChain(), ReplStore); 15448 15449 // Make sure the new and old chains are cleaned up. 15450 AddToWorklist(Token.getNode()); 15451 15452 // Don't add users to work list. 15453 return CombineTo(ST, Token, false); 15454 } 15455 15456 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 15457 SDValue Value = ST->getValue(); 15458 if (Value.getOpcode() == ISD::TargetConstantFP) 15459 return SDValue(); 15460 15461 SDLoc DL(ST); 15462 15463 SDValue Chain = ST->getChain(); 15464 SDValue Ptr = ST->getBasePtr(); 15465 15466 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 15467 15468 // NOTE: If the original store is volatile, this transform must not increase 15469 // the number of stores. For example, on x86-32 an f64 can be stored in one 15470 // processor operation but an i64 (which is not legal) requires two. So the 15471 // transform should not be done in this case. 15472 15473 SDValue Tmp; 15474 switch (CFP->getSimpleValueType(0).SimpleTy) { 15475 default: 15476 llvm_unreachable("Unknown FP type"); 15477 case MVT::f16: // We don't do this for these yet. 15478 case MVT::f80: 15479 case MVT::f128: 15480 case MVT::ppcf128: 15481 return SDValue(); 15482 case MVT::f32: 15483 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) || 15484 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 15485 ; 15486 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 15487 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 15488 MVT::i32); 15489 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 15490 } 15491 15492 return SDValue(); 15493 case MVT::f64: 15494 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 15495 !ST->isVolatile()) || 15496 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 15497 ; 15498 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 15499 getZExtValue(), SDLoc(CFP), MVT::i64); 15500 return DAG.getStore(Chain, DL, Tmp, 15501 Ptr, ST->getMemOperand()); 15502 } 15503 15504 if (!ST->isVolatile() && 15505 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 15506 // Many FP stores are not made apparent until after legalize, e.g. for 15507 // argument passing. Since this is so common, custom legalize the 15508 // 64-bit integer store into two 32-bit stores. 15509 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 15510 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 15511 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 15512 if (DAG.getDataLayout().isBigEndian()) 15513 std::swap(Lo, Hi); 15514 15515 unsigned Alignment = ST->getAlignment(); 15516 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 15517 AAMDNodes AAInfo = ST->getAAInfo(); 15518 15519 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 15520 ST->getAlignment(), MMOFlags, AAInfo); 15521 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 15522 DAG.getConstant(4, DL, Ptr.getValueType())); 15523 Alignment = MinAlign(Alignment, 4U); 15524 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 15525 ST->getPointerInfo().getWithOffset(4), 15526 Alignment, MMOFlags, AAInfo); 15527 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 15528 St0, St1); 15529 } 15530 15531 return SDValue(); 15532 } 15533 } 15534 15535 SDValue DAGCombiner::visitSTORE(SDNode *N) { 15536 StoreSDNode *ST = cast<StoreSDNode>(N); 15537 SDValue Chain = ST->getChain(); 15538 SDValue Value = ST->getValue(); 15539 SDValue Ptr = ST->getBasePtr(); 15540 15541 // If this is a store of a bit convert, store the input value if the 15542 // resultant store does not need a higher alignment than the original. 15543 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 15544 ST->isUnindexed()) { 15545 EVT SVT = Value.getOperand(0).getValueType(); 15546 // If the store is volatile, we only want to change the store type if the 15547 // resulting store is legal. Otherwise we might increase the number of 15548 // memory accesses. We don't care if the original type was legal or not 15549 // as we assume software couldn't rely on the number of accesses of an 15550 // illegal type. 15551 if (((!LegalOperations && !ST->isVolatile()) || 15552 TLI.isOperationLegal(ISD::STORE, SVT)) && 15553 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT)) { 15554 unsigned OrigAlign = ST->getAlignment(); 15555 bool Fast = false; 15556 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), SVT, 15557 ST->getAddressSpace(), OrigAlign, &Fast) && 15558 Fast) { 15559 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 15560 ST->getPointerInfo(), OrigAlign, 15561 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 15562 } 15563 } 15564 } 15565 15566 // Turn 'store undef, Ptr' -> nothing. 15567 if (Value.isUndef() && ST->isUnindexed()) 15568 return Chain; 15569 15570 // Try to infer better alignment information than the store already has. 15571 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) { 15572 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) { 15573 if (Align > ST->getAlignment() && ST->getSrcValueOffset() % Align == 0) { 15574 SDValue NewStore = 15575 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 15576 ST->getMemoryVT(), Align, 15577 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 15578 // NewStore will always be N as we are only refining the alignment 15579 assert(NewStore.getNode() == N); 15580 (void)NewStore; 15581 } 15582 } 15583 } 15584 15585 // Try transforming a pair floating point load / store ops to integer 15586 // load / store ops. 15587 if (SDValue NewST = TransformFPLoadStorePair(N)) 15588 return NewST; 15589 15590 if (ST->isUnindexed()) { 15591 // Walk up chain skipping non-aliasing memory nodes, on this store and any 15592 // adjacent stores. 15593 if (findBetterNeighborChains(ST)) { 15594 // replaceStoreChain uses CombineTo, which handled all of the worklist 15595 // manipulation. Return the original node to not do anything else. 15596 return SDValue(ST, 0); 15597 } 15598 Chain = ST->getChain(); 15599 } 15600 15601 // FIXME: is there such a thing as a truncating indexed store? 15602 if (ST->isTruncatingStore() && ST->isUnindexed() && 15603 Value.getValueType().isInteger() && 15604 (!isa<ConstantSDNode>(Value) || 15605 !cast<ConstantSDNode>(Value)->isOpaque())) { 15606 APInt TruncDemandedBits = 15607 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 15608 ST->getMemoryVT().getScalarSizeInBits()); 15609 15610 // See if we can simplify the input to this truncstore with knowledge that 15611 // only the low bits are being used. For example: 15612 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 15613 SDValue Shorter = DAG.GetDemandedBits(Value, TruncDemandedBits); 15614 AddToWorklist(Value.getNode()); 15615 if (Shorter) 15616 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, Ptr, ST->getMemoryVT(), 15617 ST->getMemOperand()); 15618 15619 // Otherwise, see if we can simplify the operation with 15620 // SimplifyDemandedBits, which only works if the value has a single use. 15621 if (SimplifyDemandedBits(Value, TruncDemandedBits)) { 15622 // Re-visit the store if anything changed and the store hasn't been merged 15623 // with another node (N is deleted) SimplifyDemandedBits will add Value's 15624 // node back to the worklist if necessary, but we also need to re-visit 15625 // the Store node itself. 15626 if (N->getOpcode() != ISD::DELETED_NODE) 15627 AddToWorklist(N); 15628 return SDValue(N, 0); 15629 } 15630 } 15631 15632 // If this is a load followed by a store to the same location, then the store 15633 // is dead/noop. 15634 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 15635 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 15636 ST->isUnindexed() && !ST->isVolatile() && 15637 // There can't be any side effects between the load and store, such as 15638 // a call or store. 15639 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 15640 // The store is dead, remove it. 15641 return Chain; 15642 } 15643 } 15644 15645 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 15646 if (ST->isUnindexed() && !ST->isVolatile() && ST1->isUnindexed() && 15647 !ST1->isVolatile()) { 15648 if (ST1->getBasePtr() == Ptr && ST1->getValue() == Value && 15649 ST->getMemoryVT() == ST1->getMemoryVT()) { 15650 // If this is a store followed by a store with the same value to the 15651 // same location, then the store is dead/noop. 15652 return Chain; 15653 } 15654 15655 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 15656 !ST1->getBasePtr().isUndef()) { 15657 const BaseIndexOffset STBase = BaseIndexOffset::match(ST, DAG); 15658 const BaseIndexOffset ChainBase = BaseIndexOffset::match(ST1, DAG); 15659 unsigned STBitSize = ST->getMemoryVT().getSizeInBits(); 15660 unsigned ChainBitSize = ST1->getMemoryVT().getSizeInBits(); 15661 // If this is a store who's preceding store to a subset of the current 15662 // location and no one other node is chained to that store we can 15663 // effectively drop the store. Do not remove stores to undef as they may 15664 // be used as data sinks. 15665 if (STBase.contains(DAG, STBitSize, ChainBase, ChainBitSize)) { 15666 CombineTo(ST1, ST1->getChain()); 15667 return SDValue(); 15668 } 15669 15670 // If ST stores to a subset of preceding store's write set, we may be 15671 // able to fold ST's value into the preceding stored value. As we know 15672 // the other uses of ST1's chain are unconcerned with ST, this folding 15673 // will not affect those nodes. 15674 int64_t BitOffset; 15675 if (ChainBase.contains(DAG, ChainBitSize, STBase, STBitSize, 15676 BitOffset)) { 15677 SDValue ChainValue = ST1->getValue(); 15678 if (auto *C1 = dyn_cast<ConstantSDNode>(ChainValue)) { 15679 if (auto *C = dyn_cast<ConstantSDNode>(Value)) { 15680 APInt Val = C1->getAPIntValue(); 15681 APInt InsertVal = C->getAPIntValue().zextOrTrunc(STBitSize); 15682 // FIXME: Handle Big-endian mode. 15683 if (!DAG.getDataLayout().isBigEndian()) { 15684 Val.insertBits(InsertVal, BitOffset); 15685 SDValue NewSDVal = 15686 DAG.getConstant(Val, SDLoc(C), ChainValue.getValueType(), 15687 C1->isTargetOpcode(), C1->isOpaque()); 15688 SDNode *NewST1 = DAG.UpdateNodeOperands( 15689 ST1, ST1->getChain(), NewSDVal, ST1->getOperand(2), 15690 ST1->getOperand(3)); 15691 return CombineTo(ST, SDValue(NewST1, 0)); 15692 } 15693 } 15694 } 15695 } // End ST subset of ST1 case. 15696 } 15697 } 15698 } 15699 15700 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 15701 // truncating store. We can do this even if this is already a truncstore. 15702 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE) 15703 && Value.getNode()->hasOneUse() && ST->isUnindexed() && 15704 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(), 15705 ST->getMemoryVT())) { 15706 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 15707 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 15708 } 15709 15710 // Always perform this optimization before types are legal. If the target 15711 // prefers, also try this after legalization to catch stores that were created 15712 // by intrinsics or other nodes. 15713 if (!LegalTypes || (TLI.mergeStoresAfterLegalization())) { 15714 while (true) { 15715 // There can be multiple store sequences on the same chain. 15716 // Keep trying to merge store sequences until we are unable to do so 15717 // or until we merge the last store on the chain. 15718 bool Changed = MergeConsecutiveStores(ST); 15719 if (!Changed) break; 15720 // Return N as merge only uses CombineTo and no worklist clean 15721 // up is necessary. 15722 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 15723 return SDValue(N, 0); 15724 } 15725 } 15726 15727 // Try transforming N to an indexed store. 15728 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 15729 return SDValue(N, 0); 15730 15731 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 15732 // 15733 // Make sure to do this only after attempting to merge stores in order to 15734 // avoid changing the types of some subset of stores due to visit order, 15735 // preventing their merging. 15736 if (isa<ConstantFPSDNode>(ST->getValue())) { 15737 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 15738 return NewSt; 15739 } 15740 15741 if (SDValue NewSt = splitMergedValStore(ST)) 15742 return NewSt; 15743 15744 return ReduceLoadOpStoreWidth(N); 15745 } 15746 15747 SDValue DAGCombiner::visitLIFETIME_END(SDNode *N) { 15748 const auto *LifetimeEnd = cast<LifetimeSDNode>(N); 15749 if (!LifetimeEnd->hasOffset()) 15750 return SDValue(); 15751 15752 const BaseIndexOffset LifetimeEndBase(N->getOperand(1), SDValue(), 15753 LifetimeEnd->getOffset(), false); 15754 15755 // We walk up the chains to find stores. 15756 SmallVector<SDValue, 8> Chains = {N->getOperand(0)}; 15757 while (!Chains.empty()) { 15758 SDValue Chain = Chains.back(); 15759 Chains.pop_back(); 15760 if (!Chain.hasOneUse()) 15761 continue; 15762 switch (Chain.getOpcode()) { 15763 case ISD::TokenFactor: 15764 for (unsigned Nops = Chain.getNumOperands(); Nops;) 15765 Chains.push_back(Chain.getOperand(--Nops)); 15766 break; 15767 case ISD::LIFETIME_START: 15768 case ISD::LIFETIME_END: 15769 // We can forward past any lifetime start/end that can be proven not to 15770 // alias the node. 15771 if (!isAlias(Chain.getNode(), N)) 15772 Chains.push_back(Chain.getOperand(0)); 15773 break; 15774 case ISD::STORE: { 15775 StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain); 15776 if (ST->isVolatile() || ST->isIndexed()) 15777 continue; 15778 const BaseIndexOffset StoreBase = BaseIndexOffset::match(ST, DAG); 15779 // If we store purely within object bounds just before its lifetime ends, 15780 // we can remove the store. 15781 if (LifetimeEndBase.contains(DAG, LifetimeEnd->getSize() * 8, StoreBase, 15782 ST->getMemoryVT().getStoreSizeInBits())) { 15783 LLVM_DEBUG(dbgs() << "\nRemoving store:"; StoreBase.dump(); 15784 dbgs() << "\nwithin LIFETIME_END of : "; 15785 LifetimeEndBase.dump(); dbgs() << "\n"); 15786 CombineTo(ST, ST->getChain()); 15787 return SDValue(N, 0); 15788 } 15789 } 15790 } 15791 } 15792 return SDValue(); 15793 } 15794 15795 /// For the instruction sequence of store below, F and I values 15796 /// are bundled together as an i64 value before being stored into memory. 15797 /// Sometimes it is more efficent to generate separate stores for F and I, 15798 /// which can remove the bitwise instructions or sink them to colder places. 15799 /// 15800 /// (store (or (zext (bitcast F to i32) to i64), 15801 /// (shl (zext I to i64), 32)), addr) --> 15802 /// (store F, addr) and (store I, addr+4) 15803 /// 15804 /// Similarly, splitting for other merged store can also be beneficial, like: 15805 /// For pair of {i32, i32}, i64 store --> two i32 stores. 15806 /// For pair of {i32, i16}, i64 store --> two i32 stores. 15807 /// For pair of {i16, i16}, i32 store --> two i16 stores. 15808 /// For pair of {i16, i8}, i32 store --> two i16 stores. 15809 /// For pair of {i8, i8}, i16 store --> two i8 stores. 15810 /// 15811 /// We allow each target to determine specifically which kind of splitting is 15812 /// supported. 15813 /// 15814 /// The store patterns are commonly seen from the simple code snippet below 15815 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 15816 /// void goo(const std::pair<int, float> &); 15817 /// hoo() { 15818 /// ... 15819 /// goo(std::make_pair(tmp, ftmp)); 15820 /// ... 15821 /// } 15822 /// 15823 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 15824 if (OptLevel == CodeGenOpt::None) 15825 return SDValue(); 15826 15827 SDValue Val = ST->getValue(); 15828 SDLoc DL(ST); 15829 15830 // Match OR operand. 15831 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 15832 return SDValue(); 15833 15834 // Match SHL operand and get Lower and Higher parts of Val. 15835 SDValue Op1 = Val.getOperand(0); 15836 SDValue Op2 = Val.getOperand(1); 15837 SDValue Lo, Hi; 15838 if (Op1.getOpcode() != ISD::SHL) { 15839 std::swap(Op1, Op2); 15840 if (Op1.getOpcode() != ISD::SHL) 15841 return SDValue(); 15842 } 15843 Lo = Op2; 15844 Hi = Op1.getOperand(0); 15845 if (!Op1.hasOneUse()) 15846 return SDValue(); 15847 15848 // Match shift amount to HalfValBitSize. 15849 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 15850 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 15851 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 15852 return SDValue(); 15853 15854 // Lo and Hi are zero-extended from int with size less equal than 32 15855 // to i64. 15856 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 15857 !Lo.getOperand(0).getValueType().isScalarInteger() || 15858 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 15859 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 15860 !Hi.getOperand(0).getValueType().isScalarInteger() || 15861 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 15862 return SDValue(); 15863 15864 // Use the EVT of low and high parts before bitcast as the input 15865 // of target query. 15866 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 15867 ? Lo.getOperand(0).getValueType() 15868 : Lo.getValueType(); 15869 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 15870 ? Hi.getOperand(0).getValueType() 15871 : Hi.getValueType(); 15872 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 15873 return SDValue(); 15874 15875 // Start to split store. 15876 unsigned Alignment = ST->getAlignment(); 15877 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 15878 AAMDNodes AAInfo = ST->getAAInfo(); 15879 15880 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 15881 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 15882 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 15883 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 15884 15885 SDValue Chain = ST->getChain(); 15886 SDValue Ptr = ST->getBasePtr(); 15887 // Lower value store. 15888 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 15889 ST->getAlignment(), MMOFlags, AAInfo); 15890 Ptr = 15891 DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, 15892 DAG.getConstant(HalfValBitSize / 8, DL, Ptr.getValueType())); 15893 // Higher value store. 15894 SDValue St1 = 15895 DAG.getStore(St0, DL, Hi, Ptr, 15896 ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 15897 Alignment / 2, MMOFlags, AAInfo); 15898 return St1; 15899 } 15900 15901 /// Convert a disguised subvector insertion into a shuffle: 15902 /// insert_vector_elt V, (bitcast X from vector type), IdxC --> 15903 /// bitcast(shuffle (bitcast V), (extended X), Mask) 15904 /// Note: We do not use an insert_subvector node because that requires a legal 15905 /// subvector type. 15906 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { 15907 SDValue InsertVal = N->getOperand(1); 15908 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || 15909 !InsertVal.getOperand(0).getValueType().isVector()) 15910 return SDValue(); 15911 15912 SDValue SubVec = InsertVal.getOperand(0); 15913 SDValue DestVec = N->getOperand(0); 15914 EVT SubVecVT = SubVec.getValueType(); 15915 EVT VT = DestVec.getValueType(); 15916 unsigned NumSrcElts = SubVecVT.getVectorNumElements(); 15917 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); 15918 unsigned NumMaskVals = ExtendRatio * NumSrcElts; 15919 15920 // Step 1: Create a shuffle mask that implements this insert operation. The 15921 // vector that we are inserting into will be operand 0 of the shuffle, so 15922 // those elements are just 'i'. The inserted subvector is in the first 15923 // positions of operand 1 of the shuffle. Example: 15924 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} 15925 SmallVector<int, 16> Mask(NumMaskVals); 15926 for (unsigned i = 0; i != NumMaskVals; ++i) { 15927 if (i / NumSrcElts == InsIndex) 15928 Mask[i] = (i % NumSrcElts) + NumMaskVals; 15929 else 15930 Mask[i] = i; 15931 } 15932 15933 // Bail out if the target can not handle the shuffle we want to create. 15934 EVT SubVecEltVT = SubVecVT.getVectorElementType(); 15935 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); 15936 if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) 15937 return SDValue(); 15938 15939 // Step 2: Create a wide vector from the inserted source vector by appending 15940 // undefined elements. This is the same size as our destination vector. 15941 SDLoc DL(N); 15942 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); 15943 ConcatOps[0] = SubVec; 15944 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); 15945 15946 // Step 3: Shuffle in the padded subvector. 15947 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); 15948 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); 15949 AddToWorklist(PaddedSubV.getNode()); 15950 AddToWorklist(DestVecBC.getNode()); 15951 AddToWorklist(Shuf.getNode()); 15952 return DAG.getBitcast(VT, Shuf); 15953 } 15954 15955 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 15956 SDValue InVec = N->getOperand(0); 15957 SDValue InVal = N->getOperand(1); 15958 SDValue EltNo = N->getOperand(2); 15959 SDLoc DL(N); 15960 15961 // If the inserted element is an UNDEF, just use the input vector. 15962 if (InVal.isUndef()) 15963 return InVec; 15964 15965 EVT VT = InVec.getValueType(); 15966 unsigned NumElts = VT.getVectorNumElements(); 15967 15968 // Remove redundant insertions: 15969 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 15970 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 15971 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 15972 return InVec; 15973 15974 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); 15975 if (!IndexC) { 15976 // If this is variable insert to undef vector, it might be better to splat: 15977 // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... > 15978 if (InVec.isUndef() && TLI.shouldSplatInsEltVarIndex(VT)) { 15979 SmallVector<SDValue, 8> Ops(NumElts, InVal); 15980 return DAG.getBuildVector(VT, DL, Ops); 15981 } 15982 return SDValue(); 15983 } 15984 15985 // We must know which element is being inserted for folds below here. 15986 unsigned Elt = IndexC->getZExtValue(); 15987 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) 15988 return Shuf; 15989 15990 // Canonicalize insert_vector_elt dag nodes. 15991 // Example: 15992 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 15993 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 15994 // 15995 // Do this only if the child insert_vector node has one use; also 15996 // do this only if indices are both constants and Idx1 < Idx0. 15997 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 15998 && isa<ConstantSDNode>(InVec.getOperand(2))) { 15999 unsigned OtherElt = InVec.getConstantOperandVal(2); 16000 if (Elt < OtherElt) { 16001 // Swap nodes. 16002 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 16003 InVec.getOperand(0), InVal, EltNo); 16004 AddToWorklist(NewOp.getNode()); 16005 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 16006 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 16007 } 16008 } 16009 16010 // If we can't generate a legal BUILD_VECTOR, exit 16011 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 16012 return SDValue(); 16013 16014 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 16015 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 16016 // vector elements. 16017 SmallVector<SDValue, 8> Ops; 16018 // Do not combine these two vectors if the output vector will not replace 16019 // the input vector. 16020 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 16021 Ops.append(InVec.getNode()->op_begin(), 16022 InVec.getNode()->op_end()); 16023 } else if (InVec.isUndef()) { 16024 Ops.append(NumElts, DAG.getUNDEF(InVal.getValueType())); 16025 } else { 16026 return SDValue(); 16027 } 16028 assert(Ops.size() == NumElts && "Unexpected vector size"); 16029 16030 // Insert the element 16031 if (Elt < Ops.size()) { 16032 // All the operands of BUILD_VECTOR must have the same type; 16033 // we enforce that here. 16034 EVT OpVT = Ops[0].getValueType(); 16035 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 16036 } 16037 16038 // Return the new vector 16039 return DAG.getBuildVector(VT, DL, Ops); 16040 } 16041 16042 SDValue DAGCombiner::scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT, 16043 SDValue EltNo, 16044 LoadSDNode *OriginalLoad) { 16045 assert(!OriginalLoad->isVolatile()); 16046 16047 EVT ResultVT = EVE->getValueType(0); 16048 EVT VecEltVT = InVecVT.getVectorElementType(); 16049 unsigned Align = OriginalLoad->getAlignment(); 16050 unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment( 16051 VecEltVT.getTypeForEVT(*DAG.getContext())); 16052 16053 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT)) 16054 return SDValue(); 16055 16056 ISD::LoadExtType ExtTy = ResultVT.bitsGT(VecEltVT) ? 16057 ISD::NON_EXTLOAD : ISD::EXTLOAD; 16058 if (!TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 16059 return SDValue(); 16060 16061 Align = NewAlign; 16062 16063 SDValue NewPtr = OriginalLoad->getBasePtr(); 16064 SDValue Offset; 16065 EVT PtrType = NewPtr.getValueType(); 16066 MachinePointerInfo MPI; 16067 SDLoc DL(EVE); 16068 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 16069 int Elt = ConstEltNo->getZExtValue(); 16070 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 16071 Offset = DAG.getConstant(PtrOff, DL, PtrType); 16072 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 16073 } else { 16074 Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType); 16075 Offset = DAG.getNode( 16076 ISD::MUL, DL, PtrType, Offset, 16077 DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType)); 16078 // Discard the pointer info except the address space because the memory 16079 // operand can't represent this new access since the offset is variable. 16080 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace()); 16081 } 16082 NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset); 16083 16084 // The replacement we need to do here is a little tricky: we need to 16085 // replace an extractelement of a load with a load. 16086 // Use ReplaceAllUsesOfValuesWith to do the replacement. 16087 // Note that this replacement assumes that the extractvalue is the only 16088 // use of the load; that's okay because we don't want to perform this 16089 // transformation in other cases anyway. 16090 SDValue Load; 16091 SDValue Chain; 16092 if (ResultVT.bitsGT(VecEltVT)) { 16093 // If the result type of vextract is wider than the load, then issue an 16094 // extending load instead. 16095 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 16096 VecEltVT) 16097 ? ISD::ZEXTLOAD 16098 : ISD::EXTLOAD; 16099 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 16100 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 16101 Align, OriginalLoad->getMemOperand()->getFlags(), 16102 OriginalLoad->getAAInfo()); 16103 Chain = Load.getValue(1); 16104 } else { 16105 Load = DAG.getLoad(VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, 16106 MPI, Align, OriginalLoad->getMemOperand()->getFlags(), 16107 OriginalLoad->getAAInfo()); 16108 Chain = Load.getValue(1); 16109 if (ResultVT.bitsLT(VecEltVT)) 16110 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 16111 else 16112 Load = DAG.getBitcast(ResultVT, Load); 16113 } 16114 WorklistRemover DeadNodes(*this); 16115 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 16116 SDValue To[] = { Load, Chain }; 16117 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 16118 // Since we're explicitly calling ReplaceAllUses, add the new node to the 16119 // worklist explicitly as well. 16120 AddToWorklist(Load.getNode()); 16121 AddUsersToWorklist(Load.getNode()); // Add users too 16122 // Make sure to revisit this node to clean it up; it will usually be dead. 16123 AddToWorklist(EVE); 16124 ++OpsNarrowed; 16125 return SDValue(EVE, 0); 16126 } 16127 16128 /// Transform a vector binary operation into a scalar binary operation by moving 16129 /// the math/logic after an extract element of a vector. 16130 static SDValue scalarizeExtractedBinop(SDNode *ExtElt, SelectionDAG &DAG, 16131 bool LegalOperations) { 16132 SDValue Vec = ExtElt->getOperand(0); 16133 SDValue Index = ExtElt->getOperand(1); 16134 auto *IndexC = dyn_cast<ConstantSDNode>(Index); 16135 if (!IndexC || !ISD::isBinaryOp(Vec.getNode()) || !Vec.hasOneUse()) 16136 return SDValue(); 16137 16138 // Targets may want to avoid this to prevent an expensive register transfer. 16139 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16140 if (!TLI.shouldScalarizeBinop(Vec)) 16141 return SDValue(); 16142 16143 // Extracting an element of a vector constant is constant-folded, so this 16144 // transform is just replacing a vector op with a scalar op while moving the 16145 // extract. 16146 SDValue Op0 = Vec.getOperand(0); 16147 SDValue Op1 = Vec.getOperand(1); 16148 if (isAnyConstantBuildVector(Op0, true) || 16149 isAnyConstantBuildVector(Op1, true)) { 16150 // extractelt (binop X, C), IndexC --> binop (extractelt X, IndexC), C' 16151 // extractelt (binop C, X), IndexC --> binop C', (extractelt X, IndexC) 16152 SDLoc DL(ExtElt); 16153 EVT VT = ExtElt->getValueType(0); 16154 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Index); 16155 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op1, Index); 16156 return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1); 16157 } 16158 16159 return SDValue(); 16160 } 16161 16162 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 16163 SDValue VecOp = N->getOperand(0); 16164 SDValue Index = N->getOperand(1); 16165 EVT ScalarVT = N->getValueType(0); 16166 EVT VecVT = VecOp.getValueType(); 16167 if (VecOp.isUndef()) 16168 return DAG.getUNDEF(ScalarVT); 16169 16170 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 16171 // 16172 // This only really matters if the index is non-constant since other combines 16173 // on the constant elements already work. 16174 SDLoc DL(N); 16175 if (VecOp.getOpcode() == ISD::INSERT_VECTOR_ELT && 16176 Index == VecOp.getOperand(2)) { 16177 SDValue Elt = VecOp.getOperand(1); 16178 return VecVT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, DL, ScalarVT) : Elt; 16179 } 16180 16181 // (vextract (scalar_to_vector val, 0) -> val 16182 if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR) { 16183 // Check if the result type doesn't match the inserted element type. A 16184 // SCALAR_TO_VECTOR may truncate the inserted element and the 16185 // EXTRACT_VECTOR_ELT may widen the extracted vector. 16186 SDValue InOp = VecOp.getOperand(0); 16187 if (InOp.getValueType() != ScalarVT) { 16188 assert(InOp.getValueType().isInteger() && ScalarVT.isInteger()); 16189 return DAG.getSExtOrTrunc(InOp, DL, ScalarVT); 16190 } 16191 return InOp; 16192 } 16193 16194 // extract_vector_elt of out-of-bounds element -> UNDEF 16195 auto *IndexC = dyn_cast<ConstantSDNode>(Index); 16196 unsigned NumElts = VecVT.getVectorNumElements(); 16197 if (IndexC && IndexC->getAPIntValue().uge(NumElts)) 16198 return DAG.getUNDEF(ScalarVT); 16199 16200 // extract_vector_elt (build_vector x, y), 1 -> y 16201 if (IndexC && VecOp.getOpcode() == ISD::BUILD_VECTOR && 16202 TLI.isTypeLegal(VecVT) && 16203 (VecOp.hasOneUse() || TLI.aggressivelyPreferBuildVectorSources(VecVT))) { 16204 SDValue Elt = VecOp.getOperand(IndexC->getZExtValue()); 16205 EVT InEltVT = Elt.getValueType(); 16206 16207 // Sometimes build_vector's scalar input types do not match result type. 16208 if (ScalarVT == InEltVT) 16209 return Elt; 16210 16211 // TODO: It may be useful to truncate if free if the build_vector implicitly 16212 // converts. 16213 } 16214 16215 // TODO: These transforms should not require the 'hasOneUse' restriction, but 16216 // there are regressions on multiple targets without it. We can end up with a 16217 // mess of scalar and vector code if we reduce only part of the DAG to scalar. 16218 if (IndexC && VecOp.getOpcode() == ISD::BITCAST && VecVT.isInteger() && 16219 VecOp.hasOneUse()) { 16220 // The vector index of the LSBs of the source depend on the endian-ness. 16221 bool IsLE = DAG.getDataLayout().isLittleEndian(); 16222 unsigned ExtractIndex = IndexC->getZExtValue(); 16223 // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x) 16224 unsigned BCTruncElt = IsLE ? 0 : NumElts - 1; 16225 SDValue BCSrc = VecOp.getOperand(0); 16226 if (ExtractIndex == BCTruncElt && BCSrc.getValueType().isScalarInteger()) 16227 return DAG.getNode(ISD::TRUNCATE, DL, ScalarVT, BCSrc); 16228 16229 if (LegalTypes && BCSrc.getValueType().isInteger() && 16230 BCSrc.getOpcode() == ISD::SCALAR_TO_VECTOR) { 16231 // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt --> 16232 // trunc i64 X to i32 16233 SDValue X = BCSrc.getOperand(0); 16234 assert(X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() && 16235 "Extract element and scalar to vector can't change element type " 16236 "from FP to integer."); 16237 unsigned XBitWidth = X.getValueSizeInBits(); 16238 unsigned VecEltBitWidth = VecVT.getScalarSizeInBits(); 16239 BCTruncElt = IsLE ? 0 : XBitWidth / VecEltBitWidth - 1; 16240 16241 // An extract element return value type can be wider than its vector 16242 // operand element type. In that case, the high bits are undefined, so 16243 // it's possible that we may need to extend rather than truncate. 16244 if (ExtractIndex == BCTruncElt && XBitWidth > VecEltBitWidth) { 16245 assert(XBitWidth % VecEltBitWidth == 0 && 16246 "Scalar bitwidth must be a multiple of vector element bitwidth"); 16247 return DAG.getAnyExtOrTrunc(X, DL, ScalarVT); 16248 } 16249 } 16250 } 16251 16252 if (SDValue BO = scalarizeExtractedBinop(N, DAG, LegalOperations)) 16253 return BO; 16254 16255 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 16256 // We only perform this optimization before the op legalization phase because 16257 // we may introduce new vector instructions which are not backed by TD 16258 // patterns. For example on AVX, extracting elements from a wide vector 16259 // without using extract_subvector. However, if we can find an underlying 16260 // scalar value, then we can always use that. 16261 if (IndexC && VecOp.getOpcode() == ISD::VECTOR_SHUFFLE) { 16262 auto *Shuf = cast<ShuffleVectorSDNode>(VecOp); 16263 // Find the new index to extract from. 16264 int OrigElt = Shuf->getMaskElt(IndexC->getZExtValue()); 16265 16266 // Extracting an undef index is undef. 16267 if (OrigElt == -1) 16268 return DAG.getUNDEF(ScalarVT); 16269 16270 // Select the right vector half to extract from. 16271 SDValue SVInVec; 16272 if (OrigElt < (int)NumElts) { 16273 SVInVec = VecOp.getOperand(0); 16274 } else { 16275 SVInVec = VecOp.getOperand(1); 16276 OrigElt -= NumElts; 16277 } 16278 16279 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 16280 SDValue InOp = SVInVec.getOperand(OrigElt); 16281 if (InOp.getValueType() != ScalarVT) { 16282 assert(InOp.getValueType().isInteger() && ScalarVT.isInteger()); 16283 InOp = DAG.getSExtOrTrunc(InOp, DL, ScalarVT); 16284 } 16285 16286 return InOp; 16287 } 16288 16289 // FIXME: We should handle recursing on other vector shuffles and 16290 // scalar_to_vector here as well. 16291 16292 if (!LegalOperations || 16293 // FIXME: Should really be just isOperationLegalOrCustom. 16294 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecVT) || 16295 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VecVT)) { 16296 EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 16297 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, SVInVec, 16298 DAG.getConstant(OrigElt, DL, IndexTy)); 16299 } 16300 } 16301 16302 // If only EXTRACT_VECTOR_ELT nodes use the source vector we can 16303 // simplify it based on the (valid) extraction indices. 16304 if (llvm::all_of(VecOp->uses(), [&](SDNode *Use) { 16305 return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 16306 Use->getOperand(0) == VecOp && 16307 isa<ConstantSDNode>(Use->getOperand(1)); 16308 })) { 16309 APInt DemandedElts = APInt::getNullValue(NumElts); 16310 for (SDNode *Use : VecOp->uses()) { 16311 auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1)); 16312 if (CstElt->getAPIntValue().ult(NumElts)) 16313 DemandedElts.setBit(CstElt->getZExtValue()); 16314 } 16315 if (SimplifyDemandedVectorElts(VecOp, DemandedElts, true)) { 16316 // We simplified the vector operand of this extract element. If this 16317 // extract is not dead, visit it again so it is folded properly. 16318 if (N->getOpcode() != ISD::DELETED_NODE) 16319 AddToWorklist(N); 16320 return SDValue(N, 0); 16321 } 16322 } 16323 16324 // Everything under here is trying to match an extract of a loaded value. 16325 // If the result of load has to be truncated, then it's not necessarily 16326 // profitable. 16327 bool BCNumEltsChanged = false; 16328 EVT ExtVT = VecVT.getVectorElementType(); 16329 EVT LVT = ExtVT; 16330 if (ScalarVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, ScalarVT)) 16331 return SDValue(); 16332 16333 if (VecOp.getOpcode() == ISD::BITCAST) { 16334 // Don't duplicate a load with other uses. 16335 if (!VecOp.hasOneUse()) 16336 return SDValue(); 16337 16338 EVT BCVT = VecOp.getOperand(0).getValueType(); 16339 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 16340 return SDValue(); 16341 if (NumElts != BCVT.getVectorNumElements()) 16342 BCNumEltsChanged = true; 16343 VecOp = VecOp.getOperand(0); 16344 ExtVT = BCVT.getVectorElementType(); 16345 } 16346 16347 // extract (vector load $addr), i --> load $addr + i * size 16348 if (!LegalOperations && !IndexC && VecOp.hasOneUse() && 16349 ISD::isNormalLoad(VecOp.getNode()) && 16350 !Index->hasPredecessor(VecOp.getNode())) { 16351 auto *VecLoad = dyn_cast<LoadSDNode>(VecOp); 16352 if (VecLoad && !VecLoad->isVolatile()) 16353 return scalarizeExtractedVectorLoad(N, VecVT, Index, VecLoad); 16354 } 16355 16356 // Perform only after legalization to ensure build_vector / vector_shuffle 16357 // optimizations have already been done. 16358 if (!LegalOperations || !IndexC) 16359 return SDValue(); 16360 16361 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 16362 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 16363 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 16364 int Elt = IndexC->getZExtValue(); 16365 LoadSDNode *LN0 = nullptr; 16366 if (ISD::isNormalLoad(VecOp.getNode())) { 16367 LN0 = cast<LoadSDNode>(VecOp); 16368 } else if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 16369 VecOp.getOperand(0).getValueType() == ExtVT && 16370 ISD::isNormalLoad(VecOp.getOperand(0).getNode())) { 16371 // Don't duplicate a load with other uses. 16372 if (!VecOp.hasOneUse()) 16373 return SDValue(); 16374 16375 LN0 = cast<LoadSDNode>(VecOp.getOperand(0)); 16376 } 16377 if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(VecOp)) { 16378 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 16379 // => 16380 // (load $addr+1*size) 16381 16382 // Don't duplicate a load with other uses. 16383 if (!VecOp.hasOneUse()) 16384 return SDValue(); 16385 16386 // If the bit convert changed the number of elements, it is unsafe 16387 // to examine the mask. 16388 if (BCNumEltsChanged) 16389 return SDValue(); 16390 16391 // Select the input vector, guarding against out of range extract vector. 16392 int Idx = (Elt > (int)NumElts) ? -1 : Shuf->getMaskElt(Elt); 16393 VecOp = (Idx < (int)NumElts) ? VecOp.getOperand(0) : VecOp.getOperand(1); 16394 16395 if (VecOp.getOpcode() == ISD::BITCAST) { 16396 // Don't duplicate a load with other uses. 16397 if (!VecOp.hasOneUse()) 16398 return SDValue(); 16399 16400 VecOp = VecOp.getOperand(0); 16401 } 16402 if (ISD::isNormalLoad(VecOp.getNode())) { 16403 LN0 = cast<LoadSDNode>(VecOp); 16404 Elt = (Idx < (int)NumElts) ? Idx : Idx - (int)NumElts; 16405 Index = DAG.getConstant(Elt, DL, Index.getValueType()); 16406 } 16407 } 16408 16409 // Make sure we found a non-volatile load and the extractelement is 16410 // the only use. 16411 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile()) 16412 return SDValue(); 16413 16414 // If Idx was -1 above, Elt is going to be -1, so just return undef. 16415 if (Elt == -1) 16416 return DAG.getUNDEF(LVT); 16417 16418 return scalarizeExtractedVectorLoad(N, VecVT, Index, LN0); 16419 } 16420 16421 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 16422 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 16423 // We perform this optimization post type-legalization because 16424 // the type-legalizer often scalarizes integer-promoted vectors. 16425 // Performing this optimization before may create bit-casts which 16426 // will be type-legalized to complex code sequences. 16427 // We perform this optimization only before the operation legalizer because we 16428 // may introduce illegal operations. 16429 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 16430 return SDValue(); 16431 16432 unsigned NumInScalars = N->getNumOperands(); 16433 SDLoc DL(N); 16434 EVT VT = N->getValueType(0); 16435 16436 // Check to see if this is a BUILD_VECTOR of a bunch of values 16437 // which come from any_extend or zero_extend nodes. If so, we can create 16438 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 16439 // optimizations. We do not handle sign-extend because we can't fill the sign 16440 // using shuffles. 16441 EVT SourceType = MVT::Other; 16442 bool AllAnyExt = true; 16443 16444 for (unsigned i = 0; i != NumInScalars; ++i) { 16445 SDValue In = N->getOperand(i); 16446 // Ignore undef inputs. 16447 if (In.isUndef()) continue; 16448 16449 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 16450 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 16451 16452 // Abort if the element is not an extension. 16453 if (!ZeroExt && !AnyExt) { 16454 SourceType = MVT::Other; 16455 break; 16456 } 16457 16458 // The input is a ZeroExt or AnyExt. Check the original type. 16459 EVT InTy = In.getOperand(0).getValueType(); 16460 16461 // Check that all of the widened source types are the same. 16462 if (SourceType == MVT::Other) 16463 // First time. 16464 SourceType = InTy; 16465 else if (InTy != SourceType) { 16466 // Multiple income types. Abort. 16467 SourceType = MVT::Other; 16468 break; 16469 } 16470 16471 // Check if all of the extends are ANY_EXTENDs. 16472 AllAnyExt &= AnyExt; 16473 } 16474 16475 // In order to have valid types, all of the inputs must be extended from the 16476 // same source type and all of the inputs must be any or zero extend. 16477 // Scalar sizes must be a power of two. 16478 EVT OutScalarTy = VT.getScalarType(); 16479 bool ValidTypes = SourceType != MVT::Other && 16480 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 16481 isPowerOf2_32(SourceType.getSizeInBits()); 16482 16483 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 16484 // turn into a single shuffle instruction. 16485 if (!ValidTypes) 16486 return SDValue(); 16487 16488 bool isLE = DAG.getDataLayout().isLittleEndian(); 16489 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 16490 assert(ElemRatio > 1 && "Invalid element size ratio"); 16491 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 16492 DAG.getConstant(0, DL, SourceType); 16493 16494 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 16495 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 16496 16497 // Populate the new build_vector 16498 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 16499 SDValue Cast = N->getOperand(i); 16500 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 16501 Cast.getOpcode() == ISD::ZERO_EXTEND || 16502 Cast.isUndef()) && "Invalid cast opcode"); 16503 SDValue In; 16504 if (Cast.isUndef()) 16505 In = DAG.getUNDEF(SourceType); 16506 else 16507 In = Cast->getOperand(0); 16508 unsigned Index = isLE ? (i * ElemRatio) : 16509 (i * ElemRatio + (ElemRatio - 1)); 16510 16511 assert(Index < Ops.size() && "Invalid index"); 16512 Ops[Index] = In; 16513 } 16514 16515 // The type of the new BUILD_VECTOR node. 16516 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 16517 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 16518 "Invalid vector size"); 16519 // Check if the new vector type is legal. 16520 if (!isTypeLegal(VecVT) || 16521 (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) && 16522 TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))) 16523 return SDValue(); 16524 16525 // Make the new BUILD_VECTOR. 16526 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 16527 16528 // The new BUILD_VECTOR node has the potential to be further optimized. 16529 AddToWorklist(BV.getNode()); 16530 // Bitcast to the desired type. 16531 return DAG.getBitcast(VT, BV); 16532 } 16533 16534 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 16535 ArrayRef<int> VectorMask, 16536 SDValue VecIn1, SDValue VecIn2, 16537 unsigned LeftIdx, bool DidSplitVec) { 16538 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 16539 SDValue ZeroIdx = DAG.getConstant(0, DL, IdxTy); 16540 16541 EVT VT = N->getValueType(0); 16542 EVT InVT1 = VecIn1.getValueType(); 16543 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 16544 16545 unsigned NumElems = VT.getVectorNumElements(); 16546 unsigned ShuffleNumElems = NumElems; 16547 16548 // If we artificially split a vector in two already, then the offsets in the 16549 // operands will all be based off of VecIn1, even those in VecIn2. 16550 unsigned Vec2Offset = DidSplitVec ? 0 : InVT1.getVectorNumElements(); 16551 16552 // We can't generate a shuffle node with mismatched input and output types. 16553 // Try to make the types match the type of the output. 16554 if (InVT1 != VT || InVT2 != VT) { 16555 if ((VT.getSizeInBits() % InVT1.getSizeInBits() == 0) && InVT1 == InVT2) { 16556 // If the output vector length is a multiple of both input lengths, 16557 // we can concatenate them and pad the rest with undefs. 16558 unsigned NumConcats = VT.getSizeInBits() / InVT1.getSizeInBits(); 16559 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 16560 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 16561 ConcatOps[0] = VecIn1; 16562 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 16563 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 16564 VecIn2 = SDValue(); 16565 } else if (InVT1.getSizeInBits() == VT.getSizeInBits() * 2) { 16566 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) 16567 return SDValue(); 16568 16569 if (!VecIn2.getNode()) { 16570 // If we only have one input vector, and it's twice the size of the 16571 // output, split it in two. 16572 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 16573 DAG.getConstant(NumElems, DL, IdxTy)); 16574 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 16575 // Since we now have shorter input vectors, adjust the offset of the 16576 // second vector's start. 16577 Vec2Offset = NumElems; 16578 } else if (InVT2.getSizeInBits() <= InVT1.getSizeInBits()) { 16579 // VecIn1 is wider than the output, and we have another, possibly 16580 // smaller input. Pad the smaller input with undefs, shuffle at the 16581 // input vector width, and extract the output. 16582 // The shuffle type is different than VT, so check legality again. 16583 if (LegalOperations && 16584 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 16585 return SDValue(); 16586 16587 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 16588 // lower it back into a BUILD_VECTOR. So if the inserted type is 16589 // illegal, don't even try. 16590 if (InVT1 != InVT2) { 16591 if (!TLI.isTypeLegal(InVT2)) 16592 return SDValue(); 16593 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 16594 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 16595 } 16596 ShuffleNumElems = NumElems * 2; 16597 } else { 16598 // Both VecIn1 and VecIn2 are wider than the output, and VecIn2 is wider 16599 // than VecIn1. We can't handle this for now - this case will disappear 16600 // when we start sorting the vectors by type. 16601 return SDValue(); 16602 } 16603 } else if (InVT2.getSizeInBits() * 2 == VT.getSizeInBits() && 16604 InVT1.getSizeInBits() == VT.getSizeInBits()) { 16605 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 16606 ConcatOps[0] = VecIn2; 16607 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 16608 } else { 16609 // TODO: Support cases where the length mismatch isn't exactly by a 16610 // factor of 2. 16611 // TODO: Move this check upwards, so that if we have bad type 16612 // mismatches, we don't create any DAG nodes. 16613 return SDValue(); 16614 } 16615 } 16616 16617 // Initialize mask to undef. 16618 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 16619 16620 // Only need to run up to the number of elements actually used, not the 16621 // total number of elements in the shuffle - if we are shuffling a wider 16622 // vector, the high lanes should be set to undef. 16623 for (unsigned i = 0; i != NumElems; ++i) { 16624 if (VectorMask[i] <= 0) 16625 continue; 16626 16627 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 16628 if (VectorMask[i] == (int)LeftIdx) { 16629 Mask[i] = ExtIndex; 16630 } else if (VectorMask[i] == (int)LeftIdx + 1) { 16631 Mask[i] = Vec2Offset + ExtIndex; 16632 } 16633 } 16634 16635 // The type the input vectors may have changed above. 16636 InVT1 = VecIn1.getValueType(); 16637 16638 // If we already have a VecIn2, it should have the same type as VecIn1. 16639 // If we don't, get an undef/zero vector of the appropriate type. 16640 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 16641 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 16642 16643 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 16644 if (ShuffleNumElems > NumElems) 16645 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 16646 16647 return Shuffle; 16648 } 16649 16650 static SDValue reduceBuildVecToShuffleWithZero(SDNode *BV, SelectionDAG &DAG) { 16651 assert(BV->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector"); 16652 16653 // First, determine where the build vector is not undef. 16654 // TODO: We could extend this to handle zero elements as well as undefs. 16655 int NumBVOps = BV->getNumOperands(); 16656 int ZextElt = -1; 16657 for (int i = 0; i != NumBVOps; ++i) { 16658 SDValue Op = BV->getOperand(i); 16659 if (Op.isUndef()) 16660 continue; 16661 if (ZextElt == -1) 16662 ZextElt = i; 16663 else 16664 return SDValue(); 16665 } 16666 // Bail out if there's no non-undef element. 16667 if (ZextElt == -1) 16668 return SDValue(); 16669 16670 // The build vector contains some number of undef elements and exactly 16671 // one other element. That other element must be a zero-extended scalar 16672 // extracted from a vector at a constant index to turn this into a shuffle. 16673 // Also, require that the build vector does not implicitly truncate/extend 16674 // its elements. 16675 // TODO: This could be enhanced to allow ANY_EXTEND as well as ZERO_EXTEND. 16676 EVT VT = BV->getValueType(0); 16677 SDValue Zext = BV->getOperand(ZextElt); 16678 if (Zext.getOpcode() != ISD::ZERO_EXTEND || !Zext.hasOneUse() || 16679 Zext.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 16680 !isa<ConstantSDNode>(Zext.getOperand(0).getOperand(1)) || 16681 Zext.getValueSizeInBits() != VT.getScalarSizeInBits()) 16682 return SDValue(); 16683 16684 // The zero-extend must be a multiple of the source size, and we must be 16685 // building a vector of the same size as the source of the extract element. 16686 SDValue Extract = Zext.getOperand(0); 16687 unsigned DestSize = Zext.getValueSizeInBits(); 16688 unsigned SrcSize = Extract.getValueSizeInBits(); 16689 if (DestSize % SrcSize != 0 || 16690 Extract.getOperand(0).getValueSizeInBits() != VT.getSizeInBits()) 16691 return SDValue(); 16692 16693 // Create a shuffle mask that will combine the extracted element with zeros 16694 // and undefs. 16695 int ZextRatio = DestSize / SrcSize; 16696 int NumMaskElts = NumBVOps * ZextRatio; 16697 SmallVector<int, 32> ShufMask(NumMaskElts, -1); 16698 for (int i = 0; i != NumMaskElts; ++i) { 16699 if (i / ZextRatio == ZextElt) { 16700 // The low bits of the (potentially translated) extracted element map to 16701 // the source vector. The high bits map to zero. We will use a zero vector 16702 // as the 2nd source operand of the shuffle, so use the 1st element of 16703 // that vector (mask value is number-of-elements) for the high bits. 16704 if (i % ZextRatio == 0) 16705 ShufMask[i] = Extract.getConstantOperandVal(1); 16706 else 16707 ShufMask[i] = NumMaskElts; 16708 } 16709 16710 // Undef elements of the build vector remain undef because we initialize 16711 // the shuffle mask with -1. 16712 } 16713 16714 // Turn this into a shuffle with zero if that's legal. 16715 EVT VecVT = Extract.getOperand(0).getValueType(); 16716 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(ShufMask, VecVT)) 16717 return SDValue(); 16718 16719 // buildvec undef, ..., (zext (extractelt V, IndexC)), undef... --> 16720 // bitcast (shuffle V, ZeroVec, VectorMask) 16721 SDLoc DL(BV); 16722 SDValue ZeroVec = DAG.getConstant(0, DL, VecVT); 16723 SDValue Shuf = DAG.getVectorShuffle(VecVT, DL, Extract.getOperand(0), ZeroVec, 16724 ShufMask); 16725 return DAG.getBitcast(VT, Shuf); 16726 } 16727 16728 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 16729 // operations. If the types of the vectors we're extracting from allow it, 16730 // turn this into a vector_shuffle node. 16731 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 16732 SDLoc DL(N); 16733 EVT VT = N->getValueType(0); 16734 16735 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 16736 if (!isTypeLegal(VT)) 16737 return SDValue(); 16738 16739 if (SDValue V = reduceBuildVecToShuffleWithZero(N, DAG)) 16740 return V; 16741 16742 // May only combine to shuffle after legalize if shuffle is legal. 16743 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 16744 return SDValue(); 16745 16746 bool UsesZeroVector = false; 16747 unsigned NumElems = N->getNumOperands(); 16748 16749 // Record, for each element of the newly built vector, which input vector 16750 // that element comes from. -1 stands for undef, 0 for the zero vector, 16751 // and positive values for the input vectors. 16752 // VectorMask maps each element to its vector number, and VecIn maps vector 16753 // numbers to their initial SDValues. 16754 16755 SmallVector<int, 8> VectorMask(NumElems, -1); 16756 SmallVector<SDValue, 8> VecIn; 16757 VecIn.push_back(SDValue()); 16758 16759 for (unsigned i = 0; i != NumElems; ++i) { 16760 SDValue Op = N->getOperand(i); 16761 16762 if (Op.isUndef()) 16763 continue; 16764 16765 // See if we can use a blend with a zero vector. 16766 // TODO: Should we generalize this to a blend with an arbitrary constant 16767 // vector? 16768 if (isNullConstant(Op) || isNullFPConstant(Op)) { 16769 UsesZeroVector = true; 16770 VectorMask[i] = 0; 16771 continue; 16772 } 16773 16774 // Not an undef or zero. If the input is something other than an 16775 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out. 16776 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 16777 !isa<ConstantSDNode>(Op.getOperand(1))) 16778 return SDValue(); 16779 SDValue ExtractedFromVec = Op.getOperand(0); 16780 16781 const APInt &ExtractIdx = Op.getConstantOperandAPInt(1); 16782 if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements())) 16783 return SDValue(); 16784 16785 // All inputs must have the same element type as the output. 16786 if (VT.getVectorElementType() != 16787 ExtractedFromVec.getValueType().getVectorElementType()) 16788 return SDValue(); 16789 16790 // Have we seen this input vector before? 16791 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 16792 // a map back from SDValues to numbers isn't worth it. 16793 unsigned Idx = std::distance( 16794 VecIn.begin(), std::find(VecIn.begin(), VecIn.end(), ExtractedFromVec)); 16795 if (Idx == VecIn.size()) 16796 VecIn.push_back(ExtractedFromVec); 16797 16798 VectorMask[i] = Idx; 16799 } 16800 16801 // If we didn't find at least one input vector, bail out. 16802 if (VecIn.size() < 2) 16803 return SDValue(); 16804 16805 // If all the Operands of BUILD_VECTOR extract from same 16806 // vector, then split the vector efficiently based on the maximum 16807 // vector access index and adjust the VectorMask and 16808 // VecIn accordingly. 16809 bool DidSplitVec = false; 16810 if (VecIn.size() == 2) { 16811 unsigned MaxIndex = 0; 16812 unsigned NearestPow2 = 0; 16813 SDValue Vec = VecIn.back(); 16814 EVT InVT = Vec.getValueType(); 16815 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 16816 SmallVector<unsigned, 8> IndexVec(NumElems, 0); 16817 16818 for (unsigned i = 0; i < NumElems; i++) { 16819 if (VectorMask[i] <= 0) 16820 continue; 16821 unsigned Index = N->getOperand(i).getConstantOperandVal(1); 16822 IndexVec[i] = Index; 16823 MaxIndex = std::max(MaxIndex, Index); 16824 } 16825 16826 NearestPow2 = PowerOf2Ceil(MaxIndex); 16827 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && 16828 NumElems * 2 < NearestPow2) { 16829 unsigned SplitSize = NearestPow2 / 2; 16830 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), 16831 InVT.getVectorElementType(), SplitSize); 16832 if (TLI.isTypeLegal(SplitVT)) { 16833 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 16834 DAG.getConstant(SplitSize, DL, IdxTy)); 16835 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 16836 DAG.getConstant(0, DL, IdxTy)); 16837 VecIn.pop_back(); 16838 VecIn.push_back(VecIn1); 16839 VecIn.push_back(VecIn2); 16840 DidSplitVec = true; 16841 16842 for (unsigned i = 0; i < NumElems; i++) { 16843 if (VectorMask[i] <= 0) 16844 continue; 16845 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; 16846 } 16847 } 16848 } 16849 } 16850 16851 // TODO: We want to sort the vectors by descending length, so that adjacent 16852 // pairs have similar length, and the longer vector is always first in the 16853 // pair. 16854 16855 // TODO: Should this fire if some of the input vectors has illegal type (like 16856 // it does now), or should we let legalization run its course first? 16857 16858 // Shuffle phase: 16859 // Take pairs of vectors, and shuffle them so that the result has elements 16860 // from these vectors in the correct places. 16861 // For example, given: 16862 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 16863 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 16864 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 16865 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 16866 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 16867 // We will generate: 16868 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 16869 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 16870 SmallVector<SDValue, 4> Shuffles; 16871 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 16872 unsigned LeftIdx = 2 * In + 1; 16873 SDValue VecLeft = VecIn[LeftIdx]; 16874 SDValue VecRight = 16875 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 16876 16877 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 16878 VecRight, LeftIdx, DidSplitVec)) 16879 Shuffles.push_back(Shuffle); 16880 else 16881 return SDValue(); 16882 } 16883 16884 // If we need the zero vector as an "ingredient" in the blend tree, add it 16885 // to the list of shuffles. 16886 if (UsesZeroVector) 16887 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 16888 : DAG.getConstantFP(0.0, DL, VT)); 16889 16890 // If we only have one shuffle, we're done. 16891 if (Shuffles.size() == 1) 16892 return Shuffles[0]; 16893 16894 // Update the vector mask to point to the post-shuffle vectors. 16895 for (int &Vec : VectorMask) 16896 if (Vec == 0) 16897 Vec = Shuffles.size() - 1; 16898 else 16899 Vec = (Vec - 1) / 2; 16900 16901 // More than one shuffle. Generate a binary tree of blends, e.g. if from 16902 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 16903 // generate: 16904 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 16905 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 16906 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 16907 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 16908 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 16909 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 16910 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 16911 16912 // Make sure the initial size of the shuffle list is even. 16913 if (Shuffles.size() % 2) 16914 Shuffles.push_back(DAG.getUNDEF(VT)); 16915 16916 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 16917 if (CurSize % 2) { 16918 Shuffles[CurSize] = DAG.getUNDEF(VT); 16919 CurSize++; 16920 } 16921 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 16922 int Left = 2 * In; 16923 int Right = 2 * In + 1; 16924 SmallVector<int, 8> Mask(NumElems, -1); 16925 for (unsigned i = 0; i != NumElems; ++i) { 16926 if (VectorMask[i] == Left) { 16927 Mask[i] = i; 16928 VectorMask[i] = In; 16929 } else if (VectorMask[i] == Right) { 16930 Mask[i] = i + NumElems; 16931 VectorMask[i] = In; 16932 } 16933 } 16934 16935 Shuffles[In] = 16936 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 16937 } 16938 } 16939 return Shuffles[0]; 16940 } 16941 16942 // Try to turn a build vector of zero extends of extract vector elts into a 16943 // a vector zero extend and possibly an extract subvector. 16944 // TODO: Support sign extend? 16945 // TODO: Allow undef elements? 16946 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) { 16947 if (LegalOperations) 16948 return SDValue(); 16949 16950 EVT VT = N->getValueType(0); 16951 16952 bool FoundZeroExtend = false; 16953 SDValue Op0 = N->getOperand(0); 16954 auto checkElem = [&](SDValue Op) -> int64_t { 16955 unsigned Opc = Op.getOpcode(); 16956 FoundZeroExtend |= (Opc == ISD::ZERO_EXTEND); 16957 if ((Op.getOpcode() == ISD::ZERO_EXTEND || Opc == ISD::ANY_EXTEND) && 16958 Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 16959 Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0)) 16960 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1))) 16961 return C->getZExtValue(); 16962 return -1; 16963 }; 16964 16965 // Make sure the first element matches 16966 // (zext (extract_vector_elt X, C)) 16967 int64_t Offset = checkElem(Op0); 16968 if (Offset < 0) 16969 return SDValue(); 16970 16971 unsigned NumElems = N->getNumOperands(); 16972 SDValue In = Op0.getOperand(0).getOperand(0); 16973 EVT InSVT = In.getValueType().getScalarType(); 16974 EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems); 16975 16976 // Don't create an illegal input type after type legalization. 16977 if (LegalTypes && !TLI.isTypeLegal(InVT)) 16978 return SDValue(); 16979 16980 // Ensure all the elements come from the same vector and are adjacent. 16981 for (unsigned i = 1; i != NumElems; ++i) { 16982 if ((Offset + i) != checkElem(N->getOperand(i))) 16983 return SDValue(); 16984 } 16985 16986 SDLoc DL(N); 16987 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In, 16988 Op0.getOperand(0).getOperand(1)); 16989 return DAG.getNode(FoundZeroExtend ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, DL, 16990 VT, In); 16991 } 16992 16993 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 16994 EVT VT = N->getValueType(0); 16995 16996 // A vector built entirely of undefs is undef. 16997 if (ISD::allOperandsUndef(N)) 16998 return DAG.getUNDEF(VT); 16999 17000 // If this is a splat of a bitcast from another vector, change to a 17001 // concat_vector. 17002 // For example: 17003 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) -> 17004 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X)))) 17005 // 17006 // If X is a build_vector itself, the concat can become a larger build_vector. 17007 // TODO: Maybe this is useful for non-splat too? 17008 if (!LegalOperations) { 17009 if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) { 17010 Splat = peekThroughBitcasts(Splat); 17011 EVT SrcVT = Splat.getValueType(); 17012 if (SrcVT.isVector()) { 17013 unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements(); 17014 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), 17015 SrcVT.getVectorElementType(), NumElts); 17016 if (!LegalTypes || TLI.isTypeLegal(NewVT)) { 17017 SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat); 17018 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), 17019 NewVT, Ops); 17020 return DAG.getBitcast(VT, Concat); 17021 } 17022 } 17023 } 17024 } 17025 17026 // Check if we can express BUILD VECTOR via subvector extract. 17027 if (!LegalTypes && (N->getNumOperands() > 1)) { 17028 SDValue Op0 = N->getOperand(0); 17029 auto checkElem = [&](SDValue Op) -> uint64_t { 17030 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 17031 (Op0.getOperand(0) == Op.getOperand(0))) 17032 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 17033 return CNode->getZExtValue(); 17034 return -1; 17035 }; 17036 17037 int Offset = checkElem(Op0); 17038 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 17039 if (Offset + i != checkElem(N->getOperand(i))) { 17040 Offset = -1; 17041 break; 17042 } 17043 } 17044 17045 if ((Offset == 0) && 17046 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 17047 return Op0.getOperand(0); 17048 if ((Offset != -1) && 17049 ((Offset % N->getValueType(0).getVectorNumElements()) == 17050 0)) // IDX must be multiple of output size. 17051 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 17052 Op0.getOperand(0), Op0.getOperand(1)); 17053 } 17054 17055 if (SDValue V = convertBuildVecZextToZext(N)) 17056 return V; 17057 17058 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 17059 return V; 17060 17061 if (SDValue V = reduceBuildVecToShuffle(N)) 17062 return V; 17063 17064 return SDValue(); 17065 } 17066 17067 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 17068 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17069 EVT OpVT = N->getOperand(0).getValueType(); 17070 17071 // If the operands are legal vectors, leave them alone. 17072 if (TLI.isTypeLegal(OpVT)) 17073 return SDValue(); 17074 17075 SDLoc DL(N); 17076 EVT VT = N->getValueType(0); 17077 SmallVector<SDValue, 8> Ops; 17078 17079 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 17080 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 17081 17082 // Keep track of what we encounter. 17083 bool AnyInteger = false; 17084 bool AnyFP = false; 17085 for (const SDValue &Op : N->ops()) { 17086 if (ISD::BITCAST == Op.getOpcode() && 17087 !Op.getOperand(0).getValueType().isVector()) 17088 Ops.push_back(Op.getOperand(0)); 17089 else if (ISD::UNDEF == Op.getOpcode()) 17090 Ops.push_back(ScalarUndef); 17091 else 17092 return SDValue(); 17093 17094 // Note whether we encounter an integer or floating point scalar. 17095 // If it's neither, bail out, it could be something weird like x86mmx. 17096 EVT LastOpVT = Ops.back().getValueType(); 17097 if (LastOpVT.isFloatingPoint()) 17098 AnyFP = true; 17099 else if (LastOpVT.isInteger()) 17100 AnyInteger = true; 17101 else 17102 return SDValue(); 17103 } 17104 17105 // If any of the operands is a floating point scalar bitcast to a vector, 17106 // use floating point types throughout, and bitcast everything. 17107 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 17108 if (AnyFP) { 17109 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 17110 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 17111 if (AnyInteger) { 17112 for (SDValue &Op : Ops) { 17113 if (Op.getValueType() == SVT) 17114 continue; 17115 if (Op.isUndef()) 17116 Op = ScalarUndef; 17117 else 17118 Op = DAG.getBitcast(SVT, Op); 17119 } 17120 } 17121 } 17122 17123 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 17124 VT.getSizeInBits() / SVT.getSizeInBits()); 17125 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 17126 } 17127 17128 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 17129 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 17130 // most two distinct vectors the same size as the result, attempt to turn this 17131 // into a legal shuffle. 17132 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 17133 EVT VT = N->getValueType(0); 17134 EVT OpVT = N->getOperand(0).getValueType(); 17135 int NumElts = VT.getVectorNumElements(); 17136 int NumOpElts = OpVT.getVectorNumElements(); 17137 17138 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 17139 SmallVector<int, 8> Mask; 17140 17141 for (SDValue Op : N->ops()) { 17142 Op = peekThroughBitcasts(Op); 17143 17144 // UNDEF nodes convert to UNDEF shuffle mask values. 17145 if (Op.isUndef()) { 17146 Mask.append((unsigned)NumOpElts, -1); 17147 continue; 17148 } 17149 17150 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 17151 return SDValue(); 17152 17153 // What vector are we extracting the subvector from and at what index? 17154 SDValue ExtVec = Op.getOperand(0); 17155 17156 // We want the EVT of the original extraction to correctly scale the 17157 // extraction index. 17158 EVT ExtVT = ExtVec.getValueType(); 17159 ExtVec = peekThroughBitcasts(ExtVec); 17160 17161 // UNDEF nodes convert to UNDEF shuffle mask values. 17162 if (ExtVec.isUndef()) { 17163 Mask.append((unsigned)NumOpElts, -1); 17164 continue; 17165 } 17166 17167 if (!isa<ConstantSDNode>(Op.getOperand(1))) 17168 return SDValue(); 17169 int ExtIdx = Op.getConstantOperandVal(1); 17170 17171 // Ensure that we are extracting a subvector from a vector the same 17172 // size as the result. 17173 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 17174 return SDValue(); 17175 17176 // Scale the subvector index to account for any bitcast. 17177 int NumExtElts = ExtVT.getVectorNumElements(); 17178 if (0 == (NumExtElts % NumElts)) 17179 ExtIdx /= (NumExtElts / NumElts); 17180 else if (0 == (NumElts % NumExtElts)) 17181 ExtIdx *= (NumElts / NumExtElts); 17182 else 17183 return SDValue(); 17184 17185 // At most we can reference 2 inputs in the final shuffle. 17186 if (SV0.isUndef() || SV0 == ExtVec) { 17187 SV0 = ExtVec; 17188 for (int i = 0; i != NumOpElts; ++i) 17189 Mask.push_back(i + ExtIdx); 17190 } else if (SV1.isUndef() || SV1 == ExtVec) { 17191 SV1 = ExtVec; 17192 for (int i = 0; i != NumOpElts; ++i) 17193 Mask.push_back(i + ExtIdx + NumElts); 17194 } else { 17195 return SDValue(); 17196 } 17197 } 17198 17199 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT)) 17200 return SDValue(); 17201 17202 return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 17203 DAG.getBitcast(VT, SV1), Mask); 17204 } 17205 17206 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 17207 // If we only have one input vector, we don't need to do any concatenation. 17208 if (N->getNumOperands() == 1) 17209 return N->getOperand(0); 17210 17211 // Check if all of the operands are undefs. 17212 EVT VT = N->getValueType(0); 17213 if (ISD::allOperandsUndef(N)) 17214 return DAG.getUNDEF(VT); 17215 17216 // Optimize concat_vectors where all but the first of the vectors are undef. 17217 if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) { 17218 return Op.isUndef(); 17219 })) { 17220 SDValue In = N->getOperand(0); 17221 assert(In.getValueType().isVector() && "Must concat vectors"); 17222 17223 SDValue Scalar = peekThroughOneUseBitcasts(In); 17224 17225 // concat_vectors(scalar_to_vector(scalar), undef) -> 17226 // scalar_to_vector(scalar) 17227 if (!LegalOperations && Scalar.getOpcode() == ISD::SCALAR_TO_VECTOR && 17228 Scalar.hasOneUse()) { 17229 EVT SVT = Scalar.getValueType().getVectorElementType(); 17230 if (SVT == Scalar.getOperand(0).getValueType()) 17231 Scalar = Scalar.getOperand(0); 17232 } 17233 17234 // concat_vectors(scalar, undef) -> scalar_to_vector(scalar) 17235 if (!Scalar.getValueType().isVector()) { 17236 // If the bitcast type isn't legal, it might be a trunc of a legal type; 17237 // look through the trunc so we can still do the transform: 17238 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 17239 if (Scalar->getOpcode() == ISD::TRUNCATE && 17240 !TLI.isTypeLegal(Scalar.getValueType()) && 17241 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 17242 Scalar = Scalar->getOperand(0); 17243 17244 EVT SclTy = Scalar.getValueType(); 17245 17246 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 17247 return SDValue(); 17248 17249 // Bail out if the vector size is not a multiple of the scalar size. 17250 if (VT.getSizeInBits() % SclTy.getSizeInBits()) 17251 return SDValue(); 17252 17253 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 17254 if (VNTNumElms < 2) 17255 return SDValue(); 17256 17257 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 17258 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 17259 return SDValue(); 17260 17261 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 17262 return DAG.getBitcast(VT, Res); 17263 } 17264 } 17265 17266 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 17267 // We have already tested above for an UNDEF only concatenation. 17268 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 17269 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 17270 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 17271 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 17272 }; 17273 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 17274 SmallVector<SDValue, 8> Opnds; 17275 EVT SVT = VT.getScalarType(); 17276 17277 EVT MinVT = SVT; 17278 if (!SVT.isFloatingPoint()) { 17279 // If BUILD_VECTOR are from built from integer, they may have different 17280 // operand types. Get the smallest type and truncate all operands to it. 17281 bool FoundMinVT = false; 17282 for (const SDValue &Op : N->ops()) 17283 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 17284 EVT OpSVT = Op.getOperand(0).getValueType(); 17285 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 17286 FoundMinVT = true; 17287 } 17288 assert(FoundMinVT && "Concat vector type mismatch"); 17289 } 17290 17291 for (const SDValue &Op : N->ops()) { 17292 EVT OpVT = Op.getValueType(); 17293 unsigned NumElts = OpVT.getVectorNumElements(); 17294 17295 if (ISD::UNDEF == Op.getOpcode()) 17296 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 17297 17298 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 17299 if (SVT.isFloatingPoint()) { 17300 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 17301 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 17302 } else { 17303 for (unsigned i = 0; i != NumElts; ++i) 17304 Opnds.push_back( 17305 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 17306 } 17307 } 17308 } 17309 17310 assert(VT.getVectorNumElements() == Opnds.size() && 17311 "Concat vector type mismatch"); 17312 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 17313 } 17314 17315 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 17316 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 17317 return V; 17318 17319 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 17320 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) 17321 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 17322 return V; 17323 17324 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 17325 // nodes often generate nop CONCAT_VECTOR nodes. 17326 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that 17327 // place the incoming vectors at the exact same location. 17328 SDValue SingleSource = SDValue(); 17329 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements(); 17330 17331 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 17332 SDValue Op = N->getOperand(i); 17333 17334 if (Op.isUndef()) 17335 continue; 17336 17337 // Check if this is the identity extract: 17338 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 17339 return SDValue(); 17340 17341 // Find the single incoming vector for the extract_subvector. 17342 if (SingleSource.getNode()) { 17343 if (Op.getOperand(0) != SingleSource) 17344 return SDValue(); 17345 } else { 17346 SingleSource = Op.getOperand(0); 17347 17348 // Check the source type is the same as the type of the result. 17349 // If not, this concat may extend the vector, so we can not 17350 // optimize it away. 17351 if (SingleSource.getValueType() != N->getValueType(0)) 17352 return SDValue(); 17353 } 17354 17355 unsigned IdentityIndex = i * PartNumElem; 17356 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 17357 // The extract index must be constant. 17358 if (!CS) 17359 return SDValue(); 17360 17361 // Check that we are reading from the identity index. 17362 if (CS->getZExtValue() != IdentityIndex) 17363 return SDValue(); 17364 } 17365 17366 if (SingleSource.getNode()) 17367 return SingleSource; 17368 17369 return SDValue(); 17370 } 17371 17372 /// If we are extracting a subvector produced by a wide binary operator try 17373 /// to use a narrow binary operator and/or avoid concatenation and extraction. 17374 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG) { 17375 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 17376 // some of these bailouts with other transforms. 17377 17378 // The extract index must be a constant, so we can map it to a concat operand. 17379 auto *ExtractIndexC = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 17380 if (!ExtractIndexC) 17381 return SDValue(); 17382 17383 // We are looking for an optionally bitcasted wide vector binary operator 17384 // feeding an extract subvector. 17385 SDValue BinOp = peekThroughBitcasts(Extract->getOperand(0)); 17386 if (!ISD::isBinaryOp(BinOp.getNode())) 17387 return SDValue(); 17388 17389 // The binop must be a vector type, so we can extract some fraction of it. 17390 EVT WideBVT = BinOp.getValueType(); 17391 if (!WideBVT.isVector()) 17392 return SDValue(); 17393 17394 EVT VT = Extract->getValueType(0); 17395 unsigned ExtractIndex = ExtractIndexC->getZExtValue(); 17396 assert(ExtractIndex % VT.getVectorNumElements() == 0 && 17397 "Extract index is not a multiple of the vector length."); 17398 17399 // Bail out if this is not a proper multiple width extraction. 17400 unsigned WideWidth = WideBVT.getSizeInBits(); 17401 unsigned NarrowWidth = VT.getSizeInBits(); 17402 if (WideWidth % NarrowWidth != 0) 17403 return SDValue(); 17404 17405 // Bail out if we are extracting a fraction of a single operation. This can 17406 // occur because we potentially looked through a bitcast of the binop. 17407 unsigned NarrowingRatio = WideWidth / NarrowWidth; 17408 unsigned WideNumElts = WideBVT.getVectorNumElements(); 17409 if (WideNumElts % NarrowingRatio != 0) 17410 return SDValue(); 17411 17412 // Bail out if the target does not support a narrower version of the binop. 17413 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 17414 WideNumElts / NarrowingRatio); 17415 unsigned BOpcode = BinOp.getOpcode(); 17416 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17417 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 17418 return SDValue(); 17419 17420 // If extraction is cheap, we don't need to look at the binop operands 17421 // for concat ops. The narrow binop alone makes this transform profitable. 17422 // We can't just reuse the original extract index operand because we may have 17423 // bitcasted. 17424 unsigned ConcatOpNum = ExtractIndex / VT.getVectorNumElements(); 17425 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 17426 EVT ExtBOIdxVT = Extract->getOperand(1).getValueType(); 17427 if (TLI.isExtractSubvectorCheap(NarrowBVT, WideBVT, ExtBOIdx) && 17428 BinOp.hasOneUse() && Extract->getOperand(0)->hasOneUse()) { 17429 // extract (binop B0, B1), N --> binop (extract B0, N), (extract B1, N) 17430 SDLoc DL(Extract); 17431 SDValue NewExtIndex = DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT); 17432 SDValue X = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 17433 BinOp.getOperand(0), NewExtIndex); 17434 SDValue Y = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 17435 BinOp.getOperand(1), NewExtIndex); 17436 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y, 17437 BinOp.getNode()->getFlags()); 17438 return DAG.getBitcast(VT, NarrowBinOp); 17439 } 17440 17441 // Only handle the case where we are doubling and then halving. A larger ratio 17442 // may require more than two narrow binops to replace the wide binop. 17443 if (NarrowingRatio != 2) 17444 return SDValue(); 17445 17446 // TODO: The motivating case for this transform is an x86 AVX1 target. That 17447 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 17448 // flavors, but no other 256-bit integer support. This could be extended to 17449 // handle any binop, but that may require fixing/adding other folds to avoid 17450 // codegen regressions. 17451 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 17452 return SDValue(); 17453 17454 // We need at least one concatenation operation of a binop operand to make 17455 // this transform worthwhile. The concat must double the input vector sizes. 17456 // TODO: Should we also handle INSERT_SUBVECTOR patterns? 17457 SDValue LHS = peekThroughBitcasts(BinOp.getOperand(0)); 17458 SDValue RHS = peekThroughBitcasts(BinOp.getOperand(1)); 17459 bool ConcatL = 17460 LHS.getOpcode() == ISD::CONCAT_VECTORS && LHS.getNumOperands() == 2; 17461 bool ConcatR = 17462 RHS.getOpcode() == ISD::CONCAT_VECTORS && RHS.getNumOperands() == 2; 17463 if (ConcatL || ConcatR) { 17464 // If a binop operand was not the result of a concat, we must extract a 17465 // half-sized operand for our new narrow binop: 17466 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 17467 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, IndexC) 17468 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, IndexC), YN 17469 SDLoc DL(Extract); 17470 SDValue IndexC = DAG.getConstant(ExtBOIdx, DL, ExtBOIdxVT); 17471 SDValue X = ConcatL ? DAG.getBitcast(NarrowBVT, LHS.getOperand(ConcatOpNum)) 17472 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 17473 BinOp.getOperand(0), IndexC); 17474 17475 SDValue Y = ConcatR ? DAG.getBitcast(NarrowBVT, RHS.getOperand(ConcatOpNum)) 17476 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 17477 BinOp.getOperand(1), IndexC); 17478 17479 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 17480 return DAG.getBitcast(VT, NarrowBinOp); 17481 } 17482 17483 return SDValue(); 17484 } 17485 17486 /// If we are extracting a subvector from a wide vector load, convert to a 17487 /// narrow load to eliminate the extraction: 17488 /// (extract_subvector (load wide vector)) --> (load narrow vector) 17489 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 17490 // TODO: Add support for big-endian. The offset calculation must be adjusted. 17491 if (DAG.getDataLayout().isBigEndian()) 17492 return SDValue(); 17493 17494 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 17495 auto *ExtIdx = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 17496 if (!Ld || Ld->getExtensionType() || Ld->isVolatile() || !ExtIdx) 17497 return SDValue(); 17498 17499 // Allow targets to opt-out. 17500 EVT VT = Extract->getValueType(0); 17501 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17502 if (!TLI.shouldReduceLoadWidth(Ld, Ld->getExtensionType(), VT)) 17503 return SDValue(); 17504 17505 // The narrow load will be offset from the base address of the old load if 17506 // we are extracting from something besides index 0 (little-endian). 17507 SDLoc DL(Extract); 17508 SDValue BaseAddr = Ld->getOperand(1); 17509 unsigned Offset = ExtIdx->getZExtValue() * VT.getScalarType().getStoreSize(); 17510 17511 // TODO: Use "BaseIndexOffset" to make this more effective. 17512 SDValue NewAddr = DAG.getMemBasePlusOffset(BaseAddr, Offset, DL); 17513 MachineFunction &MF = DAG.getMachineFunction(); 17514 MachineMemOperand *MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset, 17515 VT.getStoreSize()); 17516 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 17517 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 17518 return NewLd; 17519 } 17520 17521 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) { 17522 EVT NVT = N->getValueType(0); 17523 SDValue V = N->getOperand(0); 17524 17525 // Extract from UNDEF is UNDEF. 17526 if (V.isUndef()) 17527 return DAG.getUNDEF(NVT); 17528 17529 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 17530 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 17531 return NarrowLoad; 17532 17533 // Combine an extract of an extract into a single extract_subvector. 17534 // ext (ext X, C), 0 --> ext X, C 17535 if (isNullConstant(N->getOperand(1)) && 17536 V.getOpcode() == ISD::EXTRACT_SUBVECTOR && V.hasOneUse() && 17537 isa<ConstantSDNode>(V.getOperand(1))) { 17538 if (TLI.isExtractSubvectorCheap(NVT, V.getOperand(0).getValueType(), 17539 V.getConstantOperandVal(1)) && 17540 TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NVT)) { 17541 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, V.getOperand(0), 17542 V.getOperand(1)); 17543 } 17544 } 17545 17546 // Combine: 17547 // (extract_subvec (concat V1, V2, ...), i) 17548 // Into: 17549 // Vi if possible 17550 // Only operand 0 is checked as 'concat' assumes all inputs of the same 17551 // type. 17552 if (V.getOpcode() == ISD::CONCAT_VECTORS && 17553 isa<ConstantSDNode>(N->getOperand(1)) && 17554 V.getOperand(0).getValueType() == NVT) { 17555 unsigned Idx = N->getConstantOperandVal(1); 17556 unsigned NumElems = NVT.getVectorNumElements(); 17557 assert((Idx % NumElems) == 0 && 17558 "IDX in concat is not a multiple of the result vector length."); 17559 return V->getOperand(Idx / NumElems); 17560 } 17561 17562 V = peekThroughBitcasts(V); 17563 17564 // If the input is a build vector. Try to make a smaller build vector. 17565 if (V.getOpcode() == ISD::BUILD_VECTOR) { 17566 if (auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))) { 17567 EVT InVT = V.getValueType(); 17568 unsigned ExtractSize = NVT.getSizeInBits(); 17569 unsigned EltSize = InVT.getScalarSizeInBits(); 17570 // Only do this if we won't split any elements. 17571 if (ExtractSize % EltSize == 0) { 17572 unsigned NumElems = ExtractSize / EltSize; 17573 EVT EltVT = InVT.getVectorElementType(); 17574 EVT ExtractVT = NumElems == 1 ? EltVT : 17575 EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems); 17576 if ((Level < AfterLegalizeDAG || 17577 (NumElems == 1 || 17578 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) && 17579 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { 17580 unsigned IdxVal = (Idx->getZExtValue() * NVT.getScalarSizeInBits()) / 17581 EltSize; 17582 if (NumElems == 1) { 17583 SDValue Src = V->getOperand(IdxVal); 17584 if (EltVT != Src.getValueType()) 17585 Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src); 17586 17587 return DAG.getBitcast(NVT, Src); 17588 } 17589 17590 // Extract the pieces from the original build_vector. 17591 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), 17592 makeArrayRef(V->op_begin() + IdxVal, 17593 NumElems)); 17594 return DAG.getBitcast(NVT, BuildVec); 17595 } 17596 } 17597 } 17598 } 17599 17600 if (V.getOpcode() == ISD::INSERT_SUBVECTOR) { 17601 // Handle only simple case where vector being inserted and vector 17602 // being extracted are of same size. 17603 EVT SmallVT = V.getOperand(1).getValueType(); 17604 if (!NVT.bitsEq(SmallVT)) 17605 return SDValue(); 17606 17607 // Only handle cases where both indexes are constants. 17608 auto *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 17609 auto *InsIdx = dyn_cast<ConstantSDNode>(V.getOperand(2)); 17610 17611 if (InsIdx && ExtIdx) { 17612 // Combine: 17613 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 17614 // Into: 17615 // indices are equal or bit offsets are equal => V1 17616 // otherwise => (extract_subvec V1, ExtIdx) 17617 if (InsIdx->getZExtValue() * SmallVT.getScalarSizeInBits() == 17618 ExtIdx->getZExtValue() * NVT.getScalarSizeInBits()) 17619 return DAG.getBitcast(NVT, V.getOperand(1)); 17620 return DAG.getNode( 17621 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 17622 DAG.getBitcast(N->getOperand(0).getValueType(), V.getOperand(0)), 17623 N->getOperand(1)); 17624 } 17625 } 17626 17627 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG)) 17628 return NarrowBOp; 17629 17630 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 17631 return SDValue(N, 0); 17632 17633 return SDValue(); 17634 } 17635 17636 /// Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles 17637 /// followed by concatenation. Narrow vector ops may have better performance 17638 /// than wide ops, and this can unlock further narrowing of other vector ops. 17639 /// Targets can invert this transform later if it is not profitable. 17640 static SDValue foldShuffleOfConcatUndefs(ShuffleVectorSDNode *Shuf, 17641 SelectionDAG &DAG) { 17642 SDValue N0 = Shuf->getOperand(0), N1 = Shuf->getOperand(1); 17643 if (N0.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 || 17644 N1.getOpcode() != ISD::CONCAT_VECTORS || N1.getNumOperands() != 2 || 17645 !N0.getOperand(1).isUndef() || !N1.getOperand(1).isUndef()) 17646 return SDValue(); 17647 17648 // Split the wide shuffle mask into halves. Any mask element that is accessing 17649 // operand 1 is offset down to account for narrowing of the vectors. 17650 ArrayRef<int> Mask = Shuf->getMask(); 17651 EVT VT = Shuf->getValueType(0); 17652 unsigned NumElts = VT.getVectorNumElements(); 17653 unsigned HalfNumElts = NumElts / 2; 17654 SmallVector<int, 16> Mask0(HalfNumElts, -1); 17655 SmallVector<int, 16> Mask1(HalfNumElts, -1); 17656 for (unsigned i = 0; i != NumElts; ++i) { 17657 if (Mask[i] == -1) 17658 continue; 17659 int M = Mask[i] < (int)NumElts ? Mask[i] : Mask[i] - (int)HalfNumElts; 17660 if (i < HalfNumElts) 17661 Mask0[i] = M; 17662 else 17663 Mask1[i - HalfNumElts] = M; 17664 } 17665 17666 // Ask the target if this is a valid transform. 17667 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 17668 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 17669 HalfNumElts); 17670 if (!TLI.isShuffleMaskLegal(Mask0, HalfVT) || 17671 !TLI.isShuffleMaskLegal(Mask1, HalfVT)) 17672 return SDValue(); 17673 17674 // shuffle (concat X, undef), (concat Y, undef), Mask --> 17675 // concat (shuffle X, Y, Mask0), (shuffle X, Y, Mask1) 17676 SDValue X = N0.getOperand(0), Y = N1.getOperand(0); 17677 SDLoc DL(Shuf); 17678 SDValue Shuf0 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask0); 17679 SDValue Shuf1 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask1); 17680 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Shuf0, Shuf1); 17681 } 17682 17683 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 17684 // or turn a shuffle of a single concat into simpler shuffle then concat. 17685 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 17686 EVT VT = N->getValueType(0); 17687 unsigned NumElts = VT.getVectorNumElements(); 17688 17689 SDValue N0 = N->getOperand(0); 17690 SDValue N1 = N->getOperand(1); 17691 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 17692 ArrayRef<int> Mask = SVN->getMask(); 17693 17694 SmallVector<SDValue, 4> Ops; 17695 EVT ConcatVT = N0.getOperand(0).getValueType(); 17696 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 17697 unsigned NumConcats = NumElts / NumElemsPerConcat; 17698 17699 auto IsUndefMaskElt = [](int i) { return i == -1; }; 17700 17701 // Special case: shuffle(concat(A,B)) can be more efficiently represented 17702 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 17703 // half vector elements. 17704 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 17705 llvm::all_of(Mask.slice(NumElemsPerConcat, NumElemsPerConcat), 17706 IsUndefMaskElt)) { 17707 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), 17708 N0.getOperand(1), 17709 Mask.slice(0, NumElemsPerConcat)); 17710 N1 = DAG.getUNDEF(ConcatVT); 17711 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 17712 } 17713 17714 // Look at every vector that's inserted. We're looking for exact 17715 // subvector-sized copies from a concatenated vector 17716 for (unsigned I = 0; I != NumConcats; ++I) { 17717 unsigned Begin = I * NumElemsPerConcat; 17718 ArrayRef<int> SubMask = Mask.slice(Begin, NumElemsPerConcat); 17719 17720 // Make sure we're dealing with a copy. 17721 if (llvm::all_of(SubMask, IsUndefMaskElt)) { 17722 Ops.push_back(DAG.getUNDEF(ConcatVT)); 17723 continue; 17724 } 17725 17726 int OpIdx = -1; 17727 for (int i = 0; i != (int)NumElemsPerConcat; ++i) { 17728 if (IsUndefMaskElt(SubMask[i])) 17729 continue; 17730 if ((SubMask[i] % (int)NumElemsPerConcat) != i) 17731 return SDValue(); 17732 int EltOpIdx = SubMask[i] / NumElemsPerConcat; 17733 if (0 <= OpIdx && EltOpIdx != OpIdx) 17734 return SDValue(); 17735 OpIdx = EltOpIdx; 17736 } 17737 assert(0 <= OpIdx && "Unknown concat_vectors op"); 17738 17739 if (OpIdx < (int)N0.getNumOperands()) 17740 Ops.push_back(N0.getOperand(OpIdx)); 17741 else 17742 Ops.push_back(N1.getOperand(OpIdx - N0.getNumOperands())); 17743 } 17744 17745 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 17746 } 17747 17748 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 17749 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 17750 // 17751 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 17752 // a simplification in some sense, but it isn't appropriate in general: some 17753 // BUILD_VECTORs are substantially cheaper than others. The general case 17754 // of a BUILD_VECTOR requires inserting each element individually (or 17755 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 17756 // all constants is a single constant pool load. A BUILD_VECTOR where each 17757 // element is identical is a splat. A BUILD_VECTOR where most of the operands 17758 // are undef lowers to a small number of element insertions. 17759 // 17760 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 17761 // We don't fold shuffles where one side is a non-zero constant, and we don't 17762 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate 17763 // non-constant operands. This seems to work out reasonably well in practice. 17764 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 17765 SelectionDAG &DAG, 17766 const TargetLowering &TLI) { 17767 EVT VT = SVN->getValueType(0); 17768 unsigned NumElts = VT.getVectorNumElements(); 17769 SDValue N0 = SVN->getOperand(0); 17770 SDValue N1 = SVN->getOperand(1); 17771 17772 if (!N0->hasOneUse()) 17773 return SDValue(); 17774 17775 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 17776 // discussed above. 17777 if (!N1.isUndef()) { 17778 if (!N1->hasOneUse()) 17779 return SDValue(); 17780 17781 bool N0AnyConst = isAnyConstantBuildVector(N0); 17782 bool N1AnyConst = isAnyConstantBuildVector(N1); 17783 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 17784 return SDValue(); 17785 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 17786 return SDValue(); 17787 } 17788 17789 // If both inputs are splats of the same value then we can safely merge this 17790 // to a single BUILD_VECTOR with undef elements based on the shuffle mask. 17791 bool IsSplat = false; 17792 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); 17793 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 17794 if (BV0 && BV1) 17795 if (SDValue Splat0 = BV0->getSplatValue()) 17796 IsSplat = (Splat0 == BV1->getSplatValue()); 17797 17798 SmallVector<SDValue, 8> Ops; 17799 SmallSet<SDValue, 16> DuplicateOps; 17800 for (int M : SVN->getMask()) { 17801 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 17802 if (M >= 0) { 17803 int Idx = M < (int)NumElts ? M : M - NumElts; 17804 SDValue &S = (M < (int)NumElts ? N0 : N1); 17805 if (S.getOpcode() == ISD::BUILD_VECTOR) { 17806 Op = S.getOperand(Idx); 17807 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 17808 SDValue Op0 = S.getOperand(0); 17809 Op = Idx == 0 ? Op0 : DAG.getUNDEF(Op0.getValueType()); 17810 } else { 17811 // Operand can't be combined - bail out. 17812 return SDValue(); 17813 } 17814 } 17815 17816 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're 17817 // generating a splat; semantically, this is fine, but it's likely to 17818 // generate low-quality code if the target can't reconstruct an appropriate 17819 // shuffle. 17820 if (!Op.isUndef() && !isa<ConstantSDNode>(Op) && !isa<ConstantFPSDNode>(Op)) 17821 if (!IsSplat && !DuplicateOps.insert(Op).second) 17822 return SDValue(); 17823 17824 Ops.push_back(Op); 17825 } 17826 17827 // BUILD_VECTOR requires all inputs to be of the same type, find the 17828 // maximum type and extend them all. 17829 EVT SVT = VT.getScalarType(); 17830 if (SVT.isInteger()) 17831 for (SDValue &Op : Ops) 17832 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 17833 if (SVT != VT.getScalarType()) 17834 for (SDValue &Op : Ops) 17835 Op = TLI.isZExtFree(Op.getValueType(), SVT) 17836 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 17837 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 17838 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 17839 } 17840 17841 // Match shuffles that can be converted to any_vector_extend_in_reg. 17842 // This is often generated during legalization. 17843 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 17844 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 17845 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 17846 SelectionDAG &DAG, 17847 const TargetLowering &TLI, 17848 bool LegalOperations) { 17849 EVT VT = SVN->getValueType(0); 17850 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 17851 17852 // TODO Add support for big-endian when we have a test case. 17853 if (!VT.isInteger() || IsBigEndian) 17854 return SDValue(); 17855 17856 unsigned NumElts = VT.getVectorNumElements(); 17857 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 17858 ArrayRef<int> Mask = SVN->getMask(); 17859 SDValue N0 = SVN->getOperand(0); 17860 17861 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 17862 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 17863 for (unsigned i = 0; i != NumElts; ++i) { 17864 if (Mask[i] < 0) 17865 continue; 17866 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 17867 continue; 17868 return false; 17869 } 17870 return true; 17871 }; 17872 17873 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 17874 // power-of-2 extensions as they are the most likely. 17875 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 17876 // Check for non power of 2 vector sizes 17877 if (NumElts % Scale != 0) 17878 continue; 17879 if (!isAnyExtend(Scale)) 17880 continue; 17881 17882 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 17883 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 17884 // Never create an illegal type. Only create unsupported operations if we 17885 // are pre-legalization. 17886 if (TLI.isTypeLegal(OutVT)) 17887 if (!LegalOperations || 17888 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 17889 return DAG.getBitcast(VT, 17890 DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, 17891 SDLoc(SVN), OutVT, N0)); 17892 } 17893 17894 return SDValue(); 17895 } 17896 17897 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 17898 // each source element of a large type into the lowest elements of a smaller 17899 // destination type. This is often generated during legalization. 17900 // If the source node itself was a '*_extend_vector_inreg' node then we should 17901 // then be able to remove it. 17902 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 17903 SelectionDAG &DAG) { 17904 EVT VT = SVN->getValueType(0); 17905 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 17906 17907 // TODO Add support for big-endian when we have a test case. 17908 if (!VT.isInteger() || IsBigEndian) 17909 return SDValue(); 17910 17911 SDValue N0 = peekThroughBitcasts(SVN->getOperand(0)); 17912 17913 unsigned Opcode = N0.getOpcode(); 17914 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 17915 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 17916 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 17917 return SDValue(); 17918 17919 SDValue N00 = N0.getOperand(0); 17920 ArrayRef<int> Mask = SVN->getMask(); 17921 unsigned NumElts = VT.getVectorNumElements(); 17922 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 17923 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 17924 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 17925 17926 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 17927 return SDValue(); 17928 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 17929 17930 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 17931 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 17932 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 17933 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 17934 for (unsigned i = 0; i != NumElts; ++i) { 17935 if (Mask[i] < 0) 17936 continue; 17937 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 17938 continue; 17939 return false; 17940 } 17941 return true; 17942 }; 17943 17944 // At the moment we just handle the case where we've truncated back to the 17945 // same size as before the extension. 17946 // TODO: handle more extension/truncation cases as cases arise. 17947 if (EltSizeInBits != ExtSrcSizeInBits) 17948 return SDValue(); 17949 17950 // We can remove *extend_vector_inreg only if the truncation happens at 17951 // the same scale as the extension. 17952 if (isTruncate(ExtScale)) 17953 return DAG.getBitcast(VT, N00); 17954 17955 return SDValue(); 17956 } 17957 17958 // Combine shuffles of splat-shuffles of the form: 17959 // shuffle (shuffle V, undef, splat-mask), undef, M 17960 // If splat-mask contains undef elements, we need to be careful about 17961 // introducing undef's in the folded mask which are not the result of composing 17962 // the masks of the shuffles. 17963 static SDValue combineShuffleOfSplatVal(ShuffleVectorSDNode *Shuf, 17964 SelectionDAG &DAG) { 17965 if (!Shuf->getOperand(1).isUndef()) 17966 return SDValue(); 17967 auto *Splat = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0)); 17968 if (!Splat || !Splat->isSplat()) 17969 return SDValue(); 17970 17971 ArrayRef<int> ShufMask = Shuf->getMask(); 17972 ArrayRef<int> SplatMask = Splat->getMask(); 17973 assert(ShufMask.size() == SplatMask.size() && "Mask length mismatch"); 17974 17975 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 17976 // every undef mask element in the splat-shuffle has a corresponding undef 17977 // element in the user-shuffle's mask or if the composition of mask elements 17978 // would result in undef. 17979 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 17980 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 17981 // In this case it is not legal to simplify to the splat-shuffle because we 17982 // may be exposing the users of the shuffle an undef element at index 1 17983 // which was not there before the combine. 17984 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 17985 // In this case the composition of masks yields SplatMask, so it's ok to 17986 // simplify to the splat-shuffle. 17987 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 17988 // In this case the composed mask includes all undef elements of SplatMask 17989 // and in addition sets element zero to undef. It is safe to simplify to 17990 // the splat-shuffle. 17991 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 17992 ArrayRef<int> SplatMask) { 17993 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 17994 if (UserMask[i] != -1 && SplatMask[i] == -1 && 17995 SplatMask[UserMask[i]] != -1) 17996 return false; 17997 return true; 17998 }; 17999 if (CanSimplifyToExistingSplat(ShufMask, SplatMask)) 18000 return Shuf->getOperand(0); 18001 18002 // Create a new shuffle with a mask that is composed of the two shuffles' 18003 // masks. 18004 SmallVector<int, 32> NewMask; 18005 for (int Idx : ShufMask) 18006 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 18007 18008 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 18009 Splat->getOperand(0), Splat->getOperand(1), 18010 NewMask); 18011 } 18012 18013 /// If the shuffle mask is taking exactly one element from the first vector 18014 /// operand and passing through all other elements from the second vector 18015 /// operand, return the index of the mask element that is choosing an element 18016 /// from the first operand. Otherwise, return -1. 18017 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) { 18018 int MaskSize = Mask.size(); 18019 int EltFromOp0 = -1; 18020 // TODO: This does not match if there are undef elements in the shuffle mask. 18021 // Should we ignore undefs in the shuffle mask instead? The trade-off is 18022 // removing an instruction (a shuffle), but losing the knowledge that some 18023 // vector lanes are not needed. 18024 for (int i = 0; i != MaskSize; ++i) { 18025 if (Mask[i] >= 0 && Mask[i] < MaskSize) { 18026 // We're looking for a shuffle of exactly one element from operand 0. 18027 if (EltFromOp0 != -1) 18028 return -1; 18029 EltFromOp0 = i; 18030 } else if (Mask[i] != i + MaskSize) { 18031 // Nothing from operand 1 can change lanes. 18032 return -1; 18033 } 18034 } 18035 return EltFromOp0; 18036 } 18037 18038 /// If a shuffle inserts exactly one element from a source vector operand into 18039 /// another vector operand and we can access the specified element as a scalar, 18040 /// then we can eliminate the shuffle. 18041 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, 18042 SelectionDAG &DAG) { 18043 // First, check if we are taking one element of a vector and shuffling that 18044 // element into another vector. 18045 ArrayRef<int> Mask = Shuf->getMask(); 18046 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end()); 18047 SDValue Op0 = Shuf->getOperand(0); 18048 SDValue Op1 = Shuf->getOperand(1); 18049 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask); 18050 if (ShufOp0Index == -1) { 18051 // Commute mask and check again. 18052 ShuffleVectorSDNode::commuteMask(CommutedMask); 18053 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask); 18054 if (ShufOp0Index == -1) 18055 return SDValue(); 18056 // Commute operands to match the commuted shuffle mask. 18057 std::swap(Op0, Op1); 18058 Mask = CommutedMask; 18059 } 18060 18061 // The shuffle inserts exactly one element from operand 0 into operand 1. 18062 // Now see if we can access that element as a scalar via a real insert element 18063 // instruction. 18064 // TODO: We can try harder to locate the element as a scalar. Examples: it 18065 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant. 18066 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && 18067 "Shuffle mask value must be from operand 0"); 18068 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT) 18069 return SDValue(); 18070 18071 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2)); 18072 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index]) 18073 return SDValue(); 18074 18075 // There's an existing insertelement with constant insertion index, so we 18076 // don't need to check the legality/profitability of a replacement operation 18077 // that differs at most in the constant value. The target should be able to 18078 // lower any of those in a similar way. If not, legalization will expand this 18079 // to a scalar-to-vector plus shuffle. 18080 // 18081 // Note that the shuffle may move the scalar from the position that the insert 18082 // element used. Therefore, our new insert element occurs at the shuffle's 18083 // mask index value, not the insert's index value. 18084 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C' 18085 SDValue NewInsIndex = DAG.getConstant(ShufOp0Index, SDLoc(Shuf), 18086 Op0.getOperand(2).getValueType()); 18087 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(), 18088 Op1, Op0.getOperand(1), NewInsIndex); 18089 } 18090 18091 /// If we have a unary shuffle of a shuffle, see if it can be folded away 18092 /// completely. This has the potential to lose undef knowledge because the first 18093 /// shuffle may not have an undef mask element where the second one does. So 18094 /// only call this after doing simplifications based on demanded elements. 18095 static SDValue simplifyShuffleOfShuffle(ShuffleVectorSDNode *Shuf) { 18096 // shuf (shuf0 X, Y, Mask0), undef, Mask 18097 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0)); 18098 if (!Shuf0 || !Shuf->getOperand(1).isUndef()) 18099 return SDValue(); 18100 18101 ArrayRef<int> Mask = Shuf->getMask(); 18102 ArrayRef<int> Mask0 = Shuf0->getMask(); 18103 for (int i = 0, e = (int)Mask.size(); i != e; ++i) { 18104 // Ignore undef elements. 18105 if (Mask[i] == -1) 18106 continue; 18107 assert(Mask[i] >= 0 && Mask[i] < e && "Unexpected shuffle mask value"); 18108 18109 // Is the element of the shuffle operand chosen by this shuffle the same as 18110 // the element chosen by the shuffle operand itself? 18111 if (Mask0[Mask[i]] != Mask0[i]) 18112 return SDValue(); 18113 } 18114 // Every element of this shuffle is identical to the result of the previous 18115 // shuffle, so we can replace this value. 18116 return Shuf->getOperand(0); 18117 } 18118 18119 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 18120 EVT VT = N->getValueType(0); 18121 unsigned NumElts = VT.getVectorNumElements(); 18122 18123 SDValue N0 = N->getOperand(0); 18124 SDValue N1 = N->getOperand(1); 18125 18126 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 18127 18128 // Canonicalize shuffle undef, undef -> undef 18129 if (N0.isUndef() && N1.isUndef()) 18130 return DAG.getUNDEF(VT); 18131 18132 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 18133 18134 // Canonicalize shuffle v, v -> v, undef 18135 if (N0 == N1) { 18136 SmallVector<int, 8> NewMask; 18137 for (unsigned i = 0; i != NumElts; ++i) { 18138 int Idx = SVN->getMaskElt(i); 18139 if (Idx >= (int)NumElts) Idx -= NumElts; 18140 NewMask.push_back(Idx); 18141 } 18142 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), NewMask); 18143 } 18144 18145 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 18146 if (N0.isUndef()) 18147 return DAG.getCommutedVectorShuffle(*SVN); 18148 18149 // Remove references to rhs if it is undef 18150 if (N1.isUndef()) { 18151 bool Changed = false; 18152 SmallVector<int, 8> NewMask; 18153 for (unsigned i = 0; i != NumElts; ++i) { 18154 int Idx = SVN->getMaskElt(i); 18155 if (Idx >= (int)NumElts) { 18156 Idx = -1; 18157 Changed = true; 18158 } 18159 NewMask.push_back(Idx); 18160 } 18161 if (Changed) 18162 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 18163 } 18164 18165 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG)) 18166 return InsElt; 18167 18168 // A shuffle of a single vector that is a splatted value can always be folded. 18169 if (SDValue V = combineShuffleOfSplatVal(SVN, DAG)) 18170 return V; 18171 18172 // If it is a splat, check if the argument vector is another splat or a 18173 // build_vector. 18174 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 18175 int SplatIndex = SVN->getSplatIndex(); 18176 if (TLI.isExtractVecEltCheap(VT, SplatIndex) && 18177 ISD::isBinaryOp(N0.getNode())) { 18178 // splat (vector_bo L, R), Index --> 18179 // splat (scalar_bo (extelt L, Index), (extelt R, Index)) 18180 SDValue L = N0.getOperand(0), R = N0.getOperand(1); 18181 SDLoc DL(N); 18182 EVT EltVT = VT.getScalarType(); 18183 SDValue Index = DAG.getIntPtrConstant(SplatIndex, DL); 18184 SDValue ExtL = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, L, Index); 18185 SDValue ExtR = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, R, Index); 18186 SDValue NewBO = DAG.getNode(N0.getOpcode(), DL, EltVT, ExtL, ExtR, 18187 N0.getNode()->getFlags()); 18188 SDValue Insert = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, NewBO); 18189 SmallVector<int, 16> ZeroMask(VT.getVectorNumElements(), 0); 18190 return DAG.getVectorShuffle(VT, DL, Insert, DAG.getUNDEF(VT), ZeroMask); 18191 } 18192 18193 // If this is a bit convert that changes the element type of the vector but 18194 // not the number of vector elements, look through it. Be careful not to 18195 // look though conversions that change things like v4f32 to v2f64. 18196 SDNode *V = N0.getNode(); 18197 if (V->getOpcode() == ISD::BITCAST) { 18198 SDValue ConvInput = V->getOperand(0); 18199 if (ConvInput.getValueType().isVector() && 18200 ConvInput.getValueType().getVectorNumElements() == NumElts) 18201 V = ConvInput.getNode(); 18202 } 18203 18204 if (V->getOpcode() == ISD::BUILD_VECTOR) { 18205 assert(V->getNumOperands() == NumElts && 18206 "BUILD_VECTOR has wrong number of operands"); 18207 SDValue Base; 18208 bool AllSame = true; 18209 for (unsigned i = 0; i != NumElts; ++i) { 18210 if (!V->getOperand(i).isUndef()) { 18211 Base = V->getOperand(i); 18212 break; 18213 } 18214 } 18215 // Splat of <u, u, u, u>, return <u, u, u, u> 18216 if (!Base.getNode()) 18217 return N0; 18218 for (unsigned i = 0; i != NumElts; ++i) { 18219 if (V->getOperand(i) != Base) { 18220 AllSame = false; 18221 break; 18222 } 18223 } 18224 // Splat of <x, x, x, x>, return <x, x, x, x> 18225 if (AllSame) 18226 return N0; 18227 18228 // Canonicalize any other splat as a build_vector. 18229 SDValue Splatted = V->getOperand(SplatIndex); 18230 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 18231 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 18232 18233 // We may have jumped through bitcasts, so the type of the 18234 // BUILD_VECTOR may not match the type of the shuffle. 18235 if (V->getValueType(0) != VT) 18236 NewBV = DAG.getBitcast(VT, NewBV); 18237 return NewBV; 18238 } 18239 } 18240 18241 // Simplify source operands based on shuffle mask. 18242 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 18243 return SDValue(N, 0); 18244 18245 // This is intentionally placed after demanded elements simplification because 18246 // it could eliminate knowledge of undef elements created by this shuffle. 18247 if (SDValue ShufOp = simplifyShuffleOfShuffle(SVN)) 18248 return ShufOp; 18249 18250 // Match shuffles that can be converted to any_vector_extend_in_reg. 18251 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) 18252 return V; 18253 18254 // Combine "truncate_vector_in_reg" style shuffles. 18255 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 18256 return V; 18257 18258 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 18259 Level < AfterLegalizeVectorOps && 18260 (N1.isUndef() || 18261 (N1.getOpcode() == ISD::CONCAT_VECTORS && 18262 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 18263 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 18264 return V; 18265 } 18266 18267 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 18268 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 18269 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) 18270 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 18271 return Res; 18272 18273 // If this shuffle only has a single input that is a bitcasted shuffle, 18274 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 18275 // back to their original types. 18276 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 18277 N1.isUndef() && Level < AfterLegalizeVectorOps && 18278 TLI.isTypeLegal(VT)) { 18279 auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) { 18280 if (Scale == 1) 18281 return SmallVector<int, 8>(Mask.begin(), Mask.end()); 18282 18283 SmallVector<int, 8> NewMask; 18284 for (int M : Mask) 18285 for (int s = 0; s != Scale; ++s) 18286 NewMask.push_back(M < 0 ? -1 : Scale * M + s); 18287 return NewMask; 18288 }; 18289 18290 SDValue BC0 = peekThroughOneUseBitcasts(N0); 18291 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 18292 EVT SVT = VT.getScalarType(); 18293 EVT InnerVT = BC0->getValueType(0); 18294 EVT InnerSVT = InnerVT.getScalarType(); 18295 18296 // Determine which shuffle works with the smaller scalar type. 18297 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 18298 EVT ScaleSVT = ScaleVT.getScalarType(); 18299 18300 if (TLI.isTypeLegal(ScaleVT) && 18301 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 18302 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 18303 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 18304 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 18305 18306 // Scale the shuffle masks to the smaller scalar type. 18307 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 18308 SmallVector<int, 8> InnerMask = 18309 ScaleShuffleMask(InnerSVN->getMask(), InnerScale); 18310 SmallVector<int, 8> OuterMask = 18311 ScaleShuffleMask(SVN->getMask(), OuterScale); 18312 18313 // Merge the shuffle masks. 18314 SmallVector<int, 8> NewMask; 18315 for (int M : OuterMask) 18316 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 18317 18318 // Test for shuffle mask legality over both commutations. 18319 SDValue SV0 = BC0->getOperand(0); 18320 SDValue SV1 = BC0->getOperand(1); 18321 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 18322 if (!LegalMask) { 18323 std::swap(SV0, SV1); 18324 ShuffleVectorSDNode::commuteMask(NewMask); 18325 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 18326 } 18327 18328 if (LegalMask) { 18329 SV0 = DAG.getBitcast(ScaleVT, SV0); 18330 SV1 = DAG.getBitcast(ScaleVT, SV1); 18331 return DAG.getBitcast( 18332 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 18333 } 18334 } 18335 } 18336 } 18337 18338 // Canonicalize shuffles according to rules: 18339 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 18340 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 18341 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 18342 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 18343 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG && 18344 TLI.isTypeLegal(VT)) { 18345 // The incoming shuffle must be of the same type as the result of the 18346 // current shuffle. 18347 assert(N1->getOperand(0).getValueType() == VT && 18348 "Shuffle types don't match"); 18349 18350 SDValue SV0 = N1->getOperand(0); 18351 SDValue SV1 = N1->getOperand(1); 18352 bool HasSameOp0 = N0 == SV0; 18353 bool IsSV1Undef = SV1.isUndef(); 18354 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 18355 // Commute the operands of this shuffle so that next rule 18356 // will trigger. 18357 return DAG.getCommutedVectorShuffle(*SVN); 18358 } 18359 18360 // Try to fold according to rules: 18361 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 18362 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 18363 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 18364 // Don't try to fold shuffles with illegal type. 18365 // Only fold if this shuffle is the only user of the other shuffle. 18366 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) && 18367 Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 18368 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0); 18369 18370 // Don't try to fold splats; they're likely to simplify somehow, or they 18371 // might be free. 18372 if (OtherSV->isSplat()) 18373 return SDValue(); 18374 18375 // The incoming shuffle must be of the same type as the result of the 18376 // current shuffle. 18377 assert(OtherSV->getOperand(0).getValueType() == VT && 18378 "Shuffle types don't match"); 18379 18380 SDValue SV0, SV1; 18381 SmallVector<int, 4> Mask; 18382 // Compute the combined shuffle mask for a shuffle with SV0 as the first 18383 // operand, and SV1 as the second operand. 18384 for (unsigned i = 0; i != NumElts; ++i) { 18385 int Idx = SVN->getMaskElt(i); 18386 if (Idx < 0) { 18387 // Propagate Undef. 18388 Mask.push_back(Idx); 18389 continue; 18390 } 18391 18392 SDValue CurrentVec; 18393 if (Idx < (int)NumElts) { 18394 // This shuffle index refers to the inner shuffle N0. Lookup the inner 18395 // shuffle mask to identify which vector is actually referenced. 18396 Idx = OtherSV->getMaskElt(Idx); 18397 if (Idx < 0) { 18398 // Propagate Undef. 18399 Mask.push_back(Idx); 18400 continue; 18401 } 18402 18403 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0) 18404 : OtherSV->getOperand(1); 18405 } else { 18406 // This shuffle index references an element within N1. 18407 CurrentVec = N1; 18408 } 18409 18410 // Simple case where 'CurrentVec' is UNDEF. 18411 if (CurrentVec.isUndef()) { 18412 Mask.push_back(-1); 18413 continue; 18414 } 18415 18416 // Canonicalize the shuffle index. We don't know yet if CurrentVec 18417 // will be the first or second operand of the combined shuffle. 18418 Idx = Idx % NumElts; 18419 if (!SV0.getNode() || SV0 == CurrentVec) { 18420 // Ok. CurrentVec is the left hand side. 18421 // Update the mask accordingly. 18422 SV0 = CurrentVec; 18423 Mask.push_back(Idx); 18424 continue; 18425 } 18426 18427 // Bail out if we cannot convert the shuffle pair into a single shuffle. 18428 if (SV1.getNode() && SV1 != CurrentVec) 18429 return SDValue(); 18430 18431 // Ok. CurrentVec is the right hand side. 18432 // Update the mask accordingly. 18433 SV1 = CurrentVec; 18434 Mask.push_back(Idx + NumElts); 18435 } 18436 18437 // Check if all indices in Mask are Undef. In case, propagate Undef. 18438 bool isUndefMask = true; 18439 for (unsigned i = 0; i != NumElts && isUndefMask; ++i) 18440 isUndefMask &= Mask[i] < 0; 18441 18442 if (isUndefMask) 18443 return DAG.getUNDEF(VT); 18444 18445 if (!SV0.getNode()) 18446 SV0 = DAG.getUNDEF(VT); 18447 if (!SV1.getNode()) 18448 SV1 = DAG.getUNDEF(VT); 18449 18450 // Avoid introducing shuffles with illegal mask. 18451 if (!TLI.isShuffleMaskLegal(Mask, VT)) { 18452 ShuffleVectorSDNode::commuteMask(Mask); 18453 18454 if (!TLI.isShuffleMaskLegal(Mask, VT)) 18455 return SDValue(); 18456 18457 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 18458 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 18459 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 18460 std::swap(SV0, SV1); 18461 } 18462 18463 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 18464 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 18465 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 18466 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, Mask); 18467 } 18468 18469 if (SDValue V = foldShuffleOfConcatUndefs(SVN, DAG)) 18470 return V; 18471 18472 return SDValue(); 18473 } 18474 18475 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 18476 SDValue InVal = N->getOperand(0); 18477 EVT VT = N->getValueType(0); 18478 18479 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 18480 // with a VECTOR_SHUFFLE and possible truncate. 18481 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 18482 SDValue InVec = InVal->getOperand(0); 18483 SDValue EltNo = InVal->getOperand(1); 18484 auto InVecT = InVec.getValueType(); 18485 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { 18486 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); 18487 int Elt = C0->getZExtValue(); 18488 NewMask[0] = Elt; 18489 SDValue Val; 18490 // If we have an implict truncate do truncate here as long as it's legal. 18491 // if it's not legal, this should 18492 if (VT.getScalarType() != InVal.getValueType() && 18493 InVal.getValueType().isScalarInteger() && 18494 isTypeLegal(VT.getScalarType())) { 18495 Val = 18496 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); 18497 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); 18498 } 18499 if (VT.getScalarType() == InVecT.getScalarType() && 18500 VT.getVectorNumElements() <= InVecT.getVectorNumElements() && 18501 TLI.isShuffleMaskLegal(NewMask, VT)) { 18502 Val = DAG.getVectorShuffle(InVecT, SDLoc(N), InVec, 18503 DAG.getUNDEF(InVecT), NewMask); 18504 // If the initial vector is the correct size this shuffle is a 18505 // valid result. 18506 if (VT == InVecT) 18507 return Val; 18508 // If not we must truncate the vector. 18509 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { 18510 MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout()); 18511 SDValue ZeroIdx = DAG.getConstant(0, SDLoc(N), IdxTy); 18512 EVT SubVT = 18513 EVT::getVectorVT(*DAG.getContext(), InVecT.getVectorElementType(), 18514 VT.getVectorNumElements()); 18515 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, Val, 18516 ZeroIdx); 18517 return Val; 18518 } 18519 } 18520 } 18521 } 18522 18523 return SDValue(); 18524 } 18525 18526 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 18527 EVT VT = N->getValueType(0); 18528 SDValue N0 = N->getOperand(0); 18529 SDValue N1 = N->getOperand(1); 18530 SDValue N2 = N->getOperand(2); 18531 18532 // If inserting an UNDEF, just return the original vector. 18533 if (N1.isUndef()) 18534 return N0; 18535 18536 // If this is an insert of an extracted vector into an undef vector, we can 18537 // just use the input to the extract. 18538 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 18539 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 18540 return N1.getOperand(0); 18541 18542 // If we are inserting a bitcast value into an undef, with the same 18543 // number of elements, just use the bitcast input of the extract. 18544 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> 18545 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) 18546 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && 18547 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && 18548 N1.getOperand(0).getOperand(1) == N2 && 18549 N1.getOperand(0).getOperand(0).getValueType().getVectorNumElements() == 18550 VT.getVectorNumElements() && 18551 N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() == 18552 VT.getSizeInBits()) { 18553 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); 18554 } 18555 18556 // If both N1 and N2 are bitcast values on which insert_subvector 18557 // would makes sense, pull the bitcast through. 18558 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> 18559 // BITCAST (INSERT_SUBVECTOR N0 N1 N2) 18560 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { 18561 SDValue CN0 = N0.getOperand(0); 18562 SDValue CN1 = N1.getOperand(0); 18563 EVT CN0VT = CN0.getValueType(); 18564 EVT CN1VT = CN1.getValueType(); 18565 if (CN0VT.isVector() && CN1VT.isVector() && 18566 CN0VT.getVectorElementType() == CN1VT.getVectorElementType() && 18567 CN0VT.getVectorNumElements() == VT.getVectorNumElements()) { 18568 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), 18569 CN0.getValueType(), CN0, CN1, N2); 18570 return DAG.getBitcast(VT, NewINSERT); 18571 } 18572 } 18573 18574 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 18575 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 18576 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 18577 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 18578 N0.getOperand(1).getValueType() == N1.getValueType() && 18579 N0.getOperand(2) == N2) 18580 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 18581 N1, N2); 18582 18583 // Eliminate an intermediate insert into an undef vector: 18584 // insert_subvector undef, (insert_subvector undef, X, 0), N2 --> 18585 // insert_subvector undef, X, N2 18586 if (N0.isUndef() && N1.getOpcode() == ISD::INSERT_SUBVECTOR && 18587 N1.getOperand(0).isUndef() && isNullConstant(N1.getOperand(2))) 18588 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0, 18589 N1.getOperand(1), N2); 18590 18591 if (!isa<ConstantSDNode>(N2)) 18592 return SDValue(); 18593 18594 unsigned InsIdx = cast<ConstantSDNode>(N2)->getZExtValue(); 18595 18596 // Canonicalize insert_subvector dag nodes. 18597 // Example: 18598 // (insert_subvector (insert_subvector A, Idx0), Idx1) 18599 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 18600 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 18601 N1.getValueType() == N0.getOperand(1).getValueType() && 18602 isa<ConstantSDNode>(N0.getOperand(2))) { 18603 unsigned OtherIdx = N0.getConstantOperandVal(2); 18604 if (InsIdx < OtherIdx) { 18605 // Swap nodes. 18606 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 18607 N0.getOperand(0), N1, N2); 18608 AddToWorklist(NewOp.getNode()); 18609 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 18610 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 18611 } 18612 } 18613 18614 // If the input vector is a concatenation, and the insert replaces 18615 // one of the pieces, we can optimize into a single concat_vectors. 18616 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 18617 N0.getOperand(0).getValueType() == N1.getValueType()) { 18618 unsigned Factor = N1.getValueType().getVectorNumElements(); 18619 18620 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 18621 Ops[cast<ConstantSDNode>(N2)->getZExtValue() / Factor] = N1; 18622 18623 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 18624 } 18625 18626 // Simplify source operands based on insertion. 18627 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 18628 return SDValue(N, 0); 18629 18630 return SDValue(); 18631 } 18632 18633 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 18634 SDValue N0 = N->getOperand(0); 18635 18636 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 18637 if (N0->getOpcode() == ISD::FP16_TO_FP) 18638 return N0->getOperand(0); 18639 18640 return SDValue(); 18641 } 18642 18643 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 18644 SDValue N0 = N->getOperand(0); 18645 18646 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 18647 if (N0->getOpcode() == ISD::AND) { 18648 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 18649 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 18650 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 18651 N0.getOperand(0)); 18652 } 18653 } 18654 18655 return SDValue(); 18656 } 18657 18658 SDValue DAGCombiner::visitVECREDUCE(SDNode *N) { 18659 SDValue N0 = N->getOperand(0); 18660 EVT VT = N0.getValueType(); 18661 18662 // VECREDUCE over 1-element vector is just an extract. 18663 if (VT.getVectorNumElements() == 1) { 18664 SDLoc dl(N); 18665 SDValue Res = DAG.getNode( 18666 ISD::EXTRACT_VECTOR_ELT, dl, VT.getVectorElementType(), N0, 18667 DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))); 18668 if (Res.getValueType() != N->getValueType(0)) 18669 Res = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Res); 18670 return Res; 18671 } 18672 18673 return SDValue(); 18674 } 18675 18676 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 18677 /// with the destination vector and a zero vector. 18678 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 18679 /// vector_shuffle V, Zero, <0, 4, 2, 4> 18680 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 18681 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!"); 18682 18683 EVT VT = N->getValueType(0); 18684 SDValue LHS = N->getOperand(0); 18685 SDValue RHS = peekThroughBitcasts(N->getOperand(1)); 18686 SDLoc DL(N); 18687 18688 // Make sure we're not running after operation legalization where it 18689 // may have custom lowered the vector shuffles. 18690 if (LegalOperations) 18691 return SDValue(); 18692 18693 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 18694 return SDValue(); 18695 18696 EVT RVT = RHS.getValueType(); 18697 unsigned NumElts = RHS.getNumOperands(); 18698 18699 // Attempt to create a valid clear mask, splitting the mask into 18700 // sub elements and checking to see if each is 18701 // all zeros or all ones - suitable for shuffle masking. 18702 auto BuildClearMask = [&](int Split) { 18703 int NumSubElts = NumElts * Split; 18704 int NumSubBits = RVT.getScalarSizeInBits() / Split; 18705 18706 SmallVector<int, 8> Indices; 18707 for (int i = 0; i != NumSubElts; ++i) { 18708 int EltIdx = i / Split; 18709 int SubIdx = i % Split; 18710 SDValue Elt = RHS.getOperand(EltIdx); 18711 if (Elt.isUndef()) { 18712 Indices.push_back(-1); 18713 continue; 18714 } 18715 18716 APInt Bits; 18717 if (isa<ConstantSDNode>(Elt)) 18718 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 18719 else if (isa<ConstantFPSDNode>(Elt)) 18720 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 18721 else 18722 return SDValue(); 18723 18724 // Extract the sub element from the constant bit mask. 18725 if (DAG.getDataLayout().isBigEndian()) { 18726 Bits.lshrInPlace((Split - SubIdx - 1) * NumSubBits); 18727 } else { 18728 Bits.lshrInPlace(SubIdx * NumSubBits); 18729 } 18730 18731 if (Split > 1) 18732 Bits = Bits.trunc(NumSubBits); 18733 18734 if (Bits.isAllOnesValue()) 18735 Indices.push_back(i); 18736 else if (Bits == 0) 18737 Indices.push_back(i + NumSubElts); 18738 else 18739 return SDValue(); 18740 } 18741 18742 // Let's see if the target supports this vector_shuffle. 18743 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 18744 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 18745 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 18746 return SDValue(); 18747 18748 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 18749 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 18750 DAG.getBitcast(ClearVT, LHS), 18751 Zero, Indices)); 18752 }; 18753 18754 // Determine maximum split level (byte level masking). 18755 int MaxSplit = 1; 18756 if (RVT.getScalarSizeInBits() % 8 == 0) 18757 MaxSplit = RVT.getScalarSizeInBits() / 8; 18758 18759 for (int Split = 1; Split <= MaxSplit; ++Split) 18760 if (RVT.getScalarSizeInBits() % Split == 0) 18761 if (SDValue S = BuildClearMask(Split)) 18762 return S; 18763 18764 return SDValue(); 18765 } 18766 18767 /// If a vector binop is performed on splat values, it may be profitable to 18768 /// extract, scalarize, and insert/splat. 18769 static SDValue scalarizeBinOpOfSplats(SDNode *N, SelectionDAG &DAG) { 18770 SDValue N0 = N->getOperand(0); 18771 SDValue N1 = N->getOperand(1); 18772 unsigned Opcode = N->getOpcode(); 18773 EVT VT = N->getValueType(0); 18774 EVT EltVT = VT.getVectorElementType(); 18775 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 18776 18777 // TODO: Remove/replace the extract cost check? If the elements are available 18778 // as scalars, then there may be no extract cost. Should we ask if 18779 // inserting a scalar back into a vector is cheap instead? 18780 int Index0, Index1; 18781 SDValue Src0 = DAG.getSplatSourceVector(N0, Index0); 18782 SDValue Src1 = DAG.getSplatSourceVector(N1, Index1); 18783 if (!Src0 || !Src1 || Index0 != Index1 || 18784 Src0.getValueType().getVectorElementType() != EltVT || 18785 Src1.getValueType().getVectorElementType() != EltVT || 18786 !TLI.isExtractVecEltCheap(VT, Index0) || 18787 !TLI.isOperationLegalOrCustom(Opcode, EltVT)) 18788 return SDValue(); 18789 18790 SDLoc DL(N); 18791 SDValue IndexC = 18792 DAG.getConstant(Index0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())); 18793 SDValue X = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, N0, IndexC); 18794 SDValue Y = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, N1, IndexC); 18795 SDValue ScalarBO = DAG.getNode(Opcode, DL, EltVT, X, Y, N->getFlags()); 18796 18797 // If all lanes but 1 are undefined, no need to splat the scalar result. 18798 // TODO: Keep track of undefs and use that info in the general case. 18799 if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getOpcode() == N1.getOpcode() && 18800 count_if(N0->ops(), [](SDValue V) { return !V.isUndef(); }) == 1 && 18801 count_if(N1->ops(), [](SDValue V) { return !V.isUndef(); }) == 1) { 18802 // bo (build_vec ..undef, X, undef...), (build_vec ..undef, Y, undef...) --> 18803 // build_vec ..undef, (bo X, Y), undef... 18804 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), DAG.getUNDEF(EltVT)); 18805 Ops[Index0] = ScalarBO; 18806 return DAG.getBuildVector(VT, DL, Ops); 18807 } 18808 18809 // bo (splat X, Index), (splat Y, Index) --> splat (bo X, Y), Index 18810 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), ScalarBO); 18811 return DAG.getBuildVector(VT, DL, Ops); 18812 } 18813 18814 /// Visit a binary vector operation, like ADD. 18815 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) { 18816 assert(N->getValueType(0).isVector() && 18817 "SimplifyVBinOp only works on vectors!"); 18818 18819 SDValue LHS = N->getOperand(0); 18820 SDValue RHS = N->getOperand(1); 18821 SDValue Ops[] = {LHS, RHS}; 18822 EVT VT = N->getValueType(0); 18823 unsigned Opcode = N->getOpcode(); 18824 18825 // See if we can constant fold the vector operation. 18826 if (SDValue Fold = DAG.FoldConstantVectorArithmetic( 18827 Opcode, SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags())) 18828 return Fold; 18829 18830 // Move unary shuffles with identical masks after a vector binop: 18831 // VBinOp (shuffle A, Undef, Mask), (shuffle B, Undef, Mask)) 18832 // --> shuffle (VBinOp A, B), Undef, Mask 18833 // This does not require type legality checks because we are creating the 18834 // same types of operations that are in the original sequence. We do have to 18835 // restrict ops like integer div that have immediate UB (eg, div-by-zero) 18836 // though. This code is adapted from the identical transform in instcombine. 18837 if (Opcode != ISD::UDIV && Opcode != ISD::SDIV && 18838 Opcode != ISD::UREM && Opcode != ISD::SREM && 18839 Opcode != ISD::UDIVREM && Opcode != ISD::SDIVREM) { 18840 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS); 18841 auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS); 18842 if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) && 18843 LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() && 18844 (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) { 18845 SDLoc DL(N); 18846 SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS.getOperand(0), 18847 RHS.getOperand(0), N->getFlags()); 18848 SDValue UndefV = LHS.getOperand(1); 18849 return DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask()); 18850 } 18851 } 18852 18853 // The following pattern is likely to emerge with vector reduction ops. Moving 18854 // the binary operation ahead of insertion may allow using a narrower vector 18855 // instruction that has better performance than the wide version of the op: 18856 // VBinOp (ins undef, X, Z), (ins undef, Y, Z) --> ins VecC, (VBinOp X, Y), Z 18857 if (LHS.getOpcode() == ISD::INSERT_SUBVECTOR && LHS.getOperand(0).isUndef() && 18858 RHS.getOpcode() == ISD::INSERT_SUBVECTOR && RHS.getOperand(0).isUndef() && 18859 LHS.getOperand(2) == RHS.getOperand(2) && 18860 (LHS.hasOneUse() || RHS.hasOneUse())) { 18861 SDValue X = LHS.getOperand(1); 18862 SDValue Y = RHS.getOperand(1); 18863 SDValue Z = LHS.getOperand(2); 18864 EVT NarrowVT = X.getValueType(); 18865 if (NarrowVT == Y.getValueType() && 18866 TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT)) { 18867 // (binop undef, undef) may not return undef, so compute that result. 18868 SDLoc DL(N); 18869 SDValue VecC = 18870 DAG.getNode(Opcode, DL, VT, DAG.getUNDEF(VT), DAG.getUNDEF(VT)); 18871 SDValue NarrowBO = DAG.getNode(Opcode, DL, NarrowVT, X, Y); 18872 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, VecC, NarrowBO, Z); 18873 } 18874 } 18875 18876 if (SDValue V = scalarizeBinOpOfSplats(N, DAG)) 18877 return V; 18878 18879 return SDValue(); 18880 } 18881 18882 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 18883 SDValue N2) { 18884 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 18885 18886 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 18887 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 18888 18889 // If we got a simplified select_cc node back from SimplifySelectCC, then 18890 // break it down into a new SETCC node, and a new SELECT node, and then return 18891 // the SELECT node, since we were called with a SELECT node. 18892 if (SCC.getNode()) { 18893 // Check to see if we got a select_cc back (to turn into setcc/select). 18894 // Otherwise, just return whatever node we got back, like fabs. 18895 if (SCC.getOpcode() == ISD::SELECT_CC) { 18896 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 18897 N0.getValueType(), 18898 SCC.getOperand(0), SCC.getOperand(1), 18899 SCC.getOperand(4)); 18900 AddToWorklist(SETCC.getNode()); 18901 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 18902 SCC.getOperand(2), SCC.getOperand(3)); 18903 } 18904 18905 return SCC; 18906 } 18907 return SDValue(); 18908 } 18909 18910 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 18911 /// being selected between, see if we can simplify the select. Callers of this 18912 /// should assume that TheSelect is deleted if this returns true. As such, they 18913 /// should return the appropriate thing (e.g. the node) back to the top-level of 18914 /// the DAG combiner loop to avoid it being looked at. 18915 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 18916 SDValue RHS) { 18917 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 18918 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 18919 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 18920 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 18921 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 18922 SDValue Sqrt = RHS; 18923 ISD::CondCode CC; 18924 SDValue CmpLHS; 18925 const ConstantFPSDNode *Zero = nullptr; 18926 18927 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 18928 CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 18929 CmpLHS = TheSelect->getOperand(0); 18930 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 18931 } else { 18932 // SELECT or VSELECT 18933 SDValue Cmp = TheSelect->getOperand(0); 18934 if (Cmp.getOpcode() == ISD::SETCC) { 18935 CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 18936 CmpLHS = Cmp.getOperand(0); 18937 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 18938 } 18939 } 18940 if (Zero && Zero->isZero() && 18941 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 18942 CC == ISD::SETULT || CC == ISD::SETLT)) { 18943 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 18944 CombineTo(TheSelect, Sqrt); 18945 return true; 18946 } 18947 } 18948 } 18949 // Cannot simplify select with vector condition 18950 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 18951 18952 // If this is a select from two identical things, try to pull the operation 18953 // through the select. 18954 if (LHS.getOpcode() != RHS.getOpcode() || 18955 !LHS.hasOneUse() || !RHS.hasOneUse()) 18956 return false; 18957 18958 // If this is a load and the token chain is identical, replace the select 18959 // of two loads with a load through a select of the address to load from. 18960 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 18961 // constants have been dropped into the constant pool. 18962 if (LHS.getOpcode() == ISD::LOAD) { 18963 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 18964 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 18965 18966 // Token chains must be identical. 18967 if (LHS.getOperand(0) != RHS.getOperand(0) || 18968 // Do not let this transformation reduce the number of volatile loads. 18969 LLD->isVolatile() || RLD->isVolatile() || 18970 // FIXME: If either is a pre/post inc/dec load, 18971 // we'd need to split out the address adjustment. 18972 LLD->isIndexed() || RLD->isIndexed() || 18973 // If this is an EXTLOAD, the VT's must match. 18974 LLD->getMemoryVT() != RLD->getMemoryVT() || 18975 // If this is an EXTLOAD, the kind of extension must match. 18976 (LLD->getExtensionType() != RLD->getExtensionType() && 18977 // The only exception is if one of the extensions is anyext. 18978 LLD->getExtensionType() != ISD::EXTLOAD && 18979 RLD->getExtensionType() != ISD::EXTLOAD) || 18980 // FIXME: this discards src value information. This is 18981 // over-conservative. It would be beneficial to be able to remember 18982 // both potential memory locations. Since we are discarding 18983 // src value info, don't do the transformation if the memory 18984 // locations are not in the default address space. 18985 LLD->getPointerInfo().getAddrSpace() != 0 || 18986 RLD->getPointerInfo().getAddrSpace() != 0 || 18987 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 18988 LLD->getBasePtr().getValueType())) 18989 return false; 18990 18991 // The loads must not depend on one another. 18992 if (LLD->isPredecessorOf(RLD) || RLD->isPredecessorOf(LLD)) 18993 return false; 18994 18995 // Check that the select condition doesn't reach either load. If so, 18996 // folding this will induce a cycle into the DAG. If not, this is safe to 18997 // xform, so create a select of the addresses. 18998 18999 SmallPtrSet<const SDNode *, 32> Visited; 19000 SmallVector<const SDNode *, 16> Worklist; 19001 19002 // Always fail if LLD and RLD are not independent. TheSelect is a 19003 // predecessor to all Nodes in question so we need not search past it. 19004 19005 Visited.insert(TheSelect); 19006 Worklist.push_back(LLD); 19007 Worklist.push_back(RLD); 19008 19009 if (SDNode::hasPredecessorHelper(LLD, Visited, Worklist) || 19010 SDNode::hasPredecessorHelper(RLD, Visited, Worklist)) 19011 return false; 19012 19013 SDValue Addr; 19014 if (TheSelect->getOpcode() == ISD::SELECT) { 19015 // We cannot do this optimization if any pair of {RLD, LLD} is a 19016 // predecessor to {RLD, LLD, CondNode}. As we've already compared the 19017 // Loads, we only need to check if CondNode is a successor to one of the 19018 // loads. We can further avoid this if there's no use of their chain 19019 // value. 19020 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 19021 Worklist.push_back(CondNode); 19022 19023 if ((LLD->hasAnyUseOfValue(1) && 19024 SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) || 19025 (RLD->hasAnyUseOfValue(1) && 19026 SDNode::hasPredecessorHelper(RLD, Visited, Worklist))) 19027 return false; 19028 19029 Addr = DAG.getSelect(SDLoc(TheSelect), 19030 LLD->getBasePtr().getValueType(), 19031 TheSelect->getOperand(0), LLD->getBasePtr(), 19032 RLD->getBasePtr()); 19033 } else { // Otherwise SELECT_CC 19034 // We cannot do this optimization if any pair of {RLD, LLD} is a 19035 // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared 19036 // the Loads, we only need to check if CondLHS/CondRHS is a successor to 19037 // one of the loads. We can further avoid this if there's no use of their 19038 // chain value. 19039 19040 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 19041 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 19042 Worklist.push_back(CondLHS); 19043 Worklist.push_back(CondRHS); 19044 19045 if ((LLD->hasAnyUseOfValue(1) && 19046 SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) || 19047 (RLD->hasAnyUseOfValue(1) && 19048 SDNode::hasPredecessorHelper(RLD, Visited, Worklist))) 19049 return false; 19050 19051 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 19052 LLD->getBasePtr().getValueType(), 19053 TheSelect->getOperand(0), 19054 TheSelect->getOperand(1), 19055 LLD->getBasePtr(), RLD->getBasePtr(), 19056 TheSelect->getOperand(4)); 19057 } 19058 19059 SDValue Load; 19060 // It is safe to replace the two loads if they have different alignments, 19061 // but the new load must be the minimum (most restrictive) alignment of the 19062 // inputs. 19063 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment()); 19064 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 19065 if (!RLD->isInvariant()) 19066 MMOFlags &= ~MachineMemOperand::MOInvariant; 19067 if (!RLD->isDereferenceable()) 19068 MMOFlags &= ~MachineMemOperand::MODereferenceable; 19069 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 19070 // FIXME: Discards pointer and AA info. 19071 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 19072 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 19073 MMOFlags); 19074 } else { 19075 // FIXME: Discards pointer and AA info. 19076 Load = DAG.getExtLoad( 19077 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 19078 : LLD->getExtensionType(), 19079 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 19080 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 19081 } 19082 19083 // Users of the select now use the result of the load. 19084 CombineTo(TheSelect, Load); 19085 19086 // Users of the old loads now use the new load's chain. We know the 19087 // old-load value is dead now. 19088 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 19089 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 19090 return true; 19091 } 19092 19093 return false; 19094 } 19095 19096 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 19097 /// bitwise 'and'. 19098 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 19099 SDValue N1, SDValue N2, SDValue N3, 19100 ISD::CondCode CC) { 19101 // If this is a select where the false operand is zero and the compare is a 19102 // check of the sign bit, see if we can perform the "gzip trick": 19103 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 19104 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 19105 EVT XType = N0.getValueType(); 19106 EVT AType = N2.getValueType(); 19107 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 19108 return SDValue(); 19109 19110 // If the comparison is testing for a positive value, we have to invert 19111 // the sign bit mask, so only do that transform if the target has a bitwise 19112 // 'and not' instruction (the invert is free). 19113 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 19114 // (X > -1) ? A : 0 19115 // (X > 0) ? X : 0 <-- This is canonical signed max. 19116 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 19117 return SDValue(); 19118 } else if (CC == ISD::SETLT) { 19119 // (X < 0) ? A : 0 19120 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 19121 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 19122 return SDValue(); 19123 } else { 19124 return SDValue(); 19125 } 19126 19127 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 19128 // constant. 19129 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 19130 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 19131 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 19132 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 19133 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 19134 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 19135 AddToWorklist(Shift.getNode()); 19136 19137 if (XType.bitsGT(AType)) { 19138 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 19139 AddToWorklist(Shift.getNode()); 19140 } 19141 19142 if (CC == ISD::SETGT) 19143 Shift = DAG.getNOT(DL, Shift, AType); 19144 19145 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 19146 } 19147 19148 SDValue ShiftAmt = DAG.getConstant(XType.getSizeInBits() - 1, DL, ShiftAmtTy); 19149 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 19150 AddToWorklist(Shift.getNode()); 19151 19152 if (XType.bitsGT(AType)) { 19153 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 19154 AddToWorklist(Shift.getNode()); 19155 } 19156 19157 if (CC == ISD::SETGT) 19158 Shift = DAG.getNOT(DL, Shift, AType); 19159 19160 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 19161 } 19162 19163 /// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 19164 /// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 19165 /// in it. This may be a win when the constant is not otherwise available 19166 /// because it replaces two constant pool loads with one. 19167 SDValue DAGCombiner::convertSelectOfFPConstantsToLoadOffset( 19168 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3, 19169 ISD::CondCode CC) { 19170 if (!TLI.reduceSelectOfFPConstantLoads(N0.getValueType().isFloatingPoint())) 19171 return SDValue(); 19172 19173 // If we are before legalize types, we want the other legalization to happen 19174 // first (for example, to avoid messing with soft float). 19175 auto *TV = dyn_cast<ConstantFPSDNode>(N2); 19176 auto *FV = dyn_cast<ConstantFPSDNode>(N3); 19177 EVT VT = N2.getValueType(); 19178 if (!TV || !FV || !TLI.isTypeLegal(VT)) 19179 return SDValue(); 19180 19181 // If a constant can be materialized without loads, this does not make sense. 19182 if (TLI.getOperationAction(ISD::ConstantFP, VT) == TargetLowering::Legal || 19183 TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0), ForCodeSize) || 19184 TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0), ForCodeSize)) 19185 return SDValue(); 19186 19187 // If both constants have multiple uses, then we won't need to do an extra 19188 // load. The values are likely around in registers for other users. 19189 if (!TV->hasOneUse() && !FV->hasOneUse()) 19190 return SDValue(); 19191 19192 Constant *Elts[] = { const_cast<ConstantFP*>(FV->getConstantFPValue()), 19193 const_cast<ConstantFP*>(TV->getConstantFPValue()) }; 19194 Type *FPTy = Elts[0]->getType(); 19195 const DataLayout &TD = DAG.getDataLayout(); 19196 19197 // Create a ConstantArray of the two constants. 19198 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 19199 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 19200 TD.getPrefTypeAlignment(FPTy)); 19201 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment(); 19202 19203 // Get offsets to the 0 and 1 elements of the array, so we can select between 19204 // them. 19205 SDValue Zero = DAG.getIntPtrConstant(0, DL); 19206 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 19207 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 19208 SDValue Cond = 19209 DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), N0, N1, CC); 19210 AddToWorklist(Cond.getNode()); 19211 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), Cond, One, Zero); 19212 AddToWorklist(CstOffset.getNode()); 19213 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, CstOffset); 19214 AddToWorklist(CPIdx.getNode()); 19215 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 19216 MachinePointerInfo::getConstantPool( 19217 DAG.getMachineFunction()), Alignment); 19218 } 19219 19220 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 19221 /// where 'cond' is the comparison specified by CC. 19222 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 19223 SDValue N2, SDValue N3, ISD::CondCode CC, 19224 bool NotExtCompare) { 19225 // (x ? y : y) -> y. 19226 if (N2 == N3) return N2; 19227 19228 EVT CmpOpVT = N0.getValueType(); 19229 EVT CmpResVT = getSetCCResultType(CmpOpVT); 19230 EVT VT = N2.getValueType(); 19231 auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 19232 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 19233 auto *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 19234 19235 // Determine if the condition we're dealing with is constant. 19236 if (SDValue SCC = DAG.FoldSetCC(CmpResVT, N0, N1, CC, DL)) { 19237 AddToWorklist(SCC.getNode()); 19238 if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC)) { 19239 // fold select_cc true, x, y -> x 19240 // fold select_cc false, x, y -> y 19241 return !(SCCC->isNullValue()) ? N2 : N3; 19242 } 19243 } 19244 19245 if (SDValue V = 19246 convertSelectOfFPConstantsToLoadOffset(DL, N0, N1, N2, N3, CC)) 19247 return V; 19248 19249 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 19250 return V; 19251 19252 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 19253 // where y is has a single bit set. 19254 // A plaintext description would be, we can turn the SELECT_CC into an AND 19255 // when the condition can be materialized as an all-ones register. Any 19256 // single bit-test can be materialized as an all-ones register with 19257 // shift-left and shift-right-arith. 19258 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 19259 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 19260 SDValue AndLHS = N0->getOperand(0); 19261 auto *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 19262 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 19263 // Shift the tested bit over the sign bit. 19264 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 19265 SDValue ShlAmt = 19266 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 19267 getShiftAmountTy(AndLHS.getValueType())); 19268 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 19269 19270 // Now arithmetic right shift it all the way over, so the result is either 19271 // all-ones, or zero. 19272 SDValue ShrAmt = 19273 DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl), 19274 getShiftAmountTy(Shl.getValueType())); 19275 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 19276 19277 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 19278 } 19279 } 19280 19281 // fold select C, 16, 0 -> shl C, 4 19282 bool Fold = N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2(); 19283 bool Swap = N3C && isNullConstant(N2) && N3C->getAPIntValue().isPowerOf2(); 19284 19285 if ((Fold || Swap) && 19286 TLI.getBooleanContents(CmpOpVT) == 19287 TargetLowering::ZeroOrOneBooleanContent && 19288 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, CmpOpVT))) { 19289 19290 if (Swap) { 19291 CC = ISD::getSetCCInverse(CC, CmpOpVT.isInteger()); 19292 std::swap(N2C, N3C); 19293 } 19294 19295 // If the caller doesn't want us to simplify this into a zext of a compare, 19296 // don't do it. 19297 if (NotExtCompare && N2C->isOne()) 19298 return SDValue(); 19299 19300 SDValue Temp, SCC; 19301 // zext (setcc n0, n1) 19302 if (LegalTypes) { 19303 SCC = DAG.getSetCC(DL, CmpResVT, N0, N1, CC); 19304 if (VT.bitsLT(SCC.getValueType())) 19305 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), VT); 19306 else 19307 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC); 19308 } else { 19309 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 19310 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC); 19311 } 19312 19313 AddToWorklist(SCC.getNode()); 19314 AddToWorklist(Temp.getNode()); 19315 19316 if (N2C->isOne()) 19317 return Temp; 19318 19319 // shl setcc result by log2 n2c 19320 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp, 19321 DAG.getConstant(N2C->getAPIntValue().logBase2(), 19322 SDLoc(Temp), 19323 getShiftAmountTy(Temp.getValueType()))); 19324 } 19325 19326 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 19327 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 19328 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 19329 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 19330 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 19331 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 19332 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 19333 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 19334 if (N1C && N1C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 19335 SDValue ValueOnZero = N2; 19336 SDValue Count = N3; 19337 // If the condition is NE instead of E, swap the operands. 19338 if (CC == ISD::SETNE) 19339 std::swap(ValueOnZero, Count); 19340 // Check if the value on zero is a constant equal to the bits in the type. 19341 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 19342 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 19343 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 19344 // legal, combine to just cttz. 19345 if ((Count.getOpcode() == ISD::CTTZ || 19346 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 19347 N0 == Count.getOperand(0) && 19348 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 19349 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 19350 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 19351 // legal, combine to just ctlz. 19352 if ((Count.getOpcode() == ISD::CTLZ || 19353 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 19354 N0 == Count.getOperand(0) && 19355 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 19356 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 19357 } 19358 } 19359 } 19360 19361 return SDValue(); 19362 } 19363 19364 /// This is a stub for TargetLowering::SimplifySetCC. 19365 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 19366 ISD::CondCode Cond, const SDLoc &DL, 19367 bool foldBooleans) { 19368 TargetLowering::DAGCombinerInfo 19369 DagCombineInfo(DAG, Level, false, this); 19370 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 19371 } 19372 19373 /// Given an ISD::SDIV node expressing a divide by constant, return 19374 /// a DAG expression to select that will generate the same value by multiplying 19375 /// by a magic number. 19376 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 19377 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 19378 // when optimising for minimum size, we don't want to expand a div to a mul 19379 // and a shift. 19380 if (DAG.getMachineFunction().getFunction().hasMinSize()) 19381 return SDValue(); 19382 19383 SmallVector<SDNode *, 8> Built; 19384 if (SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, Built)) { 19385 for (SDNode *N : Built) 19386 AddToWorklist(N); 19387 return S; 19388 } 19389 19390 return SDValue(); 19391 } 19392 19393 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 19394 /// DAG expression that will generate the same value by right shifting. 19395 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 19396 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 19397 if (!C) 19398 return SDValue(); 19399 19400 // Avoid division by zero. 19401 if (C->isNullValue()) 19402 return SDValue(); 19403 19404 SmallVector<SDNode *, 8> Built; 19405 if (SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built)) { 19406 for (SDNode *N : Built) 19407 AddToWorklist(N); 19408 return S; 19409 } 19410 19411 return SDValue(); 19412 } 19413 19414 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 19415 /// expression that will generate the same value by multiplying by a magic 19416 /// number. 19417 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 19418 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 19419 // when optimising for minimum size, we don't want to expand a div to a mul 19420 // and a shift. 19421 if (DAG.getMachineFunction().getFunction().hasMinSize()) 19422 return SDValue(); 19423 19424 SmallVector<SDNode *, 8> Built; 19425 if (SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, Built)) { 19426 for (SDNode *N : Built) 19427 AddToWorklist(N); 19428 return S; 19429 } 19430 19431 return SDValue(); 19432 } 19433 19434 /// Determines the LogBase2 value for a non-null input value using the 19435 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 19436 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 19437 EVT VT = V.getValueType(); 19438 unsigned EltBits = VT.getScalarSizeInBits(); 19439 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 19440 SDValue Base = DAG.getConstant(EltBits - 1, DL, VT); 19441 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 19442 return LogBase2; 19443 } 19444 19445 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 19446 /// For the reciprocal, we need to find the zero of the function: 19447 /// F(X) = A X - 1 [which has a zero at X = 1/A] 19448 /// => 19449 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 19450 /// does not require additional intermediate precision] 19451 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags Flags) { 19452 if (Level >= AfterLegalizeDAG) 19453 return SDValue(); 19454 19455 // TODO: Handle half and/or extended types? 19456 EVT VT = Op.getValueType(); 19457 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 19458 return SDValue(); 19459 19460 // If estimates are explicitly disabled for this function, we're done. 19461 MachineFunction &MF = DAG.getMachineFunction(); 19462 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 19463 if (Enabled == TLI.ReciprocalEstimate::Disabled) 19464 return SDValue(); 19465 19466 // Estimates may be explicitly enabled for this type with a custom number of 19467 // refinement steps. 19468 int Iterations = TLI.getDivRefinementSteps(VT, MF); 19469 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 19470 AddToWorklist(Est.getNode()); 19471 19472 if (Iterations) { 19473 EVT VT = Op.getValueType(); 19474 SDLoc DL(Op); 19475 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 19476 19477 // Newton iterations: Est = Est + Est (1 - Arg * Est) 19478 for (int i = 0; i < Iterations; ++i) { 19479 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags); 19480 AddToWorklist(NewEst.getNode()); 19481 19482 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags); 19483 AddToWorklist(NewEst.getNode()); 19484 19485 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 19486 AddToWorklist(NewEst.getNode()); 19487 19488 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags); 19489 AddToWorklist(Est.getNode()); 19490 } 19491 } 19492 return Est; 19493 } 19494 19495 return SDValue(); 19496 } 19497 19498 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 19499 /// For the reciprocal sqrt, we need to find the zero of the function: 19500 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 19501 /// => 19502 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 19503 /// As a result, we precompute A/2 prior to the iteration loop. 19504 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 19505 unsigned Iterations, 19506 SDNodeFlags Flags, bool Reciprocal) { 19507 EVT VT = Arg.getValueType(); 19508 SDLoc DL(Arg); 19509 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 19510 19511 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 19512 // this entire sequence requires only one FP constant. 19513 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 19514 AddToWorklist(HalfArg.getNode()); 19515 19516 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 19517 AddToWorklist(HalfArg.getNode()); 19518 19519 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 19520 for (unsigned i = 0; i < Iterations; ++i) { 19521 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 19522 AddToWorklist(NewEst.getNode()); 19523 19524 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 19525 AddToWorklist(NewEst.getNode()); 19526 19527 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 19528 AddToWorklist(NewEst.getNode()); 19529 19530 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 19531 AddToWorklist(Est.getNode()); 19532 } 19533 19534 // If non-reciprocal square root is requested, multiply the result by Arg. 19535 if (!Reciprocal) { 19536 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 19537 AddToWorklist(Est.getNode()); 19538 } 19539 19540 return Est; 19541 } 19542 19543 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 19544 /// For the reciprocal sqrt, we need to find the zero of the function: 19545 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 19546 /// => 19547 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 19548 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 19549 unsigned Iterations, 19550 SDNodeFlags Flags, bool Reciprocal) { 19551 EVT VT = Arg.getValueType(); 19552 SDLoc DL(Arg); 19553 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 19554 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 19555 19556 // This routine must enter the loop below to work correctly 19557 // when (Reciprocal == false). 19558 assert(Iterations > 0); 19559 19560 // Newton iterations for reciprocal square root: 19561 // E = (E * -0.5) * ((A * E) * E + -3.0) 19562 for (unsigned i = 0; i < Iterations; ++i) { 19563 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 19564 AddToWorklist(AE.getNode()); 19565 19566 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 19567 AddToWorklist(AEE.getNode()); 19568 19569 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 19570 AddToWorklist(RHS.getNode()); 19571 19572 // When calculating a square root at the last iteration build: 19573 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 19574 // (notice a common subexpression) 19575 SDValue LHS; 19576 if (Reciprocal || (i + 1) < Iterations) { 19577 // RSQRT: LHS = (E * -0.5) 19578 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 19579 } else { 19580 // SQRT: LHS = (A * E) * -0.5 19581 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 19582 } 19583 AddToWorklist(LHS.getNode()); 19584 19585 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 19586 AddToWorklist(Est.getNode()); 19587 } 19588 19589 return Est; 19590 } 19591 19592 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 19593 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 19594 /// Op can be zero. 19595 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 19596 bool Reciprocal) { 19597 if (Level >= AfterLegalizeDAG) 19598 return SDValue(); 19599 19600 // TODO: Handle half and/or extended types? 19601 EVT VT = Op.getValueType(); 19602 if (VT.getScalarType() != MVT::f32 && VT.getScalarType() != MVT::f64) 19603 return SDValue(); 19604 19605 // If estimates are explicitly disabled for this function, we're done. 19606 MachineFunction &MF = DAG.getMachineFunction(); 19607 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 19608 if (Enabled == TLI.ReciprocalEstimate::Disabled) 19609 return SDValue(); 19610 19611 // Estimates may be explicitly enabled for this type with a custom number of 19612 // refinement steps. 19613 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 19614 19615 bool UseOneConstNR = false; 19616 if (SDValue Est = 19617 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 19618 Reciprocal)) { 19619 AddToWorklist(Est.getNode()); 19620 19621 if (Iterations) { 19622 Est = UseOneConstNR 19623 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 19624 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 19625 19626 if (!Reciprocal) { 19627 // The estimate is now completely wrong if the input was exactly 0.0 or 19628 // possibly a denormal. Force the answer to 0.0 for those cases. 19629 EVT VT = Op.getValueType(); 19630 SDLoc DL(Op); 19631 EVT CCVT = getSetCCResultType(VT); 19632 ISD::NodeType SelOpcode = VT.isVector() ? ISD::VSELECT : ISD::SELECT; 19633 const Function &F = DAG.getMachineFunction().getFunction(); 19634 Attribute Denorms = F.getFnAttribute("denormal-fp-math"); 19635 if (Denorms.getValueAsString().equals("ieee")) { 19636 // fabs(X) < SmallestNormal ? 0.0 : Est 19637 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 19638 APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem); 19639 SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT); 19640 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 19641 SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op); 19642 SDValue IsDenorm = DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT); 19643 Est = DAG.getNode(SelOpcode, DL, VT, IsDenorm, FPZero, Est); 19644 AddToWorklist(Fabs.getNode()); 19645 AddToWorklist(IsDenorm.getNode()); 19646 AddToWorklist(Est.getNode()); 19647 } else { 19648 // X == 0.0 ? 0.0 : Est 19649 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 19650 SDValue IsZero = DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ); 19651 Est = DAG.getNode(SelOpcode, DL, VT, IsZero, FPZero, Est); 19652 AddToWorklist(IsZero.getNode()); 19653 AddToWorklist(Est.getNode()); 19654 } 19655 } 19656 } 19657 return Est; 19658 } 19659 19660 return SDValue(); 19661 } 19662 19663 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 19664 return buildSqrtEstimateImpl(Op, Flags, true); 19665 } 19666 19667 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 19668 return buildSqrtEstimateImpl(Op, Flags, false); 19669 } 19670 19671 /// Return true if there is any possibility that the two addresses overlap. 19672 bool DAGCombiner::isAlias(SDNode *Op0, SDNode *Op1) const { 19673 19674 struct MemUseCharacteristics { 19675 bool IsVolatile; 19676 SDValue BasePtr; 19677 int64_t Offset; 19678 Optional<int64_t> NumBytes; 19679 MachineMemOperand *MMO; 19680 }; 19681 19682 auto getCharacteristics = [](SDNode *N) -> MemUseCharacteristics { 19683 if (const auto *LSN = dyn_cast<LSBaseSDNode>(N)) { 19684 int64_t Offset = 0; 19685 if (auto *C = dyn_cast<ConstantSDNode>(LSN->getOffset())) 19686 Offset = (LSN->getAddressingMode() == ISD::PRE_INC) 19687 ? C->getSExtValue() 19688 : (LSN->getAddressingMode() == ISD::PRE_DEC) 19689 ? -1 * C->getSExtValue() 19690 : 0; 19691 return {LSN->isVolatile(), LSN->getBasePtr(), Offset /*base offset*/, 19692 Optional<int64_t>(LSN->getMemoryVT().getStoreSize()), 19693 LSN->getMemOperand()}; 19694 } 19695 if (const auto *LN = cast<LifetimeSDNode>(N)) 19696 return {false /*isVolatile*/, LN->getOperand(1), 19697 (LN->hasOffset()) ? LN->getOffset() : 0, 19698 (LN->hasOffset()) ? Optional<int64_t>(LN->getSize()) 19699 : Optional<int64_t>(), 19700 (MachineMemOperand *)nullptr}; 19701 // Default. 19702 return {false /*isvolatile*/, SDValue(), (int64_t)0 /*offset*/, 19703 Optional<int64_t>() /*size*/, (MachineMemOperand *)nullptr}; 19704 }; 19705 19706 MemUseCharacteristics MUC0 = getCharacteristics(Op0), 19707 MUC1 = getCharacteristics(Op1); 19708 19709 // If they are to the same address, then they must be aliases. 19710 if (MUC0.BasePtr.getNode() && MUC0.BasePtr == MUC1.BasePtr && 19711 MUC0.Offset == MUC1.Offset) 19712 return true; 19713 19714 // If they are both volatile then they cannot be reordered. 19715 if (MUC0.IsVolatile && MUC1.IsVolatile) 19716 return true; 19717 19718 if (MUC0.MMO && MUC1.MMO) { 19719 if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) || 19720 (MUC1.MMO->isInvariant() && MUC0.MMO->isStore())) 19721 return false; 19722 } 19723 19724 bool IsAlias; 19725 if (BaseIndexOffset::computeAliasing(Op0, MUC0.NumBytes, Op1, MUC1.NumBytes, 19726 DAG, IsAlias) && 19727 !IsAlias) 19728 return IsAlias; 19729 19730 // The following all rely on MMO0 and MMO1 being valid. Fail conservatively if 19731 // either are not known. 19732 if (!MUC0.MMO || !MUC1.MMO) 19733 return true; 19734 19735 // If one operation reads from invariant memory, and the other may store, they 19736 // cannot alias. These should really be checking the equivalent of mayWrite, 19737 // but it only matters for memory nodes other than load /store. 19738 if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) || 19739 (MUC1.MMO->isInvariant() && MUC0.MMO->isStore())) 19740 return false; 19741 19742 // If we know required SrcValue1 and SrcValue2 have relatively large 19743 // alignment compared to the size and offset of the access, we may be able 19744 // to prove they do not alias. This check is conservative for now to catch 19745 // cases created by splitting vector types. 19746 int64_t SrcValOffset0 = MUC0.MMO->getOffset(); 19747 int64_t SrcValOffset1 = MUC1.MMO->getOffset(); 19748 unsigned OrigAlignment0 = MUC0.MMO->getBaseAlignment(); 19749 unsigned OrigAlignment1 = MUC1.MMO->getBaseAlignment(); 19750 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 19751 MUC0.NumBytes.hasValue() && MUC1.NumBytes.hasValue() && 19752 *MUC0.NumBytes == *MUC1.NumBytes && OrigAlignment0 > *MUC0.NumBytes) { 19753 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0; 19754 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1; 19755 19756 // There is no overlap between these relatively aligned accesses of 19757 // similar size. Return no alias. 19758 if ((OffAlign0 + *MUC0.NumBytes) <= OffAlign1 || 19759 (OffAlign1 + *MUC1.NumBytes) <= OffAlign0) 19760 return false; 19761 } 19762 19763 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 19764 ? CombinerGlobalAA 19765 : DAG.getSubtarget().useAA(); 19766 #ifndef NDEBUG 19767 if (CombinerAAOnlyFunc.getNumOccurrences() && 19768 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 19769 UseAA = false; 19770 #endif 19771 19772 if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue()) { 19773 // Use alias analysis information. 19774 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 19775 int64_t Overlap0 = *MUC0.NumBytes + SrcValOffset0 - MinOffset; 19776 int64_t Overlap1 = *MUC1.NumBytes + SrcValOffset1 - MinOffset; 19777 AliasResult AAResult = AA->alias( 19778 MemoryLocation(MUC0.MMO->getValue(), Overlap0, 19779 UseTBAA ? MUC0.MMO->getAAInfo() : AAMDNodes()), 19780 MemoryLocation(MUC1.MMO->getValue(), Overlap1, 19781 UseTBAA ? MUC1.MMO->getAAInfo() : AAMDNodes())); 19782 if (AAResult == NoAlias) 19783 return false; 19784 } 19785 19786 // Otherwise we have to assume they alias. 19787 return true; 19788 } 19789 19790 /// Walk up chain skipping non-aliasing memory nodes, 19791 /// looking for aliasing nodes and adding them to the Aliases vector. 19792 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 19793 SmallVectorImpl<SDValue> &Aliases) { 19794 SmallVector<SDValue, 8> Chains; // List of chains to visit. 19795 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 19796 19797 // Get alias information for node. 19798 const bool IsLoad = isa<LoadSDNode>(N) && !cast<LoadSDNode>(N)->isVolatile(); 19799 19800 // Starting off. 19801 Chains.push_back(OriginalChain); 19802 unsigned Depth = 0; 19803 19804 // Attempt to improve chain by a single step 19805 std::function<bool(SDValue &)> ImproveChain = [&](SDValue &C) -> bool { 19806 switch (C.getOpcode()) { 19807 case ISD::EntryToken: 19808 // No need to mark EntryToken. 19809 C = SDValue(); 19810 return true; 19811 case ISD::LOAD: 19812 case ISD::STORE: { 19813 // Get alias information for C. 19814 bool IsOpLoad = isa<LoadSDNode>(C.getNode()) && 19815 !cast<LSBaseSDNode>(C.getNode())->isVolatile(); 19816 if ((IsLoad && IsOpLoad) || !isAlias(N, C.getNode())) { 19817 // Look further up the chain. 19818 C = C.getOperand(0); 19819 return true; 19820 } 19821 // Alias, so stop here. 19822 return false; 19823 } 19824 19825 case ISD::CopyFromReg: 19826 // Always forward past past CopyFromReg. 19827 C = C.getOperand(0); 19828 return true; 19829 19830 case ISD::LIFETIME_START: 19831 case ISD::LIFETIME_END: { 19832 // We can forward past any lifetime start/end that can be proven not to 19833 // alias the memory access. 19834 if (!isAlias(N, C.getNode())) { 19835 // Look further up the chain. 19836 C = C.getOperand(0); 19837 return true; 19838 } 19839 return false; 19840 } 19841 default: 19842 return false; 19843 } 19844 }; 19845 19846 // Look at each chain and determine if it is an alias. If so, add it to the 19847 // aliases list. If not, then continue up the chain looking for the next 19848 // candidate. 19849 while (!Chains.empty()) { 19850 SDValue Chain = Chains.pop_back_val(); 19851 19852 // Don't bother if we've seen Chain before. 19853 if (!Visited.insert(Chain.getNode()).second) 19854 continue; 19855 19856 // For TokenFactor nodes, look at each operand and only continue up the 19857 // chain until we reach the depth limit. 19858 // 19859 // FIXME: The depth check could be made to return the last non-aliasing 19860 // chain we found before we hit a tokenfactor rather than the original 19861 // chain. 19862 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 19863 Aliases.clear(); 19864 Aliases.push_back(OriginalChain); 19865 return; 19866 } 19867 19868 if (Chain.getOpcode() == ISD::TokenFactor) { 19869 // We have to check each of the operands of the token factor for "small" 19870 // token factors, so we queue them up. Adding the operands to the queue 19871 // (stack) in reverse order maintains the original order and increases the 19872 // likelihood that getNode will find a matching token factor (CSE.) 19873 if (Chain.getNumOperands() > 16) { 19874 Aliases.push_back(Chain); 19875 continue; 19876 } 19877 for (unsigned n = Chain.getNumOperands(); n;) 19878 Chains.push_back(Chain.getOperand(--n)); 19879 ++Depth; 19880 continue; 19881 } 19882 // Everything else 19883 if (ImproveChain(Chain)) { 19884 // Updated Chain Found, Consider new chain if one exists. 19885 if (Chain.getNode()) 19886 Chains.push_back(Chain); 19887 ++Depth; 19888 continue; 19889 } 19890 // No Improved Chain Possible, treat as Alias. 19891 Aliases.push_back(Chain); 19892 } 19893 } 19894 19895 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 19896 /// (aliasing node.) 19897 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 19898 if (OptLevel == CodeGenOpt::None) 19899 return OldChain; 19900 19901 // Ops for replacing token factor. 19902 SmallVector<SDValue, 8> Aliases; 19903 19904 // Accumulate all the aliases to this node. 19905 GatherAllAliases(N, OldChain, Aliases); 19906 19907 // If no operands then chain to entry token. 19908 if (Aliases.size() == 0) 19909 return DAG.getEntryNode(); 19910 19911 // If a single operand then chain to it. We don't need to revisit it. 19912 if (Aliases.size() == 1) 19913 return Aliases[0]; 19914 19915 // Construct a custom tailored token factor. 19916 return DAG.getTokenFactor(SDLoc(N), Aliases); 19917 } 19918 19919 namespace { 19920 // TODO: Replace with with std::monostate when we move to C++17. 19921 struct UnitT { } Unit; 19922 bool operator==(const UnitT &, const UnitT &) { return true; } 19923 bool operator!=(const UnitT &, const UnitT &) { return false; } 19924 } // namespace 19925 19926 // This function tries to collect a bunch of potentially interesting 19927 // nodes to improve the chains of, all at once. This might seem 19928 // redundant, as this function gets called when visiting every store 19929 // node, so why not let the work be done on each store as it's visited? 19930 // 19931 // I believe this is mainly important because MergeConsecutiveStores 19932 // is unable to deal with merging stores of different sizes, so unless 19933 // we improve the chains of all the potential candidates up-front 19934 // before running MergeConsecutiveStores, it might only see some of 19935 // the nodes that will eventually be candidates, and then not be able 19936 // to go from a partially-merged state to the desired final 19937 // fully-merged state. 19938 19939 bool DAGCombiner::parallelizeChainedStores(StoreSDNode *St) { 19940 SmallVector<StoreSDNode *, 8> ChainedStores; 19941 StoreSDNode *STChain = St; 19942 // Intervals records which offsets from BaseIndex have been covered. In 19943 // the common case, every store writes to the immediately previous address 19944 // space and thus merged with the previous interval at insertion time. 19945 19946 using IMap = 19947 llvm::IntervalMap<int64_t, UnitT, 8, IntervalMapHalfOpenInfo<int64_t>>; 19948 IMap::Allocator A; 19949 IMap Intervals(A); 19950 19951 // This holds the base pointer, index, and the offset in bytes from the base 19952 // pointer. 19953 const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 19954 19955 // We must have a base and an offset. 19956 if (!BasePtr.getBase().getNode()) 19957 return false; 19958 19959 // Do not handle stores to undef base pointers. 19960 if (BasePtr.getBase().isUndef()) 19961 return false; 19962 19963 // Add ST's interval. 19964 Intervals.insert(0, (St->getMemoryVT().getSizeInBits() + 7) / 8, Unit); 19965 19966 while (StoreSDNode *Chain = dyn_cast<StoreSDNode>(STChain->getChain())) { 19967 // If the chain has more than one use, then we can't reorder the mem ops. 19968 if (!SDValue(Chain, 0)->hasOneUse()) 19969 break; 19970 if (Chain->isVolatile() || Chain->isIndexed()) 19971 break; 19972 19973 // Find the base pointer and offset for this memory node. 19974 const BaseIndexOffset Ptr = BaseIndexOffset::match(Chain, DAG); 19975 // Check that the base pointer is the same as the original one. 19976 int64_t Offset; 19977 if (!BasePtr.equalBaseIndex(Ptr, DAG, Offset)) 19978 break; 19979 int64_t Length = (Chain->getMemoryVT().getSizeInBits() + 7) / 8; 19980 // Make sure we don't overlap with other intervals by checking the ones to 19981 // the left or right before inserting. 19982 auto I = Intervals.find(Offset); 19983 // If there's a next interval, we should end before it. 19984 if (I != Intervals.end() && I.start() < (Offset + Length)) 19985 break; 19986 // If there's a previous interval, we should start after it. 19987 if (I != Intervals.begin() && (--I).stop() <= Offset) 19988 break; 19989 Intervals.insert(Offset, Offset + Length, Unit); 19990 19991 ChainedStores.push_back(Chain); 19992 STChain = Chain; 19993 } 19994 19995 // If we didn't find a chained store, exit. 19996 if (ChainedStores.size() == 0) 19997 return false; 19998 19999 // Improve all chained stores (St and ChainedStores members) starting from 20000 // where the store chain ended and return single TokenFactor. 20001 SDValue NewChain = STChain->getChain(); 20002 SmallVector<SDValue, 8> TFOps; 20003 for (unsigned I = ChainedStores.size(); I;) { 20004 StoreSDNode *S = ChainedStores[--I]; 20005 SDValue BetterChain = FindBetterChain(S, NewChain); 20006 S = cast<StoreSDNode>(DAG.UpdateNodeOperands( 20007 S, BetterChain, S->getOperand(1), S->getOperand(2), S->getOperand(3))); 20008 TFOps.push_back(SDValue(S, 0)); 20009 ChainedStores[I] = S; 20010 } 20011 20012 // Improve St's chain. Use a new node to avoid creating a loop from CombineTo. 20013 SDValue BetterChain = FindBetterChain(St, NewChain); 20014 SDValue NewST; 20015 if (St->isTruncatingStore()) 20016 NewST = DAG.getTruncStore(BetterChain, SDLoc(St), St->getValue(), 20017 St->getBasePtr(), St->getMemoryVT(), 20018 St->getMemOperand()); 20019 else 20020 NewST = DAG.getStore(BetterChain, SDLoc(St), St->getValue(), 20021 St->getBasePtr(), St->getMemOperand()); 20022 20023 TFOps.push_back(NewST); 20024 20025 // If we improved every element of TFOps, then we've lost the dependence on 20026 // NewChain to successors of St and we need to add it back to TFOps. Do so at 20027 // the beginning to keep relative order consistent with FindBetterChains. 20028 auto hasImprovedChain = [&](SDValue ST) -> bool { 20029 return ST->getOperand(0) != NewChain; 20030 }; 20031 bool AddNewChain = llvm::all_of(TFOps, hasImprovedChain); 20032 if (AddNewChain) 20033 TFOps.insert(TFOps.begin(), NewChain); 20034 20035 SDValue TF = DAG.getTokenFactor(SDLoc(STChain), TFOps); 20036 CombineTo(St, TF); 20037 20038 AddToWorklist(STChain); 20039 // Add TF operands worklist in reverse order. 20040 for (auto I = TF->getNumOperands(); I;) 20041 AddToWorklist(TF->getOperand(--I).getNode()); 20042 AddToWorklist(TF.getNode()); 20043 return true; 20044 } 20045 20046 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 20047 if (OptLevel == CodeGenOpt::None) 20048 return false; 20049 20050 const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 20051 20052 // We must have a base and an offset. 20053 if (!BasePtr.getBase().getNode()) 20054 return false; 20055 20056 // Do not handle stores to undef base pointers. 20057 if (BasePtr.getBase().isUndef()) 20058 return false; 20059 20060 // Directly improve a chain of disjoint stores starting at St. 20061 if (parallelizeChainedStores(St)) 20062 return true; 20063 20064 // Improve St's Chain.. 20065 SDValue BetterChain = FindBetterChain(St, St->getChain()); 20066 if (St->getChain() != BetterChain) { 20067 replaceStoreChain(St, BetterChain); 20068 return true; 20069 } 20070 return false; 20071 } 20072 20073 /// This is the entry point for the file. 20074 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 20075 CodeGenOpt::Level OptLevel) { 20076 /// This is the main entry point to this class. 20077 DAGCombiner(*this, AA, OptLevel).Run(Level); 20078 } 20079