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/Analysis/TargetLibraryInfo.h" 35 #include "llvm/Analysis/VectorUtils.h" 36 #include "llvm/CodeGen/DAGCombine.h" 37 #include "llvm/CodeGen/ISDOpcodes.h" 38 #include "llvm/CodeGen/MachineFrameInfo.h" 39 #include "llvm/CodeGen/MachineFunction.h" 40 #include "llvm/CodeGen/MachineMemOperand.h" 41 #include "llvm/CodeGen/RuntimeLibcalls.h" 42 #include "llvm/CodeGen/SelectionDAG.h" 43 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h" 44 #include "llvm/CodeGen/SelectionDAGNodes.h" 45 #include "llvm/CodeGen/SelectionDAGTargetInfo.h" 46 #include "llvm/CodeGen/TargetLowering.h" 47 #include "llvm/CodeGen/TargetRegisterInfo.h" 48 #include "llvm/CodeGen/TargetSubtargetInfo.h" 49 #include "llvm/CodeGen/ValueTypes.h" 50 #include "llvm/IR/Attributes.h" 51 #include "llvm/IR/Constant.h" 52 #include "llvm/IR/DataLayout.h" 53 #include "llvm/IR/DerivedTypes.h" 54 #include "llvm/IR/Function.h" 55 #include "llvm/IR/LLVMContext.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/Support/Casting.h" 58 #include "llvm/Support/CodeGen.h" 59 #include "llvm/Support/CommandLine.h" 60 #include "llvm/Support/Compiler.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/ErrorHandling.h" 63 #include "llvm/Support/KnownBits.h" 64 #include "llvm/Support/MachineValueType.h" 65 #include "llvm/Support/MathExtras.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include "llvm/Target/TargetMachine.h" 68 #include "llvm/Target/TargetOptions.h" 69 #include <algorithm> 70 #include <cassert> 71 #include <cstdint> 72 #include <functional> 73 #include <iterator> 74 #include <string> 75 #include <tuple> 76 #include <utility> 77 78 using namespace llvm; 79 80 #define DEBUG_TYPE "dagcombine" 81 82 STATISTIC(NodesCombined , "Number of dag nodes combined"); 83 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created"); 84 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created"); 85 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed"); 86 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int"); 87 STATISTIC(SlicedLoads, "Number of load sliced"); 88 STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops"); 89 90 static cl::opt<bool> 91 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden, 92 cl::desc("Enable DAG combiner's use of IR alias analysis")); 93 94 static cl::opt<bool> 95 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true), 96 cl::desc("Enable DAG combiner's use of TBAA")); 97 98 #ifndef NDEBUG 99 static cl::opt<std::string> 100 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden, 101 cl::desc("Only use DAG-combiner alias analysis in this" 102 " function")); 103 #endif 104 105 /// Hidden option to stress test load slicing, i.e., when this option 106 /// is enabled, load slicing bypasses most of its profitability guards. 107 static cl::opt<bool> 108 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden, 109 cl::desc("Bypass the profitability model of load slicing"), 110 cl::init(false)); 111 112 static cl::opt<bool> 113 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true), 114 cl::desc("DAG combiner may split indexing from loads")); 115 116 static cl::opt<bool> 117 EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true), 118 cl::desc("DAG combiner enable merging multiple stores " 119 "into a wider store")); 120 121 static cl::opt<unsigned> TokenFactorInlineLimit( 122 "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048), 123 cl::desc("Limit the number of operands to inline for Token Factors")); 124 125 static cl::opt<unsigned> StoreMergeDependenceLimit( 126 "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10), 127 cl::desc("Limit the number of times for the same StoreNode and RootNode " 128 "to bail out in store merging dependence check")); 129 130 static cl::opt<bool> EnableReduceLoadOpStoreWidth( 131 "combiner-reduce-load-op-store-width", cl::Hidden, cl::init(true), 132 cl::desc("DAG combiner enable reducing the width of load/op/store " 133 "sequence")); 134 135 static cl::opt<bool> EnableShrinkLoadReplaceStoreWithStore( 136 "combiner-shrink-load-replace-store-with-store", cl::Hidden, cl::init(true), 137 cl::desc("DAG combiner enable load/<replace bytes>/store with " 138 "a narrower store")); 139 140 namespace { 141 142 class DAGCombiner { 143 SelectionDAG &DAG; 144 const TargetLowering &TLI; 145 const SelectionDAGTargetInfo *STI; 146 CombineLevel Level; 147 CodeGenOpt::Level OptLevel; 148 bool LegalDAG = false; 149 bool LegalOperations = false; 150 bool LegalTypes = false; 151 bool ForCodeSize; 152 bool DisableGenericCombines; 153 154 /// Worklist of all of the nodes that need to be simplified. 155 /// 156 /// This must behave as a stack -- new nodes to process are pushed onto the 157 /// back and when processing we pop off of the back. 158 /// 159 /// The worklist will not contain duplicates but may contain null entries 160 /// due to nodes being deleted from the underlying DAG. 161 SmallVector<SDNode *, 64> Worklist; 162 163 /// Mapping from an SDNode to its position on the worklist. 164 /// 165 /// This is used to find and remove nodes from the worklist (by nulling 166 /// them) when they are deleted from the underlying DAG. It relies on 167 /// stable indices of nodes within the worklist. 168 DenseMap<SDNode *, unsigned> WorklistMap; 169 /// This records all nodes attempted to add to the worklist since we 170 /// considered a new worklist entry. As we keep do not add duplicate nodes 171 /// in the worklist, this is different from the tail of the worklist. 172 SmallSetVector<SDNode *, 32> PruningList; 173 174 /// Set of nodes which have been combined (at least once). 175 /// 176 /// This is used to allow us to reliably add any operands of a DAG node 177 /// which have not yet been combined to the worklist. 178 SmallPtrSet<SDNode *, 32> CombinedNodes; 179 180 /// Map from candidate StoreNode to the pair of RootNode and count. 181 /// The count is used to track how many times we have seen the StoreNode 182 /// with the same RootNode bail out in dependence check. If we have seen 183 /// the bail out for the same pair many times over a limit, we won't 184 /// consider the StoreNode with the same RootNode as store merging 185 /// candidate again. 186 DenseMap<SDNode *, std::pair<SDNode *, unsigned>> StoreRootCountMap; 187 188 // AA - Used for DAG load/store alias analysis. 189 AliasAnalysis *AA; 190 191 /// When an instruction is simplified, add all users of the instruction to 192 /// the work lists because they might get more simplified now. 193 void AddUsersToWorklist(SDNode *N) { 194 for (SDNode *Node : N->uses()) 195 AddToWorklist(Node); 196 } 197 198 /// Convenient shorthand to add a node and all of its user to the worklist. 199 void AddToWorklistWithUsers(SDNode *N) { 200 AddUsersToWorklist(N); 201 AddToWorklist(N); 202 } 203 204 // Prune potentially dangling nodes. This is called after 205 // any visit to a node, but should also be called during a visit after any 206 // failed combine which may have created a DAG node. 207 void clearAddedDanglingWorklistEntries() { 208 // Check any nodes added to the worklist to see if they are prunable. 209 while (!PruningList.empty()) { 210 auto *N = PruningList.pop_back_val(); 211 if (N->use_empty()) 212 recursivelyDeleteUnusedNodes(N); 213 } 214 } 215 216 SDNode *getNextWorklistEntry() { 217 // Before we do any work, remove nodes that are not in use. 218 clearAddedDanglingWorklistEntries(); 219 SDNode *N = nullptr; 220 // The Worklist holds the SDNodes in order, but it may contain null 221 // entries. 222 while (!N && !Worklist.empty()) { 223 N = Worklist.pop_back_val(); 224 } 225 226 if (N) { 227 bool GoodWorklistEntry = WorklistMap.erase(N); 228 (void)GoodWorklistEntry; 229 assert(GoodWorklistEntry && 230 "Found a worklist entry without a corresponding map entry!"); 231 } 232 return N; 233 } 234 235 /// Call the node-specific routine that folds each particular type of node. 236 SDValue visit(SDNode *N); 237 238 public: 239 DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL) 240 : DAG(D), TLI(D.getTargetLoweringInfo()), 241 STI(D.getSubtarget().getSelectionDAGInfo()), 242 Level(BeforeLegalizeTypes), OptLevel(OL), AA(AA) { 243 ForCodeSize = DAG.shouldOptForSize(); 244 DisableGenericCombines = STI && STI->disableGenericCombines(OptLevel); 245 246 MaximumLegalStoreInBits = 0; 247 // We use the minimum store size here, since that's all we can guarantee 248 // for the scalable vector types. 249 for (MVT VT : MVT::all_valuetypes()) 250 if (EVT(VT).isSimple() && VT != MVT::Other && 251 TLI.isTypeLegal(EVT(VT)) && 252 VT.getSizeInBits().getKnownMinSize() >= MaximumLegalStoreInBits) 253 MaximumLegalStoreInBits = VT.getSizeInBits().getKnownMinSize(); 254 } 255 256 void ConsiderForPruning(SDNode *N) { 257 // Mark this for potential pruning. 258 PruningList.insert(N); 259 } 260 261 /// Add to the worklist making sure its instance is at the back (next to be 262 /// processed.) 263 void AddToWorklist(SDNode *N) { 264 assert(N->getOpcode() != ISD::DELETED_NODE && 265 "Deleted Node added to Worklist"); 266 267 // Skip handle nodes as they can't usefully be combined and confuse the 268 // zero-use deletion strategy. 269 if (N->getOpcode() == ISD::HANDLENODE) 270 return; 271 272 ConsiderForPruning(N); 273 274 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second) 275 Worklist.push_back(N); 276 } 277 278 /// Remove all instances of N from the worklist. 279 void removeFromWorklist(SDNode *N) { 280 CombinedNodes.erase(N); 281 PruningList.remove(N); 282 StoreRootCountMap.erase(N); 283 284 auto It = WorklistMap.find(N); 285 if (It == WorklistMap.end()) 286 return; // Not in the worklist. 287 288 // Null out the entry rather than erasing it to avoid a linear operation. 289 Worklist[It->second] = nullptr; 290 WorklistMap.erase(It); 291 } 292 293 void deleteAndRecombine(SDNode *N); 294 bool recursivelyDeleteUnusedNodes(SDNode *N); 295 296 /// Replaces all uses of the results of one DAG node with new values. 297 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 298 bool AddTo = true); 299 300 /// Replaces all uses of the results of one DAG node with new values. 301 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) { 302 return CombineTo(N, &Res, 1, AddTo); 303 } 304 305 /// Replaces all uses of the results of one DAG node with new values. 306 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1, 307 bool AddTo = true) { 308 SDValue To[] = { Res0, Res1 }; 309 return CombineTo(N, To, 2, AddTo); 310 } 311 312 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO); 313 314 private: 315 unsigned MaximumLegalStoreInBits; 316 317 /// Check the specified integer node value to see if it can be simplified or 318 /// if things it uses can be simplified by bit propagation. 319 /// If so, return true. 320 bool SimplifyDemandedBits(SDValue Op) { 321 unsigned BitWidth = Op.getScalarValueSizeInBits(); 322 APInt DemandedBits = APInt::getAllOnes(BitWidth); 323 return SimplifyDemandedBits(Op, DemandedBits); 324 } 325 326 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) { 327 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 328 KnownBits Known; 329 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, Known, TLO, 0, false)) 330 return false; 331 332 // Revisit the node. 333 AddToWorklist(Op.getNode()); 334 335 CommitTargetLoweringOpt(TLO); 336 return true; 337 } 338 339 /// Check the specified vector node value to see if it can be simplified or 340 /// if things it uses can be simplified as it only uses some of the 341 /// elements. If so, return true. 342 bool SimplifyDemandedVectorElts(SDValue Op) { 343 // TODO: For now just pretend it cannot be simplified. 344 if (Op.getValueType().isScalableVector()) 345 return false; 346 347 unsigned NumElts = Op.getValueType().getVectorNumElements(); 348 APInt DemandedElts = APInt::getAllOnes(NumElts); 349 return SimplifyDemandedVectorElts(Op, DemandedElts); 350 } 351 352 bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 353 const APInt &DemandedElts, 354 bool AssumeSingleUse = false); 355 bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts, 356 bool AssumeSingleUse = false); 357 358 bool CombineToPreIndexedLoadStore(SDNode *N); 359 bool CombineToPostIndexedLoadStore(SDNode *N); 360 SDValue SplitIndexingFromLoad(LoadSDNode *LD); 361 bool SliceUpLoad(SDNode *N); 362 363 // Scalars have size 0 to distinguish from singleton vectors. 364 SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD); 365 bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val); 366 bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val); 367 368 /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed 369 /// load. 370 /// 371 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced. 372 /// \param InVecVT type of the input vector to EVE with bitcasts resolved. 373 /// \param EltNo index of the vector element to load. 374 /// \param OriginalLoad load that EVE came from to be replaced. 375 /// \returns EVE on success SDValue() on failure. 376 SDValue scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT, 377 SDValue EltNo, 378 LoadSDNode *OriginalLoad); 379 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad); 380 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace); 381 SDValue SExtPromoteOperand(SDValue Op, EVT PVT); 382 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT); 383 SDValue PromoteIntBinOp(SDValue Op); 384 SDValue PromoteIntShiftOp(SDValue Op); 385 SDValue PromoteExtend(SDValue Op); 386 bool PromoteLoad(SDValue Op); 387 388 /// Call the node-specific routine that knows how to fold each 389 /// particular type of node. If that doesn't do anything, try the 390 /// target-specific DAG combines. 391 SDValue combine(SDNode *N); 392 393 // Visitation implementation - Implement dag node combining for different 394 // node types. The semantics are as follows: 395 // Return Value: 396 // SDValue.getNode() == 0 - No change was made 397 // SDValue.getNode() == N - N was replaced, is dead and has been handled. 398 // otherwise - N should be replaced by the returned Operand. 399 // 400 SDValue visitTokenFactor(SDNode *N); 401 SDValue visitMERGE_VALUES(SDNode *N); 402 SDValue visitADD(SDNode *N); 403 SDValue visitADDLike(SDNode *N); 404 SDValue visitADDLikeCommutative(SDValue N0, SDValue N1, SDNode *LocReference); 405 SDValue visitSUB(SDNode *N); 406 SDValue visitADDSAT(SDNode *N); 407 SDValue visitSUBSAT(SDNode *N); 408 SDValue visitADDC(SDNode *N); 409 SDValue visitADDO(SDNode *N); 410 SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N); 411 SDValue visitSUBC(SDNode *N); 412 SDValue visitSUBO(SDNode *N); 413 SDValue visitADDE(SDNode *N); 414 SDValue visitADDCARRY(SDNode *N); 415 SDValue visitSADDO_CARRY(SDNode *N); 416 SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N); 417 SDValue visitSUBE(SDNode *N); 418 SDValue visitSUBCARRY(SDNode *N); 419 SDValue visitSSUBO_CARRY(SDNode *N); 420 SDValue visitMUL(SDNode *N); 421 SDValue visitMULFIX(SDNode *N); 422 SDValue useDivRem(SDNode *N); 423 SDValue visitSDIV(SDNode *N); 424 SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N); 425 SDValue visitUDIV(SDNode *N); 426 SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N); 427 SDValue visitREM(SDNode *N); 428 SDValue visitMULHU(SDNode *N); 429 SDValue visitMULHS(SDNode *N); 430 SDValue visitSMUL_LOHI(SDNode *N); 431 SDValue visitUMUL_LOHI(SDNode *N); 432 SDValue visitMULO(SDNode *N); 433 SDValue visitIMINMAX(SDNode *N); 434 SDValue visitAND(SDNode *N); 435 SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N); 436 SDValue visitOR(SDNode *N); 437 SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N); 438 SDValue visitXOR(SDNode *N); 439 SDValue SimplifyVBinOp(SDNode *N, const SDLoc &DL); 440 SDValue visitSHL(SDNode *N); 441 SDValue visitSRA(SDNode *N); 442 SDValue visitSRL(SDNode *N); 443 SDValue visitFunnelShift(SDNode *N); 444 SDValue visitRotate(SDNode *N); 445 SDValue visitABS(SDNode *N); 446 SDValue visitBSWAP(SDNode *N); 447 SDValue visitBITREVERSE(SDNode *N); 448 SDValue visitCTLZ(SDNode *N); 449 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N); 450 SDValue visitCTTZ(SDNode *N); 451 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N); 452 SDValue visitCTPOP(SDNode *N); 453 SDValue visitSELECT(SDNode *N); 454 SDValue visitVSELECT(SDNode *N); 455 SDValue visitSELECT_CC(SDNode *N); 456 SDValue visitSETCC(SDNode *N); 457 SDValue visitSETCCCARRY(SDNode *N); 458 SDValue visitSIGN_EXTEND(SDNode *N); 459 SDValue visitZERO_EXTEND(SDNode *N); 460 SDValue visitANY_EXTEND(SDNode *N); 461 SDValue visitAssertExt(SDNode *N); 462 SDValue visitAssertAlign(SDNode *N); 463 SDValue visitSIGN_EXTEND_INREG(SDNode *N); 464 SDValue visitEXTEND_VECTOR_INREG(SDNode *N); 465 SDValue visitTRUNCATE(SDNode *N); 466 SDValue visitBITCAST(SDNode *N); 467 SDValue visitFREEZE(SDNode *N); 468 SDValue visitBUILD_PAIR(SDNode *N); 469 SDValue visitFADD(SDNode *N); 470 SDValue visitSTRICT_FADD(SDNode *N); 471 SDValue visitFSUB(SDNode *N); 472 SDValue visitFMUL(SDNode *N); 473 SDValue visitFMA(SDNode *N); 474 SDValue visitFDIV(SDNode *N); 475 SDValue visitFREM(SDNode *N); 476 SDValue visitFSQRT(SDNode *N); 477 SDValue visitFCOPYSIGN(SDNode *N); 478 SDValue visitFPOW(SDNode *N); 479 SDValue visitSINT_TO_FP(SDNode *N); 480 SDValue visitUINT_TO_FP(SDNode *N); 481 SDValue visitFP_TO_SINT(SDNode *N); 482 SDValue visitFP_TO_UINT(SDNode *N); 483 SDValue visitFP_ROUND(SDNode *N); 484 SDValue visitFP_EXTEND(SDNode *N); 485 SDValue visitFNEG(SDNode *N); 486 SDValue visitFABS(SDNode *N); 487 SDValue visitFCEIL(SDNode *N); 488 SDValue visitFTRUNC(SDNode *N); 489 SDValue visitFFLOOR(SDNode *N); 490 SDValue visitFMINNUM(SDNode *N); 491 SDValue visitFMAXNUM(SDNode *N); 492 SDValue visitFMINIMUM(SDNode *N); 493 SDValue visitFMAXIMUM(SDNode *N); 494 SDValue visitBRCOND(SDNode *N); 495 SDValue visitBR_CC(SDNode *N); 496 SDValue visitLOAD(SDNode *N); 497 498 SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain); 499 SDValue replaceStoreOfFPConstant(StoreSDNode *ST); 500 501 SDValue visitSTORE(SDNode *N); 502 SDValue visitLIFETIME_END(SDNode *N); 503 SDValue visitINSERT_VECTOR_ELT(SDNode *N); 504 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N); 505 SDValue visitBUILD_VECTOR(SDNode *N); 506 SDValue visitCONCAT_VECTORS(SDNode *N); 507 SDValue visitEXTRACT_SUBVECTOR(SDNode *N); 508 SDValue visitVECTOR_SHUFFLE(SDNode *N); 509 SDValue visitSCALAR_TO_VECTOR(SDNode *N); 510 SDValue visitINSERT_SUBVECTOR(SDNode *N); 511 SDValue visitMLOAD(SDNode *N); 512 SDValue visitMSTORE(SDNode *N); 513 SDValue visitMGATHER(SDNode *N); 514 SDValue visitMSCATTER(SDNode *N); 515 SDValue visitFP_TO_FP16(SDNode *N); 516 SDValue visitFP16_TO_FP(SDNode *N); 517 SDValue visitVECREDUCE(SDNode *N); 518 SDValue visitVPOp(SDNode *N); 519 520 SDValue visitFADDForFMACombine(SDNode *N); 521 SDValue visitFSUBForFMACombine(SDNode *N); 522 SDValue visitFMULForFMADistributiveCombine(SDNode *N); 523 524 SDValue XformToShuffleWithZero(SDNode *N); 525 bool reassociationCanBreakAddressingModePattern(unsigned Opc, 526 const SDLoc &DL, SDValue N0, 527 SDValue N1); 528 SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0, 529 SDValue N1); 530 SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 531 SDValue N1, SDNodeFlags Flags); 532 533 SDValue visitShiftByConstant(SDNode *N); 534 535 SDValue foldSelectOfConstants(SDNode *N); 536 SDValue foldVSelectOfConstants(SDNode *N); 537 SDValue foldBinOpIntoSelect(SDNode *BO); 538 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS); 539 SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N); 540 SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2); 541 SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 542 SDValue N2, SDValue N3, ISD::CondCode CC, 543 bool NotExtCompare = false); 544 SDValue convertSelectOfFPConstantsToLoadOffset( 545 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3, 546 ISD::CondCode CC); 547 SDValue foldSignChangeInBitcast(SDNode *N); 548 SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1, 549 SDValue N2, SDValue N3, ISD::CondCode CC); 550 SDValue foldSelectOfBinops(SDNode *N); 551 SDValue foldSextSetcc(SDNode *N); 552 SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 553 const SDLoc &DL); 554 SDValue foldSubToUSubSat(EVT DstVT, SDNode *N); 555 SDValue unfoldMaskedMerge(SDNode *N); 556 SDValue unfoldExtremeBitClearingToShifts(SDNode *N); 557 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond, 558 const SDLoc &DL, bool foldBooleans); 559 SDValue rebuildSetCC(SDValue N); 560 561 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 562 SDValue &CC, bool MatchStrict = false) const; 563 bool isOneUseSetCC(SDValue N) const; 564 565 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 566 unsigned HiOp); 567 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT); 568 SDValue CombineExtLoad(SDNode *N); 569 SDValue CombineZExtLogicopShiftLoad(SDNode *N); 570 SDValue combineRepeatedFPDivisors(SDNode *N); 571 SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex); 572 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT); 573 SDValue BuildSDIV(SDNode *N); 574 SDValue BuildSDIVPow2(SDNode *N); 575 SDValue BuildUDIV(SDNode *N); 576 SDValue BuildLogBase2(SDValue V, const SDLoc &DL); 577 SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags); 578 SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags); 579 SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags); 580 SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip); 581 SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations, 582 SDNodeFlags Flags, bool Reciprocal); 583 SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations, 584 SDNodeFlags Flags, bool Reciprocal); 585 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 586 bool DemandHighBits = true); 587 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1); 588 SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg, 589 SDValue InnerPos, SDValue InnerNeg, 590 unsigned PosOpcode, unsigned NegOpcode, 591 const SDLoc &DL); 592 SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg, 593 SDValue InnerPos, SDValue InnerNeg, 594 unsigned PosOpcode, unsigned NegOpcode, 595 const SDLoc &DL); 596 SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL); 597 SDValue MatchLoadCombine(SDNode *N); 598 SDValue mergeTruncStores(StoreSDNode *N); 599 SDValue ReduceLoadWidth(SDNode *N); 600 SDValue ReduceLoadOpStoreWidth(SDNode *N); 601 SDValue splitMergedValStore(StoreSDNode *ST); 602 SDValue TransformFPLoadStorePair(SDNode *N); 603 SDValue convertBuildVecZextToZext(SDNode *N); 604 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N); 605 SDValue reduceBuildVecTruncToBitCast(SDNode *N); 606 SDValue reduceBuildVecToShuffle(SDNode *N); 607 SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N, 608 ArrayRef<int> VectorMask, SDValue VecIn1, 609 SDValue VecIn2, unsigned LeftIdx, 610 bool DidSplitVec); 611 SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast); 612 613 /// Walk up chain skipping non-aliasing memory nodes, 614 /// looking for aliasing nodes and adding them to the Aliases vector. 615 void GatherAllAliases(SDNode *N, SDValue OriginalChain, 616 SmallVectorImpl<SDValue> &Aliases); 617 618 /// Return true if there is any possibility that the two addresses overlap. 619 bool mayAlias(SDNode *Op0, SDNode *Op1) const; 620 621 /// Walk up chain skipping non-aliasing memory nodes, looking for a better 622 /// chain (aliasing node.) 623 SDValue FindBetterChain(SDNode *N, SDValue Chain); 624 625 /// Try to replace a store and any possibly adjacent stores on 626 /// consecutive chains with better chains. Return true only if St is 627 /// replaced. 628 /// 629 /// Notice that other chains may still be replaced even if the function 630 /// returns false. 631 bool findBetterNeighborChains(StoreSDNode *St); 632 633 // Helper for findBetterNeighborChains. Walk up store chain add additional 634 // chained stores that do not overlap and can be parallelized. 635 bool parallelizeChainedStores(StoreSDNode *St); 636 637 /// Holds a pointer to an LSBaseSDNode as well as information on where it 638 /// is located in a sequence of memory operations connected by a chain. 639 struct MemOpLink { 640 // Ptr to the mem node. 641 LSBaseSDNode *MemNode; 642 643 // Offset from the base ptr. 644 int64_t OffsetFromBase; 645 646 MemOpLink(LSBaseSDNode *N, int64_t Offset) 647 : MemNode(N), OffsetFromBase(Offset) {} 648 }; 649 650 // Classify the origin of a stored value. 651 enum class StoreSource { Unknown, Constant, Extract, Load }; 652 StoreSource getStoreSource(SDValue StoreVal) { 653 switch (StoreVal.getOpcode()) { 654 case ISD::Constant: 655 case ISD::ConstantFP: 656 return StoreSource::Constant; 657 case ISD::EXTRACT_VECTOR_ELT: 658 case ISD::EXTRACT_SUBVECTOR: 659 return StoreSource::Extract; 660 case ISD::LOAD: 661 return StoreSource::Load; 662 default: 663 return StoreSource::Unknown; 664 } 665 } 666 667 /// This is a helper function for visitMUL to check the profitability 668 /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 669 /// MulNode is the original multiply, AddNode is (add x, c1), 670 /// and ConstNode is c2. 671 bool isMulAddWithConstProfitable(SDNode *MulNode, 672 SDValue &AddNode, 673 SDValue &ConstNode); 674 675 /// This is a helper function for visitAND and visitZERO_EXTEND. Returns 676 /// true if the (and (load x) c) pattern matches an extload. ExtVT returns 677 /// the type of the loaded value to be extended. 678 bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 679 EVT LoadResultTy, EVT &ExtVT); 680 681 /// Helper function to calculate whether the given Load/Store can have its 682 /// width reduced to ExtVT. 683 bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType, 684 EVT &MemVT, unsigned ShAmt = 0); 685 686 /// Used by BackwardsPropagateMask to find suitable loads. 687 bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads, 688 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 689 ConstantSDNode *Mask, SDNode *&NodeToMask); 690 /// Attempt to propagate a given AND node back to load leaves so that they 691 /// can be combined into narrow loads. 692 bool BackwardsPropagateMask(SDNode *N); 693 694 /// Helper function for mergeConsecutiveStores which merges the component 695 /// store chains. 696 SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 697 unsigned NumStores); 698 699 /// This is a helper function for mergeConsecutiveStores. When the source 700 /// elements of the consecutive stores are all constants or all extracted 701 /// vector elements, try to merge them into one larger store introducing 702 /// bitcasts if necessary. \return True if a merged store was created. 703 bool mergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes, 704 EVT MemVT, unsigned NumStores, 705 bool IsConstantSrc, bool UseVector, 706 bool UseTrunc); 707 708 /// This is a helper function for mergeConsecutiveStores. Stores that 709 /// potentially may be merged with St are placed in StoreNodes. RootNode is 710 /// a chain predecessor to all store candidates. 711 void getStoreMergeCandidates(StoreSDNode *St, 712 SmallVectorImpl<MemOpLink> &StoreNodes, 713 SDNode *&Root); 714 715 /// Helper function for mergeConsecutiveStores. Checks if candidate stores 716 /// have indirect dependency through their operands. RootNode is the 717 /// predecessor to all stores calculated by getStoreMergeCandidates and is 718 /// used to prune the dependency check. \return True if safe to merge. 719 bool checkMergeStoreCandidatesForDependencies( 720 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 721 SDNode *RootNode); 722 723 /// This is a helper function for mergeConsecutiveStores. Given a list of 724 /// store candidates, find the first N that are consecutive in memory. 725 /// Returns 0 if there are not at least 2 consecutive stores to try merging. 726 unsigned getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes, 727 int64_t ElementSizeBytes) const; 728 729 /// This is a helper function for mergeConsecutiveStores. It is used for 730 /// store chains that are composed entirely of constant values. 731 bool tryStoreMergeOfConstants(SmallVectorImpl<MemOpLink> &StoreNodes, 732 unsigned NumConsecutiveStores, 733 EVT MemVT, SDNode *Root, bool AllowVectors); 734 735 /// This is a helper function for mergeConsecutiveStores. It is used for 736 /// store chains that are composed entirely of extracted vector elements. 737 /// When extracting multiple vector elements, try to store them in one 738 /// vector store rather than a sequence of scalar stores. 739 bool tryStoreMergeOfExtracts(SmallVectorImpl<MemOpLink> &StoreNodes, 740 unsigned NumConsecutiveStores, EVT MemVT, 741 SDNode *Root); 742 743 /// This is a helper function for mergeConsecutiveStores. It is used for 744 /// store chains that are composed entirely of loaded values. 745 bool tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes, 746 unsigned NumConsecutiveStores, EVT MemVT, 747 SDNode *Root, bool AllowVectors, 748 bool IsNonTemporalStore, bool IsNonTemporalLoad); 749 750 /// Merge consecutive store operations into a wide store. 751 /// This optimization uses wide integers or vectors when possible. 752 /// \return true if stores were merged. 753 bool mergeConsecutiveStores(StoreSDNode *St); 754 755 /// Try to transform a truncation where C is a constant: 756 /// (trunc (and X, C)) -> (and (trunc X), (trunc C)) 757 /// 758 /// \p N needs to be a truncation and its first operand an AND. Other 759 /// requirements are checked by the function (e.g. that trunc is 760 /// single-use) and if missed an empty SDValue is returned. 761 SDValue distributeTruncateThroughAnd(SDNode *N); 762 763 /// Helper function to determine whether the target supports operation 764 /// given by \p Opcode for type \p VT, that is, whether the operation 765 /// is legal or custom before legalizing operations, and whether is 766 /// legal (but not custom) after legalization. 767 bool hasOperation(unsigned Opcode, EVT VT) { 768 return TLI.isOperationLegalOrCustom(Opcode, VT, LegalOperations); 769 } 770 771 public: 772 /// Runs the dag combiner on all nodes in the work list 773 void Run(CombineLevel AtLevel); 774 775 SelectionDAG &getDAG() const { return DAG; } 776 777 /// Returns a type large enough to hold any valid shift amount - before type 778 /// legalization these can be huge. 779 EVT getShiftAmountTy(EVT LHSTy) { 780 assert(LHSTy.isInteger() && "Shift amount is not an integer type!"); 781 return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes); 782 } 783 784 /// This method returns true if we are running before type legalization or 785 /// if the specified VT is legal. 786 bool isTypeLegal(const EVT &VT) { 787 if (!LegalTypes) return true; 788 return TLI.isTypeLegal(VT); 789 } 790 791 /// Convenience wrapper around TargetLowering::getSetCCResultType 792 EVT getSetCCResultType(EVT VT) const { 793 return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 794 } 795 796 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 797 SDValue OrigLoad, SDValue ExtLoad, 798 ISD::NodeType ExtType); 799 }; 800 801 /// This class is a DAGUpdateListener that removes any deleted 802 /// nodes from the worklist. 803 class WorklistRemover : public SelectionDAG::DAGUpdateListener { 804 DAGCombiner &DC; 805 806 public: 807 explicit WorklistRemover(DAGCombiner &dc) 808 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 809 810 void NodeDeleted(SDNode *N, SDNode *E) override { 811 DC.removeFromWorklist(N); 812 } 813 }; 814 815 class WorklistInserter : public SelectionDAG::DAGUpdateListener { 816 DAGCombiner &DC; 817 818 public: 819 explicit WorklistInserter(DAGCombiner &dc) 820 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {} 821 822 // FIXME: Ideally we could add N to the worklist, but this causes exponential 823 // compile time costs in large DAGs, e.g. Halide. 824 void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); } 825 }; 826 827 } // end anonymous namespace 828 829 //===----------------------------------------------------------------------===// 830 // TargetLowering::DAGCombinerInfo implementation 831 //===----------------------------------------------------------------------===// 832 833 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) { 834 ((DAGCombiner*)DC)->AddToWorklist(N); 835 } 836 837 SDValue TargetLowering::DAGCombinerInfo:: 838 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) { 839 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo); 840 } 841 842 SDValue TargetLowering::DAGCombinerInfo:: 843 CombineTo(SDNode *N, SDValue Res, bool AddTo) { 844 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo); 845 } 846 847 SDValue TargetLowering::DAGCombinerInfo:: 848 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) { 849 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo); 850 } 851 852 bool TargetLowering::DAGCombinerInfo:: 853 recursivelyDeleteUnusedNodes(SDNode *N) { 854 return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N); 855 } 856 857 void TargetLowering::DAGCombinerInfo:: 858 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 859 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO); 860 } 861 862 //===----------------------------------------------------------------------===// 863 // Helper Functions 864 //===----------------------------------------------------------------------===// 865 866 void DAGCombiner::deleteAndRecombine(SDNode *N) { 867 removeFromWorklist(N); 868 869 // If the operands of this node are only used by the node, they will now be 870 // dead. Make sure to re-visit them and recursively delete dead nodes. 871 for (const SDValue &Op : N->ops()) 872 // For an operand generating multiple values, one of the values may 873 // become dead allowing further simplification (e.g. split index 874 // arithmetic from an indexed load). 875 if (Op->hasOneUse() || Op->getNumValues() > 1) 876 AddToWorklist(Op.getNode()); 877 878 DAG.DeleteNode(N); 879 } 880 881 // APInts must be the same size for most operations, this helper 882 // function zero extends the shorter of the pair so that they match. 883 // We provide an Offset so that we can create bitwidths that won't overflow. 884 static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) { 885 unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth()); 886 LHS = LHS.zextOrSelf(Bits); 887 RHS = RHS.zextOrSelf(Bits); 888 } 889 890 // Return true if this node is a setcc, or is a select_cc 891 // that selects between the target values used for true and false, making it 892 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to 893 // the appropriate nodes based on the type of node we are checking. This 894 // simplifies life a bit for the callers. 895 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS, 896 SDValue &CC, bool MatchStrict) const { 897 if (N.getOpcode() == ISD::SETCC) { 898 LHS = N.getOperand(0); 899 RHS = N.getOperand(1); 900 CC = N.getOperand(2); 901 return true; 902 } 903 904 if (MatchStrict && 905 (N.getOpcode() == ISD::STRICT_FSETCC || 906 N.getOpcode() == ISD::STRICT_FSETCCS)) { 907 LHS = N.getOperand(1); 908 RHS = N.getOperand(2); 909 CC = N.getOperand(3); 910 return true; 911 } 912 913 if (N.getOpcode() != ISD::SELECT_CC || 914 !TLI.isConstTrueVal(N.getOperand(2).getNode()) || 915 !TLI.isConstFalseVal(N.getOperand(3).getNode())) 916 return false; 917 918 if (TLI.getBooleanContents(N.getValueType()) == 919 TargetLowering::UndefinedBooleanContent) 920 return false; 921 922 LHS = N.getOperand(0); 923 RHS = N.getOperand(1); 924 CC = N.getOperand(4); 925 return true; 926 } 927 928 /// Return true if this is a SetCC-equivalent operation with only one use. 929 /// If this is true, it allows the users to invert the operation for free when 930 /// it is profitable to do so. 931 bool DAGCombiner::isOneUseSetCC(SDValue N) const { 932 SDValue N0, N1, N2; 933 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse()) 934 return true; 935 return false; 936 } 937 938 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT ScalarTy) { 939 if (!ScalarTy.isSimple()) 940 return false; 941 942 uint64_t MaskForTy = 0ULL; 943 switch (ScalarTy.getSimpleVT().SimpleTy) { 944 case MVT::i8: 945 MaskForTy = 0xFFULL; 946 break; 947 case MVT::i16: 948 MaskForTy = 0xFFFFULL; 949 break; 950 case MVT::i32: 951 MaskForTy = 0xFFFFFFFFULL; 952 break; 953 default: 954 return false; 955 break; 956 } 957 958 APInt Val; 959 if (ISD::isConstantSplatVector(N, Val)) 960 return Val.getLimitedValue() == MaskForTy; 961 962 return false; 963 } 964 965 // Determines if it is a constant integer or a splat/build vector of constant 966 // integers (and undefs). 967 // Do not permit build vector implicit truncation. 968 static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) { 969 if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N)) 970 return !(Const->isOpaque() && NoOpaques); 971 if (N.getOpcode() != ISD::BUILD_VECTOR && N.getOpcode() != ISD::SPLAT_VECTOR) 972 return false; 973 unsigned BitWidth = N.getScalarValueSizeInBits(); 974 for (const SDValue &Op : N->op_values()) { 975 if (Op.isUndef()) 976 continue; 977 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op); 978 if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth || 979 (Const->isOpaque() && NoOpaques)) 980 return false; 981 } 982 return true; 983 } 984 985 // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with 986 // undef's. 987 static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) { 988 if (V.getOpcode() != ISD::BUILD_VECTOR) 989 return false; 990 return isConstantOrConstantVector(V, NoOpaques) || 991 ISD::isBuildVectorOfConstantFPSDNodes(V.getNode()); 992 } 993 994 // Determine if this an indexed load with an opaque target constant index. 995 static bool canSplitIdx(LoadSDNode *LD) { 996 return MaySplitLoadIndex && 997 (LD->getOperand(2).getOpcode() != ISD::TargetConstant || 998 !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque()); 999 } 1000 1001 bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc, 1002 const SDLoc &DL, 1003 SDValue N0, 1004 SDValue N1) { 1005 // Currently this only tries to ensure we don't undo the GEP splits done by 1006 // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this, 1007 // we check if the following transformation would be problematic: 1008 // (load/store (add, (add, x, offset1), offset2)) -> 1009 // (load/store (add, x, offset1+offset2)). 1010 1011 if (Opc != ISD::ADD || N0.getOpcode() != ISD::ADD) 1012 return false; 1013 1014 if (N0.hasOneUse()) 1015 return false; 1016 1017 auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 1018 auto *C2 = dyn_cast<ConstantSDNode>(N1); 1019 if (!C1 || !C2) 1020 return false; 1021 1022 const APInt &C1APIntVal = C1->getAPIntValue(); 1023 const APInt &C2APIntVal = C2->getAPIntValue(); 1024 if (C1APIntVal.getBitWidth() > 64 || C2APIntVal.getBitWidth() > 64) 1025 return false; 1026 1027 const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal; 1028 if (CombinedValueIntVal.getBitWidth() > 64) 1029 return false; 1030 const int64_t CombinedValue = CombinedValueIntVal.getSExtValue(); 1031 1032 for (SDNode *Node : N0->uses()) { 1033 auto LoadStore = dyn_cast<MemSDNode>(Node); 1034 if (LoadStore) { 1035 // Is x[offset2] already not a legal addressing mode? If so then 1036 // reassociating the constants breaks nothing (we test offset2 because 1037 // that's the one we hope to fold into the load or store). 1038 TargetLoweringBase::AddrMode AM; 1039 AM.HasBaseReg = true; 1040 AM.BaseOffs = C2APIntVal.getSExtValue(); 1041 EVT VT = LoadStore->getMemoryVT(); 1042 unsigned AS = LoadStore->getAddressSpace(); 1043 Type *AccessTy = VT.getTypeForEVT(*DAG.getContext()); 1044 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS)) 1045 continue; 1046 1047 // Would x[offset1+offset2] still be a legal addressing mode? 1048 AM.BaseOffs = CombinedValue; 1049 if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS)) 1050 return true; 1051 } 1052 } 1053 1054 return false; 1055 } 1056 1057 // Helper for DAGCombiner::reassociateOps. Try to reassociate an expression 1058 // such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc. 1059 SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, 1060 SDValue N0, SDValue N1) { 1061 EVT VT = N0.getValueType(); 1062 1063 if (N0.getOpcode() != Opc) 1064 return SDValue(); 1065 1066 SDValue N00 = N0.getOperand(0); 1067 SDValue N01 = N0.getOperand(1); 1068 1069 if (DAG.isConstantIntBuildVectorOrConstantInt(peekThroughBitcasts(N01))) { 1070 if (DAG.isConstantIntBuildVectorOrConstantInt(peekThroughBitcasts(N1))) { 1071 // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2)) 1072 if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, {N01, N1})) 1073 return DAG.getNode(Opc, DL, VT, N00, OpNode); 1074 return SDValue(); 1075 } 1076 if (N0.hasOneUse()) { 1077 // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1) 1078 // iff (op x, c1) has one use 1079 if (SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N00, N1)) 1080 return DAG.getNode(Opc, DL, VT, OpNode, N01); 1081 return SDValue(); 1082 } 1083 } 1084 return SDValue(); 1085 } 1086 1087 // Try to reassociate commutative binops. 1088 SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0, 1089 SDValue N1, SDNodeFlags Flags) { 1090 assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative."); 1091 1092 // Floating-point reassociation is not allowed without loose FP math. 1093 if (N0.getValueType().isFloatingPoint() || 1094 N1.getValueType().isFloatingPoint()) 1095 if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros()) 1096 return SDValue(); 1097 1098 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1)) 1099 return Combined; 1100 if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0)) 1101 return Combined; 1102 return SDValue(); 1103 } 1104 1105 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo, 1106 bool AddTo) { 1107 assert(N->getNumValues() == NumTo && "Broken CombineTo call!"); 1108 ++NodesCombined; 1109 LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: "; 1110 To[0].getNode()->dump(&DAG); 1111 dbgs() << " and " << NumTo - 1 << " other values\n"); 1112 for (unsigned i = 0, e = NumTo; i != e; ++i) 1113 assert((!To[i].getNode() || 1114 N->getValueType(i) == To[i].getValueType()) && 1115 "Cannot combine value to value of different type!"); 1116 1117 WorklistRemover DeadNodes(*this); 1118 DAG.ReplaceAllUsesWith(N, To); 1119 if (AddTo) { 1120 // Push the new nodes and any users onto the worklist 1121 for (unsigned i = 0, e = NumTo; i != e; ++i) { 1122 if (To[i].getNode()) { 1123 AddToWorklist(To[i].getNode()); 1124 AddUsersToWorklist(To[i].getNode()); 1125 } 1126 } 1127 } 1128 1129 // Finally, if the node is now dead, remove it from the graph. The node 1130 // may not be dead if the replacement process recursively simplified to 1131 // something else needing this node. 1132 if (N->use_empty()) 1133 deleteAndRecombine(N); 1134 return SDValue(N, 0); 1135 } 1136 1137 void DAGCombiner:: 1138 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) { 1139 // Replace the old value with the new one. 1140 ++NodesCombined; 1141 LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG); 1142 dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG); 1143 dbgs() << '\n'); 1144 1145 // Replace all uses. If any nodes become isomorphic to other nodes and 1146 // are deleted, make sure to remove them from our worklist. 1147 WorklistRemover DeadNodes(*this); 1148 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New); 1149 1150 // Push the new node and any (possibly new) users onto the worklist. 1151 AddToWorklistWithUsers(TLO.New.getNode()); 1152 1153 // Finally, if the node is now dead, remove it from the graph. The node 1154 // may not be dead if the replacement process recursively simplified to 1155 // something else needing this node. 1156 if (TLO.Old.getNode()->use_empty()) 1157 deleteAndRecombine(TLO.Old.getNode()); 1158 } 1159 1160 /// Check the specified integer node value to see if it can be simplified or if 1161 /// things it uses can be simplified by bit propagation. If so, return true. 1162 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits, 1163 const APInt &DemandedElts, 1164 bool AssumeSingleUse) { 1165 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1166 KnownBits Known; 1167 if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0, 1168 AssumeSingleUse)) 1169 return false; 1170 1171 // Revisit the node. 1172 AddToWorklist(Op.getNode()); 1173 1174 CommitTargetLoweringOpt(TLO); 1175 return true; 1176 } 1177 1178 /// Check the specified vector node value to see if it can be simplified or 1179 /// if things it uses can be simplified as it only uses some of the elements. 1180 /// If so, return true. 1181 bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op, 1182 const APInt &DemandedElts, 1183 bool AssumeSingleUse) { 1184 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations); 1185 APInt KnownUndef, KnownZero; 1186 if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, 1187 TLO, 0, AssumeSingleUse)) 1188 return false; 1189 1190 // Revisit the node. 1191 AddToWorklist(Op.getNode()); 1192 1193 CommitTargetLoweringOpt(TLO); 1194 return true; 1195 } 1196 1197 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) { 1198 SDLoc DL(Load); 1199 EVT VT = Load->getValueType(0); 1200 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0)); 1201 1202 LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: "; 1203 Trunc.getNode()->dump(&DAG); dbgs() << '\n'); 1204 WorklistRemover DeadNodes(*this); 1205 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc); 1206 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1)); 1207 deleteAndRecombine(Load); 1208 AddToWorklist(Trunc.getNode()); 1209 } 1210 1211 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) { 1212 Replace = false; 1213 SDLoc DL(Op); 1214 if (ISD::isUNINDEXEDLoad(Op.getNode())) { 1215 LoadSDNode *LD = cast<LoadSDNode>(Op); 1216 EVT MemVT = LD->getMemoryVT(); 1217 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1218 : LD->getExtensionType(); 1219 Replace = true; 1220 return DAG.getExtLoad(ExtType, DL, PVT, 1221 LD->getChain(), LD->getBasePtr(), 1222 MemVT, LD->getMemOperand()); 1223 } 1224 1225 unsigned Opc = Op.getOpcode(); 1226 switch (Opc) { 1227 default: break; 1228 case ISD::AssertSext: 1229 if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT)) 1230 return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1)); 1231 break; 1232 case ISD::AssertZext: 1233 if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT)) 1234 return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1)); 1235 break; 1236 case ISD::Constant: { 1237 unsigned ExtOpc = 1238 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1239 return DAG.getNode(ExtOpc, DL, PVT, Op); 1240 } 1241 } 1242 1243 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT)) 1244 return SDValue(); 1245 return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op); 1246 } 1247 1248 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) { 1249 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT)) 1250 return SDValue(); 1251 EVT OldVT = Op.getValueType(); 1252 SDLoc DL(Op); 1253 bool Replace = false; 1254 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1255 if (!NewOp.getNode()) 1256 return SDValue(); 1257 AddToWorklist(NewOp.getNode()); 1258 1259 if (Replace) 1260 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1261 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp, 1262 DAG.getValueType(OldVT)); 1263 } 1264 1265 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) { 1266 EVT OldVT = Op.getValueType(); 1267 SDLoc DL(Op); 1268 bool Replace = false; 1269 SDValue NewOp = PromoteOperand(Op, PVT, Replace); 1270 if (!NewOp.getNode()) 1271 return SDValue(); 1272 AddToWorklist(NewOp.getNode()); 1273 1274 if (Replace) 1275 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode()); 1276 return DAG.getZeroExtendInReg(NewOp, DL, OldVT); 1277 } 1278 1279 /// Promote the specified integer binary operation if the target indicates it is 1280 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1281 /// i32 since i16 instructions are longer. 1282 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) { 1283 if (!LegalOperations) 1284 return SDValue(); 1285 1286 EVT VT = Op.getValueType(); 1287 if (VT.isVector() || !VT.isInteger()) 1288 return SDValue(); 1289 1290 // If operation type is 'undesirable', e.g. i16 on x86, consider 1291 // promoting it. 1292 unsigned Opc = Op.getOpcode(); 1293 if (TLI.isTypeDesirableForOp(Opc, VT)) 1294 return SDValue(); 1295 1296 EVT PVT = VT; 1297 // Consult target whether it is a good idea to promote this operation and 1298 // what's the right type to promote it to. 1299 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1300 assert(PVT != VT && "Don't know what type to promote to!"); 1301 1302 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1303 1304 bool Replace0 = false; 1305 SDValue N0 = Op.getOperand(0); 1306 SDValue NN0 = PromoteOperand(N0, PVT, Replace0); 1307 1308 bool Replace1 = false; 1309 SDValue N1 = Op.getOperand(1); 1310 SDValue NN1 = PromoteOperand(N1, PVT, Replace1); 1311 SDLoc DL(Op); 1312 1313 SDValue RV = 1314 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1)); 1315 1316 // We are always replacing N0/N1's use in N and only need additional 1317 // replacements if there are additional uses. 1318 // Note: We are checking uses of the *nodes* (SDNode) rather than values 1319 // (SDValue) here because the node may reference multiple values 1320 // (for example, the chain value of a load node). 1321 Replace0 &= !N0->hasOneUse(); 1322 Replace1 &= (N0 != N1) && !N1->hasOneUse(); 1323 1324 // Combine Op here so it is preserved past replacements. 1325 CombineTo(Op.getNode(), RV); 1326 1327 // If operands have a use ordering, make sure we deal with 1328 // predecessor first. 1329 if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) { 1330 std::swap(N0, N1); 1331 std::swap(NN0, NN1); 1332 } 1333 1334 if (Replace0) { 1335 AddToWorklist(NN0.getNode()); 1336 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode()); 1337 } 1338 if (Replace1) { 1339 AddToWorklist(NN1.getNode()); 1340 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode()); 1341 } 1342 return Op; 1343 } 1344 return SDValue(); 1345 } 1346 1347 /// Promote the specified integer shift operation if the target indicates it is 1348 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to 1349 /// i32 since i16 instructions are longer. 1350 SDValue DAGCombiner::PromoteIntShiftOp(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 1370 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1371 1372 bool Replace = false; 1373 SDValue N0 = Op.getOperand(0); 1374 SDValue N1 = Op.getOperand(1); 1375 if (Opc == ISD::SRA) 1376 N0 = SExtPromoteOperand(N0, PVT); 1377 else if (Opc == ISD::SRL) 1378 N0 = ZExtPromoteOperand(N0, PVT); 1379 else 1380 N0 = PromoteOperand(N0, PVT, Replace); 1381 1382 if (!N0.getNode()) 1383 return SDValue(); 1384 1385 SDLoc DL(Op); 1386 SDValue RV = 1387 DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1)); 1388 1389 if (Replace) 1390 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode()); 1391 1392 // Deal with Op being deleted. 1393 if (Op && Op.getOpcode() != ISD::DELETED_NODE) 1394 return RV; 1395 } 1396 return SDValue(); 1397 } 1398 1399 SDValue DAGCombiner::PromoteExtend(SDValue Op) { 1400 if (!LegalOperations) 1401 return SDValue(); 1402 1403 EVT VT = Op.getValueType(); 1404 if (VT.isVector() || !VT.isInteger()) 1405 return SDValue(); 1406 1407 // If operation type is 'undesirable', e.g. i16 on x86, consider 1408 // promoting it. 1409 unsigned Opc = Op.getOpcode(); 1410 if (TLI.isTypeDesirableForOp(Opc, VT)) 1411 return SDValue(); 1412 1413 EVT PVT = VT; 1414 // Consult target whether it is a good idea to promote this operation and 1415 // what's the right type to promote it to. 1416 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1417 assert(PVT != VT && "Don't know what type to promote to!"); 1418 // fold (aext (aext x)) -> (aext x) 1419 // fold (aext (zext x)) -> (zext x) 1420 // fold (aext (sext x)) -> (sext x) 1421 LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG)); 1422 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0)); 1423 } 1424 return SDValue(); 1425 } 1426 1427 bool DAGCombiner::PromoteLoad(SDValue Op) { 1428 if (!LegalOperations) 1429 return false; 1430 1431 if (!ISD::isUNINDEXEDLoad(Op.getNode())) 1432 return false; 1433 1434 EVT VT = Op.getValueType(); 1435 if (VT.isVector() || !VT.isInteger()) 1436 return false; 1437 1438 // If operation type is 'undesirable', e.g. i16 on x86, consider 1439 // promoting it. 1440 unsigned Opc = Op.getOpcode(); 1441 if (TLI.isTypeDesirableForOp(Opc, VT)) 1442 return false; 1443 1444 EVT PVT = VT; 1445 // Consult target whether it is a good idea to promote this operation and 1446 // what's the right type to promote it to. 1447 if (TLI.IsDesirableToPromoteOp(Op, PVT)) { 1448 assert(PVT != VT && "Don't know what type to promote to!"); 1449 1450 SDLoc DL(Op); 1451 SDNode *N = Op.getNode(); 1452 LoadSDNode *LD = cast<LoadSDNode>(N); 1453 EVT MemVT = LD->getMemoryVT(); 1454 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD 1455 : LD->getExtensionType(); 1456 SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT, 1457 LD->getChain(), LD->getBasePtr(), 1458 MemVT, LD->getMemOperand()); 1459 SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD); 1460 1461 LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: "; 1462 Result.getNode()->dump(&DAG); dbgs() << '\n'); 1463 WorklistRemover DeadNodes(*this); 1464 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1465 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1)); 1466 deleteAndRecombine(N); 1467 AddToWorklist(Result.getNode()); 1468 return true; 1469 } 1470 return false; 1471 } 1472 1473 /// Recursively delete a node which has no uses and any operands for 1474 /// which it is the only use. 1475 /// 1476 /// Note that this both deletes the nodes and removes them from the worklist. 1477 /// It also adds any nodes who have had a user deleted to the worklist as they 1478 /// may now have only one use and subject to other combines. 1479 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) { 1480 if (!N->use_empty()) 1481 return false; 1482 1483 SmallSetVector<SDNode *, 16> Nodes; 1484 Nodes.insert(N); 1485 do { 1486 N = Nodes.pop_back_val(); 1487 if (!N) 1488 continue; 1489 1490 if (N->use_empty()) { 1491 for (const SDValue &ChildN : N->op_values()) 1492 Nodes.insert(ChildN.getNode()); 1493 1494 removeFromWorklist(N); 1495 DAG.DeleteNode(N); 1496 } else { 1497 AddToWorklist(N); 1498 } 1499 } while (!Nodes.empty()); 1500 return true; 1501 } 1502 1503 //===----------------------------------------------------------------------===// 1504 // Main DAG Combiner implementation 1505 //===----------------------------------------------------------------------===// 1506 1507 void DAGCombiner::Run(CombineLevel AtLevel) { 1508 // set the instance variables, so that the various visit routines may use it. 1509 Level = AtLevel; 1510 LegalDAG = Level >= AfterLegalizeDAG; 1511 LegalOperations = Level >= AfterLegalizeVectorOps; 1512 LegalTypes = Level >= AfterLegalizeTypes; 1513 1514 WorklistInserter AddNodes(*this); 1515 1516 // Add all the dag nodes to the worklist. 1517 for (SDNode &Node : DAG.allnodes()) 1518 AddToWorklist(&Node); 1519 1520 // Create a dummy node (which is not added to allnodes), that adds a reference 1521 // to the root node, preventing it from being deleted, and tracking any 1522 // changes of the root. 1523 HandleSDNode Dummy(DAG.getRoot()); 1524 1525 // While we have a valid worklist entry node, try to combine it. 1526 while (SDNode *N = getNextWorklistEntry()) { 1527 // If N has no uses, it is dead. Make sure to revisit all N's operands once 1528 // N is deleted from the DAG, since they too may now be dead or may have a 1529 // reduced number of uses, allowing other xforms. 1530 if (recursivelyDeleteUnusedNodes(N)) 1531 continue; 1532 1533 WorklistRemover DeadNodes(*this); 1534 1535 // If this combine is running after legalizing the DAG, re-legalize any 1536 // nodes pulled off the worklist. 1537 if (LegalDAG) { 1538 SmallSetVector<SDNode *, 16> UpdatedNodes; 1539 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes); 1540 1541 for (SDNode *LN : UpdatedNodes) 1542 AddToWorklistWithUsers(LN); 1543 1544 if (!NIsValid) 1545 continue; 1546 } 1547 1548 LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG)); 1549 1550 // Add any operands of the new node which have not yet been combined to the 1551 // worklist as well. Because the worklist uniques things already, this 1552 // won't repeatedly process the same operand. 1553 CombinedNodes.insert(N); 1554 for (const SDValue &ChildN : N->op_values()) 1555 if (!CombinedNodes.count(ChildN.getNode())) 1556 AddToWorklist(ChildN.getNode()); 1557 1558 SDValue RV = combine(N); 1559 1560 if (!RV.getNode()) 1561 continue; 1562 1563 ++NodesCombined; 1564 1565 // If we get back the same node we passed in, rather than a new node or 1566 // zero, we know that the node must have defined multiple values and 1567 // CombineTo was used. Since CombineTo takes care of the worklist 1568 // mechanics for us, we have no work to do in this case. 1569 if (RV.getNode() == N) 1570 continue; 1571 1572 assert(N->getOpcode() != ISD::DELETED_NODE && 1573 RV.getOpcode() != ISD::DELETED_NODE && 1574 "Node was deleted but visit returned new node!"); 1575 1576 LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG)); 1577 1578 if (N->getNumValues() == RV.getNode()->getNumValues()) 1579 DAG.ReplaceAllUsesWith(N, RV.getNode()); 1580 else { 1581 assert(N->getValueType(0) == RV.getValueType() && 1582 N->getNumValues() == 1 && "Type mismatch"); 1583 DAG.ReplaceAllUsesWith(N, &RV); 1584 } 1585 1586 // Push the new node and any users onto the worklist. Omit this if the 1587 // new node is the EntryToken (e.g. if a store managed to get optimized 1588 // out), because re-visiting the EntryToken and its users will not uncover 1589 // any additional opportunities, but there may be a large number of such 1590 // users, potentially causing compile time explosion. 1591 if (RV.getOpcode() != ISD::EntryToken) { 1592 AddToWorklist(RV.getNode()); 1593 AddUsersToWorklist(RV.getNode()); 1594 } 1595 1596 // Finally, if the node is now dead, remove it from the graph. The node 1597 // may not be dead if the replacement process recursively simplified to 1598 // something else needing this node. This will also take care of adding any 1599 // operands which have lost a user to the worklist. 1600 recursivelyDeleteUnusedNodes(N); 1601 } 1602 1603 // If the root changed (e.g. it was a dead load, update the root). 1604 DAG.setRoot(Dummy.getValue()); 1605 DAG.RemoveDeadNodes(); 1606 } 1607 1608 SDValue DAGCombiner::visit(SDNode *N) { 1609 switch (N->getOpcode()) { 1610 default: break; 1611 case ISD::TokenFactor: return visitTokenFactor(N); 1612 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N); 1613 case ISD::ADD: return visitADD(N); 1614 case ISD::SUB: return visitSUB(N); 1615 case ISD::SADDSAT: 1616 case ISD::UADDSAT: return visitADDSAT(N); 1617 case ISD::SSUBSAT: 1618 case ISD::USUBSAT: return visitSUBSAT(N); 1619 case ISD::ADDC: return visitADDC(N); 1620 case ISD::SADDO: 1621 case ISD::UADDO: return visitADDO(N); 1622 case ISD::SUBC: return visitSUBC(N); 1623 case ISD::SSUBO: 1624 case ISD::USUBO: return visitSUBO(N); 1625 case ISD::ADDE: return visitADDE(N); 1626 case ISD::ADDCARRY: return visitADDCARRY(N); 1627 case ISD::SADDO_CARRY: return visitSADDO_CARRY(N); 1628 case ISD::SUBE: return visitSUBE(N); 1629 case ISD::SUBCARRY: return visitSUBCARRY(N); 1630 case ISD::SSUBO_CARRY: return visitSSUBO_CARRY(N); 1631 case ISD::SMULFIX: 1632 case ISD::SMULFIXSAT: 1633 case ISD::UMULFIX: 1634 case ISD::UMULFIXSAT: return visitMULFIX(N); 1635 case ISD::MUL: return visitMUL(N); 1636 case ISD::SDIV: return visitSDIV(N); 1637 case ISD::UDIV: return visitUDIV(N); 1638 case ISD::SREM: 1639 case ISD::UREM: return visitREM(N); 1640 case ISD::MULHU: return visitMULHU(N); 1641 case ISD::MULHS: return visitMULHS(N); 1642 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N); 1643 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N); 1644 case ISD::SMULO: 1645 case ISD::UMULO: return visitMULO(N); 1646 case ISD::SMIN: 1647 case ISD::SMAX: 1648 case ISD::UMIN: 1649 case ISD::UMAX: return visitIMINMAX(N); 1650 case ISD::AND: return visitAND(N); 1651 case ISD::OR: return visitOR(N); 1652 case ISD::XOR: return visitXOR(N); 1653 case ISD::SHL: return visitSHL(N); 1654 case ISD::SRA: return visitSRA(N); 1655 case ISD::SRL: return visitSRL(N); 1656 case ISD::ROTR: 1657 case ISD::ROTL: return visitRotate(N); 1658 case ISD::FSHL: 1659 case ISD::FSHR: return visitFunnelShift(N); 1660 case ISD::ABS: return visitABS(N); 1661 case ISD::BSWAP: return visitBSWAP(N); 1662 case ISD::BITREVERSE: return visitBITREVERSE(N); 1663 case ISD::CTLZ: return visitCTLZ(N); 1664 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N); 1665 case ISD::CTTZ: return visitCTTZ(N); 1666 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N); 1667 case ISD::CTPOP: return visitCTPOP(N); 1668 case ISD::SELECT: return visitSELECT(N); 1669 case ISD::VSELECT: return visitVSELECT(N); 1670 case ISD::SELECT_CC: return visitSELECT_CC(N); 1671 case ISD::SETCC: return visitSETCC(N); 1672 case ISD::SETCCCARRY: return visitSETCCCARRY(N); 1673 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N); 1674 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N); 1675 case ISD::ANY_EXTEND: return visitANY_EXTEND(N); 1676 case ISD::AssertSext: 1677 case ISD::AssertZext: return visitAssertExt(N); 1678 case ISD::AssertAlign: return visitAssertAlign(N); 1679 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N); 1680 case ISD::SIGN_EXTEND_VECTOR_INREG: 1681 case ISD::ZERO_EXTEND_VECTOR_INREG: return visitEXTEND_VECTOR_INREG(N); 1682 case ISD::TRUNCATE: return visitTRUNCATE(N); 1683 case ISD::BITCAST: return visitBITCAST(N); 1684 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N); 1685 case ISD::FADD: return visitFADD(N); 1686 case ISD::STRICT_FADD: return visitSTRICT_FADD(N); 1687 case ISD::FSUB: return visitFSUB(N); 1688 case ISD::FMUL: return visitFMUL(N); 1689 case ISD::FMA: return visitFMA(N); 1690 case ISD::FDIV: return visitFDIV(N); 1691 case ISD::FREM: return visitFREM(N); 1692 case ISD::FSQRT: return visitFSQRT(N); 1693 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N); 1694 case ISD::FPOW: return visitFPOW(N); 1695 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N); 1696 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N); 1697 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N); 1698 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N); 1699 case ISD::FP_ROUND: return visitFP_ROUND(N); 1700 case ISD::FP_EXTEND: return visitFP_EXTEND(N); 1701 case ISD::FNEG: return visitFNEG(N); 1702 case ISD::FABS: return visitFABS(N); 1703 case ISD::FFLOOR: return visitFFLOOR(N); 1704 case ISD::FMINNUM: return visitFMINNUM(N); 1705 case ISD::FMAXNUM: return visitFMAXNUM(N); 1706 case ISD::FMINIMUM: return visitFMINIMUM(N); 1707 case ISD::FMAXIMUM: return visitFMAXIMUM(N); 1708 case ISD::FCEIL: return visitFCEIL(N); 1709 case ISD::FTRUNC: return visitFTRUNC(N); 1710 case ISD::BRCOND: return visitBRCOND(N); 1711 case ISD::BR_CC: return visitBR_CC(N); 1712 case ISD::LOAD: return visitLOAD(N); 1713 case ISD::STORE: return visitSTORE(N); 1714 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N); 1715 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N); 1716 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N); 1717 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N); 1718 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N); 1719 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N); 1720 case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N); 1721 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N); 1722 case ISD::MGATHER: return visitMGATHER(N); 1723 case ISD::MLOAD: return visitMLOAD(N); 1724 case ISD::MSCATTER: return visitMSCATTER(N); 1725 case ISD::MSTORE: return visitMSTORE(N); 1726 case ISD::LIFETIME_END: return visitLIFETIME_END(N); 1727 case ISD::FP_TO_FP16: return visitFP_TO_FP16(N); 1728 case ISD::FP16_TO_FP: return visitFP16_TO_FP(N); 1729 case ISD::FREEZE: return visitFREEZE(N); 1730 case ISD::VECREDUCE_FADD: 1731 case ISD::VECREDUCE_FMUL: 1732 case ISD::VECREDUCE_ADD: 1733 case ISD::VECREDUCE_MUL: 1734 case ISD::VECREDUCE_AND: 1735 case ISD::VECREDUCE_OR: 1736 case ISD::VECREDUCE_XOR: 1737 case ISD::VECREDUCE_SMAX: 1738 case ISD::VECREDUCE_SMIN: 1739 case ISD::VECREDUCE_UMAX: 1740 case ISD::VECREDUCE_UMIN: 1741 case ISD::VECREDUCE_FMAX: 1742 case ISD::VECREDUCE_FMIN: return visitVECREDUCE(N); 1743 #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) case ISD::SDOPC: 1744 #include "llvm/IR/VPIntrinsics.def" 1745 return visitVPOp(N); 1746 } 1747 return SDValue(); 1748 } 1749 1750 SDValue DAGCombiner::combine(SDNode *N) { 1751 SDValue RV; 1752 if (!DisableGenericCombines) 1753 RV = visit(N); 1754 1755 // If nothing happened, try a target-specific DAG combine. 1756 if (!RV.getNode()) { 1757 assert(N->getOpcode() != ISD::DELETED_NODE && 1758 "Node was deleted but visit returned NULL!"); 1759 1760 if (N->getOpcode() >= ISD::BUILTIN_OP_END || 1761 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) { 1762 1763 // Expose the DAG combiner to the target combiner impls. 1764 TargetLowering::DAGCombinerInfo 1765 DagCombineInfo(DAG, Level, false, this); 1766 1767 RV = TLI.PerformDAGCombine(N, DagCombineInfo); 1768 } 1769 } 1770 1771 // If nothing happened still, try promoting the operation. 1772 if (!RV.getNode()) { 1773 switch (N->getOpcode()) { 1774 default: break; 1775 case ISD::ADD: 1776 case ISD::SUB: 1777 case ISD::MUL: 1778 case ISD::AND: 1779 case ISD::OR: 1780 case ISD::XOR: 1781 RV = PromoteIntBinOp(SDValue(N, 0)); 1782 break; 1783 case ISD::SHL: 1784 case ISD::SRA: 1785 case ISD::SRL: 1786 RV = PromoteIntShiftOp(SDValue(N, 0)); 1787 break; 1788 case ISD::SIGN_EXTEND: 1789 case ISD::ZERO_EXTEND: 1790 case ISD::ANY_EXTEND: 1791 RV = PromoteExtend(SDValue(N, 0)); 1792 break; 1793 case ISD::LOAD: 1794 if (PromoteLoad(SDValue(N, 0))) 1795 RV = SDValue(N, 0); 1796 break; 1797 } 1798 } 1799 1800 // If N is a commutative binary node, try to eliminate it if the commuted 1801 // version is already present in the DAG. 1802 if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) && 1803 N->getNumValues() == 1) { 1804 SDValue N0 = N->getOperand(0); 1805 SDValue N1 = N->getOperand(1); 1806 1807 // Constant operands are canonicalized to RHS. 1808 if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) { 1809 SDValue Ops[] = {N1, N0}; 1810 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops, 1811 N->getFlags()); 1812 if (CSENode) 1813 return SDValue(CSENode, 0); 1814 } 1815 } 1816 1817 return RV; 1818 } 1819 1820 /// Given a node, return its input chain if it has one, otherwise return a null 1821 /// sd operand. 1822 static SDValue getInputChainForNode(SDNode *N) { 1823 if (unsigned NumOps = N->getNumOperands()) { 1824 if (N->getOperand(0).getValueType() == MVT::Other) 1825 return N->getOperand(0); 1826 if (N->getOperand(NumOps-1).getValueType() == MVT::Other) 1827 return N->getOperand(NumOps-1); 1828 for (unsigned i = 1; i < NumOps-1; ++i) 1829 if (N->getOperand(i).getValueType() == MVT::Other) 1830 return N->getOperand(i); 1831 } 1832 return SDValue(); 1833 } 1834 1835 SDValue DAGCombiner::visitTokenFactor(SDNode *N) { 1836 // If N has two operands, where one has an input chain equal to the other, 1837 // the 'other' chain is redundant. 1838 if (N->getNumOperands() == 2) { 1839 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1)) 1840 return N->getOperand(0); 1841 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0)) 1842 return N->getOperand(1); 1843 } 1844 1845 // Don't simplify token factors if optnone. 1846 if (OptLevel == CodeGenOpt::None) 1847 return SDValue(); 1848 1849 // Don't simplify the token factor if the node itself has too many operands. 1850 if (N->getNumOperands() > TokenFactorInlineLimit) 1851 return SDValue(); 1852 1853 // If the sole user is a token factor, we should make sure we have a 1854 // chance to merge them together. This prevents TF chains from inhibiting 1855 // optimizations. 1856 if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor) 1857 AddToWorklist(*(N->use_begin())); 1858 1859 SmallVector<SDNode *, 8> TFs; // List of token factors to visit. 1860 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor. 1861 SmallPtrSet<SDNode*, 16> SeenOps; 1862 bool Changed = false; // If we should replace this token factor. 1863 1864 // Start out with this token factor. 1865 TFs.push_back(N); 1866 1867 // Iterate through token factors. The TFs grows when new token factors are 1868 // encountered. 1869 for (unsigned i = 0; i < TFs.size(); ++i) { 1870 // Limit number of nodes to inline, to avoid quadratic compile times. 1871 // We have to add the outstanding Token Factors to Ops, otherwise we might 1872 // drop Ops from the resulting Token Factors. 1873 if (Ops.size() > TokenFactorInlineLimit) { 1874 for (unsigned j = i; j < TFs.size(); j++) 1875 Ops.emplace_back(TFs[j], 0); 1876 // Drop unprocessed Token Factors from TFs, so we do not add them to the 1877 // combiner worklist later. 1878 TFs.resize(i); 1879 break; 1880 } 1881 1882 SDNode *TF = TFs[i]; 1883 // Check each of the operands. 1884 for (const SDValue &Op : TF->op_values()) { 1885 switch (Op.getOpcode()) { 1886 case ISD::EntryToken: 1887 // Entry tokens don't need to be added to the list. They are 1888 // redundant. 1889 Changed = true; 1890 break; 1891 1892 case ISD::TokenFactor: 1893 if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) { 1894 // Queue up for processing. 1895 TFs.push_back(Op.getNode()); 1896 Changed = true; 1897 break; 1898 } 1899 LLVM_FALLTHROUGH; 1900 1901 default: 1902 // Only add if it isn't already in the list. 1903 if (SeenOps.insert(Op.getNode()).second) 1904 Ops.push_back(Op); 1905 else 1906 Changed = true; 1907 break; 1908 } 1909 } 1910 } 1911 1912 // Re-visit inlined Token Factors, to clean them up in case they have been 1913 // removed. Skip the first Token Factor, as this is the current node. 1914 for (unsigned i = 1, e = TFs.size(); i < e; i++) 1915 AddToWorklist(TFs[i]); 1916 1917 // Remove Nodes that are chained to another node in the list. Do so 1918 // by walking up chains breath-first stopping when we've seen 1919 // another operand. In general we must climb to the EntryNode, but we can exit 1920 // early if we find all remaining work is associated with just one operand as 1921 // no further pruning is possible. 1922 1923 // List of nodes to search through and original Ops from which they originate. 1924 SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist; 1925 SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op. 1926 SmallPtrSet<SDNode *, 16> SeenChains; 1927 bool DidPruneOps = false; 1928 1929 unsigned NumLeftToConsider = 0; 1930 for (const SDValue &Op : Ops) { 1931 Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++)); 1932 OpWorkCount.push_back(1); 1933 } 1934 1935 auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) { 1936 // If this is an Op, we can remove the op from the list. Remark any 1937 // search associated with it as from the current OpNumber. 1938 if (SeenOps.contains(Op)) { 1939 Changed = true; 1940 DidPruneOps = true; 1941 unsigned OrigOpNumber = 0; 1942 while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op) 1943 OrigOpNumber++; 1944 assert((OrigOpNumber != Ops.size()) && 1945 "expected to find TokenFactor Operand"); 1946 // Re-mark worklist from OrigOpNumber to OpNumber 1947 for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) { 1948 if (Worklist[i].second == OrigOpNumber) { 1949 Worklist[i].second = OpNumber; 1950 } 1951 } 1952 OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber]; 1953 OpWorkCount[OrigOpNumber] = 0; 1954 NumLeftToConsider--; 1955 } 1956 // Add if it's a new chain 1957 if (SeenChains.insert(Op).second) { 1958 OpWorkCount[OpNumber]++; 1959 Worklist.push_back(std::make_pair(Op, OpNumber)); 1960 } 1961 }; 1962 1963 for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) { 1964 // We need at least be consider at least 2 Ops to prune. 1965 if (NumLeftToConsider <= 1) 1966 break; 1967 auto CurNode = Worklist[i].first; 1968 auto CurOpNumber = Worklist[i].second; 1969 assert((OpWorkCount[CurOpNumber] > 0) && 1970 "Node should not appear in worklist"); 1971 switch (CurNode->getOpcode()) { 1972 case ISD::EntryToken: 1973 // Hitting EntryToken is the only way for the search to terminate without 1974 // hitting 1975 // another operand's search. Prevent us from marking this operand 1976 // considered. 1977 NumLeftToConsider++; 1978 break; 1979 case ISD::TokenFactor: 1980 for (const SDValue &Op : CurNode->op_values()) 1981 AddToWorklist(i, Op.getNode(), CurOpNumber); 1982 break; 1983 case ISD::LIFETIME_START: 1984 case ISD::LIFETIME_END: 1985 case ISD::CopyFromReg: 1986 case ISD::CopyToReg: 1987 AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber); 1988 break; 1989 default: 1990 if (auto *MemNode = dyn_cast<MemSDNode>(CurNode)) 1991 AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber); 1992 break; 1993 } 1994 OpWorkCount[CurOpNumber]--; 1995 if (OpWorkCount[CurOpNumber] == 0) 1996 NumLeftToConsider--; 1997 } 1998 1999 // If we've changed things around then replace token factor. 2000 if (Changed) { 2001 SDValue Result; 2002 if (Ops.empty()) { 2003 // The entry token is the only possible outcome. 2004 Result = DAG.getEntryNode(); 2005 } else { 2006 if (DidPruneOps) { 2007 SmallVector<SDValue, 8> PrunedOps; 2008 // 2009 for (const SDValue &Op : Ops) { 2010 if (SeenChains.count(Op.getNode()) == 0) 2011 PrunedOps.push_back(Op); 2012 } 2013 Result = DAG.getTokenFactor(SDLoc(N), PrunedOps); 2014 } else { 2015 Result = DAG.getTokenFactor(SDLoc(N), Ops); 2016 } 2017 } 2018 return Result; 2019 } 2020 return SDValue(); 2021 } 2022 2023 /// MERGE_VALUES can always be eliminated. 2024 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) { 2025 WorklistRemover DeadNodes(*this); 2026 // Replacing results may cause a different MERGE_VALUES to suddenly 2027 // be CSE'd with N, and carry its uses with it. Iterate until no 2028 // uses remain, to ensure that the node can be safely deleted. 2029 // First add the users of this node to the work list so that they 2030 // can be tried again once they have new operands. 2031 AddUsersToWorklist(N); 2032 do { 2033 // Do as a single replacement to avoid rewalking use lists. 2034 SmallVector<SDValue, 8> Ops; 2035 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) 2036 Ops.push_back(N->getOperand(i)); 2037 DAG.ReplaceAllUsesWith(N, Ops.data()); 2038 } while (!N->use_empty()); 2039 deleteAndRecombine(N); 2040 return SDValue(N, 0); // Return N so it doesn't get rechecked! 2041 } 2042 2043 /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a 2044 /// ConstantSDNode pointer else nullptr. 2045 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) { 2046 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N); 2047 return Const != nullptr && !Const->isOpaque() ? Const : nullptr; 2048 } 2049 2050 /// Return true if 'Use' is a load or a store that uses N as its base pointer 2051 /// and that N may be folded in the load / store addressing mode. 2052 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, SelectionDAG &DAG, 2053 const TargetLowering &TLI) { 2054 EVT VT; 2055 unsigned AS; 2056 2057 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) { 2058 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 2059 return false; 2060 VT = LD->getMemoryVT(); 2061 AS = LD->getAddressSpace(); 2062 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) { 2063 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 2064 return false; 2065 VT = ST->getMemoryVT(); 2066 AS = ST->getAddressSpace(); 2067 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Use)) { 2068 if (LD->isIndexed() || LD->getBasePtr().getNode() != N) 2069 return false; 2070 VT = LD->getMemoryVT(); 2071 AS = LD->getAddressSpace(); 2072 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Use)) { 2073 if (ST->isIndexed() || ST->getBasePtr().getNode() != N) 2074 return false; 2075 VT = ST->getMemoryVT(); 2076 AS = ST->getAddressSpace(); 2077 } else 2078 return false; 2079 2080 TargetLowering::AddrMode AM; 2081 if (N->getOpcode() == ISD::ADD) { 2082 AM.HasBaseReg = true; 2083 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2084 if (Offset) 2085 // [reg +/- imm] 2086 AM.BaseOffs = Offset->getSExtValue(); 2087 else 2088 // [reg +/- reg] 2089 AM.Scale = 1; 2090 } else if (N->getOpcode() == ISD::SUB) { 2091 AM.HasBaseReg = true; 2092 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2093 if (Offset) 2094 // [reg +/- imm] 2095 AM.BaseOffs = -Offset->getSExtValue(); 2096 else 2097 // [reg +/- reg] 2098 AM.Scale = 1; 2099 } else 2100 return false; 2101 2102 return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, 2103 VT.getTypeForEVT(*DAG.getContext()), AS); 2104 } 2105 2106 SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) { 2107 assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 && 2108 "Unexpected binary operator"); 2109 2110 // Don't do this unless the old select is going away. We want to eliminate the 2111 // binary operator, not replace a binop with a select. 2112 // TODO: Handle ISD::SELECT_CC. 2113 unsigned SelOpNo = 0; 2114 SDValue Sel = BO->getOperand(0); 2115 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) { 2116 SelOpNo = 1; 2117 Sel = BO->getOperand(1); 2118 } 2119 2120 if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) 2121 return SDValue(); 2122 2123 SDValue CT = Sel.getOperand(1); 2124 if (!isConstantOrConstantVector(CT, true) && 2125 !DAG.isConstantFPBuildVectorOrConstantFP(CT)) 2126 return SDValue(); 2127 2128 SDValue CF = Sel.getOperand(2); 2129 if (!isConstantOrConstantVector(CF, true) && 2130 !DAG.isConstantFPBuildVectorOrConstantFP(CF)) 2131 return SDValue(); 2132 2133 // Bail out if any constants are opaque because we can't constant fold those. 2134 // The exception is "and" and "or" with either 0 or -1 in which case we can 2135 // propagate non constant operands into select. I.e.: 2136 // and (select Cond, 0, -1), X --> select Cond, 0, X 2137 // or X, (select Cond, -1, 0) --> select Cond, -1, X 2138 auto BinOpcode = BO->getOpcode(); 2139 bool CanFoldNonConst = 2140 (BinOpcode == ISD::AND || BinOpcode == ISD::OR) && 2141 (isNullOrNullSplat(CT) || isAllOnesOrAllOnesSplat(CT)) && 2142 (isNullOrNullSplat(CF) || isAllOnesOrAllOnesSplat(CF)); 2143 2144 SDValue CBO = BO->getOperand(SelOpNo ^ 1); 2145 if (!CanFoldNonConst && 2146 !isConstantOrConstantVector(CBO, true) && 2147 !DAG.isConstantFPBuildVectorOrConstantFP(CBO)) 2148 return SDValue(); 2149 2150 EVT VT = BO->getValueType(0); 2151 2152 // We have a select-of-constants followed by a binary operator with a 2153 // constant. Eliminate the binop by pulling the constant math into the select. 2154 // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO 2155 SDLoc DL(Sel); 2156 SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT) 2157 : DAG.getNode(BinOpcode, DL, VT, CT, CBO); 2158 if (!CanFoldNonConst && !NewCT.isUndef() && 2159 !isConstantOrConstantVector(NewCT, true) && 2160 !DAG.isConstantFPBuildVectorOrConstantFP(NewCT)) 2161 return SDValue(); 2162 2163 SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF) 2164 : DAG.getNode(BinOpcode, DL, VT, CF, CBO); 2165 if (!CanFoldNonConst && !NewCF.isUndef() && 2166 !isConstantOrConstantVector(NewCF, true) && 2167 !DAG.isConstantFPBuildVectorOrConstantFP(NewCF)) 2168 return SDValue(); 2169 2170 SDValue SelectOp = DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF); 2171 SelectOp->setFlags(BO->getFlags()); 2172 return SelectOp; 2173 } 2174 2175 static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) { 2176 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 2177 "Expecting add or sub"); 2178 2179 // Match a constant operand and a zext operand for the math instruction: 2180 // add Z, C 2181 // sub C, Z 2182 bool IsAdd = N->getOpcode() == ISD::ADD; 2183 SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0); 2184 SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1); 2185 auto *CN = dyn_cast<ConstantSDNode>(C); 2186 if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND) 2187 return SDValue(); 2188 2189 // Match the zext operand as a setcc of a boolean. 2190 if (Z.getOperand(0).getOpcode() != ISD::SETCC || 2191 Z.getOperand(0).getValueType() != MVT::i1) 2192 return SDValue(); 2193 2194 // Match the compare as: setcc (X & 1), 0, eq. 2195 SDValue SetCC = Z.getOperand(0); 2196 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 2197 if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) || 2198 SetCC.getOperand(0).getOpcode() != ISD::AND || 2199 !isOneConstant(SetCC.getOperand(0).getOperand(1))) 2200 return SDValue(); 2201 2202 // We are adding/subtracting a constant and an inverted low bit. Turn that 2203 // into a subtract/add of the low bit with incremented/decremented constant: 2204 // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1)) 2205 // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1)) 2206 EVT VT = C.getValueType(); 2207 SDLoc DL(N); 2208 SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT); 2209 SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) : 2210 DAG.getConstant(CN->getAPIntValue() - 1, DL, VT); 2211 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit); 2212 } 2213 2214 /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into 2215 /// a shift and add with a different constant. 2216 static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) { 2217 assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 2218 "Expecting add or sub"); 2219 2220 // We need a constant operand for the add/sub, and the other operand is a 2221 // logical shift right: add (srl), C or sub C, (srl). 2222 bool IsAdd = N->getOpcode() == ISD::ADD; 2223 SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0); 2224 SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1); 2225 if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) || 2226 ShiftOp.getOpcode() != ISD::SRL) 2227 return SDValue(); 2228 2229 // The shift must be of a 'not' value. 2230 SDValue Not = ShiftOp.getOperand(0); 2231 if (!Not.hasOneUse() || !isBitwiseNot(Not)) 2232 return SDValue(); 2233 2234 // The shift must be moving the sign bit to the least-significant-bit. 2235 EVT VT = ShiftOp.getValueType(); 2236 SDValue ShAmt = ShiftOp.getOperand(1); 2237 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 2238 if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1)) 2239 return SDValue(); 2240 2241 // Eliminate the 'not' by adjusting the shift and add/sub constant: 2242 // add (srl (not X), 31), C --> add (sra X, 31), (C + 1) 2243 // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1) 2244 SDLoc DL(N); 2245 auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL; 2246 SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt); 2247 if (SDValue NewC = 2248 DAG.FoldConstantArithmetic(IsAdd ? ISD::ADD : ISD::SUB, DL, VT, 2249 {ConstantOp, DAG.getConstant(1, DL, VT)})) 2250 return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC); 2251 return SDValue(); 2252 } 2253 2254 /// Try to fold a node that behaves like an ADD (note that N isn't necessarily 2255 /// an ISD::ADD here, it could for example be an ISD::OR if we know that there 2256 /// are no common bits set in the operands). 2257 SDValue DAGCombiner::visitADDLike(SDNode *N) { 2258 SDValue N0 = N->getOperand(0); 2259 SDValue N1 = N->getOperand(1); 2260 EVT VT = N0.getValueType(); 2261 SDLoc DL(N); 2262 2263 // fold vector ops 2264 if (VT.isVector()) { 2265 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL)) 2266 return FoldedVOp; 2267 2268 // fold (add x, 0) -> x, vector edition 2269 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 2270 return N0; 2271 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 2272 return N1; 2273 } 2274 2275 // fold (add x, undef) -> undef 2276 if (N0.isUndef()) 2277 return N0; 2278 2279 if (N1.isUndef()) 2280 return N1; 2281 2282 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 2283 // canonicalize constant to RHS 2284 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2285 return DAG.getNode(ISD::ADD, DL, VT, N1, N0); 2286 // fold (add c1, c2) -> c1+c2 2287 return DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1}); 2288 } 2289 2290 // fold (add x, 0) -> x 2291 if (isNullConstant(N1)) 2292 return N0; 2293 2294 if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) { 2295 // fold ((A-c1)+c2) -> (A+(c2-c1)) 2296 if (N0.getOpcode() == ISD::SUB && 2297 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) { 2298 SDValue Sub = 2299 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N0.getOperand(1)}); 2300 assert(Sub && "Constant folding failed"); 2301 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub); 2302 } 2303 2304 // fold ((c1-A)+c2) -> (c1+c2)-A 2305 if (N0.getOpcode() == ISD::SUB && 2306 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) { 2307 SDValue Add = 2308 DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N0.getOperand(0)}); 2309 assert(Add && "Constant folding failed"); 2310 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1)); 2311 } 2312 2313 // add (sext i1 X), 1 -> zext (not i1 X) 2314 // We don't transform this pattern: 2315 // add (zext i1 X), -1 -> sext (not i1 X) 2316 // because most (?) targets generate better code for the zext form. 2317 if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() && 2318 isOneOrOneSplat(N1)) { 2319 SDValue X = N0.getOperand(0); 2320 if ((!LegalOperations || 2321 (TLI.isOperationLegal(ISD::XOR, X.getValueType()) && 2322 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) && 2323 X.getScalarValueSizeInBits() == 1) { 2324 SDValue Not = DAG.getNOT(DL, X, X.getValueType()); 2325 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not); 2326 } 2327 } 2328 2329 // Fold (add (or x, c0), c1) -> (add x, (c0 + c1)) if (or x, c0) is 2330 // equivalent to (add x, c0). 2331 if (N0.getOpcode() == ISD::OR && 2332 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true) && 2333 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { 2334 if (SDValue Add0 = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, 2335 {N1, N0.getOperand(1)})) 2336 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0); 2337 } 2338 } 2339 2340 if (SDValue NewSel = foldBinOpIntoSelect(N)) 2341 return NewSel; 2342 2343 // reassociate add 2344 if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N0, N1)) { 2345 if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags())) 2346 return RADD; 2347 2348 // Reassociate (add (or x, c), y) -> (add add(x, y), c)) if (or x, c) is 2349 // equivalent to (add x, c). 2350 auto ReassociateAddOr = [&](SDValue N0, SDValue N1) { 2351 if (N0.getOpcode() == ISD::OR && N0.hasOneUse() && 2352 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true) && 2353 DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) { 2354 return DAG.getNode(ISD::ADD, DL, VT, 2355 DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)), 2356 N0.getOperand(1)); 2357 } 2358 return SDValue(); 2359 }; 2360 if (SDValue Add = ReassociateAddOr(N0, N1)) 2361 return Add; 2362 if (SDValue Add = ReassociateAddOr(N1, N0)) 2363 return Add; 2364 } 2365 // fold ((0-A) + B) -> B-A 2366 if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0))) 2367 return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2368 2369 // fold (A + (0-B)) -> A-B 2370 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0))) 2371 return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1)); 2372 2373 // fold (A+(B-A)) -> B 2374 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1)) 2375 return N1.getOperand(0); 2376 2377 // fold ((B-A)+A) -> B 2378 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1)) 2379 return N0.getOperand(0); 2380 2381 // fold ((A-B)+(C-A)) -> (C-B) 2382 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB && 2383 N0.getOperand(0) == N1.getOperand(1)) 2384 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2385 N0.getOperand(1)); 2386 2387 // fold ((A-B)+(B-C)) -> (A-C) 2388 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB && 2389 N0.getOperand(1) == N1.getOperand(0)) 2390 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 2391 N1.getOperand(1)); 2392 2393 // fold (A+(B-(A+C))) to (B-C) 2394 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2395 N0 == N1.getOperand(1).getOperand(0)) 2396 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2397 N1.getOperand(1).getOperand(1)); 2398 2399 // fold (A+(B-(C+A))) to (B-C) 2400 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD && 2401 N0 == N1.getOperand(1).getOperand(1)) 2402 return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0), 2403 N1.getOperand(1).getOperand(0)); 2404 2405 // fold (A+((B-A)+or-C)) to (B+or-C) 2406 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) && 2407 N1.getOperand(0).getOpcode() == ISD::SUB && 2408 N0 == N1.getOperand(0).getOperand(1)) 2409 return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0), 2410 N1.getOperand(1)); 2411 2412 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant 2413 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) { 2414 SDValue N00 = N0.getOperand(0); 2415 SDValue N01 = N0.getOperand(1); 2416 SDValue N10 = N1.getOperand(0); 2417 SDValue N11 = N1.getOperand(1); 2418 2419 if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10)) 2420 return DAG.getNode(ISD::SUB, DL, VT, 2421 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10), 2422 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11)); 2423 } 2424 2425 // fold (add (umax X, C), -C) --> (usubsat X, C) 2426 if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) { 2427 auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) { 2428 return (!Max && !Op) || 2429 (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue())); 2430 }; 2431 if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT, 2432 /*AllowUndefs*/ true)) 2433 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0), 2434 N0.getOperand(1)); 2435 } 2436 2437 if (SimplifyDemandedBits(SDValue(N, 0))) 2438 return SDValue(N, 0); 2439 2440 if (isOneOrOneSplat(N1)) { 2441 // fold (add (xor a, -1), 1) -> (sub 0, a) 2442 if (isBitwiseNot(N0)) 2443 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 2444 N0.getOperand(0)); 2445 2446 // fold (add (add (xor a, -1), b), 1) -> (sub b, a) 2447 if (N0.getOpcode() == ISD::ADD) { 2448 SDValue A, Xor; 2449 2450 if (isBitwiseNot(N0.getOperand(0))) { 2451 A = N0.getOperand(1); 2452 Xor = N0.getOperand(0); 2453 } else if (isBitwiseNot(N0.getOperand(1))) { 2454 A = N0.getOperand(0); 2455 Xor = N0.getOperand(1); 2456 } 2457 2458 if (Xor) 2459 return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0)); 2460 } 2461 2462 // Look for: 2463 // add (add x, y), 1 2464 // And if the target does not like this form then turn into: 2465 // sub y, (xor x, -1) 2466 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() && 2467 N0.getOpcode() == ISD::ADD) { 2468 SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 2469 DAG.getAllOnesConstant(DL, VT)); 2470 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not); 2471 } 2472 } 2473 2474 // (x - y) + -1 -> add (xor y, -1), x 2475 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && 2476 isAllOnesOrAllOnesSplat(N1)) { 2477 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), N1); 2478 return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0)); 2479 } 2480 2481 if (SDValue Combined = visitADDLikeCommutative(N0, N1, N)) 2482 return Combined; 2483 2484 if (SDValue Combined = visitADDLikeCommutative(N1, N0, N)) 2485 return Combined; 2486 2487 return SDValue(); 2488 } 2489 2490 SDValue DAGCombiner::visitADD(SDNode *N) { 2491 SDValue N0 = N->getOperand(0); 2492 SDValue N1 = N->getOperand(1); 2493 EVT VT = N0.getValueType(); 2494 SDLoc DL(N); 2495 2496 if (SDValue Combined = visitADDLike(N)) 2497 return Combined; 2498 2499 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 2500 return V; 2501 2502 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 2503 return V; 2504 2505 // fold (a+b) -> (a|b) iff a and b share no bits. 2506 if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) && 2507 DAG.haveNoCommonBitsSet(N0, N1)) 2508 return DAG.getNode(ISD::OR, DL, VT, N0, N1); 2509 2510 // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)). 2511 if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) { 2512 const APInt &C0 = N0->getConstantOperandAPInt(0); 2513 const APInt &C1 = N1->getConstantOperandAPInt(0); 2514 return DAG.getVScale(DL, VT, C0 + C1); 2515 } 2516 2517 // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2) 2518 if ((N0.getOpcode() == ISD::ADD) && 2519 (N0.getOperand(1).getOpcode() == ISD::VSCALE) && 2520 (N1.getOpcode() == ISD::VSCALE)) { 2521 const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0); 2522 const APInt &VS1 = N1->getConstantOperandAPInt(0); 2523 SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1); 2524 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS); 2525 } 2526 2527 // Fold (add step_vector(c1), step_vector(c2) to step_vector(c1+c2)) 2528 if (N0.getOpcode() == ISD::STEP_VECTOR && 2529 N1.getOpcode() == ISD::STEP_VECTOR) { 2530 const APInt &C0 = N0->getConstantOperandAPInt(0); 2531 const APInt &C1 = N1->getConstantOperandAPInt(0); 2532 APInt NewStep = C0 + C1; 2533 return DAG.getStepVector(DL, VT, NewStep); 2534 } 2535 2536 // Fold a + step_vector(c1) + step_vector(c2) to a + step_vector(c1+c2) 2537 if ((N0.getOpcode() == ISD::ADD) && 2538 (N0.getOperand(1).getOpcode() == ISD::STEP_VECTOR) && 2539 (N1.getOpcode() == ISD::STEP_VECTOR)) { 2540 const APInt &SV0 = N0.getOperand(1)->getConstantOperandAPInt(0); 2541 const APInt &SV1 = N1->getConstantOperandAPInt(0); 2542 APInt NewStep = SV0 + SV1; 2543 SDValue SV = DAG.getStepVector(DL, VT, NewStep); 2544 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), SV); 2545 } 2546 2547 return SDValue(); 2548 } 2549 2550 SDValue DAGCombiner::visitADDSAT(SDNode *N) { 2551 unsigned Opcode = N->getOpcode(); 2552 SDValue N0 = N->getOperand(0); 2553 SDValue N1 = N->getOperand(1); 2554 EVT VT = N0.getValueType(); 2555 SDLoc DL(N); 2556 2557 // fold vector ops 2558 if (VT.isVector()) { 2559 // TODO SimplifyVBinOp 2560 2561 // fold (add_sat x, 0) -> x, vector edition 2562 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 2563 return N0; 2564 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 2565 return N1; 2566 } 2567 2568 // fold (add_sat x, undef) -> -1 2569 if (N0.isUndef() || N1.isUndef()) 2570 return DAG.getAllOnesConstant(DL, VT); 2571 2572 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 2573 // canonicalize constant to RHS 2574 if (!DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2575 return DAG.getNode(Opcode, DL, VT, N1, N0); 2576 // fold (add_sat c1, c2) -> c3 2577 return DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}); 2578 } 2579 2580 // fold (add_sat x, 0) -> x 2581 if (isNullConstant(N1)) 2582 return N0; 2583 2584 // If it cannot overflow, transform into an add. 2585 if (Opcode == ISD::UADDSAT) 2586 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2587 return DAG.getNode(ISD::ADD, DL, VT, N0, N1); 2588 2589 return SDValue(); 2590 } 2591 2592 static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) { 2593 bool Masked = false; 2594 2595 // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization. 2596 while (true) { 2597 if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) { 2598 V = V.getOperand(0); 2599 continue; 2600 } 2601 2602 if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) { 2603 Masked = true; 2604 V = V.getOperand(0); 2605 continue; 2606 } 2607 2608 break; 2609 } 2610 2611 // If this is not a carry, return. 2612 if (V.getResNo() != 1) 2613 return SDValue(); 2614 2615 if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY && 2616 V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO) 2617 return SDValue(); 2618 2619 EVT VT = V.getNode()->getValueType(0); 2620 if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT)) 2621 return SDValue(); 2622 2623 // If the result is masked, then no matter what kind of bool it is we can 2624 // return. If it isn't, then we need to make sure the bool type is either 0 or 2625 // 1 and not other values. 2626 if (Masked || 2627 TLI.getBooleanContents(V.getValueType()) == 2628 TargetLoweringBase::ZeroOrOneBooleanContent) 2629 return V; 2630 2631 return SDValue(); 2632 } 2633 2634 /// Given the operands of an add/sub operation, see if the 2nd operand is a 2635 /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert 2636 /// the opcode and bypass the mask operation. 2637 static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1, 2638 SelectionDAG &DAG, const SDLoc &DL) { 2639 if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1))) 2640 return SDValue(); 2641 2642 EVT VT = N0.getValueType(); 2643 if (DAG.ComputeNumSignBits(N1.getOperand(0)) != VT.getScalarSizeInBits()) 2644 return SDValue(); 2645 2646 // add N0, (and (AssertSext X, i1), 1) --> sub N0, X 2647 // sub N0, (and (AssertSext X, i1), 1) --> add N0, X 2648 return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N1.getOperand(0)); 2649 } 2650 2651 /// Helper for doing combines based on N0 and N1 being added to each other. 2652 SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1, 2653 SDNode *LocReference) { 2654 EVT VT = N0.getValueType(); 2655 SDLoc DL(LocReference); 2656 2657 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n)) 2658 if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB && 2659 isNullOrNullSplat(N1.getOperand(0).getOperand(0))) 2660 return DAG.getNode(ISD::SUB, DL, VT, N0, 2661 DAG.getNode(ISD::SHL, DL, VT, 2662 N1.getOperand(0).getOperand(1), 2663 N1.getOperand(1))); 2664 2665 if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL)) 2666 return V; 2667 2668 // Look for: 2669 // add (add x, 1), y 2670 // And if the target does not like this form then turn into: 2671 // sub y, (xor x, -1) 2672 if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() && 2673 N0.getOpcode() == ISD::ADD && isOneOrOneSplat(N0.getOperand(1))) { 2674 SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0), 2675 DAG.getAllOnesConstant(DL, VT)); 2676 return DAG.getNode(ISD::SUB, DL, VT, N1, Not); 2677 } 2678 2679 // Hoist one-use subtraction by non-opaque constant: 2680 // (x - C) + y -> (x + y) - C 2681 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors. 2682 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && 2683 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) { 2684 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1); 2685 return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1)); 2686 } 2687 // Hoist one-use subtraction from non-opaque constant: 2688 // (C - x) + y -> (y - x) + C 2689 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && 2690 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) { 2691 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1)); 2692 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0)); 2693 } 2694 2695 // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1' 2696 // rather than 'add 0/-1' (the zext should get folded). 2697 // add (sext i1 Y), X --> sub X, (zext i1 Y) 2698 if (N0.getOpcode() == ISD::SIGN_EXTEND && 2699 N0.getOperand(0).getScalarValueSizeInBits() == 1 && 2700 TLI.getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent) { 2701 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 2702 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt); 2703 } 2704 2705 // add X, (sextinreg Y i1) -> sub X, (and Y 1) 2706 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 2707 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 2708 if (TN->getVT() == MVT::i1) { 2709 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 2710 DAG.getConstant(1, DL, VT)); 2711 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt); 2712 } 2713 } 2714 2715 // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2716 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) && 2717 N1.getResNo() == 0) 2718 return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(), 2719 N0, N1.getOperand(0), N1.getOperand(2)); 2720 2721 // (add X, Carry) -> (addcarry X, 0, Carry) 2722 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2723 if (SDValue Carry = getAsCarry(TLI, N1)) 2724 return DAG.getNode(ISD::ADDCARRY, DL, 2725 DAG.getVTList(VT, Carry.getValueType()), N0, 2726 DAG.getConstant(0, DL, VT), Carry); 2727 2728 return SDValue(); 2729 } 2730 2731 SDValue DAGCombiner::visitADDC(SDNode *N) { 2732 SDValue N0 = N->getOperand(0); 2733 SDValue N1 = N->getOperand(1); 2734 EVT VT = N0.getValueType(); 2735 SDLoc DL(N); 2736 2737 // If the flag result is dead, turn this into an ADD. 2738 if (!N->hasAnyUseOfValue(1)) 2739 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2740 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2741 2742 // canonicalize constant to RHS. 2743 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2744 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2745 if (N0C && !N1C) 2746 return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0); 2747 2748 // fold (addc x, 0) -> x + no carry out 2749 if (isNullConstant(N1)) 2750 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, 2751 DL, MVT::Glue)); 2752 2753 // If it cannot overflow, transform into an add. 2754 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2755 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2756 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 2757 2758 return SDValue(); 2759 } 2760 2761 /** 2762 * Flips a boolean if it is cheaper to compute. If the Force parameters is set, 2763 * then the flip also occurs if computing the inverse is the same cost. 2764 * This function returns an empty SDValue in case it cannot flip the boolean 2765 * without increasing the cost of the computation. If you want to flip a boolean 2766 * no matter what, use DAG.getLogicalNOT. 2767 */ 2768 static SDValue extractBooleanFlip(SDValue V, SelectionDAG &DAG, 2769 const TargetLowering &TLI, 2770 bool Force) { 2771 if (Force && isa<ConstantSDNode>(V)) 2772 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType()); 2773 2774 if (V.getOpcode() != ISD::XOR) 2775 return SDValue(); 2776 2777 ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false); 2778 if (!Const) 2779 return SDValue(); 2780 2781 EVT VT = V.getValueType(); 2782 2783 bool IsFlip = false; 2784 switch(TLI.getBooleanContents(VT)) { 2785 case TargetLowering::ZeroOrOneBooleanContent: 2786 IsFlip = Const->isOne(); 2787 break; 2788 case TargetLowering::ZeroOrNegativeOneBooleanContent: 2789 IsFlip = Const->isAllOnes(); 2790 break; 2791 case TargetLowering::UndefinedBooleanContent: 2792 IsFlip = (Const->getAPIntValue() & 0x01) == 1; 2793 break; 2794 } 2795 2796 if (IsFlip) 2797 return V.getOperand(0); 2798 if (Force) 2799 return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType()); 2800 return SDValue(); 2801 } 2802 2803 SDValue DAGCombiner::visitADDO(SDNode *N) { 2804 SDValue N0 = N->getOperand(0); 2805 SDValue N1 = N->getOperand(1); 2806 EVT VT = N0.getValueType(); 2807 bool IsSigned = (ISD::SADDO == N->getOpcode()); 2808 2809 EVT CarryVT = N->getValueType(1); 2810 SDLoc DL(N); 2811 2812 // If the flag result is dead, turn this into an ADD. 2813 if (!N->hasAnyUseOfValue(1)) 2814 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2815 DAG.getUNDEF(CarryVT)); 2816 2817 // canonicalize constant to RHS. 2818 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 2819 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 2820 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0); 2821 2822 // fold (addo x, 0) -> x + no carry out 2823 if (isNullOrNullSplat(N1)) 2824 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 2825 2826 if (!IsSigned) { 2827 // If it cannot overflow, transform into an add. 2828 if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never) 2829 return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1), 2830 DAG.getConstant(0, DL, CarryVT)); 2831 2832 // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry. 2833 if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) { 2834 SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(), 2835 DAG.getConstant(0, DL, VT), N0.getOperand(0)); 2836 return CombineTo( 2837 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1))); 2838 } 2839 2840 if (SDValue Combined = visitUADDOLike(N0, N1, N)) 2841 return Combined; 2842 2843 if (SDValue Combined = visitUADDOLike(N1, N0, N)) 2844 return Combined; 2845 } 2846 2847 return SDValue(); 2848 } 2849 2850 SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) { 2851 EVT VT = N0.getValueType(); 2852 if (VT.isVector()) 2853 return SDValue(); 2854 2855 // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry) 2856 // If Y + 1 cannot overflow. 2857 if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) { 2858 SDValue Y = N1.getOperand(0); 2859 SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType()); 2860 if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never) 2861 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y, 2862 N1.getOperand(2)); 2863 } 2864 2865 // (uaddo X, Carry) -> (addcarry X, 0, Carry) 2866 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) 2867 if (SDValue Carry = getAsCarry(TLI, N1)) 2868 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, 2869 DAG.getConstant(0, SDLoc(N), VT), Carry); 2870 2871 return SDValue(); 2872 } 2873 2874 SDValue DAGCombiner::visitADDE(SDNode *N) { 2875 SDValue N0 = N->getOperand(0); 2876 SDValue N1 = N->getOperand(1); 2877 SDValue CarryIn = N->getOperand(2); 2878 2879 // canonicalize constant to RHS 2880 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2881 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2882 if (N0C && !N1C) 2883 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(), 2884 N1, N0, CarryIn); 2885 2886 // fold (adde x, y, false) -> (addc x, y) 2887 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 2888 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1); 2889 2890 return SDValue(); 2891 } 2892 2893 SDValue DAGCombiner::visitADDCARRY(SDNode *N) { 2894 SDValue N0 = N->getOperand(0); 2895 SDValue N1 = N->getOperand(1); 2896 SDValue CarryIn = N->getOperand(2); 2897 SDLoc DL(N); 2898 2899 // canonicalize constant to RHS 2900 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2901 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2902 if (N0C && !N1C) 2903 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn); 2904 2905 // fold (addcarry x, y, false) -> (uaddo x, y) 2906 if (isNullConstant(CarryIn)) { 2907 if (!LegalOperations || 2908 TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0))) 2909 return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1); 2910 } 2911 2912 // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry. 2913 if (isNullConstant(N0) && isNullConstant(N1)) { 2914 EVT VT = N0.getValueType(); 2915 EVT CarryVT = CarryIn.getValueType(); 2916 SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT); 2917 AddToWorklist(CarryExt.getNode()); 2918 return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt, 2919 DAG.getConstant(1, DL, VT)), 2920 DAG.getConstant(0, DL, CarryVT)); 2921 } 2922 2923 if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N)) 2924 return Combined; 2925 2926 if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N)) 2927 return Combined; 2928 2929 return SDValue(); 2930 } 2931 2932 SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) { 2933 SDValue N0 = N->getOperand(0); 2934 SDValue N1 = N->getOperand(1); 2935 SDValue CarryIn = N->getOperand(2); 2936 SDLoc DL(N); 2937 2938 // canonicalize constant to RHS 2939 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 2940 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 2941 if (N0C && !N1C) 2942 return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn); 2943 2944 // fold (saddo_carry x, y, false) -> (saddo x, y) 2945 if (isNullConstant(CarryIn)) { 2946 if (!LegalOperations || 2947 TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0))) 2948 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1); 2949 } 2950 2951 return SDValue(); 2952 } 2953 2954 /** 2955 * If we are facing some sort of diamond carry propapagtion pattern try to 2956 * break it up to generate something like: 2957 * (addcarry X, 0, (addcarry A, B, Z):Carry) 2958 * 2959 * The end result is usually an increase in operation required, but because the 2960 * carry is now linearized, other tranforms can kick in and optimize the DAG. 2961 * 2962 * Patterns typically look something like 2963 * (uaddo A, B) 2964 * / \ 2965 * Carry Sum 2966 * | \ 2967 * | (addcarry *, 0, Z) 2968 * | / 2969 * \ Carry 2970 * | / 2971 * (addcarry X, *, *) 2972 * 2973 * But numerous variation exist. Our goal is to identify A, B, X and Z and 2974 * produce a combine with a single path for carry propagation. 2975 */ 2976 static SDValue combineADDCARRYDiamond(DAGCombiner &Combiner, SelectionDAG &DAG, 2977 SDValue X, SDValue Carry0, SDValue Carry1, 2978 SDNode *N) { 2979 if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1) 2980 return SDValue(); 2981 if (Carry1.getOpcode() != ISD::UADDO) 2982 return SDValue(); 2983 2984 SDValue Z; 2985 2986 /** 2987 * First look for a suitable Z. It will present itself in the form of 2988 * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true 2989 */ 2990 if (Carry0.getOpcode() == ISD::ADDCARRY && 2991 isNullConstant(Carry0.getOperand(1))) { 2992 Z = Carry0.getOperand(2); 2993 } else if (Carry0.getOpcode() == ISD::UADDO && 2994 isOneConstant(Carry0.getOperand(1))) { 2995 EVT VT = Combiner.getSetCCResultType(Carry0.getValueType()); 2996 Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT); 2997 } else { 2998 // We couldn't find a suitable Z. 2999 return SDValue(); 3000 } 3001 3002 3003 auto cancelDiamond = [&](SDValue A,SDValue B) { 3004 SDLoc DL(N); 3005 SDValue NewY = DAG.getNode(ISD::ADDCARRY, DL, Carry0->getVTList(), A, B, Z); 3006 Combiner.AddToWorklist(NewY.getNode()); 3007 return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), X, 3008 DAG.getConstant(0, DL, X.getValueType()), 3009 NewY.getValue(1)); 3010 }; 3011 3012 /** 3013 * (uaddo A, B) 3014 * | 3015 * Sum 3016 * | 3017 * (addcarry *, 0, Z) 3018 */ 3019 if (Carry0.getOperand(0) == Carry1.getValue(0)) { 3020 return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1)); 3021 } 3022 3023 /** 3024 * (addcarry A, 0, Z) 3025 * | 3026 * Sum 3027 * | 3028 * (uaddo *, B) 3029 */ 3030 if (Carry1.getOperand(0) == Carry0.getValue(0)) { 3031 return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1)); 3032 } 3033 3034 if (Carry1.getOperand(1) == Carry0.getValue(0)) { 3035 return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0)); 3036 } 3037 3038 return SDValue(); 3039 } 3040 3041 // If we are facing some sort of diamond carry/borrow in/out pattern try to 3042 // match patterns like: 3043 // 3044 // (uaddo A, B) CarryIn 3045 // | \ | 3046 // | \ | 3047 // PartialSum PartialCarryOutX / 3048 // | | / 3049 // | ____|____________/ 3050 // | / | 3051 // (uaddo *, *) \________ 3052 // | \ \ 3053 // | \ | 3054 // | PartialCarryOutY | 3055 // | \ | 3056 // | \ / 3057 // AddCarrySum | ______/ 3058 // | / 3059 // CarryOut = (or *, *) 3060 // 3061 // And generate ADDCARRY (or SUBCARRY) with two result values: 3062 // 3063 // {AddCarrySum, CarryOut} = (addcarry A, B, CarryIn) 3064 // 3065 // Our goal is to identify A, B, and CarryIn and produce ADDCARRY/SUBCARRY with 3066 // a single path for carry/borrow out propagation: 3067 static SDValue combineCarryDiamond(DAGCombiner &Combiner, SelectionDAG &DAG, 3068 const TargetLowering &TLI, SDValue Carry0, 3069 SDValue Carry1, SDNode *N) { 3070 if (Carry0.getResNo() != 1 || Carry1.getResNo() != 1) 3071 return SDValue(); 3072 unsigned Opcode = Carry0.getOpcode(); 3073 if (Opcode != Carry1.getOpcode()) 3074 return SDValue(); 3075 if (Opcode != ISD::UADDO && Opcode != ISD::USUBO) 3076 return SDValue(); 3077 3078 // Canonicalize the add/sub of A and B as Carry0 and the add/sub of the 3079 // carry/borrow in as Carry1. (The top and middle uaddo nodes respectively in 3080 // the above ASCII art.) 3081 if (Carry1.getOperand(0) != Carry0.getValue(0) && 3082 Carry1.getOperand(1) != Carry0.getValue(0)) 3083 std::swap(Carry0, Carry1); 3084 if (Carry1.getOperand(0) != Carry0.getValue(0) && 3085 Carry1.getOperand(1) != Carry0.getValue(0)) 3086 return SDValue(); 3087 3088 // The carry in value must be on the righthand side for subtraction. 3089 unsigned CarryInOperandNum = 3090 Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0; 3091 if (Opcode == ISD::USUBO && CarryInOperandNum != 1) 3092 return SDValue(); 3093 SDValue CarryIn = Carry1.getOperand(CarryInOperandNum); 3094 3095 unsigned NewOp = Opcode == ISD::UADDO ? ISD::ADDCARRY : ISD::SUBCARRY; 3096 if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType())) 3097 return SDValue(); 3098 3099 // Verify that the carry/borrow in is plausibly a carry/borrow bit. 3100 // TODO: make getAsCarry() aware of how partial carries are merged. 3101 if (CarryIn.getOpcode() != ISD::ZERO_EXTEND) 3102 return SDValue(); 3103 CarryIn = CarryIn.getOperand(0); 3104 if (CarryIn.getValueType() != MVT::i1) 3105 return SDValue(); 3106 3107 SDLoc DL(N); 3108 SDValue Merged = 3109 DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0), 3110 Carry0.getOperand(1), CarryIn); 3111 3112 // Please note that because we have proven that the result of the UADDO/USUBO 3113 // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can 3114 // therefore prove that if the first UADDO/USUBO overflows, the second 3115 // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the 3116 // maximum value. 3117 // 3118 // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry 3119 // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow) 3120 // 3121 // This is important because it means that OR and XOR can be used to merge 3122 // carry flags; and that AND can return a constant zero. 3123 // 3124 // TODO: match other operations that can merge flags (ADD, etc) 3125 DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0)); 3126 if (N->getOpcode() == ISD::AND) 3127 return DAG.getConstant(0, DL, MVT::i1); 3128 return Merged.getValue(1); 3129 } 3130 3131 SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, 3132 SDNode *N) { 3133 // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry. 3134 if (isBitwiseNot(N0)) 3135 if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) { 3136 SDLoc DL(N); 3137 SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), N1, 3138 N0.getOperand(0), NotC); 3139 return CombineTo( 3140 N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1))); 3141 } 3142 3143 // Iff the flag result is dead: 3144 // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry) 3145 // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo 3146 // or the dependency between the instructions. 3147 if ((N0.getOpcode() == ISD::ADD || 3148 (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 && 3149 N0.getValue(1) != CarryIn)) && 3150 isNullConstant(N1) && !N->hasAnyUseOfValue(1)) 3151 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), 3152 N0.getOperand(0), N0.getOperand(1), CarryIn); 3153 3154 /** 3155 * When one of the addcarry argument is itself a carry, we may be facing 3156 * a diamond carry propagation. In which case we try to transform the DAG 3157 * to ensure linear carry propagation if that is possible. 3158 */ 3159 if (auto Y = getAsCarry(TLI, N1)) { 3160 // Because both are carries, Y and Z can be swapped. 3161 if (auto R = combineADDCARRYDiamond(*this, DAG, N0, Y, CarryIn, N)) 3162 return R; 3163 if (auto R = combineADDCARRYDiamond(*this, DAG, N0, CarryIn, Y, N)) 3164 return R; 3165 } 3166 3167 return SDValue(); 3168 } 3169 3170 // Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a 3171 // clamp/truncation if necessary. 3172 static SDValue getTruncatedUSUBSAT(EVT DstVT, EVT SrcVT, SDValue LHS, 3173 SDValue RHS, SelectionDAG &DAG, 3174 const SDLoc &DL) { 3175 assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() && 3176 "Illegal truncation"); 3177 3178 if (DstVT == SrcVT) 3179 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS); 3180 3181 // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by 3182 // clamping RHS. 3183 APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(), 3184 DstVT.getScalarSizeInBits()); 3185 if (!DAG.MaskedValueIsZero(LHS, UpperBits)) 3186 return SDValue(); 3187 3188 SDValue SatLimit = 3189 DAG.getConstant(APInt::getLowBitsSet(SrcVT.getScalarSizeInBits(), 3190 DstVT.getScalarSizeInBits()), 3191 DL, SrcVT); 3192 RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit); 3193 RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS); 3194 LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS); 3195 return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS); 3196 } 3197 3198 // Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to 3199 // usubsat(a,b), optionally as a truncated type. 3200 SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N) { 3201 if (N->getOpcode() != ISD::SUB || 3202 !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT))) 3203 return SDValue(); 3204 3205 EVT SubVT = N->getValueType(0); 3206 SDValue Op0 = N->getOperand(0); 3207 SDValue Op1 = N->getOperand(1); 3208 3209 // Try to find umax(a,b) - b or a - umin(a,b) patterns 3210 // they may be converted to usubsat(a,b). 3211 if (Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 3212 SDValue MaxLHS = Op0.getOperand(0); 3213 SDValue MaxRHS = Op0.getOperand(1); 3214 if (MaxLHS == Op1) 3215 return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, SDLoc(N)); 3216 if (MaxRHS == Op1) 3217 return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, SDLoc(N)); 3218 } 3219 3220 if (Op1.getOpcode() == ISD::UMIN && Op1.hasOneUse()) { 3221 SDValue MinLHS = Op1.getOperand(0); 3222 SDValue MinRHS = Op1.getOperand(1); 3223 if (MinLHS == Op0) 3224 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, SDLoc(N)); 3225 if (MinRHS == Op0) 3226 return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, SDLoc(N)); 3227 } 3228 3229 // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit))) 3230 if (Op1.getOpcode() == ISD::TRUNCATE && 3231 Op1.getOperand(0).getOpcode() == ISD::UMIN && 3232 Op1.getOperand(0).hasOneUse()) { 3233 SDValue MinLHS = Op1.getOperand(0).getOperand(0); 3234 SDValue MinRHS = Op1.getOperand(0).getOperand(1); 3235 if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0) 3236 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS, 3237 DAG, SDLoc(N)); 3238 if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0) 3239 return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS, 3240 DAG, SDLoc(N)); 3241 } 3242 3243 return SDValue(); 3244 } 3245 3246 // Since it may not be valid to emit a fold to zero for vector initializers 3247 // check if we can before folding. 3248 static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT, 3249 SelectionDAG &DAG, bool LegalOperations) { 3250 if (!VT.isVector()) 3251 return DAG.getConstant(0, DL, VT); 3252 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 3253 return DAG.getConstant(0, DL, VT); 3254 return SDValue(); 3255 } 3256 3257 SDValue DAGCombiner::visitSUB(SDNode *N) { 3258 SDValue N0 = N->getOperand(0); 3259 SDValue N1 = N->getOperand(1); 3260 EVT VT = N0.getValueType(); 3261 SDLoc DL(N); 3262 3263 // fold vector ops 3264 if (VT.isVector()) { 3265 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL)) 3266 return FoldedVOp; 3267 3268 // fold (sub x, 0) -> x, vector edition 3269 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 3270 return N0; 3271 } 3272 3273 // fold (sub x, x) -> 0 3274 // FIXME: Refactor this and xor and other similar operations together. 3275 if (N0 == N1) 3276 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 3277 3278 // fold (sub c1, c2) -> c3 3279 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1})) 3280 return C; 3281 3282 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3283 return NewSel; 3284 3285 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3286 3287 // fold (sub x, c) -> (add x, -c) 3288 if (N1C) { 3289 return DAG.getNode(ISD::ADD, DL, VT, N0, 3290 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 3291 } 3292 3293 if (isNullOrNullSplat(N0)) { 3294 unsigned BitWidth = VT.getScalarSizeInBits(); 3295 // Right-shifting everything out but the sign bit followed by negation is 3296 // the same as flipping arithmetic/logical shift type without the negation: 3297 // -(X >>u 31) -> (X >>s 31) 3298 // -(X >>s 31) -> (X >>u 31) 3299 if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) { 3300 ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1)); 3301 if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) { 3302 auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA; 3303 if (!LegalOperations || TLI.isOperationLegal(NewSh, VT)) 3304 return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1)); 3305 } 3306 } 3307 3308 // 0 - X --> 0 if the sub is NUW. 3309 if (N->getFlags().hasNoUnsignedWrap()) 3310 return N0; 3311 3312 if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) { 3313 // N1 is either 0 or the minimum signed value. If the sub is NSW, then 3314 // N1 must be 0 because negating the minimum signed value is undefined. 3315 if (N->getFlags().hasNoSignedWrap()) 3316 return N0; 3317 3318 // 0 - X --> X if X is 0 or the minimum signed value. 3319 return N1; 3320 } 3321 3322 // Convert 0 - abs(x). 3323 if (N1->getOpcode() == ISD::ABS && 3324 !TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 3325 if (SDValue Result = TLI.expandABS(N1.getNode(), DAG, true)) 3326 return Result; 3327 3328 // Fold neg(splat(neg(x)) -> splat(x) 3329 if (VT.isVector()) { 3330 SDValue N1S = DAG.getSplatValue(N1, true); 3331 if (N1S && N1S.getOpcode() == ISD::SUB && 3332 isNullConstant(N1S.getOperand(0))) { 3333 if (VT.isScalableVector()) 3334 return DAG.getSplatVector(VT, DL, N1S.getOperand(1)); 3335 return DAG.getSplatBuildVector(VT, DL, N1S.getOperand(1)); 3336 } 3337 } 3338 } 3339 3340 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) 3341 if (isAllOnesOrAllOnesSplat(N0)) 3342 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 3343 3344 // fold (A - (0-B)) -> A+B 3345 if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0))) 3346 return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1)); 3347 3348 // fold A-(A-B) -> B 3349 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0)) 3350 return N1.getOperand(1); 3351 3352 // fold (A+B)-A -> B 3353 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1) 3354 return N0.getOperand(1); 3355 3356 // fold (A+B)-B -> A 3357 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1) 3358 return N0.getOperand(0); 3359 3360 // fold (A+C1)-C2 -> A+(C1-C2) 3361 if (N0.getOpcode() == ISD::ADD && 3362 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 3363 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 3364 SDValue NewC = 3365 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(1), N1}); 3366 assert(NewC && "Constant folding failed"); 3367 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC); 3368 } 3369 3370 // fold C2-(A+C1) -> (C2-C1)-A 3371 if (N1.getOpcode() == ISD::ADD) { 3372 SDValue N11 = N1.getOperand(1); 3373 if (isConstantOrConstantVector(N0, /* NoOpaques */ true) && 3374 isConstantOrConstantVector(N11, /* NoOpaques */ true)) { 3375 SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11}); 3376 assert(NewC && "Constant folding failed"); 3377 return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0)); 3378 } 3379 } 3380 3381 // fold (A-C1)-C2 -> A-(C1+C2) 3382 if (N0.getOpcode() == ISD::SUB && 3383 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 3384 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 3385 SDValue NewC = 3386 DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0.getOperand(1), N1}); 3387 assert(NewC && "Constant folding failed"); 3388 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC); 3389 } 3390 3391 // fold (c1-A)-c2 -> (c1-c2)-A 3392 if (N0.getOpcode() == ISD::SUB && 3393 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 3394 isConstantOrConstantVector(N0.getOperand(0), /* NoOpaques */ true)) { 3395 SDValue NewC = 3396 DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(0), N1}); 3397 assert(NewC && "Constant folding failed"); 3398 return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1)); 3399 } 3400 3401 // fold ((A+(B+or-C))-B) -> A+or-C 3402 if (N0.getOpcode() == ISD::ADD && 3403 (N0.getOperand(1).getOpcode() == ISD::SUB || 3404 N0.getOperand(1).getOpcode() == ISD::ADD) && 3405 N0.getOperand(1).getOperand(0) == N1) 3406 return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0), 3407 N0.getOperand(1).getOperand(1)); 3408 3409 // fold ((A+(C+B))-B) -> A+C 3410 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD && 3411 N0.getOperand(1).getOperand(1) == N1) 3412 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), 3413 N0.getOperand(1).getOperand(0)); 3414 3415 // fold ((A-(B-C))-C) -> A-B 3416 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB && 3417 N0.getOperand(1).getOperand(1) == N1) 3418 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), 3419 N0.getOperand(1).getOperand(0)); 3420 3421 // fold (A-(B-C)) -> A+(C-B) 3422 if (N1.getOpcode() == ISD::SUB && N1.hasOneUse()) 3423 return DAG.getNode(ISD::ADD, DL, VT, N0, 3424 DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1), 3425 N1.getOperand(0))); 3426 3427 // A - (A & B) -> A & (~B) 3428 if (N1.getOpcode() == ISD::AND) { 3429 SDValue A = N1.getOperand(0); 3430 SDValue B = N1.getOperand(1); 3431 if (A != N0) 3432 std::swap(A, B); 3433 if (A == N0 && 3434 (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true))) { 3435 SDValue InvB = 3436 DAG.getNode(ISD::XOR, DL, VT, B, DAG.getAllOnesConstant(DL, VT)); 3437 return DAG.getNode(ISD::AND, DL, VT, A, InvB); 3438 } 3439 } 3440 3441 // fold (X - (-Y * Z)) -> (X + (Y * Z)) 3442 if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) { 3443 if (N1.getOperand(0).getOpcode() == ISD::SUB && 3444 isNullOrNullSplat(N1.getOperand(0).getOperand(0))) { 3445 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 3446 N1.getOperand(0).getOperand(1), 3447 N1.getOperand(1)); 3448 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 3449 } 3450 if (N1.getOperand(1).getOpcode() == ISD::SUB && 3451 isNullOrNullSplat(N1.getOperand(1).getOperand(0))) { 3452 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, 3453 N1.getOperand(0), 3454 N1.getOperand(1).getOperand(1)); 3455 return DAG.getNode(ISD::ADD, DL, VT, N0, Mul); 3456 } 3457 } 3458 3459 // If either operand of a sub is undef, the result is undef 3460 if (N0.isUndef()) 3461 return N0; 3462 if (N1.isUndef()) 3463 return N1; 3464 3465 if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG)) 3466 return V; 3467 3468 if (SDValue V = foldAddSubOfSignBit(N, DAG)) 3469 return V; 3470 3471 if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N))) 3472 return V; 3473 3474 if (SDValue V = foldSubToUSubSat(VT, N)) 3475 return V; 3476 3477 // (x - y) - 1 -> add (xor y, -1), x 3478 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && isOneOrOneSplat(N1)) { 3479 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), 3480 DAG.getAllOnesConstant(DL, VT)); 3481 return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0)); 3482 } 3483 3484 // Look for: 3485 // sub y, (xor x, -1) 3486 // And if the target does not like this form then turn into: 3487 // add (add x, y), 1 3488 if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) { 3489 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0)); 3490 return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT)); 3491 } 3492 3493 // Hoist one-use addition by non-opaque constant: 3494 // (x + C) - y -> (x - y) + C 3495 if (N0.hasOneUse() && N0.getOpcode() == ISD::ADD && 3496 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) { 3497 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1); 3498 return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1)); 3499 } 3500 // y - (x + C) -> (y - x) - C 3501 if (N1.hasOneUse() && N1.getOpcode() == ISD::ADD && 3502 isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) { 3503 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0)); 3504 return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1)); 3505 } 3506 // (x - C) - y -> (x - y) - C 3507 // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors. 3508 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && 3509 isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) { 3510 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1); 3511 return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1)); 3512 } 3513 // (C - x) - y -> C - (x + y) 3514 if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && 3515 isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) { 3516 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1); 3517 return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add); 3518 } 3519 3520 // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1' 3521 // rather than 'sub 0/1' (the sext should get folded). 3522 // sub X, (zext i1 Y) --> add X, (sext i1 Y) 3523 if (N1.getOpcode() == ISD::ZERO_EXTEND && 3524 N1.getOperand(0).getScalarValueSizeInBits() == 1 && 3525 TLI.getBooleanContents(VT) == 3526 TargetLowering::ZeroOrNegativeOneBooleanContent) { 3527 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0)); 3528 return DAG.getNode(ISD::ADD, DL, VT, N0, SExt); 3529 } 3530 3531 // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X) 3532 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 3533 if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) { 3534 SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1); 3535 SDValue S0 = N1.getOperand(0); 3536 if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0)) 3537 if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1))) 3538 if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1)) 3539 return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0); 3540 } 3541 } 3542 3543 // If the relocation model supports it, consider symbol offsets. 3544 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0)) 3545 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) { 3546 // fold (sub Sym, c) -> Sym-c 3547 if (N1C && GA->getOpcode() == ISD::GlobalAddress) 3548 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT, 3549 GA->getOffset() - 3550 (uint64_t)N1C->getSExtValue()); 3551 // fold (sub Sym+c1, Sym+c2) -> c1-c2 3552 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1)) 3553 if (GA->getGlobal() == GB->getGlobal()) 3554 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(), 3555 DL, VT); 3556 } 3557 3558 // sub X, (sextinreg Y i1) -> add X, (and Y 1) 3559 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) { 3560 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1)); 3561 if (TN->getVT() == MVT::i1) { 3562 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0), 3563 DAG.getConstant(1, DL, VT)); 3564 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt); 3565 } 3566 } 3567 3568 // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C)) 3569 if (N1.getOpcode() == ISD::VSCALE) { 3570 const APInt &IntVal = N1.getConstantOperandAPInt(0); 3571 return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal)); 3572 } 3573 3574 // canonicalize (sub X, step_vector(C)) to (add X, step_vector(-C)) 3575 if (N1.getOpcode() == ISD::STEP_VECTOR && N1.hasOneUse()) { 3576 APInt NewStep = -N1.getConstantOperandAPInt(0); 3577 return DAG.getNode(ISD::ADD, DL, VT, N0, 3578 DAG.getStepVector(DL, VT, NewStep)); 3579 } 3580 3581 // Prefer an add for more folding potential and possibly better codegen: 3582 // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1) 3583 if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) { 3584 SDValue ShAmt = N1.getOperand(1); 3585 ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt); 3586 if (ShAmtC && 3587 ShAmtC->getAPIntValue() == (N1.getScalarValueSizeInBits() - 1)) { 3588 SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt); 3589 return DAG.getNode(ISD::ADD, DL, VT, N0, SRA); 3590 } 3591 } 3592 3593 if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) { 3594 // (sub Carry, X) -> (addcarry (sub 0, X), 0, Carry) 3595 if (SDValue Carry = getAsCarry(TLI, N0)) { 3596 SDValue X = N1; 3597 SDValue Zero = DAG.getConstant(0, DL, VT); 3598 SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X); 3599 return DAG.getNode(ISD::ADDCARRY, DL, 3600 DAG.getVTList(VT, Carry.getValueType()), NegX, Zero, 3601 Carry); 3602 } 3603 } 3604 3605 return SDValue(); 3606 } 3607 3608 SDValue DAGCombiner::visitSUBSAT(SDNode *N) { 3609 SDValue N0 = N->getOperand(0); 3610 SDValue N1 = N->getOperand(1); 3611 EVT VT = N0.getValueType(); 3612 SDLoc DL(N); 3613 3614 // fold vector ops 3615 if (VT.isVector()) { 3616 // TODO SimplifyVBinOp 3617 3618 // fold (sub_sat x, 0) -> x, vector edition 3619 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 3620 return N0; 3621 } 3622 3623 // fold (sub_sat x, undef) -> 0 3624 if (N0.isUndef() || N1.isUndef()) 3625 return DAG.getConstant(0, DL, VT); 3626 3627 // fold (sub_sat x, x) -> 0 3628 if (N0 == N1) 3629 return DAG.getConstant(0, DL, VT); 3630 3631 // fold (sub_sat c1, c2) -> c3 3632 if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1})) 3633 return C; 3634 3635 // fold (sub_sat x, 0) -> x 3636 if (isNullConstant(N1)) 3637 return N0; 3638 3639 return SDValue(); 3640 } 3641 3642 SDValue DAGCombiner::visitSUBC(SDNode *N) { 3643 SDValue N0 = N->getOperand(0); 3644 SDValue N1 = N->getOperand(1); 3645 EVT VT = N0.getValueType(); 3646 SDLoc DL(N); 3647 3648 // If the flag result is dead, turn this into an SUB. 3649 if (!N->hasAnyUseOfValue(1)) 3650 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 3651 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3652 3653 // fold (subc x, x) -> 0 + no borrow 3654 if (N0 == N1) 3655 return CombineTo(N, DAG.getConstant(0, DL, VT), 3656 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3657 3658 // fold (subc x, 0) -> x + no borrow 3659 if (isNullConstant(N1)) 3660 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3661 3662 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow 3663 if (isAllOnesConstant(N0)) 3664 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 3665 DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue)); 3666 3667 return SDValue(); 3668 } 3669 3670 SDValue DAGCombiner::visitSUBO(SDNode *N) { 3671 SDValue N0 = N->getOperand(0); 3672 SDValue N1 = N->getOperand(1); 3673 EVT VT = N0.getValueType(); 3674 bool IsSigned = (ISD::SSUBO == N->getOpcode()); 3675 3676 EVT CarryVT = N->getValueType(1); 3677 SDLoc DL(N); 3678 3679 // If the flag result is dead, turn this into an SUB. 3680 if (!N->hasAnyUseOfValue(1)) 3681 return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1), 3682 DAG.getUNDEF(CarryVT)); 3683 3684 // fold (subo x, x) -> 0 + no borrow 3685 if (N0 == N1) 3686 return CombineTo(N, DAG.getConstant(0, DL, VT), 3687 DAG.getConstant(0, DL, CarryVT)); 3688 3689 ConstantSDNode *N1C = getAsNonOpaqueConstant(N1); 3690 3691 // fold (subox, c) -> (addo x, -c) 3692 if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) { 3693 return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, 3694 DAG.getConstant(-N1C->getAPIntValue(), DL, VT)); 3695 } 3696 3697 // fold (subo x, 0) -> x + no borrow 3698 if (isNullOrNullSplat(N1)) 3699 return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT)); 3700 3701 // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow 3702 if (!IsSigned && isAllOnesOrAllOnesSplat(N0)) 3703 return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0), 3704 DAG.getConstant(0, DL, CarryVT)); 3705 3706 return SDValue(); 3707 } 3708 3709 SDValue DAGCombiner::visitSUBE(SDNode *N) { 3710 SDValue N0 = N->getOperand(0); 3711 SDValue N1 = N->getOperand(1); 3712 SDValue CarryIn = N->getOperand(2); 3713 3714 // fold (sube x, y, false) -> (subc x, y) 3715 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) 3716 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1); 3717 3718 return SDValue(); 3719 } 3720 3721 SDValue DAGCombiner::visitSUBCARRY(SDNode *N) { 3722 SDValue N0 = N->getOperand(0); 3723 SDValue N1 = N->getOperand(1); 3724 SDValue CarryIn = N->getOperand(2); 3725 3726 // fold (subcarry x, y, false) -> (usubo x, y) 3727 if (isNullConstant(CarryIn)) { 3728 if (!LegalOperations || 3729 TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0))) 3730 return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1); 3731 } 3732 3733 return SDValue(); 3734 } 3735 3736 SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) { 3737 SDValue N0 = N->getOperand(0); 3738 SDValue N1 = N->getOperand(1); 3739 SDValue CarryIn = N->getOperand(2); 3740 3741 // fold (ssubo_carry x, y, false) -> (ssubo x, y) 3742 if (isNullConstant(CarryIn)) { 3743 if (!LegalOperations || 3744 TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0))) 3745 return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1); 3746 } 3747 3748 return SDValue(); 3749 } 3750 3751 // Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and 3752 // UMULFIXSAT here. 3753 SDValue DAGCombiner::visitMULFIX(SDNode *N) { 3754 SDValue N0 = N->getOperand(0); 3755 SDValue N1 = N->getOperand(1); 3756 SDValue Scale = N->getOperand(2); 3757 EVT VT = N0.getValueType(); 3758 3759 // fold (mulfix x, undef, scale) -> 0 3760 if (N0.isUndef() || N1.isUndef()) 3761 return DAG.getConstant(0, SDLoc(N), VT); 3762 3763 // Canonicalize constant to RHS (vector doesn't have to splat) 3764 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3765 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3766 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale); 3767 3768 // fold (mulfix x, 0, scale) -> 0 3769 if (isNullConstant(N1)) 3770 return DAG.getConstant(0, SDLoc(N), VT); 3771 3772 return SDValue(); 3773 } 3774 3775 SDValue DAGCombiner::visitMUL(SDNode *N) { 3776 SDValue N0 = N->getOperand(0); 3777 SDValue N1 = N->getOperand(1); 3778 EVT VT = N0.getValueType(); 3779 3780 // fold (mul x, undef) -> 0 3781 if (N0.isUndef() || N1.isUndef()) 3782 return DAG.getConstant(0, SDLoc(N), VT); 3783 3784 bool N1IsConst = false; 3785 bool N1IsOpaqueConst = false; 3786 APInt ConstValue1; 3787 3788 // fold vector ops 3789 if (VT.isVector()) { 3790 if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N))) 3791 return FoldedVOp; 3792 3793 N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1); 3794 assert((!N1IsConst || 3795 ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) && 3796 "Splat APInt should be element width"); 3797 } else { 3798 N1IsConst = isa<ConstantSDNode>(N1); 3799 if (N1IsConst) { 3800 ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 3801 N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque(); 3802 } 3803 } 3804 3805 // fold (mul c1, c2) -> c1*c2 3806 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, {N0, N1})) 3807 return C; 3808 3809 // canonicalize constant to RHS (vector doesn't have to splat) 3810 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 3811 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 3812 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0); 3813 3814 // fold (mul x, 0) -> 0 3815 if (N1IsConst && ConstValue1.isZero()) 3816 return N1; 3817 3818 // fold (mul x, 1) -> x 3819 if (N1IsConst && ConstValue1.isOne()) 3820 return N0; 3821 3822 if (SDValue NewSel = foldBinOpIntoSelect(N)) 3823 return NewSel; 3824 3825 // fold (mul x, -1) -> 0-x 3826 if (N1IsConst && ConstValue1.isAllOnes()) { 3827 SDLoc DL(N); 3828 return DAG.getNode(ISD::SUB, DL, VT, 3829 DAG.getConstant(0, DL, VT), N0); 3830 } 3831 3832 // fold (mul x, (1 << c)) -> x << c 3833 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 3834 DAG.isKnownToBeAPowerOfTwo(N1) && 3835 (!VT.isVector() || Level <= AfterLegalizeVectorOps)) { 3836 SDLoc DL(N); 3837 SDValue LogBase2 = BuildLogBase2(N1, DL); 3838 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 3839 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 3840 return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc); 3841 } 3842 3843 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c 3844 if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isNegatedPowerOf2()) { 3845 unsigned Log2Val = (-ConstValue1).logBase2(); 3846 SDLoc DL(N); 3847 // FIXME: If the input is something that is easily negated (e.g. a 3848 // single-use add), we should put the negate there. 3849 return DAG.getNode(ISD::SUB, DL, VT, 3850 DAG.getConstant(0, DL, VT), 3851 DAG.getNode(ISD::SHL, DL, VT, N0, 3852 DAG.getConstant(Log2Val, DL, 3853 getShiftAmountTy(N0.getValueType())))); 3854 } 3855 3856 // Try to transform: 3857 // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub. 3858 // mul x, (2^N + 1) --> add (shl x, N), x 3859 // mul x, (2^N - 1) --> sub (shl x, N), x 3860 // Examples: x * 33 --> (x << 5) + x 3861 // x * 15 --> (x << 4) - x 3862 // x * -33 --> -((x << 5) + x) 3863 // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4) 3864 // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub. 3865 // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M)) 3866 // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M)) 3867 // Examples: x * 0x8800 --> (x << 15) + (x << 11) 3868 // x * 0xf800 --> (x << 16) - (x << 11) 3869 // x * -0x8800 --> -((x << 15) + (x << 11)) 3870 // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16) 3871 if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) { 3872 // TODO: We could handle more general decomposition of any constant by 3873 // having the target set a limit on number of ops and making a 3874 // callback to determine that sequence (similar to sqrt expansion). 3875 unsigned MathOp = ISD::DELETED_NODE; 3876 APInt MulC = ConstValue1.abs(); 3877 // The constant `2` should be treated as (2^0 + 1). 3878 unsigned TZeros = MulC == 2 ? 0 : MulC.countTrailingZeros(); 3879 MulC.lshrInPlace(TZeros); 3880 if ((MulC - 1).isPowerOf2()) 3881 MathOp = ISD::ADD; 3882 else if ((MulC + 1).isPowerOf2()) 3883 MathOp = ISD::SUB; 3884 3885 if (MathOp != ISD::DELETED_NODE) { 3886 unsigned ShAmt = 3887 MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2(); 3888 ShAmt += TZeros; 3889 assert(ShAmt < VT.getScalarSizeInBits() && 3890 "multiply-by-constant generated out of bounds shift"); 3891 SDLoc DL(N); 3892 SDValue Shl = 3893 DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT)); 3894 SDValue R = 3895 TZeros ? DAG.getNode(MathOp, DL, VT, Shl, 3896 DAG.getNode(ISD::SHL, DL, VT, N0, 3897 DAG.getConstant(TZeros, DL, VT))) 3898 : DAG.getNode(MathOp, DL, VT, Shl, N0); 3899 if (ConstValue1.isNegative()) 3900 R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R); 3901 return R; 3902 } 3903 } 3904 3905 // (mul (shl X, c1), c2) -> (mul X, c2 << c1) 3906 if (N0.getOpcode() == ISD::SHL && 3907 isConstantOrConstantVector(N1, /* NoOpaques */ true) && 3908 isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) { 3909 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1)); 3910 if (isConstantOrConstantVector(C3)) 3911 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3); 3912 } 3913 3914 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one 3915 // use. 3916 { 3917 SDValue Sh(nullptr, 0), Y(nullptr, 0); 3918 3919 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)). 3920 if (N0.getOpcode() == ISD::SHL && 3921 isConstantOrConstantVector(N0.getOperand(1)) && 3922 N0.getNode()->hasOneUse()) { 3923 Sh = N0; Y = N1; 3924 } else if (N1.getOpcode() == ISD::SHL && 3925 isConstantOrConstantVector(N1.getOperand(1)) && 3926 N1.getNode()->hasOneUse()) { 3927 Sh = N1; Y = N0; 3928 } 3929 3930 if (Sh.getNode()) { 3931 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y); 3932 return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1)); 3933 } 3934 } 3935 3936 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2) 3937 if (DAG.isConstantIntBuildVectorOrConstantInt(N1) && 3938 N0.getOpcode() == ISD::ADD && 3939 DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) && 3940 isMulAddWithConstProfitable(N, N0, N1)) 3941 return DAG.getNode(ISD::ADD, SDLoc(N), VT, 3942 DAG.getNode(ISD::MUL, SDLoc(N0), VT, 3943 N0.getOperand(0), N1), 3944 DAG.getNode(ISD::MUL, SDLoc(N1), VT, 3945 N0.getOperand(1), N1)); 3946 3947 // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)). 3948 if (N0.getOpcode() == ISD::VSCALE) 3949 if (ConstantSDNode *NC1 = isConstOrConstSplat(N1)) { 3950 const APInt &C0 = N0.getConstantOperandAPInt(0); 3951 const APInt &C1 = NC1->getAPIntValue(); 3952 return DAG.getVScale(SDLoc(N), VT, C0 * C1); 3953 } 3954 3955 // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)). 3956 APInt MulVal; 3957 if (N0.getOpcode() == ISD::STEP_VECTOR) 3958 if (ISD::isConstantSplatVector(N1.getNode(), MulVal)) { 3959 const APInt &C0 = N0.getConstantOperandAPInt(0); 3960 APInt NewStep = C0 * MulVal; 3961 return DAG.getStepVector(SDLoc(N), VT, NewStep); 3962 } 3963 3964 // Fold ((mul x, 0/undef) -> 0, 3965 // (mul x, 1) -> x) -> x) 3966 // -> and(x, mask) 3967 // We can replace vectors with '0' and '1' factors with a clearing mask. 3968 if (VT.isFixedLengthVector()) { 3969 unsigned NumElts = VT.getVectorNumElements(); 3970 SmallBitVector ClearMask; 3971 ClearMask.reserve(NumElts); 3972 auto IsClearMask = [&ClearMask](ConstantSDNode *V) { 3973 if (!V || V->isZero()) { 3974 ClearMask.push_back(true); 3975 return true; 3976 } 3977 ClearMask.push_back(false); 3978 return V->isOne(); 3979 }; 3980 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) && 3981 ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) { 3982 assert(N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector"); 3983 SDLoc DL(N); 3984 EVT LegalSVT = N1.getOperand(0).getValueType(); 3985 SDValue Zero = DAG.getConstant(0, DL, LegalSVT); 3986 SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT); 3987 SmallVector<SDValue, 16> Mask(NumElts, AllOnes); 3988 for (unsigned I = 0; I != NumElts; ++I) 3989 if (ClearMask[I]) 3990 Mask[I] = Zero; 3991 return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask)); 3992 } 3993 } 3994 3995 // reassociate mul 3996 if (SDValue RMUL = reassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags())) 3997 return RMUL; 3998 3999 return SDValue(); 4000 } 4001 4002 /// Return true if divmod libcall is available. 4003 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned, 4004 const TargetLowering &TLI) { 4005 RTLIB::Libcall LC; 4006 EVT NodeType = Node->getValueType(0); 4007 if (!NodeType.isSimple()) 4008 return false; 4009 switch (NodeType.getSimpleVT().SimpleTy) { 4010 default: return false; // No libcall for vector types. 4011 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break; 4012 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break; 4013 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break; 4014 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break; 4015 case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break; 4016 } 4017 4018 return TLI.getLibcallName(LC) != nullptr; 4019 } 4020 4021 /// Issue divrem if both quotient and remainder are needed. 4022 SDValue DAGCombiner::useDivRem(SDNode *Node) { 4023 if (Node->use_empty()) 4024 return SDValue(); // This is a dead node, leave it alone. 4025 4026 unsigned Opcode = Node->getOpcode(); 4027 bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM); 4028 unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM; 4029 4030 // DivMod lib calls can still work on non-legal types if using lib-calls. 4031 EVT VT = Node->getValueType(0); 4032 if (VT.isVector() || !VT.isInteger()) 4033 return SDValue(); 4034 4035 if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT)) 4036 return SDValue(); 4037 4038 // If DIVREM is going to get expanded into a libcall, 4039 // but there is no libcall available, then don't combine. 4040 if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) && 4041 !isDivRemLibcallAvailable(Node, isSigned, TLI)) 4042 return SDValue(); 4043 4044 // If div is legal, it's better to do the normal expansion 4045 unsigned OtherOpcode = 0; 4046 if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) { 4047 OtherOpcode = isSigned ? ISD::SREM : ISD::UREM; 4048 if (TLI.isOperationLegalOrCustom(Opcode, VT)) 4049 return SDValue(); 4050 } else { 4051 OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 4052 if (TLI.isOperationLegalOrCustom(OtherOpcode, VT)) 4053 return SDValue(); 4054 } 4055 4056 SDValue Op0 = Node->getOperand(0); 4057 SDValue Op1 = Node->getOperand(1); 4058 SDValue combined; 4059 for (SDNode *User : Op0.getNode()->uses()) { 4060 if (User == Node || User->getOpcode() == ISD::DELETED_NODE || 4061 User->use_empty()) 4062 continue; 4063 // Convert the other matching node(s), too; 4064 // otherwise, the DIVREM may get target-legalized into something 4065 // target-specific that we won't be able to recognize. 4066 unsigned UserOpc = User->getOpcode(); 4067 if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) && 4068 User->getOperand(0) == Op0 && 4069 User->getOperand(1) == Op1) { 4070 if (!combined) { 4071 if (UserOpc == OtherOpcode) { 4072 SDVTList VTs = DAG.getVTList(VT, VT); 4073 combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1); 4074 } else if (UserOpc == DivRemOpc) { 4075 combined = SDValue(User, 0); 4076 } else { 4077 assert(UserOpc == Opcode); 4078 continue; 4079 } 4080 } 4081 if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV) 4082 CombineTo(User, combined); 4083 else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM) 4084 CombineTo(User, combined.getValue(1)); 4085 } 4086 } 4087 return combined; 4088 } 4089 4090 static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) { 4091 SDValue N0 = N->getOperand(0); 4092 SDValue N1 = N->getOperand(1); 4093 EVT VT = N->getValueType(0); 4094 SDLoc DL(N); 4095 4096 unsigned Opc = N->getOpcode(); 4097 bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc); 4098 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4099 4100 // X / undef -> undef 4101 // X % undef -> undef 4102 // X / 0 -> undef 4103 // X % 0 -> undef 4104 // NOTE: This includes vectors where any divisor element is zero/undef. 4105 if (DAG.isUndef(Opc, {N0, N1})) 4106 return DAG.getUNDEF(VT); 4107 4108 // undef / X -> 0 4109 // undef % X -> 0 4110 if (N0.isUndef()) 4111 return DAG.getConstant(0, DL, VT); 4112 4113 // 0 / X -> 0 4114 // 0 % X -> 0 4115 ConstantSDNode *N0C = isConstOrConstSplat(N0); 4116 if (N0C && N0C->isZero()) 4117 return N0; 4118 4119 // X / X -> 1 4120 // X % X -> 0 4121 if (N0 == N1) 4122 return DAG.getConstant(IsDiv ? 1 : 0, DL, VT); 4123 4124 // X / 1 -> X 4125 // X % 1 -> 0 4126 // If this is a boolean op (single-bit element type), we can't have 4127 // division-by-zero or remainder-by-zero, so assume the divisor is 1. 4128 // TODO: Similarly, if we're zero-extending a boolean divisor, then assume 4129 // it's a 1. 4130 if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1)) 4131 return IsDiv ? N0 : DAG.getConstant(0, DL, VT); 4132 4133 return SDValue(); 4134 } 4135 4136 SDValue DAGCombiner::visitSDIV(SDNode *N) { 4137 SDValue N0 = N->getOperand(0); 4138 SDValue N1 = N->getOperand(1); 4139 EVT VT = N->getValueType(0); 4140 EVT CCVT = getSetCCResultType(VT); 4141 SDLoc DL(N); 4142 4143 // fold vector ops 4144 if (VT.isVector()) 4145 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL)) 4146 return FoldedVOp; 4147 4148 // fold (sdiv c1, c2) -> c1/c2 4149 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4150 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1})) 4151 return C; 4152 4153 // fold (sdiv X, -1) -> 0-X 4154 if (N1C && N1C->isAllOnes()) 4155 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0); 4156 4157 // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0) 4158 if (N1C && N1C->getAPIntValue().isMinSignedValue()) 4159 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 4160 DAG.getConstant(1, DL, VT), 4161 DAG.getConstant(0, DL, VT)); 4162 4163 if (SDValue V = simplifyDivRem(N, DAG)) 4164 return V; 4165 4166 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4167 return NewSel; 4168 4169 // If we know the sign bits of both operands are zero, strength reduce to a 4170 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2 4171 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 4172 return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1); 4173 4174 if (SDValue V = visitSDIVLike(N0, N1, N)) { 4175 // If the corresponding remainder node exists, update its users with 4176 // (Dividend - (Quotient * Divisor). 4177 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(), 4178 { N0, N1 })) { 4179 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1); 4180 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 4181 AddToWorklist(Mul.getNode()); 4182 AddToWorklist(Sub.getNode()); 4183 CombineTo(RemNode, Sub); 4184 } 4185 return V; 4186 } 4187 4188 // sdiv, srem -> sdivrem 4189 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 4190 // true. Otherwise, we break the simplification logic in visitREM(). 4191 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4192 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 4193 if (SDValue DivRem = useDivRem(N)) 4194 return DivRem; 4195 4196 return SDValue(); 4197 } 4198 4199 SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) { 4200 SDLoc DL(N); 4201 EVT VT = N->getValueType(0); 4202 EVT CCVT = getSetCCResultType(VT); 4203 unsigned BitWidth = VT.getScalarSizeInBits(); 4204 4205 // Helper for determining whether a value is a power-2 constant scalar or a 4206 // vector of such elements. 4207 auto IsPowerOfTwo = [](ConstantSDNode *C) { 4208 if (C->isZero() || C->isOpaque()) 4209 return false; 4210 if (C->getAPIntValue().isPowerOf2()) 4211 return true; 4212 if (C->getAPIntValue().isNegatedPowerOf2()) 4213 return true; 4214 return false; 4215 }; 4216 4217 // fold (sdiv X, pow2) -> simple ops after legalize 4218 // FIXME: We check for the exact bit here because the generic lowering gives 4219 // better results in that case. The target-specific lowering should learn how 4220 // to handle exact sdivs efficiently. 4221 if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) { 4222 // Target-specific implementation of sdiv x, pow2. 4223 if (SDValue Res = BuildSDIVPow2(N)) 4224 return Res; 4225 4226 // Create constants that are functions of the shift amount value. 4227 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 4228 SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy); 4229 SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1); 4230 C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy); 4231 SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1); 4232 if (!isConstantOrConstantVector(Inexact)) 4233 return SDValue(); 4234 4235 // Splat the sign bit into the register 4236 SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0, 4237 DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy)); 4238 AddToWorklist(Sign.getNode()); 4239 4240 // Add (N0 < 0) ? abs2 - 1 : 0; 4241 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact); 4242 AddToWorklist(Srl.getNode()); 4243 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl); 4244 AddToWorklist(Add.getNode()); 4245 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1); 4246 AddToWorklist(Sra.getNode()); 4247 4248 // Special case: (sdiv X, 1) -> X 4249 // Special Case: (sdiv X, -1) -> 0-X 4250 SDValue One = DAG.getConstant(1, DL, VT); 4251 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 4252 SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ); 4253 SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ); 4254 SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes); 4255 Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra); 4256 4257 // If dividing by a positive value, we're done. Otherwise, the result must 4258 // be negated. 4259 SDValue Zero = DAG.getConstant(0, DL, VT); 4260 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra); 4261 4262 // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding. 4263 SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT); 4264 SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra); 4265 return Res; 4266 } 4267 4268 // If integer divide is expensive and we satisfy the requirements, emit an 4269 // alternate sequence. Targets may check function attributes for size/speed 4270 // trade-offs. 4271 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4272 if (isConstantOrConstantVector(N1) && 4273 !TLI.isIntDivCheap(N->getValueType(0), Attr)) 4274 if (SDValue Op = BuildSDIV(N)) 4275 return Op; 4276 4277 return SDValue(); 4278 } 4279 4280 SDValue DAGCombiner::visitUDIV(SDNode *N) { 4281 SDValue N0 = N->getOperand(0); 4282 SDValue N1 = N->getOperand(1); 4283 EVT VT = N->getValueType(0); 4284 EVT CCVT = getSetCCResultType(VT); 4285 SDLoc DL(N); 4286 4287 // fold vector ops 4288 if (VT.isVector()) 4289 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL)) 4290 return FoldedVOp; 4291 4292 // fold (udiv c1, c2) -> c1/c2 4293 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4294 if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1})) 4295 return C; 4296 4297 // fold (udiv X, -1) -> select(X == -1, 1, 0) 4298 if (N1C && N1C->isAllOnes()) 4299 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 4300 DAG.getConstant(1, DL, VT), 4301 DAG.getConstant(0, DL, VT)); 4302 4303 if (SDValue V = simplifyDivRem(N, DAG)) 4304 return V; 4305 4306 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4307 return NewSel; 4308 4309 if (SDValue V = visitUDIVLike(N0, N1, N)) { 4310 // If the corresponding remainder node exists, update its users with 4311 // (Dividend - (Quotient * Divisor). 4312 if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(), 4313 { N0, N1 })) { 4314 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1); 4315 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 4316 AddToWorklist(Mul.getNode()); 4317 AddToWorklist(Sub.getNode()); 4318 CombineTo(RemNode, Sub); 4319 } 4320 return V; 4321 } 4322 4323 // sdiv, srem -> sdivrem 4324 // If the divisor is constant, then return DIVREM only if isIntDivCheap() is 4325 // true. Otherwise, we break the simplification logic in visitREM(). 4326 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4327 if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr)) 4328 if (SDValue DivRem = useDivRem(N)) 4329 return DivRem; 4330 4331 return SDValue(); 4332 } 4333 4334 SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) { 4335 SDLoc DL(N); 4336 EVT VT = N->getValueType(0); 4337 4338 // fold (udiv x, (1 << c)) -> x >>u c 4339 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 4340 DAG.isKnownToBeAPowerOfTwo(N1)) { 4341 SDValue LogBase2 = BuildLogBase2(N1, DL); 4342 AddToWorklist(LogBase2.getNode()); 4343 4344 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 4345 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT); 4346 AddToWorklist(Trunc.getNode()); 4347 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 4348 } 4349 4350 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2 4351 if (N1.getOpcode() == ISD::SHL) { 4352 SDValue N10 = N1.getOperand(0); 4353 if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) && 4354 DAG.isKnownToBeAPowerOfTwo(N10)) { 4355 SDValue LogBase2 = BuildLogBase2(N10, DL); 4356 AddToWorklist(LogBase2.getNode()); 4357 4358 EVT ADDVT = N1.getOperand(1).getValueType(); 4359 SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT); 4360 AddToWorklist(Trunc.getNode()); 4361 SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc); 4362 AddToWorklist(Add.getNode()); 4363 return DAG.getNode(ISD::SRL, DL, VT, N0, Add); 4364 } 4365 } 4366 4367 // fold (udiv x, c) -> alternate 4368 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4369 if (isConstantOrConstantVector(N1) && 4370 !TLI.isIntDivCheap(N->getValueType(0), Attr)) 4371 if (SDValue Op = BuildUDIV(N)) 4372 return Op; 4373 4374 return SDValue(); 4375 } 4376 4377 // handles ISD::SREM and ISD::UREM 4378 SDValue DAGCombiner::visitREM(SDNode *N) { 4379 unsigned Opcode = N->getOpcode(); 4380 SDValue N0 = N->getOperand(0); 4381 SDValue N1 = N->getOperand(1); 4382 EVT VT = N->getValueType(0); 4383 EVT CCVT = getSetCCResultType(VT); 4384 4385 bool isSigned = (Opcode == ISD::SREM); 4386 SDLoc DL(N); 4387 4388 // fold (rem c1, c2) -> c1%c2 4389 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4390 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1})) 4391 return C; 4392 4393 // fold (urem X, -1) -> select(X == -1, 0, x) 4394 if (!isSigned && N1C && N1C->isAllOnes()) 4395 return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ), 4396 DAG.getConstant(0, DL, VT), N0); 4397 4398 if (SDValue V = simplifyDivRem(N, DAG)) 4399 return V; 4400 4401 if (SDValue NewSel = foldBinOpIntoSelect(N)) 4402 return NewSel; 4403 4404 if (isSigned) { 4405 // If we know the sign bits of both operands are zero, strength reduce to a 4406 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15 4407 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0)) 4408 return DAG.getNode(ISD::UREM, DL, VT, N0, N1); 4409 } else { 4410 if (DAG.isKnownToBeAPowerOfTwo(N1)) { 4411 // fold (urem x, pow2) -> (and x, pow2-1) 4412 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 4413 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 4414 AddToWorklist(Add.getNode()); 4415 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 4416 } 4417 if (N1.getOpcode() == ISD::SHL && 4418 DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) { 4419 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1)) 4420 SDValue NegOne = DAG.getAllOnesConstant(DL, VT); 4421 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne); 4422 AddToWorklist(Add.getNode()); 4423 return DAG.getNode(ISD::AND, DL, VT, N0, Add); 4424 } 4425 } 4426 4427 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 4428 4429 // If X/C can be simplified by the division-by-constant logic, lower 4430 // X%C to the equivalent of X-X/C*C. 4431 // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the 4432 // speculative DIV must not cause a DIVREM conversion. We guard against this 4433 // by skipping the simplification if isIntDivCheap(). When div is not cheap, 4434 // combine will not return a DIVREM. Regardless, checking cheapness here 4435 // makes sense since the simplification results in fatter code. 4436 if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) { 4437 SDValue OptimizedDiv = 4438 isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N); 4439 if (OptimizedDiv.getNode()) { 4440 // If the equivalent Div node also exists, update its users. 4441 unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV; 4442 if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(), 4443 { N0, N1 })) 4444 CombineTo(DivNode, OptimizedDiv); 4445 SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1); 4446 SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul); 4447 AddToWorklist(OptimizedDiv.getNode()); 4448 AddToWorklist(Mul.getNode()); 4449 return Sub; 4450 } 4451 } 4452 4453 // sdiv, srem -> sdivrem 4454 if (SDValue DivRem = useDivRem(N)) 4455 return DivRem.getValue(1); 4456 4457 return SDValue(); 4458 } 4459 4460 SDValue DAGCombiner::visitMULHS(SDNode *N) { 4461 SDValue N0 = N->getOperand(0); 4462 SDValue N1 = N->getOperand(1); 4463 EVT VT = N->getValueType(0); 4464 SDLoc DL(N); 4465 4466 if (VT.isVector()) { 4467 // fold (mulhs x, 0) -> 0 4468 // do not return N0/N1, because undef node may exist. 4469 if (ISD::isConstantSplatVectorAllZeros(N0.getNode()) || 4470 ISD::isConstantSplatVectorAllZeros(N1.getNode())) 4471 return DAG.getConstant(0, DL, VT); 4472 } 4473 4474 // fold (mulhs c1, c2) 4475 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHS, DL, VT, {N0, N1})) 4476 return C; 4477 4478 // canonicalize constant to RHS. 4479 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4480 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4481 return DAG.getNode(ISD::MULHS, DL, N->getVTList(), N1, N0); 4482 4483 // fold (mulhs x, 0) -> 0 4484 if (isNullConstant(N1)) 4485 return N1; 4486 // fold (mulhs x, 1) -> (sra x, size(x)-1) 4487 if (isOneConstant(N1)) 4488 return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0, 4489 DAG.getConstant(N0.getScalarValueSizeInBits() - 1, DL, 4490 getShiftAmountTy(N0.getValueType()))); 4491 4492 // fold (mulhs x, undef) -> 0 4493 if (N0.isUndef() || N1.isUndef()) 4494 return DAG.getConstant(0, DL, VT); 4495 4496 // If the type twice as wide is legal, transform the mulhs to a wider multiply 4497 // plus a shift. 4498 if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() && 4499 !VT.isVector()) { 4500 MVT Simple = VT.getSimpleVT(); 4501 unsigned SimpleSize = Simple.getSizeInBits(); 4502 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 4503 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 4504 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0); 4505 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1); 4506 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 4507 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 4508 DAG.getConstant(SimpleSize, DL, 4509 getShiftAmountTy(N1.getValueType()))); 4510 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 4511 } 4512 } 4513 4514 return SDValue(); 4515 } 4516 4517 SDValue DAGCombiner::visitMULHU(SDNode *N) { 4518 SDValue N0 = N->getOperand(0); 4519 SDValue N1 = N->getOperand(1); 4520 EVT VT = N->getValueType(0); 4521 SDLoc DL(N); 4522 4523 if (VT.isVector()) { 4524 // fold (mulhu x, 0) -> 0 4525 // do not return N0/N1, because undef node may exist. 4526 if (ISD::isConstantSplatVectorAllZeros(N0.getNode()) || 4527 ISD::isConstantSplatVectorAllZeros(N1.getNode())) 4528 return DAG.getConstant(0, DL, VT); 4529 } 4530 4531 // fold (mulhu c1, c2) 4532 if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHU, DL, VT, {N0, N1})) 4533 return C; 4534 4535 // canonicalize constant to RHS. 4536 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4537 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4538 return DAG.getNode(ISD::MULHU, DL, N->getVTList(), N1, N0); 4539 4540 // fold (mulhu x, 0) -> 0 4541 if (isNullConstant(N1)) 4542 return N1; 4543 // fold (mulhu x, 1) -> 0 4544 if (isOneConstant(N1)) 4545 return DAG.getConstant(0, DL, N0.getValueType()); 4546 // fold (mulhu x, undef) -> 0 4547 if (N0.isUndef() || N1.isUndef()) 4548 return DAG.getConstant(0, DL, VT); 4549 4550 // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c) 4551 if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) && 4552 DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) { 4553 unsigned NumEltBits = VT.getScalarSizeInBits(); 4554 SDValue LogBase2 = BuildLogBase2(N1, DL); 4555 SDValue SRLAmt = DAG.getNode( 4556 ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2); 4557 EVT ShiftVT = getShiftAmountTy(N0.getValueType()); 4558 SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT); 4559 return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc); 4560 } 4561 4562 // If the type twice as wide is legal, transform the mulhu to a wider multiply 4563 // plus a shift. 4564 if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() && 4565 !VT.isVector()) { 4566 MVT Simple = VT.getSimpleVT(); 4567 unsigned SimpleSize = Simple.getSizeInBits(); 4568 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 4569 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 4570 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0); 4571 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1); 4572 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1); 4573 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1, 4574 DAG.getConstant(SimpleSize, DL, 4575 getShiftAmountTy(N1.getValueType()))); 4576 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1); 4577 } 4578 } 4579 4580 // Simplify the operands using demanded-bits information. 4581 // We don't have demanded bits support for MULHU so this just enables constant 4582 // folding based on known bits. 4583 if (SimplifyDemandedBits(SDValue(N, 0))) 4584 return SDValue(N, 0); 4585 4586 return SDValue(); 4587 } 4588 4589 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp 4590 /// give the opcodes for the two computations that are being performed. Return 4591 /// true if a simplification was made. 4592 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 4593 unsigned HiOp) { 4594 // If the high half is not needed, just compute the low half. 4595 bool HiExists = N->hasAnyUseOfValue(1); 4596 if (!HiExists && (!LegalOperations || 4597 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) { 4598 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 4599 return CombineTo(N, Res, Res); 4600 } 4601 4602 // If the low half is not needed, just compute the high half. 4603 bool LoExists = N->hasAnyUseOfValue(0); 4604 if (!LoExists && (!LegalOperations || 4605 TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) { 4606 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 4607 return CombineTo(N, Res, Res); 4608 } 4609 4610 // If both halves are used, return as it is. 4611 if (LoExists && HiExists) 4612 return SDValue(); 4613 4614 // If the two computed results can be simplified separately, separate them. 4615 if (LoExists) { 4616 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops()); 4617 AddToWorklist(Lo.getNode()); 4618 SDValue LoOpt = combine(Lo.getNode()); 4619 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() && 4620 (!LegalOperations || 4621 TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType()))) 4622 return CombineTo(N, LoOpt, LoOpt); 4623 } 4624 4625 if (HiExists) { 4626 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops()); 4627 AddToWorklist(Hi.getNode()); 4628 SDValue HiOpt = combine(Hi.getNode()); 4629 if (HiOpt.getNode() && HiOpt != Hi && 4630 (!LegalOperations || 4631 TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType()))) 4632 return CombineTo(N, HiOpt, HiOpt); 4633 } 4634 4635 return SDValue(); 4636 } 4637 4638 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) { 4639 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS)) 4640 return Res; 4641 4642 EVT VT = N->getValueType(0); 4643 SDLoc DL(N); 4644 4645 // If the type is twice as wide is legal, transform the mulhu to a wider 4646 // multiply plus a shift. 4647 if (VT.isSimple() && !VT.isVector()) { 4648 MVT Simple = VT.getSimpleVT(); 4649 unsigned SimpleSize = Simple.getSizeInBits(); 4650 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 4651 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 4652 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0)); 4653 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1)); 4654 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 4655 // Compute the high part as N1. 4656 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 4657 DAG.getConstant(SimpleSize, DL, 4658 getShiftAmountTy(Lo.getValueType()))); 4659 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 4660 // Compute the low part as N0. 4661 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 4662 return CombineTo(N, Lo, Hi); 4663 } 4664 } 4665 4666 return SDValue(); 4667 } 4668 4669 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) { 4670 if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU)) 4671 return Res; 4672 4673 EVT VT = N->getValueType(0); 4674 SDLoc DL(N); 4675 4676 // (umul_lohi N0, 0) -> (0, 0) 4677 if (isNullConstant(N->getOperand(1))) { 4678 SDValue Zero = DAG.getConstant(0, DL, VT); 4679 return CombineTo(N, Zero, Zero); 4680 } 4681 4682 // (umul_lohi N0, 1) -> (N0, 0) 4683 if (isOneConstant(N->getOperand(1))) { 4684 SDValue Zero = DAG.getConstant(0, DL, VT); 4685 return CombineTo(N, N->getOperand(0), Zero); 4686 } 4687 4688 // If the type is twice as wide is legal, transform the mulhu to a wider 4689 // multiply plus a shift. 4690 if (VT.isSimple() && !VT.isVector()) { 4691 MVT Simple = VT.getSimpleVT(); 4692 unsigned SimpleSize = Simple.getSizeInBits(); 4693 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2); 4694 if (TLI.isOperationLegal(ISD::MUL, NewVT)) { 4695 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0)); 4696 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1)); 4697 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi); 4698 // Compute the high part as N1. 4699 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo, 4700 DAG.getConstant(SimpleSize, DL, 4701 getShiftAmountTy(Lo.getValueType()))); 4702 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi); 4703 // Compute the low part as N0. 4704 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo); 4705 return CombineTo(N, Lo, Hi); 4706 } 4707 } 4708 4709 return SDValue(); 4710 } 4711 4712 SDValue DAGCombiner::visitMULO(SDNode *N) { 4713 SDValue N0 = N->getOperand(0); 4714 SDValue N1 = N->getOperand(1); 4715 EVT VT = N0.getValueType(); 4716 bool IsSigned = (ISD::SMULO == N->getOpcode()); 4717 4718 EVT CarryVT = N->getValueType(1); 4719 SDLoc DL(N); 4720 4721 ConstantSDNode *N0C = isConstOrConstSplat(N0); 4722 ConstantSDNode *N1C = isConstOrConstSplat(N1); 4723 4724 // fold operation with constant operands. 4725 // TODO: Move this to FoldConstantArithmetic when it supports nodes with 4726 // multiple results. 4727 if (N0C && N1C) { 4728 bool Overflow; 4729 APInt Result = 4730 IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow) 4731 : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow); 4732 return CombineTo(N, DAG.getConstant(Result, DL, VT), 4733 DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT)); 4734 } 4735 4736 // canonicalize constant to RHS. 4737 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4738 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4739 return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0); 4740 4741 // fold (mulo x, 0) -> 0 + no carry out 4742 if (isNullOrNullSplat(N1)) 4743 return CombineTo(N, DAG.getConstant(0, DL, VT), 4744 DAG.getConstant(0, DL, CarryVT)); 4745 4746 // (mulo x, 2) -> (addo x, x) 4747 if (N1C && N1C->getAPIntValue() == 2) 4748 return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL, 4749 N->getVTList(), N0, N0); 4750 4751 if (IsSigned) { 4752 // A 1 bit SMULO overflows if both inputs are 1. 4753 if (VT.getScalarSizeInBits() == 1) { 4754 SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1); 4755 return CombineTo(N, And, 4756 DAG.getSetCC(DL, CarryVT, And, 4757 DAG.getConstant(0, DL, VT), ISD::SETNE)); 4758 } 4759 4760 // Multiplying n * m significant bits yields a result of n + m significant 4761 // bits. If the total number of significant bits does not exceed the 4762 // result bit width (minus 1), there is no overflow. 4763 unsigned SignBits = DAG.ComputeNumSignBits(N0); 4764 if (SignBits > 1) 4765 SignBits += DAG.ComputeNumSignBits(N1); 4766 if (SignBits > VT.getScalarSizeInBits() + 1) 4767 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1), 4768 DAG.getConstant(0, DL, CarryVT)); 4769 } else { 4770 KnownBits N1Known = DAG.computeKnownBits(N1); 4771 KnownBits N0Known = DAG.computeKnownBits(N0); 4772 bool Overflow; 4773 (void)N0Known.getMaxValue().umul_ov(N1Known.getMaxValue(), Overflow); 4774 if (!Overflow) 4775 return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1), 4776 DAG.getConstant(0, DL, CarryVT)); 4777 } 4778 4779 return SDValue(); 4780 } 4781 4782 SDValue DAGCombiner::visitIMINMAX(SDNode *N) { 4783 SDValue N0 = N->getOperand(0); 4784 SDValue N1 = N->getOperand(1); 4785 EVT VT = N0.getValueType(); 4786 unsigned Opcode = N->getOpcode(); 4787 SDLoc DL(N); 4788 4789 // fold vector ops 4790 if (VT.isVector()) 4791 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL)) 4792 return FoldedVOp; 4793 4794 // fold operation with constant operands. 4795 if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1})) 4796 return C; 4797 4798 // canonicalize constant to RHS 4799 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 4800 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 4801 return DAG.getNode(N->getOpcode(), DL, VT, N1, N0); 4802 4803 // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX. 4804 // Only do this if the current op isn't legal and the flipped is. 4805 if (!TLI.isOperationLegal(Opcode, VT) && 4806 (N0.isUndef() || DAG.SignBitIsZero(N0)) && 4807 (N1.isUndef() || DAG.SignBitIsZero(N1))) { 4808 unsigned AltOpcode; 4809 switch (Opcode) { 4810 case ISD::SMIN: AltOpcode = ISD::UMIN; break; 4811 case ISD::SMAX: AltOpcode = ISD::UMAX; break; 4812 case ISD::UMIN: AltOpcode = ISD::SMIN; break; 4813 case ISD::UMAX: AltOpcode = ISD::SMAX; break; 4814 default: llvm_unreachable("Unknown MINMAX opcode"); 4815 } 4816 if (TLI.isOperationLegal(AltOpcode, VT)) 4817 return DAG.getNode(AltOpcode, DL, VT, N0, N1); 4818 } 4819 4820 // Simplify the operands using demanded-bits information. 4821 if (SimplifyDemandedBits(SDValue(N, 0))) 4822 return SDValue(N, 0); 4823 4824 return SDValue(); 4825 } 4826 4827 /// If this is a bitwise logic instruction and both operands have the same 4828 /// opcode, try to sink the other opcode after the logic instruction. 4829 SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) { 4830 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 4831 EVT VT = N0.getValueType(); 4832 unsigned LogicOpcode = N->getOpcode(); 4833 unsigned HandOpcode = N0.getOpcode(); 4834 assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR || 4835 LogicOpcode == ISD::XOR) && "Expected logic opcode"); 4836 assert(HandOpcode == N1.getOpcode() && "Bad input!"); 4837 4838 // Bail early if none of these transforms apply. 4839 if (N0.getNumOperands() == 0) 4840 return SDValue(); 4841 4842 // FIXME: We should check number of uses of the operands to not increase 4843 // the instruction count for all transforms. 4844 4845 // Handle size-changing casts. 4846 SDValue X = N0.getOperand(0); 4847 SDValue Y = N1.getOperand(0); 4848 EVT XVT = X.getValueType(); 4849 SDLoc DL(N); 4850 if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND || 4851 HandOpcode == ISD::SIGN_EXTEND) { 4852 // If both operands have other uses, this transform would create extra 4853 // instructions without eliminating anything. 4854 if (!N0.hasOneUse() && !N1.hasOneUse()) 4855 return SDValue(); 4856 // We need matching integer source types. 4857 if (XVT != Y.getValueType()) 4858 return SDValue(); 4859 // Don't create an illegal op during or after legalization. Don't ever 4860 // create an unsupported vector op. 4861 if ((VT.isVector() || LegalOperations) && 4862 !TLI.isOperationLegalOrCustom(LogicOpcode, XVT)) 4863 return SDValue(); 4864 // Avoid infinite looping with PromoteIntBinOp. 4865 // TODO: Should we apply desirable/legal constraints to all opcodes? 4866 if (HandOpcode == ISD::ANY_EXTEND && LegalTypes && 4867 !TLI.isTypeDesirableForOp(LogicOpcode, XVT)) 4868 return SDValue(); 4869 // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y) 4870 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4871 return DAG.getNode(HandOpcode, DL, VT, Logic); 4872 } 4873 4874 // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y) 4875 if (HandOpcode == ISD::TRUNCATE) { 4876 // If both operands have other uses, this transform would create extra 4877 // instructions without eliminating anything. 4878 if (!N0.hasOneUse() && !N1.hasOneUse()) 4879 return SDValue(); 4880 // We need matching source types. 4881 if (XVT != Y.getValueType()) 4882 return SDValue(); 4883 // Don't create an illegal op during or after legalization. 4884 if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT)) 4885 return SDValue(); 4886 // Be extra careful sinking truncate. If it's free, there's no benefit in 4887 // widening a binop. Also, don't create a logic op on an illegal type. 4888 if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT)) 4889 return SDValue(); 4890 if (!TLI.isTypeLegal(XVT)) 4891 return SDValue(); 4892 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4893 return DAG.getNode(HandOpcode, DL, VT, Logic); 4894 } 4895 4896 // For binops SHL/SRL/SRA/AND: 4897 // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z 4898 if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL || 4899 HandOpcode == ISD::SRA || HandOpcode == ISD::AND) && 4900 N0.getOperand(1) == N1.getOperand(1)) { 4901 // If either operand has other uses, this transform is not an improvement. 4902 if (!N0.hasOneUse() || !N1.hasOneUse()) 4903 return SDValue(); 4904 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4905 return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1)); 4906 } 4907 4908 // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y) 4909 if (HandOpcode == ISD::BSWAP) { 4910 // If either operand has other uses, this transform is not an improvement. 4911 if (!N0.hasOneUse() || !N1.hasOneUse()) 4912 return SDValue(); 4913 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4914 return DAG.getNode(HandOpcode, DL, VT, Logic); 4915 } 4916 4917 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B)) 4918 // Only perform this optimization up until type legalization, before 4919 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by 4920 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and 4921 // we don't want to undo this promotion. 4922 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper 4923 // on scalars. 4924 if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) && 4925 Level <= AfterLegalizeTypes) { 4926 // Input types must be integer and the same. 4927 if (XVT.isInteger() && XVT == Y.getValueType() && 4928 !(VT.isVector() && TLI.isTypeLegal(VT) && 4929 !XVT.isVector() && !TLI.isTypeLegal(XVT))) { 4930 SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y); 4931 return DAG.getNode(HandOpcode, DL, VT, Logic); 4932 } 4933 } 4934 4935 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value). 4936 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B)) 4937 // If both shuffles use the same mask, and both shuffle within a single 4938 // vector, then it is worthwhile to move the swizzle after the operation. 4939 // The type-legalizer generates this pattern when loading illegal 4940 // vector types from memory. In many cases this allows additional shuffle 4941 // optimizations. 4942 // There are other cases where moving the shuffle after the xor/and/or 4943 // is profitable even if shuffles don't perform a swizzle. 4944 // If both shuffles use the same mask, and both shuffles have the same first 4945 // or second operand, then it might still be profitable to move the shuffle 4946 // after the xor/and/or operation. 4947 if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) { 4948 auto *SVN0 = cast<ShuffleVectorSDNode>(N0); 4949 auto *SVN1 = cast<ShuffleVectorSDNode>(N1); 4950 assert(X.getValueType() == Y.getValueType() && 4951 "Inputs to shuffles are not the same type"); 4952 4953 // Check that both shuffles use the same mask. The masks are known to be of 4954 // the same length because the result vector type is the same. 4955 // Check also that shuffles have only one use to avoid introducing extra 4956 // instructions. 4957 if (!SVN0->hasOneUse() || !SVN1->hasOneUse() || 4958 !SVN0->getMask().equals(SVN1->getMask())) 4959 return SDValue(); 4960 4961 // Don't try to fold this node if it requires introducing a 4962 // build vector of all zeros that might be illegal at this stage. 4963 SDValue ShOp = N0.getOperand(1); 4964 if (LogicOpcode == ISD::XOR && !ShOp.isUndef()) 4965 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 4966 4967 // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C) 4968 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) { 4969 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, 4970 N0.getOperand(0), N1.getOperand(0)); 4971 return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask()); 4972 } 4973 4974 // Don't try to fold this node if it requires introducing a 4975 // build vector of all zeros that might be illegal at this stage. 4976 ShOp = N0.getOperand(0); 4977 if (LogicOpcode == ISD::XOR && !ShOp.isUndef()) 4978 ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 4979 4980 // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B)) 4981 if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) { 4982 SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1), 4983 N1.getOperand(1)); 4984 return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask()); 4985 } 4986 } 4987 4988 return SDValue(); 4989 } 4990 4991 /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient. 4992 SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1, 4993 const SDLoc &DL) { 4994 SDValue LL, LR, RL, RR, N0CC, N1CC; 4995 if (!isSetCCEquivalent(N0, LL, LR, N0CC) || 4996 !isSetCCEquivalent(N1, RL, RR, N1CC)) 4997 return SDValue(); 4998 4999 assert(N0.getValueType() == N1.getValueType() && 5000 "Unexpected operand types for bitwise logic op"); 5001 assert(LL.getValueType() == LR.getValueType() && 5002 RL.getValueType() == RR.getValueType() && 5003 "Unexpected operand types for setcc"); 5004 5005 // If we're here post-legalization or the logic op type is not i1, the logic 5006 // op type must match a setcc result type. Also, all folds require new 5007 // operations on the left and right operands, so those types must match. 5008 EVT VT = N0.getValueType(); 5009 EVT OpVT = LL.getValueType(); 5010 if (LegalOperations || VT.getScalarType() != MVT::i1) 5011 if (VT != getSetCCResultType(OpVT)) 5012 return SDValue(); 5013 if (OpVT != RL.getValueType()) 5014 return SDValue(); 5015 5016 ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get(); 5017 ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get(); 5018 bool IsInteger = OpVT.isInteger(); 5019 if (LR == RR && CC0 == CC1 && IsInteger) { 5020 bool IsZero = isNullOrNullSplat(LR); 5021 bool IsNeg1 = isAllOnesOrAllOnesSplat(LR); 5022 5023 // All bits clear? 5024 bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero; 5025 // All sign bits clear? 5026 bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1; 5027 // Any bits set? 5028 bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero; 5029 // Any sign bits set? 5030 bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero; 5031 5032 // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0) 5033 // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1) 5034 // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0) 5035 // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0) 5036 if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) { 5037 SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL); 5038 AddToWorklist(Or.getNode()); 5039 return DAG.getSetCC(DL, VT, Or, LR, CC1); 5040 } 5041 5042 // All bits set? 5043 bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1; 5044 // All sign bits set? 5045 bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero; 5046 // Any bits clear? 5047 bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1; 5048 // Any sign bits clear? 5049 bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1; 5050 5051 // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1) 5052 // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0) 5053 // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1) 5054 // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1) 5055 if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) { 5056 SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL); 5057 AddToWorklist(And.getNode()); 5058 return DAG.getSetCC(DL, VT, And, LR, CC1); 5059 } 5060 } 5061 5062 // TODO: What is the 'or' equivalent of this fold? 5063 // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2) 5064 if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 && 5065 IsInteger && CC0 == ISD::SETNE && 5066 ((isNullConstant(LR) && isAllOnesConstant(RR)) || 5067 (isAllOnesConstant(LR) && isNullConstant(RR)))) { 5068 SDValue One = DAG.getConstant(1, DL, OpVT); 5069 SDValue Two = DAG.getConstant(2, DL, OpVT); 5070 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One); 5071 AddToWorklist(Add.getNode()); 5072 return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE); 5073 } 5074 5075 // Try more general transforms if the predicates match and the only user of 5076 // the compares is the 'and' or 'or'. 5077 if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 && 5078 N0.hasOneUse() && N1.hasOneUse()) { 5079 // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0 5080 // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0 5081 if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) { 5082 SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR); 5083 SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR); 5084 SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR); 5085 SDValue Zero = DAG.getConstant(0, DL, OpVT); 5086 return DAG.getSetCC(DL, VT, Or, Zero, CC1); 5087 } 5088 5089 // Turn compare of constants whose difference is 1 bit into add+and+setcc. 5090 // TODO - support non-uniform vector amounts. 5091 if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) { 5092 // Match a shared variable operand and 2 non-opaque constant operands. 5093 ConstantSDNode *C0 = isConstOrConstSplat(LR); 5094 ConstantSDNode *C1 = isConstOrConstSplat(RR); 5095 if (LL == RL && C0 && C1 && !C0->isOpaque() && !C1->isOpaque()) { 5096 const APInt &CMax = 5097 APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue()); 5098 const APInt &CMin = 5099 APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue()); 5100 // The difference of the constants must be a single bit. 5101 if ((CMax - CMin).isPowerOf2()) { 5102 // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) --> 5103 // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq 5104 SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR); 5105 SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR); 5106 SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min); 5107 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min); 5108 SDValue Mask = DAG.getNOT(DL, Diff, OpVT); 5109 SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask); 5110 SDValue Zero = DAG.getConstant(0, DL, OpVT); 5111 return DAG.getSetCC(DL, VT, And, Zero, CC0); 5112 } 5113 } 5114 } 5115 } 5116 5117 // Canonicalize equivalent operands to LL == RL. 5118 if (LL == RR && LR == RL) { 5119 CC1 = ISD::getSetCCSwappedOperands(CC1); 5120 std::swap(RL, RR); 5121 } 5122 5123 // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 5124 // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC) 5125 if (LL == RL && LR == RR) { 5126 ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT) 5127 : ISD::getSetCCOrOperation(CC0, CC1, OpVT); 5128 if (NewCC != ISD::SETCC_INVALID && 5129 (!LegalOperations || 5130 (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) && 5131 TLI.isOperationLegal(ISD::SETCC, OpVT)))) 5132 return DAG.getSetCC(DL, VT, LL, LR, NewCC); 5133 } 5134 5135 return SDValue(); 5136 } 5137 5138 /// This contains all DAGCombine rules which reduce two values combined by 5139 /// an And operation to a single value. This makes them reusable in the context 5140 /// of visitSELECT(). Rules involving constants are not included as 5141 /// visitSELECT() already handles those cases. 5142 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) { 5143 EVT VT = N1.getValueType(); 5144 SDLoc DL(N); 5145 5146 // fold (and x, undef) -> 0 5147 if (N0.isUndef() || N1.isUndef()) 5148 return DAG.getConstant(0, DL, VT); 5149 5150 if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL)) 5151 return V; 5152 5153 // TODO: Rewrite this to return a new 'AND' instead of using CombineTo. 5154 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL && 5155 VT.getSizeInBits() <= 64 && N0->hasOneUse()) { 5156 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5157 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) { 5158 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal 5159 // immediate for an add, but it is legal if its top c2 bits are set, 5160 // transform the ADD so the immediate doesn't need to be materialized 5161 // in a register. 5162 APInt ADDC = ADDI->getAPIntValue(); 5163 APInt SRLC = SRLI->getAPIntValue(); 5164 if (ADDC.getMinSignedBits() <= 64 && 5165 SRLC.ult(VT.getSizeInBits()) && 5166 !TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 5167 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(), 5168 SRLC.getZExtValue()); 5169 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) { 5170 ADDC |= Mask; 5171 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) { 5172 SDLoc DL0(N0); 5173 SDValue NewAdd = 5174 DAG.getNode(ISD::ADD, DL0, VT, 5175 N0.getOperand(0), DAG.getConstant(ADDC, DL, VT)); 5176 CombineTo(N0.getNode(), NewAdd); 5177 // Return N so it doesn't get rechecked! 5178 return SDValue(N, 0); 5179 } 5180 } 5181 } 5182 } 5183 } 5184 } 5185 5186 // Reduce bit extract of low half of an integer to the narrower type. 5187 // (and (srl i64:x, K), KMask) -> 5188 // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask) 5189 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 5190 if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) { 5191 if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 5192 unsigned Size = VT.getSizeInBits(); 5193 const APInt &AndMask = CAnd->getAPIntValue(); 5194 unsigned ShiftBits = CShift->getZExtValue(); 5195 5196 // Bail out, this node will probably disappear anyway. 5197 if (ShiftBits == 0) 5198 return SDValue(); 5199 5200 unsigned MaskBits = AndMask.countTrailingOnes(); 5201 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2); 5202 5203 if (AndMask.isMask() && 5204 // Required bits must not span the two halves of the integer and 5205 // must fit in the half size type. 5206 (ShiftBits + MaskBits <= Size / 2) && 5207 TLI.isNarrowingProfitable(VT, HalfVT) && 5208 TLI.isTypeDesirableForOp(ISD::AND, HalfVT) && 5209 TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) && 5210 TLI.isTruncateFree(VT, HalfVT) && 5211 TLI.isZExtFree(HalfVT, VT)) { 5212 // The isNarrowingProfitable is to avoid regressions on PPC and 5213 // AArch64 which match a few 64-bit bit insert / bit extract patterns 5214 // on downstream users of this. Those patterns could probably be 5215 // extended to handle extensions mixed in. 5216 5217 SDValue SL(N0); 5218 assert(MaskBits <= Size); 5219 5220 // Extracting the highest bit of the low half. 5221 EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout()); 5222 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT, 5223 N0.getOperand(0)); 5224 5225 SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT); 5226 SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT); 5227 SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK); 5228 SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask); 5229 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And); 5230 } 5231 } 5232 } 5233 } 5234 5235 return SDValue(); 5236 } 5237 5238 bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN, 5239 EVT LoadResultTy, EVT &ExtVT) { 5240 if (!AndC->getAPIntValue().isMask()) 5241 return false; 5242 5243 unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes(); 5244 5245 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 5246 EVT LoadedVT = LoadN->getMemoryVT(); 5247 5248 if (ExtVT == LoadedVT && 5249 (!LegalOperations || 5250 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) { 5251 // ZEXTLOAD will match without needing to change the size of the value being 5252 // loaded. 5253 return true; 5254 } 5255 5256 // Do not change the width of a volatile or atomic loads. 5257 if (!LoadN->isSimple()) 5258 return false; 5259 5260 // Do not generate loads of non-round integer types since these can 5261 // be expensive (and would be wrong if the type is not byte sized). 5262 if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound()) 5263 return false; 5264 5265 if (LegalOperations && 5266 !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT)) 5267 return false; 5268 5269 if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT)) 5270 return false; 5271 5272 return true; 5273 } 5274 5275 bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST, 5276 ISD::LoadExtType ExtType, EVT &MemVT, 5277 unsigned ShAmt) { 5278 if (!LDST) 5279 return false; 5280 // Only allow byte offsets. 5281 if (ShAmt % 8) 5282 return false; 5283 5284 // Do not generate loads of non-round integer types since these can 5285 // be expensive (and would be wrong if the type is not byte sized). 5286 if (!MemVT.isRound()) 5287 return false; 5288 5289 // Don't change the width of a volatile or atomic loads. 5290 if (!LDST->isSimple()) 5291 return false; 5292 5293 EVT LdStMemVT = LDST->getMemoryVT(); 5294 5295 // Bail out when changing the scalable property, since we can't be sure that 5296 // we're actually narrowing here. 5297 if (LdStMemVT.isScalableVector() != MemVT.isScalableVector()) 5298 return false; 5299 5300 // Verify that we are actually reducing a load width here. 5301 if (LdStMemVT.bitsLT(MemVT)) 5302 return false; 5303 5304 // Ensure that this isn't going to produce an unsupported memory access. 5305 if (ShAmt) { 5306 assert(ShAmt % 8 == 0 && "ShAmt is byte offset"); 5307 const unsigned ByteShAmt = ShAmt / 8; 5308 const Align LDSTAlign = LDST->getAlign(); 5309 const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt); 5310 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 5311 LDST->getAddressSpace(), NarrowAlign, 5312 LDST->getMemOperand()->getFlags())) 5313 return false; 5314 } 5315 5316 // It's not possible to generate a constant of extended or untyped type. 5317 EVT PtrType = LDST->getBasePtr().getValueType(); 5318 if (PtrType == MVT::Untyped || PtrType.isExtended()) 5319 return false; 5320 5321 if (isa<LoadSDNode>(LDST)) { 5322 LoadSDNode *Load = cast<LoadSDNode>(LDST); 5323 // Don't transform one with multiple uses, this would require adding a new 5324 // load. 5325 if (!SDValue(Load, 0).hasOneUse()) 5326 return false; 5327 5328 if (LegalOperations && 5329 !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT)) 5330 return false; 5331 5332 // For the transform to be legal, the load must produce only two values 5333 // (the value loaded and the chain). Don't transform a pre-increment 5334 // load, for example, which produces an extra value. Otherwise the 5335 // transformation is not equivalent, and the downstream logic to replace 5336 // uses gets things wrong. 5337 if (Load->getNumValues() > 2) 5338 return false; 5339 5340 // If the load that we're shrinking is an extload and we're not just 5341 // discarding the extension we can't simply shrink the load. Bail. 5342 // TODO: It would be possible to merge the extensions in some cases. 5343 if (Load->getExtensionType() != ISD::NON_EXTLOAD && 5344 Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 5345 return false; 5346 5347 if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT)) 5348 return false; 5349 } else { 5350 assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode"); 5351 StoreSDNode *Store = cast<StoreSDNode>(LDST); 5352 // Can't write outside the original store 5353 if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt) 5354 return false; 5355 5356 if (LegalOperations && 5357 !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT)) 5358 return false; 5359 } 5360 return true; 5361 } 5362 5363 bool DAGCombiner::SearchForAndLoads(SDNode *N, 5364 SmallVectorImpl<LoadSDNode*> &Loads, 5365 SmallPtrSetImpl<SDNode*> &NodesWithConsts, 5366 ConstantSDNode *Mask, 5367 SDNode *&NodeToMask) { 5368 // Recursively search for the operands, looking for loads which can be 5369 // narrowed. 5370 for (SDValue Op : N->op_values()) { 5371 if (Op.getValueType().isVector()) 5372 return false; 5373 5374 // Some constants may need fixing up later if they are too large. 5375 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 5376 if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) && 5377 (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue()) 5378 NodesWithConsts.insert(N); 5379 continue; 5380 } 5381 5382 if (!Op.hasOneUse()) 5383 return false; 5384 5385 switch(Op.getOpcode()) { 5386 case ISD::LOAD: { 5387 auto *Load = cast<LoadSDNode>(Op); 5388 EVT ExtVT; 5389 if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) && 5390 isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) { 5391 5392 // ZEXTLOAD is already small enough. 5393 if (Load->getExtensionType() == ISD::ZEXTLOAD && 5394 ExtVT.bitsGE(Load->getMemoryVT())) 5395 continue; 5396 5397 // Use LE to convert equal sized loads to zext. 5398 if (ExtVT.bitsLE(Load->getMemoryVT())) 5399 Loads.push_back(Load); 5400 5401 continue; 5402 } 5403 return false; 5404 } 5405 case ISD::ZERO_EXTEND: 5406 case ISD::AssertZext: { 5407 unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes(); 5408 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 5409 EVT VT = Op.getOpcode() == ISD::AssertZext ? 5410 cast<VTSDNode>(Op.getOperand(1))->getVT() : 5411 Op.getOperand(0).getValueType(); 5412 5413 // We can accept extending nodes if the mask is wider or an equal 5414 // width to the original type. 5415 if (ExtVT.bitsGE(VT)) 5416 continue; 5417 break; 5418 } 5419 case ISD::OR: 5420 case ISD::XOR: 5421 case ISD::AND: 5422 if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask, 5423 NodeToMask)) 5424 return false; 5425 continue; 5426 } 5427 5428 // Allow one node which will masked along with any loads found. 5429 if (NodeToMask) 5430 return false; 5431 5432 // Also ensure that the node to be masked only produces one data result. 5433 NodeToMask = Op.getNode(); 5434 if (NodeToMask->getNumValues() > 1) { 5435 bool HasValue = false; 5436 for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) { 5437 MVT VT = SDValue(NodeToMask, i).getSimpleValueType(); 5438 if (VT != MVT::Glue && VT != MVT::Other) { 5439 if (HasValue) { 5440 NodeToMask = nullptr; 5441 return false; 5442 } 5443 HasValue = true; 5444 } 5445 } 5446 assert(HasValue && "Node to be masked has no data result?"); 5447 } 5448 } 5449 return true; 5450 } 5451 5452 bool DAGCombiner::BackwardsPropagateMask(SDNode *N) { 5453 auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1)); 5454 if (!Mask) 5455 return false; 5456 5457 if (!Mask->getAPIntValue().isMask()) 5458 return false; 5459 5460 // No need to do anything if the and directly uses a load. 5461 if (isa<LoadSDNode>(N->getOperand(0))) 5462 return false; 5463 5464 SmallVector<LoadSDNode*, 8> Loads; 5465 SmallPtrSet<SDNode*, 2> NodesWithConsts; 5466 SDNode *FixupNode = nullptr; 5467 if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) { 5468 if (Loads.size() == 0) 5469 return false; 5470 5471 LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump()); 5472 SDValue MaskOp = N->getOperand(1); 5473 5474 // If it exists, fixup the single node we allow in the tree that needs 5475 // masking. 5476 if (FixupNode) { 5477 LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump()); 5478 SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode), 5479 FixupNode->getValueType(0), 5480 SDValue(FixupNode, 0), MaskOp); 5481 DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And); 5482 if (And.getOpcode() == ISD ::AND) 5483 DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp); 5484 } 5485 5486 // Narrow any constants that need it. 5487 for (auto *LogicN : NodesWithConsts) { 5488 SDValue Op0 = LogicN->getOperand(0); 5489 SDValue Op1 = LogicN->getOperand(1); 5490 5491 if (isa<ConstantSDNode>(Op0)) 5492 std::swap(Op0, Op1); 5493 5494 SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(), 5495 Op1, MaskOp); 5496 5497 DAG.UpdateNodeOperands(LogicN, Op0, And); 5498 } 5499 5500 // Create narrow loads. 5501 for (auto *Load : Loads) { 5502 LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump()); 5503 SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0), 5504 SDValue(Load, 0), MaskOp); 5505 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And); 5506 if (And.getOpcode() == ISD ::AND) 5507 And = SDValue( 5508 DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0); 5509 SDValue NewLoad = ReduceLoadWidth(And.getNode()); 5510 assert(NewLoad && 5511 "Shouldn't be masking the load if it can't be narrowed"); 5512 CombineTo(Load, NewLoad, NewLoad.getValue(1)); 5513 } 5514 DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode()); 5515 return true; 5516 } 5517 return false; 5518 } 5519 5520 // Unfold 5521 // x & (-1 'logical shift' y) 5522 // To 5523 // (x 'opposite logical shift' y) 'logical shift' y 5524 // if it is better for performance. 5525 SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) { 5526 assert(N->getOpcode() == ISD::AND); 5527 5528 SDValue N0 = N->getOperand(0); 5529 SDValue N1 = N->getOperand(1); 5530 5531 // Do we actually prefer shifts over mask? 5532 if (!TLI.shouldFoldMaskToVariableShiftPair(N0)) 5533 return SDValue(); 5534 5535 // Try to match (-1 '[outer] logical shift' y) 5536 unsigned OuterShift; 5537 unsigned InnerShift; // The opposite direction to the OuterShift. 5538 SDValue Y; // Shift amount. 5539 auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool { 5540 if (!M.hasOneUse()) 5541 return false; 5542 OuterShift = M->getOpcode(); 5543 if (OuterShift == ISD::SHL) 5544 InnerShift = ISD::SRL; 5545 else if (OuterShift == ISD::SRL) 5546 InnerShift = ISD::SHL; 5547 else 5548 return false; 5549 if (!isAllOnesConstant(M->getOperand(0))) 5550 return false; 5551 Y = M->getOperand(1); 5552 return true; 5553 }; 5554 5555 SDValue X; 5556 if (matchMask(N1)) 5557 X = N0; 5558 else if (matchMask(N0)) 5559 X = N1; 5560 else 5561 return SDValue(); 5562 5563 SDLoc DL(N); 5564 EVT VT = N->getValueType(0); 5565 5566 // tmp = x 'opposite logical shift' y 5567 SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y); 5568 // ret = tmp 'logical shift' y 5569 SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y); 5570 5571 return T1; 5572 } 5573 5574 /// Try to replace shift/logic that tests if a bit is clear with mask + setcc. 5575 /// For a target with a bit test, this is expected to become test + set and save 5576 /// at least 1 instruction. 5577 static SDValue combineShiftAnd1ToBitTest(SDNode *And, SelectionDAG &DAG) { 5578 assert(And->getOpcode() == ISD::AND && "Expected an 'and' op"); 5579 5580 // This is probably not worthwhile without a supported type. 5581 EVT VT = And->getValueType(0); 5582 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 5583 if (!TLI.isTypeLegal(VT)) 5584 return SDValue(); 5585 5586 // Look through an optional extension and find a 'not'. 5587 // TODO: Should we favor test+set even without the 'not' op? 5588 SDValue Not = And->getOperand(0), And1 = And->getOperand(1); 5589 if (Not.getOpcode() == ISD::ANY_EXTEND) 5590 Not = Not.getOperand(0); 5591 if (!isBitwiseNot(Not) || !Not.hasOneUse() || !isOneConstant(And1)) 5592 return SDValue(); 5593 5594 // Look though an optional truncation. The source operand may not be the same 5595 // type as the original 'and', but that is ok because we are masking off 5596 // everything but the low bit. 5597 SDValue Srl = Not.getOperand(0); 5598 if (Srl.getOpcode() == ISD::TRUNCATE) 5599 Srl = Srl.getOperand(0); 5600 5601 // Match a shift-right by constant. 5602 if (Srl.getOpcode() != ISD::SRL || !Srl.hasOneUse() || 5603 !isa<ConstantSDNode>(Srl.getOperand(1))) 5604 return SDValue(); 5605 5606 // We might have looked through casts that make this transform invalid. 5607 // TODO: If the source type is wider than the result type, do the mask and 5608 // compare in the source type. 5609 const APInt &ShiftAmt = Srl.getConstantOperandAPInt(1); 5610 unsigned VTBitWidth = VT.getSizeInBits(); 5611 if (ShiftAmt.uge(VTBitWidth)) 5612 return SDValue(); 5613 5614 // Turn this into a bit-test pattern using mask op + setcc: 5615 // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0 5616 SDLoc DL(And); 5617 SDValue X = DAG.getZExtOrTrunc(Srl.getOperand(0), DL, VT); 5618 EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT); 5619 SDValue Mask = DAG.getConstant( 5620 APInt::getOneBitSet(VTBitWidth, ShiftAmt.getZExtValue()), DL, VT); 5621 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, Mask); 5622 SDValue Zero = DAG.getConstant(0, DL, VT); 5623 SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ); 5624 return DAG.getZExtOrTrunc(Setcc, DL, VT); 5625 } 5626 5627 /// For targets that support usubsat, match a bit-hack form of that operation 5628 /// that ends in 'and' and convert it. 5629 static SDValue foldAndToUsubsat(SDNode *N, SelectionDAG &DAG) { 5630 SDValue N0 = N->getOperand(0); 5631 SDValue N1 = N->getOperand(1); 5632 EVT VT = N1.getValueType(); 5633 5634 // Canonicalize SRA as operand 1. 5635 if (N0.getOpcode() == ISD::SRA) 5636 std::swap(N0, N1); 5637 5638 // xor/add with SMIN (signmask) are logically equivalent. 5639 if (N0.getOpcode() != ISD::XOR && N0.getOpcode() != ISD::ADD) 5640 return SDValue(); 5641 5642 if (N1.getOpcode() != ISD::SRA || !N0.hasOneUse() || !N1.hasOneUse() || 5643 N0.getOperand(0) != N1.getOperand(0)) 5644 return SDValue(); 5645 5646 unsigned BitWidth = VT.getScalarSizeInBits(); 5647 ConstantSDNode *XorC = isConstOrConstSplat(N0.getOperand(1), true); 5648 ConstantSDNode *SraC = isConstOrConstSplat(N1.getOperand(1), true); 5649 if (!XorC || !XorC->getAPIntValue().isSignMask() || 5650 !SraC || SraC->getAPIntValue() != BitWidth - 1) 5651 return SDValue(); 5652 5653 // (i8 X ^ 128) & (i8 X s>> 7) --> usubsat X, 128 5654 // (i8 X + 128) & (i8 X s>> 7) --> usubsat X, 128 5655 SDLoc DL(N); 5656 SDValue SignMask = DAG.getConstant(XorC->getAPIntValue(), DL, VT); 5657 return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0), SignMask); 5658 } 5659 5660 SDValue DAGCombiner::visitAND(SDNode *N) { 5661 SDValue N0 = N->getOperand(0); 5662 SDValue N1 = N->getOperand(1); 5663 EVT VT = N1.getValueType(); 5664 5665 // x & x --> x 5666 if (N0 == N1) 5667 return N0; 5668 5669 // fold vector ops 5670 if (VT.isVector()) { 5671 if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N))) 5672 return FoldedVOp; 5673 5674 // fold (and x, 0) -> 0, vector edition 5675 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 5676 // do not return N0, because undef node may exist in N0 5677 return DAG.getConstant(APInt::getZero(N0.getScalarValueSizeInBits()), 5678 SDLoc(N), N0.getValueType()); 5679 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 5680 // do not return N1, because undef node may exist in N1 5681 return DAG.getConstant(APInt::getZero(N1.getScalarValueSizeInBits()), 5682 SDLoc(N), N1.getValueType()); 5683 5684 // fold (and x, -1) -> x, vector edition 5685 if (ISD::isConstantSplatVectorAllOnes(N0.getNode())) 5686 return N1; 5687 if (ISD::isConstantSplatVectorAllOnes(N1.getNode())) 5688 return N0; 5689 5690 // fold (and (masked_load) (build_vec (x, ...))) to zext_masked_load 5691 auto *MLoad = dyn_cast<MaskedLoadSDNode>(N0); 5692 auto *BVec = dyn_cast<BuildVectorSDNode>(N1); 5693 if (MLoad && BVec && MLoad->getExtensionType() == ISD::EXTLOAD && 5694 N0.hasOneUse() && N1.hasOneUse()) { 5695 EVT LoadVT = MLoad->getMemoryVT(); 5696 EVT ExtVT = VT; 5697 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT, LoadVT)) { 5698 // For this AND to be a zero extension of the masked load the elements 5699 // of the BuildVec must mask the bottom bits of the extended element 5700 // type 5701 if (ConstantSDNode *Splat = BVec->getConstantSplatNode()) { 5702 uint64_t ElementSize = 5703 LoadVT.getVectorElementType().getScalarSizeInBits(); 5704 if (Splat->getAPIntValue().isMask(ElementSize)) { 5705 return DAG.getMaskedLoad( 5706 ExtVT, SDLoc(N), MLoad->getChain(), MLoad->getBasePtr(), 5707 MLoad->getOffset(), MLoad->getMask(), MLoad->getPassThru(), 5708 LoadVT, MLoad->getMemOperand(), MLoad->getAddressingMode(), 5709 ISD::ZEXTLOAD, MLoad->isExpandingLoad()); 5710 } 5711 } 5712 } 5713 } 5714 } 5715 5716 // fold (and c1, c2) -> c1&c2 5717 ConstantSDNode *N1C = isConstOrConstSplat(N1); 5718 if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, {N0, N1})) 5719 return C; 5720 5721 // canonicalize constant to RHS 5722 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 5723 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 5724 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0); 5725 5726 // fold (and x, -1) -> x 5727 if (isAllOnesConstant(N1)) 5728 return N0; 5729 5730 // if (and x, c) is known to be zero, return 0 5731 unsigned BitWidth = VT.getScalarSizeInBits(); 5732 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(BitWidth))) 5733 return DAG.getConstant(0, SDLoc(N), VT); 5734 5735 if (SDValue NewSel = foldBinOpIntoSelect(N)) 5736 return NewSel; 5737 5738 // reassociate and 5739 if (SDValue RAND = reassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags())) 5740 return RAND; 5741 5742 // Try to convert a constant mask AND into a shuffle clear mask. 5743 if (VT.isVector()) 5744 if (SDValue Shuffle = XformToShuffleWithZero(N)) 5745 return Shuffle; 5746 5747 if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N)) 5748 return Combined; 5749 5750 // fold (and (or x, C), D) -> D if (C & D) == D 5751 auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) { 5752 return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue()); 5753 }; 5754 if (N0.getOpcode() == ISD::OR && 5755 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset)) 5756 return N1; 5757 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits. 5758 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 5759 SDValue N0Op0 = N0.getOperand(0); 5760 APInt Mask = ~N1C->getAPIntValue(); 5761 Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits()); 5762 if (DAG.MaskedValueIsZero(N0Op0, Mask)) { 5763 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), 5764 N0.getValueType(), N0Op0); 5765 5766 // Replace uses of the AND with uses of the Zero extend node. 5767 CombineTo(N, Zext); 5768 5769 // We actually want to replace all uses of the any_extend with the 5770 // zero_extend, to avoid duplicating things. This will later cause this 5771 // AND to be folded. 5772 CombineTo(N0.getNode(), Zext); 5773 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5774 } 5775 } 5776 5777 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 5778 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must 5779 // already be zero by virtue of the width of the base type of the load. 5780 // 5781 // the 'X' node here can either be nothing or an extract_vector_elt to catch 5782 // more cases. 5783 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 5784 N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() && 5785 N0.getOperand(0).getOpcode() == ISD::LOAD && 5786 N0.getOperand(0).getResNo() == 0) || 5787 (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) { 5788 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ? 5789 N0 : N0.getOperand(0) ); 5790 5791 // Get the constant (if applicable) the zero'th operand is being ANDed with. 5792 // This can be a pure constant or a vector splat, in which case we treat the 5793 // vector as a scalar and use the splat value. 5794 APInt Constant = APInt::getZero(1); 5795 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 5796 Constant = C->getAPIntValue(); 5797 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) { 5798 APInt SplatValue, SplatUndef; 5799 unsigned SplatBitSize; 5800 bool HasAnyUndefs; 5801 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef, 5802 SplatBitSize, HasAnyUndefs); 5803 if (IsSplat) { 5804 // Undef bits can contribute to a possible optimisation if set, so 5805 // set them. 5806 SplatValue |= SplatUndef; 5807 5808 // The splat value may be something like "0x00FFFFFF", which means 0 for 5809 // the first vector value and FF for the rest, repeating. We need a mask 5810 // that will apply equally to all members of the vector, so AND all the 5811 // lanes of the constant together. 5812 unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits(); 5813 5814 // If the splat value has been compressed to a bitlength lower 5815 // than the size of the vector lane, we need to re-expand it to 5816 // the lane size. 5817 if (EltBitWidth > SplatBitSize) 5818 for (SplatValue = SplatValue.zextOrTrunc(EltBitWidth); 5819 SplatBitSize < EltBitWidth; SplatBitSize = SplatBitSize * 2) 5820 SplatValue |= SplatValue.shl(SplatBitSize); 5821 5822 // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a 5823 // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value. 5824 if ((SplatBitSize % EltBitWidth) == 0) { 5825 Constant = APInt::getAllOnes(EltBitWidth); 5826 for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i) 5827 Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth); 5828 } 5829 } 5830 } 5831 5832 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is 5833 // actually legal and isn't going to get expanded, else this is a false 5834 // optimisation. 5835 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD, 5836 Load->getValueType(0), 5837 Load->getMemoryVT()); 5838 5839 // Resize the constant to the same size as the original memory access before 5840 // extension. If it is still the AllOnesValue then this AND is completely 5841 // unneeded. 5842 Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits()); 5843 5844 bool B; 5845 switch (Load->getExtensionType()) { 5846 default: B = false; break; 5847 case ISD::EXTLOAD: B = CanZextLoadProfitably; break; 5848 case ISD::ZEXTLOAD: 5849 case ISD::NON_EXTLOAD: B = true; break; 5850 } 5851 5852 if (B && Constant.isAllOnes()) { 5853 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to 5854 // preserve semantics once we get rid of the AND. 5855 SDValue NewLoad(Load, 0); 5856 5857 // Fold the AND away. NewLoad may get replaced immediately. 5858 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0); 5859 5860 if (Load->getExtensionType() == ISD::EXTLOAD) { 5861 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD, 5862 Load->getValueType(0), SDLoc(Load), 5863 Load->getChain(), Load->getBasePtr(), 5864 Load->getOffset(), Load->getMemoryVT(), 5865 Load->getMemOperand()); 5866 // Replace uses of the EXTLOAD with the new ZEXTLOAD. 5867 if (Load->getNumValues() == 3) { 5868 // PRE/POST_INC loads have 3 values. 5869 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1), 5870 NewLoad.getValue(2) }; 5871 CombineTo(Load, To, 3, true); 5872 } else { 5873 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1)); 5874 } 5875 } 5876 5877 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5878 } 5879 } 5880 5881 // fold (and (masked_gather x)) -> (zext_masked_gather x) 5882 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) { 5883 EVT MemVT = GN0->getMemoryVT(); 5884 EVT ScalarVT = MemVT.getScalarType(); 5885 5886 if (SDValue(GN0, 0).hasOneUse() && 5887 isConstantSplatVectorMaskForType(N1.getNode(), ScalarVT) && 5888 TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) { 5889 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(), 5890 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()}; 5891 5892 SDValue ZExtLoad = DAG.getMaskedGather( 5893 DAG.getVTList(VT, MVT::Other), MemVT, SDLoc(N), Ops, 5894 GN0->getMemOperand(), GN0->getIndexType(), ISD::ZEXTLOAD); 5895 5896 CombineTo(N, ZExtLoad); 5897 AddToWorklist(ZExtLoad.getNode()); 5898 // Avoid recheck of N. 5899 return SDValue(N, 0); 5900 } 5901 } 5902 5903 // fold (and (load x), 255) -> (zextload x, i8) 5904 // fold (and (extload x, i16), 255) -> (zextload x, i8) 5905 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8) 5906 if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD || 5907 (N0.getOpcode() == ISD::ANY_EXTEND && 5908 N0.getOperand(0).getOpcode() == ISD::LOAD))) { 5909 if (SDValue Res = ReduceLoadWidth(N)) { 5910 LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND 5911 ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0); 5912 AddToWorklist(N); 5913 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 0), Res); 5914 return SDValue(N, 0); 5915 } 5916 } 5917 5918 if (LegalTypes) { 5919 // Attempt to propagate the AND back up to the leaves which, if they're 5920 // loads, can be combined to narrow loads and the AND node can be removed. 5921 // Perform after legalization so that extend nodes will already be 5922 // combined into the loads. 5923 if (BackwardsPropagateMask(N)) 5924 return SDValue(N, 0); 5925 } 5926 5927 if (SDValue Combined = visitANDLike(N0, N1, N)) 5928 return Combined; 5929 5930 // Simplify: (and (op x...), (op y...)) -> (op (and x, y)) 5931 if (N0.getOpcode() == N1.getOpcode()) 5932 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) 5933 return V; 5934 5935 // Masking the negated extension of a boolean is just the zero-extended 5936 // boolean: 5937 // and (sub 0, zext(bool X)), 1 --> zext(bool X) 5938 // and (sub 0, sext(bool X)), 1 --> zext(bool X) 5939 // 5940 // Note: the SimplifyDemandedBits fold below can make an information-losing 5941 // transform, and then we have no way to find this better fold. 5942 if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) { 5943 if (isNullOrNullSplat(N0.getOperand(0))) { 5944 SDValue SubRHS = N0.getOperand(1); 5945 if (SubRHS.getOpcode() == ISD::ZERO_EXTEND && 5946 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 5947 return SubRHS; 5948 if (SubRHS.getOpcode() == ISD::SIGN_EXTEND && 5949 SubRHS.getOperand(0).getScalarValueSizeInBits() == 1) 5950 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0)); 5951 } 5952 } 5953 5954 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1) 5955 // fold (and (sra)) -> (and (srl)) when possible. 5956 if (SimplifyDemandedBits(SDValue(N, 0))) 5957 return SDValue(N, 0); 5958 5959 // fold (zext_inreg (extload x)) -> (zextload x) 5960 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use 5961 if (ISD::isUNINDEXEDLoad(N0.getNode()) && 5962 (ISD::isEXTLoad(N0.getNode()) || 5963 (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) { 5964 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 5965 EVT MemVT = LN0->getMemoryVT(); 5966 // If we zero all the possible extended bits, then we can turn this into 5967 // a zextload if we are running before legalize or the operation is legal. 5968 unsigned ExtBitSize = N1.getScalarValueSizeInBits(); 5969 unsigned MemBitSize = MemVT.getScalarSizeInBits(); 5970 APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize); 5971 if (DAG.MaskedValueIsZero(N1, ExtBits) && 5972 ((!LegalOperations && LN0->isSimple()) || 5973 TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) { 5974 SDValue ExtLoad = 5975 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(), 5976 LN0->getBasePtr(), MemVT, LN0->getMemOperand()); 5977 AddToWorklist(N); 5978 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 5979 return SDValue(N, 0); // Return N so it doesn't get rechecked! 5980 } 5981 } 5982 5983 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const) 5984 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) { 5985 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 5986 N0.getOperand(1), false)) 5987 return BSwap; 5988 } 5989 5990 if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N)) 5991 return Shifts; 5992 5993 if (TLI.hasBitTest(N0, N1)) 5994 if (SDValue V = combineShiftAnd1ToBitTest(N, DAG)) 5995 return V; 5996 5997 // Recognize the following pattern: 5998 // 5999 // AndVT = (and (sign_extend NarrowVT to AndVT) #bitmask) 6000 // 6001 // where bitmask is a mask that clears the upper bits of AndVT. The 6002 // number of bits in bitmask must be a power of two. 6003 auto IsAndZeroExtMask = [](SDValue LHS, SDValue RHS) { 6004 if (LHS->getOpcode() != ISD::SIGN_EXTEND) 6005 return false; 6006 6007 auto *C = dyn_cast<ConstantSDNode>(RHS); 6008 if (!C) 6009 return false; 6010 6011 if (!C->getAPIntValue().isMask( 6012 LHS.getOperand(0).getValueType().getFixedSizeInBits())) 6013 return false; 6014 6015 return true; 6016 }; 6017 6018 // Replace (and (sign_extend ...) #bitmask) with (zero_extend ...). 6019 if (IsAndZeroExtMask(N0, N1)) 6020 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0.getOperand(0)); 6021 6022 if (hasOperation(ISD::USUBSAT, VT)) 6023 if (SDValue V = foldAndToUsubsat(N, DAG)) 6024 return V; 6025 6026 return SDValue(); 6027 } 6028 6029 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16. 6030 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1, 6031 bool DemandHighBits) { 6032 if (!LegalOperations) 6033 return SDValue(); 6034 6035 EVT VT = N->getValueType(0); 6036 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16) 6037 return SDValue(); 6038 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 6039 return SDValue(); 6040 6041 // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff) 6042 bool LookPassAnd0 = false; 6043 bool LookPassAnd1 = false; 6044 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL) 6045 std::swap(N0, N1); 6046 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL) 6047 std::swap(N0, N1); 6048 if (N0.getOpcode() == ISD::AND) { 6049 if (!N0.getNode()->hasOneUse()) 6050 return SDValue(); 6051 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6052 // Also handle 0xffff since the LHS is guaranteed to have zeros there. 6053 // This is needed for X86. 6054 if (!N01C || (N01C->getZExtValue() != 0xFF00 && 6055 N01C->getZExtValue() != 0xFFFF)) 6056 return SDValue(); 6057 N0 = N0.getOperand(0); 6058 LookPassAnd0 = true; 6059 } 6060 6061 if (N1.getOpcode() == ISD::AND) { 6062 if (!N1.getNode()->hasOneUse()) 6063 return SDValue(); 6064 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 6065 if (!N11C || N11C->getZExtValue() != 0xFF) 6066 return SDValue(); 6067 N1 = N1.getOperand(0); 6068 LookPassAnd1 = true; 6069 } 6070 6071 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL) 6072 std::swap(N0, N1); 6073 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL) 6074 return SDValue(); 6075 if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse()) 6076 return SDValue(); 6077 6078 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6079 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1)); 6080 if (!N01C || !N11C) 6081 return SDValue(); 6082 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8) 6083 return SDValue(); 6084 6085 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8) 6086 SDValue N00 = N0->getOperand(0); 6087 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) { 6088 if (!N00.getNode()->hasOneUse()) 6089 return SDValue(); 6090 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1)); 6091 if (!N001C || N001C->getZExtValue() != 0xFF) 6092 return SDValue(); 6093 N00 = N00.getOperand(0); 6094 LookPassAnd0 = true; 6095 } 6096 6097 SDValue N10 = N1->getOperand(0); 6098 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) { 6099 if (!N10.getNode()->hasOneUse()) 6100 return SDValue(); 6101 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1)); 6102 // Also allow 0xFFFF since the bits will be shifted out. This is needed 6103 // for X86. 6104 if (!N101C || (N101C->getZExtValue() != 0xFF00 && 6105 N101C->getZExtValue() != 0xFFFF)) 6106 return SDValue(); 6107 N10 = N10.getOperand(0); 6108 LookPassAnd1 = true; 6109 } 6110 6111 if (N00 != N10) 6112 return SDValue(); 6113 6114 // Make sure everything beyond the low halfword gets set to zero since the SRL 6115 // 16 will clear the top bits. 6116 unsigned OpSizeInBits = VT.getSizeInBits(); 6117 if (DemandHighBits && OpSizeInBits > 16) { 6118 // If the left-shift isn't masked out then the only way this is a bswap is 6119 // if all bits beyond the low 8 are 0. In that case the entire pattern 6120 // reduces to a left shift anyway: leave it for other parts of the combiner. 6121 if (!LookPassAnd0) 6122 return SDValue(); 6123 6124 // However, if the right shift isn't masked out then it might be because 6125 // it's not needed. See if we can spot that too. 6126 if (!LookPassAnd1 && 6127 !DAG.MaskedValueIsZero( 6128 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16))) 6129 return SDValue(); 6130 } 6131 6132 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00); 6133 if (OpSizeInBits > 16) { 6134 SDLoc DL(N); 6135 Res = DAG.getNode(ISD::SRL, DL, VT, Res, 6136 DAG.getConstant(OpSizeInBits - 16, DL, 6137 getShiftAmountTy(VT))); 6138 } 6139 return Res; 6140 } 6141 6142 /// Return true if the specified node is an element that makes up a 32-bit 6143 /// packed halfword byteswap. 6144 /// ((x & 0x000000ff) << 8) | 6145 /// ((x & 0x0000ff00) >> 8) | 6146 /// ((x & 0x00ff0000) << 8) | 6147 /// ((x & 0xff000000) >> 8) 6148 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) { 6149 if (!N.getNode()->hasOneUse()) 6150 return false; 6151 6152 unsigned Opc = N.getOpcode(); 6153 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL) 6154 return false; 6155 6156 SDValue N0 = N.getOperand(0); 6157 unsigned Opc0 = N0.getOpcode(); 6158 if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL) 6159 return false; 6160 6161 ConstantSDNode *N1C = nullptr; 6162 // SHL or SRL: look upstream for AND mask operand 6163 if (Opc == ISD::AND) 6164 N1C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 6165 else if (Opc0 == ISD::AND) 6166 N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6167 if (!N1C) 6168 return false; 6169 6170 unsigned MaskByteOffset; 6171 switch (N1C->getZExtValue()) { 6172 default: 6173 return false; 6174 case 0xFF: MaskByteOffset = 0; break; 6175 case 0xFF00: MaskByteOffset = 1; break; 6176 case 0xFFFF: 6177 // In case demanded bits didn't clear the bits that will be shifted out. 6178 // This is needed for X86. 6179 if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) { 6180 MaskByteOffset = 1; 6181 break; 6182 } 6183 return false; 6184 case 0xFF0000: MaskByteOffset = 2; break; 6185 case 0xFF000000: MaskByteOffset = 3; break; 6186 } 6187 6188 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00). 6189 if (Opc == ISD::AND) { 6190 if (MaskByteOffset == 0 || MaskByteOffset == 2) { 6191 // (x >> 8) & 0xff 6192 // (x >> 8) & 0xff0000 6193 if (Opc0 != ISD::SRL) 6194 return false; 6195 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6196 if (!C || C->getZExtValue() != 8) 6197 return false; 6198 } else { 6199 // (x << 8) & 0xff00 6200 // (x << 8) & 0xff000000 6201 if (Opc0 != ISD::SHL) 6202 return false; 6203 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 6204 if (!C || C->getZExtValue() != 8) 6205 return false; 6206 } 6207 } else if (Opc == ISD::SHL) { 6208 // (x & 0xff) << 8 6209 // (x & 0xff0000) << 8 6210 if (MaskByteOffset != 0 && MaskByteOffset != 2) 6211 return false; 6212 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 6213 if (!C || C->getZExtValue() != 8) 6214 return false; 6215 } else { // Opc == ISD::SRL 6216 // (x & 0xff00) >> 8 6217 // (x & 0xff000000) >> 8 6218 if (MaskByteOffset != 1 && MaskByteOffset != 3) 6219 return false; 6220 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1)); 6221 if (!C || C->getZExtValue() != 8) 6222 return false; 6223 } 6224 6225 if (Parts[MaskByteOffset]) 6226 return false; 6227 6228 Parts[MaskByteOffset] = N0.getOperand(0).getNode(); 6229 return true; 6230 } 6231 6232 // Match 2 elements of a packed halfword bswap. 6233 static bool isBSwapHWordPair(SDValue N, MutableArrayRef<SDNode *> Parts) { 6234 if (N.getOpcode() == ISD::OR) 6235 return isBSwapHWordElement(N.getOperand(0), Parts) && 6236 isBSwapHWordElement(N.getOperand(1), Parts); 6237 6238 if (N.getOpcode() == ISD::SRL && N.getOperand(0).getOpcode() == ISD::BSWAP) { 6239 ConstantSDNode *C = isConstOrConstSplat(N.getOperand(1)); 6240 if (!C || C->getAPIntValue() != 16) 6241 return false; 6242 Parts[0] = Parts[1] = N.getOperand(0).getOperand(0).getNode(); 6243 return true; 6244 } 6245 6246 return false; 6247 } 6248 6249 // Match this pattern: 6250 // (or (and (shl (A, 8)), 0xff00ff00), (and (srl (A, 8)), 0x00ff00ff)) 6251 // And rewrite this to: 6252 // (rotr (bswap A), 16) 6253 static SDValue matchBSwapHWordOrAndAnd(const TargetLowering &TLI, 6254 SelectionDAG &DAG, SDNode *N, SDValue N0, 6255 SDValue N1, EVT VT, EVT ShiftAmountTy) { 6256 assert(N->getOpcode() == ISD::OR && VT == MVT::i32 && 6257 "MatchBSwapHWordOrAndAnd: expecting i32"); 6258 if (!TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 6259 return SDValue(); 6260 if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND) 6261 return SDValue(); 6262 // TODO: this is too restrictive; lifting this restriction requires more tests 6263 if (!N0->hasOneUse() || !N1->hasOneUse()) 6264 return SDValue(); 6265 ConstantSDNode *Mask0 = isConstOrConstSplat(N0.getOperand(1)); 6266 ConstantSDNode *Mask1 = isConstOrConstSplat(N1.getOperand(1)); 6267 if (!Mask0 || !Mask1) 6268 return SDValue(); 6269 if (Mask0->getAPIntValue() != 0xff00ff00 || 6270 Mask1->getAPIntValue() != 0x00ff00ff) 6271 return SDValue(); 6272 SDValue Shift0 = N0.getOperand(0); 6273 SDValue Shift1 = N1.getOperand(0); 6274 if (Shift0.getOpcode() != ISD::SHL || Shift1.getOpcode() != ISD::SRL) 6275 return SDValue(); 6276 ConstantSDNode *ShiftAmt0 = isConstOrConstSplat(Shift0.getOperand(1)); 6277 ConstantSDNode *ShiftAmt1 = isConstOrConstSplat(Shift1.getOperand(1)); 6278 if (!ShiftAmt0 || !ShiftAmt1) 6279 return SDValue(); 6280 if (ShiftAmt0->getAPIntValue() != 8 || ShiftAmt1->getAPIntValue() != 8) 6281 return SDValue(); 6282 if (Shift0.getOperand(0) != Shift1.getOperand(0)) 6283 return SDValue(); 6284 6285 SDLoc DL(N); 6286 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Shift0.getOperand(0)); 6287 SDValue ShAmt = DAG.getConstant(16, DL, ShiftAmountTy); 6288 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 6289 } 6290 6291 /// Match a 32-bit packed halfword bswap. That is 6292 /// ((x & 0x000000ff) << 8) | 6293 /// ((x & 0x0000ff00) >> 8) | 6294 /// ((x & 0x00ff0000) << 8) | 6295 /// ((x & 0xff000000) >> 8) 6296 /// => (rotl (bswap x), 16) 6297 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) { 6298 if (!LegalOperations) 6299 return SDValue(); 6300 6301 EVT VT = N->getValueType(0); 6302 if (VT != MVT::i32) 6303 return SDValue(); 6304 if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT)) 6305 return SDValue(); 6306 6307 if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N0, N1, VT, 6308 getShiftAmountTy(VT))) 6309 return BSwap; 6310 6311 // Try again with commuted operands. 6312 if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N1, N0, VT, 6313 getShiftAmountTy(VT))) 6314 return BSwap; 6315 6316 6317 // Look for either 6318 // (or (bswaphpair), (bswaphpair)) 6319 // (or (or (bswaphpair), (and)), (and)) 6320 // (or (or (and), (bswaphpair)), (and)) 6321 SDNode *Parts[4] = {}; 6322 6323 if (isBSwapHWordPair(N0, Parts)) { 6324 // (or (or (and), (and)), (or (and), (and))) 6325 if (!isBSwapHWordPair(N1, Parts)) 6326 return SDValue(); 6327 } else if (N0.getOpcode() == ISD::OR) { 6328 // (or (or (or (and), (and)), (and)), (and)) 6329 if (!isBSwapHWordElement(N1, Parts)) 6330 return SDValue(); 6331 SDValue N00 = N0.getOperand(0); 6332 SDValue N01 = N0.getOperand(1); 6333 if (!(isBSwapHWordElement(N01, Parts) && isBSwapHWordPair(N00, Parts)) && 6334 !(isBSwapHWordElement(N00, Parts) && isBSwapHWordPair(N01, Parts))) 6335 return SDValue(); 6336 } else 6337 return SDValue(); 6338 6339 // Make sure the parts are all coming from the same node. 6340 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3]) 6341 return SDValue(); 6342 6343 SDLoc DL(N); 6344 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, 6345 SDValue(Parts[0], 0)); 6346 6347 // Result of the bswap should be rotated by 16. If it's not legal, then 6348 // do (x << 16) | (x >> 16). 6349 SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT)); 6350 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT)) 6351 return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt); 6352 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT)) 6353 return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt); 6354 return DAG.getNode(ISD::OR, DL, VT, 6355 DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt), 6356 DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt)); 6357 } 6358 6359 /// This contains all DAGCombine rules which reduce two values combined by 6360 /// an Or operation to a single value \see visitANDLike(). 6361 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) { 6362 EVT VT = N1.getValueType(); 6363 SDLoc DL(N); 6364 6365 // fold (or x, undef) -> -1 6366 if (!LegalOperations && (N0.isUndef() || N1.isUndef())) 6367 return DAG.getAllOnesConstant(DL, VT); 6368 6369 if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL)) 6370 return V; 6371 6372 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible. 6373 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND && 6374 // Don't increase # computations. 6375 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 6376 // We can only do this xform if we know that bits from X that are set in C2 6377 // but not in C1 are already zero. Likewise for Y. 6378 if (const ConstantSDNode *N0O1C = 6379 getAsNonOpaqueConstant(N0.getOperand(1))) { 6380 if (const ConstantSDNode *N1O1C = 6381 getAsNonOpaqueConstant(N1.getOperand(1))) { 6382 // We can only do this xform if we know that bits from X that are set in 6383 // C2 but not in C1 are already zero. Likewise for Y. 6384 const APInt &LHSMask = N0O1C->getAPIntValue(); 6385 const APInt &RHSMask = N1O1C->getAPIntValue(); 6386 6387 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) && 6388 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) { 6389 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 6390 N0.getOperand(0), N1.getOperand(0)); 6391 return DAG.getNode(ISD::AND, DL, VT, X, 6392 DAG.getConstant(LHSMask | RHSMask, DL, VT)); 6393 } 6394 } 6395 } 6396 } 6397 6398 // (or (and X, M), (and X, N)) -> (and X, (or M, N)) 6399 if (N0.getOpcode() == ISD::AND && 6400 N1.getOpcode() == ISD::AND && 6401 N0.getOperand(0) == N1.getOperand(0) && 6402 // Don't increase # computations. 6403 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) { 6404 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT, 6405 N0.getOperand(1), N1.getOperand(1)); 6406 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X); 6407 } 6408 6409 return SDValue(); 6410 } 6411 6412 /// OR combines for which the commuted variant will be tried as well. 6413 static SDValue visitORCommutative( 6414 SelectionDAG &DAG, SDValue N0, SDValue N1, SDNode *N) { 6415 EVT VT = N0.getValueType(); 6416 if (N0.getOpcode() == ISD::AND) { 6417 // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y) 6418 if (isBitwiseNot(N0.getOperand(1)) && N0.getOperand(1).getOperand(0) == N1) 6419 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(0), N1); 6420 6421 // fold (or (and (xor Y, -1), X), Y) -> (or X, Y) 6422 if (isBitwiseNot(N0.getOperand(0)) && N0.getOperand(0).getOperand(0) == N1) 6423 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(1), N1); 6424 } 6425 6426 return SDValue(); 6427 } 6428 6429 SDValue DAGCombiner::visitOR(SDNode *N) { 6430 SDValue N0 = N->getOperand(0); 6431 SDValue N1 = N->getOperand(1); 6432 EVT VT = N1.getValueType(); 6433 6434 // x | x --> x 6435 if (N0 == N1) 6436 return N0; 6437 6438 // fold vector ops 6439 if (VT.isVector()) { 6440 if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N))) 6441 return FoldedVOp; 6442 6443 // fold (or x, 0) -> x, vector edition 6444 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 6445 return N1; 6446 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 6447 return N0; 6448 6449 // fold (or x, -1) -> -1, vector edition 6450 if (ISD::isConstantSplatVectorAllOnes(N0.getNode())) 6451 // do not return N0, because undef node may exist in N0 6452 return DAG.getAllOnesConstant(SDLoc(N), N0.getValueType()); 6453 if (ISD::isConstantSplatVectorAllOnes(N1.getNode())) 6454 // do not return N1, because undef node may exist in N1 6455 return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType()); 6456 6457 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask) 6458 // Do this only if the resulting shuffle is legal. 6459 if (isa<ShuffleVectorSDNode>(N0) && 6460 isa<ShuffleVectorSDNode>(N1) && 6461 // Avoid folding a node with illegal type. 6462 TLI.isTypeLegal(VT)) { 6463 bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode()); 6464 bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode()); 6465 bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 6466 bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode()); 6467 // Ensure both shuffles have a zero input. 6468 if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) { 6469 assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!"); 6470 assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!"); 6471 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0); 6472 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1); 6473 bool CanFold = true; 6474 int NumElts = VT.getVectorNumElements(); 6475 SmallVector<int, 4> Mask(NumElts); 6476 6477 for (int i = 0; i != NumElts; ++i) { 6478 int M0 = SV0->getMaskElt(i); 6479 int M1 = SV1->getMaskElt(i); 6480 6481 // Determine if either index is pointing to a zero vector. 6482 bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts)); 6483 bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts)); 6484 6485 // If one element is zero and the otherside is undef, keep undef. 6486 // This also handles the case that both are undef. 6487 if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) { 6488 Mask[i] = -1; 6489 continue; 6490 } 6491 6492 // Make sure only one of the elements is zero. 6493 if (M0Zero == M1Zero) { 6494 CanFold = false; 6495 break; 6496 } 6497 6498 assert((M0 >= 0 || M1 >= 0) && "Undef index!"); 6499 6500 // We have a zero and non-zero element. If the non-zero came from 6501 // SV0 make the index a LHS index. If it came from SV1, make it 6502 // a RHS index. We need to mod by NumElts because we don't care 6503 // which operand it came from in the original shuffles. 6504 Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts; 6505 } 6506 6507 if (CanFold) { 6508 SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0); 6509 SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0); 6510 6511 SDValue LegalShuffle = 6512 TLI.buildLegalVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS, 6513 Mask, DAG); 6514 if (LegalShuffle) 6515 return LegalShuffle; 6516 } 6517 } 6518 } 6519 } 6520 6521 // fold (or c1, c2) -> c1|c2 6522 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 6523 if (SDValue C = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, {N0, N1})) 6524 return C; 6525 6526 // canonicalize constant to RHS 6527 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 6528 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 6529 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0); 6530 6531 // fold (or x, 0) -> x 6532 if (isNullConstant(N1)) 6533 return N0; 6534 6535 // fold (or x, -1) -> -1 6536 if (isAllOnesConstant(N1)) 6537 return N1; 6538 6539 if (SDValue NewSel = foldBinOpIntoSelect(N)) 6540 return NewSel; 6541 6542 // fold (or x, c) -> c iff (x & ~c) == 0 6543 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue())) 6544 return N1; 6545 6546 if (SDValue Combined = visitORLike(N0, N1, N)) 6547 return Combined; 6548 6549 if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N)) 6550 return Combined; 6551 6552 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16) 6553 if (SDValue BSwap = MatchBSwapHWord(N, N0, N1)) 6554 return BSwap; 6555 if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1)) 6556 return BSwap; 6557 6558 // reassociate or 6559 if (SDValue ROR = reassociateOps(ISD::OR, SDLoc(N), N0, N1, N->getFlags())) 6560 return ROR; 6561 6562 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2) 6563 // iff (c1 & c2) != 0 or c1/c2 are undef. 6564 auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) { 6565 return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue()); 6566 }; 6567 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 6568 ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) { 6569 if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT, 6570 {N1, N0.getOperand(1)})) { 6571 SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1); 6572 AddToWorklist(IOR.getNode()); 6573 return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR); 6574 } 6575 } 6576 6577 if (SDValue Combined = visitORCommutative(DAG, N0, N1, N)) 6578 return Combined; 6579 if (SDValue Combined = visitORCommutative(DAG, N1, N0, N)) 6580 return Combined; 6581 6582 // Simplify: (or (op x...), (op y...)) -> (op (or x, y)) 6583 if (N0.getOpcode() == N1.getOpcode()) 6584 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) 6585 return V; 6586 6587 // See if this is some rotate idiom. 6588 if (SDValue Rot = MatchRotate(N0, N1, SDLoc(N))) 6589 return Rot; 6590 6591 if (SDValue Load = MatchLoadCombine(N)) 6592 return Load; 6593 6594 // Simplify the operands using demanded-bits information. 6595 if (SimplifyDemandedBits(SDValue(N, 0))) 6596 return SDValue(N, 0); 6597 6598 // If OR can be rewritten into ADD, try combines based on ADD. 6599 if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) && 6600 DAG.haveNoCommonBitsSet(N0, N1)) 6601 if (SDValue Combined = visitADDLike(N)) 6602 return Combined; 6603 6604 return SDValue(); 6605 } 6606 6607 static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask) { 6608 if (Op.getOpcode() == ISD::AND && 6609 DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) { 6610 Mask = Op.getOperand(1); 6611 return Op.getOperand(0); 6612 } 6613 return Op; 6614 } 6615 6616 /// Match "(X shl/srl V1) & V2" where V2 may not be present. 6617 static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift, 6618 SDValue &Mask) { 6619 Op = stripConstantMask(DAG, Op, Mask); 6620 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) { 6621 Shift = Op; 6622 return true; 6623 } 6624 return false; 6625 } 6626 6627 /// Helper function for visitOR to extract the needed side of a rotate idiom 6628 /// from a shl/srl/mul/udiv. This is meant to handle cases where 6629 /// InstCombine merged some outside op with one of the shifts from 6630 /// the rotate pattern. 6631 /// \returns An empty \c SDValue if the needed shift couldn't be extracted. 6632 /// Otherwise, returns an expansion of \p ExtractFrom based on the following 6633 /// patterns: 6634 /// 6635 /// (or (add v v) (shrl v bitwidth-1)): 6636 /// expands (add v v) -> (shl v 1) 6637 /// 6638 /// (or (mul v c0) (shrl (mul v c1) c2)): 6639 /// expands (mul v c0) -> (shl (mul v c1) c3) 6640 /// 6641 /// (or (udiv v c0) (shl (udiv v c1) c2)): 6642 /// expands (udiv v c0) -> (shrl (udiv v c1) c3) 6643 /// 6644 /// (or (shl v c0) (shrl (shl v c1) c2)): 6645 /// expands (shl v c0) -> (shl (shl v c1) c3) 6646 /// 6647 /// (or (shrl v c0) (shl (shrl v c1) c2)): 6648 /// expands (shrl v c0) -> (shrl (shrl v c1) c3) 6649 /// 6650 /// Such that in all cases, c3+c2==bitwidth(op v c1). 6651 static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift, 6652 SDValue ExtractFrom, SDValue &Mask, 6653 const SDLoc &DL) { 6654 assert(OppShift && ExtractFrom && "Empty SDValue"); 6655 assert( 6656 (OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) && 6657 "Existing shift must be valid as a rotate half"); 6658 6659 ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask); 6660 6661 // Value and Type of the shift. 6662 SDValue OppShiftLHS = OppShift.getOperand(0); 6663 EVT ShiftedVT = OppShiftLHS.getValueType(); 6664 6665 // Amount of the existing shift. 6666 ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1)); 6667 6668 // (add v v) -> (shl v 1) 6669 // TODO: Should this be a general DAG canonicalization? 6670 if (OppShift.getOpcode() == ISD::SRL && OppShiftCst && 6671 ExtractFrom.getOpcode() == ISD::ADD && 6672 ExtractFrom.getOperand(0) == ExtractFrom.getOperand(1) && 6673 ExtractFrom.getOperand(0) == OppShiftLHS && 6674 OppShiftCst->getAPIntValue() == ShiftedVT.getScalarSizeInBits() - 1) 6675 return DAG.getNode(ISD::SHL, DL, ShiftedVT, OppShiftLHS, 6676 DAG.getShiftAmountConstant(1, ShiftedVT, DL)); 6677 6678 // Preconditions: 6679 // (or (op0 v c0) (shiftl/r (op0 v c1) c2)) 6680 // 6681 // Find opcode of the needed shift to be extracted from (op0 v c0). 6682 unsigned Opcode = ISD::DELETED_NODE; 6683 bool IsMulOrDiv = false; 6684 // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift 6685 // opcode or its arithmetic (mul or udiv) variant. 6686 auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) { 6687 IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant; 6688 if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift) 6689 return false; 6690 Opcode = NeededShift; 6691 return true; 6692 }; 6693 // op0 must be either the needed shift opcode or the mul/udiv equivalent 6694 // that the needed shift can be extracted from. 6695 if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) && 6696 (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV))) 6697 return SDValue(); 6698 6699 // op0 must be the same opcode on both sides, have the same LHS argument, 6700 // and produce the same value type. 6701 if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() || 6702 OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) || 6703 ShiftedVT != ExtractFrom.getValueType()) 6704 return SDValue(); 6705 6706 // Constant mul/udiv/shift amount from the RHS of the shift's LHS op. 6707 ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1)); 6708 // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op. 6709 ConstantSDNode *ExtractFromCst = 6710 isConstOrConstSplat(ExtractFrom.getOperand(1)); 6711 // TODO: We should be able to handle non-uniform constant vectors for these values 6712 // Check that we have constant values. 6713 if (!OppShiftCst || !OppShiftCst->getAPIntValue() || 6714 !OppLHSCst || !OppLHSCst->getAPIntValue() || 6715 !ExtractFromCst || !ExtractFromCst->getAPIntValue()) 6716 return SDValue(); 6717 6718 // Compute the shift amount we need to extract to complete the rotate. 6719 const unsigned VTWidth = ShiftedVT.getScalarSizeInBits(); 6720 if (OppShiftCst->getAPIntValue().ugt(VTWidth)) 6721 return SDValue(); 6722 APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue(); 6723 // Normalize the bitwidth of the two mul/udiv/shift constant operands. 6724 APInt ExtractFromAmt = ExtractFromCst->getAPIntValue(); 6725 APInt OppLHSAmt = OppLHSCst->getAPIntValue(); 6726 zeroExtendToMatch(ExtractFromAmt, OppLHSAmt); 6727 6728 // Now try extract the needed shift from the ExtractFrom op and see if the 6729 // result matches up with the existing shift's LHS op. 6730 if (IsMulOrDiv) { 6731 // Op to extract from is a mul or udiv by a constant. 6732 // Check: 6733 // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0 6734 // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0 6735 const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(), 6736 NeededShiftAmt.getZExtValue()); 6737 APInt ResultAmt; 6738 APInt Rem; 6739 APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem); 6740 if (Rem != 0 || ResultAmt != OppLHSAmt) 6741 return SDValue(); 6742 } else { 6743 // Op to extract from is a shift by a constant. 6744 // Check: 6745 // c2 - (bitwidth(op0 v c0) - c1) == c0 6746 if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc( 6747 ExtractFromAmt.getBitWidth())) 6748 return SDValue(); 6749 } 6750 6751 // Return the expanded shift op that should allow a rotate to be formed. 6752 EVT ShiftVT = OppShift.getOperand(1).getValueType(); 6753 EVT ResVT = ExtractFrom.getValueType(); 6754 SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT); 6755 return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode); 6756 } 6757 6758 // Return true if we can prove that, whenever Neg and Pos are both in the 6759 // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that 6760 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits: 6761 // 6762 // (or (shift1 X, Neg), (shift2 X, Pos)) 6763 // 6764 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate 6765 // in direction shift1 by Neg. The range [0, EltSize) means that we only need 6766 // to consider shift amounts with defined behavior. 6767 // 6768 // The IsRotate flag should be set when the LHS of both shifts is the same. 6769 // Otherwise if matching a general funnel shift, it should be clear. 6770 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize, 6771 SelectionDAG &DAG, bool IsRotate) { 6772 // If EltSize is a power of 2 then: 6773 // 6774 // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1) 6775 // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize). 6776 // 6777 // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check 6778 // for the stronger condition: 6779 // 6780 // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A] 6781 // 6782 // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1) 6783 // we can just replace Neg with Neg' for the rest of the function. 6784 // 6785 // In other cases we check for the even stronger condition: 6786 // 6787 // Neg == EltSize - Pos [B] 6788 // 6789 // for all Neg and Pos. Note that the (or ...) then invokes undefined 6790 // behavior if Pos == 0 (and consequently Neg == EltSize). 6791 // 6792 // We could actually use [A] whenever EltSize is a power of 2, but the 6793 // only extra cases that it would match are those uninteresting ones 6794 // where Neg and Pos are never in range at the same time. E.g. for 6795 // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos) 6796 // as well as (sub 32, Pos), but: 6797 // 6798 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos)) 6799 // 6800 // always invokes undefined behavior for 32-bit X. 6801 // 6802 // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise. 6803 // 6804 // NOTE: We can only do this when matching an AND and not a general 6805 // funnel shift. 6806 unsigned MaskLoBits = 0; 6807 if (IsRotate && Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) { 6808 if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) { 6809 KnownBits Known = DAG.computeKnownBits(Neg.getOperand(0)); 6810 unsigned Bits = Log2_64(EltSize); 6811 if (NegC->getAPIntValue().getActiveBits() <= Bits && 6812 ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) { 6813 Neg = Neg.getOperand(0); 6814 MaskLoBits = Bits; 6815 } 6816 } 6817 } 6818 6819 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1. 6820 if (Neg.getOpcode() != ISD::SUB) 6821 return false; 6822 ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0)); 6823 if (!NegC) 6824 return false; 6825 SDValue NegOp1 = Neg.getOperand(1); 6826 6827 // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with 6828 // Pos'. The truncation is redundant for the purpose of the equality. 6829 if (MaskLoBits && Pos.getOpcode() == ISD::AND) { 6830 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) { 6831 KnownBits Known = DAG.computeKnownBits(Pos.getOperand(0)); 6832 if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits && 6833 ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >= 6834 MaskLoBits)) 6835 Pos = Pos.getOperand(0); 6836 } 6837 } 6838 6839 // The condition we need is now: 6840 // 6841 // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask 6842 // 6843 // If NegOp1 == Pos then we need: 6844 // 6845 // EltSize & Mask == NegC & Mask 6846 // 6847 // (because "x & Mask" is a truncation and distributes through subtraction). 6848 // 6849 // We also need to account for a potential truncation of NegOp1 if the amount 6850 // has already been legalized to a shift amount type. 6851 APInt Width; 6852 if ((Pos == NegOp1) || 6853 (NegOp1.getOpcode() == ISD::TRUNCATE && Pos == NegOp1.getOperand(0))) 6854 Width = NegC->getAPIntValue(); 6855 6856 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC. 6857 // Then the condition we want to prove becomes: 6858 // 6859 // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask 6860 // 6861 // which, again because "x & Mask" is a truncation, becomes: 6862 // 6863 // NegC & Mask == (EltSize - PosC) & Mask 6864 // EltSize & Mask == (NegC + PosC) & Mask 6865 else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) { 6866 if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) 6867 Width = PosC->getAPIntValue() + NegC->getAPIntValue(); 6868 else 6869 return false; 6870 } else 6871 return false; 6872 6873 // Now we just need to check that EltSize & Mask == Width & Mask. 6874 if (MaskLoBits) 6875 // EltSize & Mask is 0 since Mask is EltSize - 1. 6876 return Width.getLoBits(MaskLoBits) == 0; 6877 return Width == EltSize; 6878 } 6879 6880 // A subroutine of MatchRotate used once we have found an OR of two opposite 6881 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces 6882 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the 6883 // former being preferred if supported. InnerPos and InnerNeg are Pos and 6884 // Neg with outer conversions stripped away. 6885 SDValue DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos, 6886 SDValue Neg, SDValue InnerPos, 6887 SDValue InnerNeg, unsigned PosOpcode, 6888 unsigned NegOpcode, const SDLoc &DL) { 6889 // fold (or (shl x, (*ext y)), 6890 // (srl x, (*ext (sub 32, y)))) -> 6891 // (rotl x, y) or (rotr x, (sub 32, y)) 6892 // 6893 // fold (or (shl x, (*ext (sub 32, y))), 6894 // (srl x, (*ext y))) -> 6895 // (rotr x, y) or (rotl x, (sub 32, y)) 6896 EVT VT = Shifted.getValueType(); 6897 if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG, 6898 /*IsRotate*/ true)) { 6899 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 6900 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted, 6901 HasPos ? Pos : Neg); 6902 } 6903 6904 return SDValue(); 6905 } 6906 6907 // A subroutine of MatchRotate used once we have found an OR of two opposite 6908 // shifts of N0 + N1. If Neg == <operand size> - Pos then the OR reduces 6909 // to both (PosOpcode N0, N1, Pos) and (NegOpcode N0, N1, Neg), with the 6910 // former being preferred if supported. InnerPos and InnerNeg are Pos and 6911 // Neg with outer conversions stripped away. 6912 // TODO: Merge with MatchRotatePosNeg. 6913 SDValue DAGCombiner::MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, 6914 SDValue Neg, SDValue InnerPos, 6915 SDValue InnerNeg, unsigned PosOpcode, 6916 unsigned NegOpcode, const SDLoc &DL) { 6917 EVT VT = N0.getValueType(); 6918 unsigned EltBits = VT.getScalarSizeInBits(); 6919 6920 // fold (or (shl x0, (*ext y)), 6921 // (srl x1, (*ext (sub 32, y)))) -> 6922 // (fshl x0, x1, y) or (fshr x0, x1, (sub 32, y)) 6923 // 6924 // fold (or (shl x0, (*ext (sub 32, y))), 6925 // (srl x1, (*ext y))) -> 6926 // (fshr x0, x1, y) or (fshl x0, x1, (sub 32, y)) 6927 if (matchRotateSub(InnerPos, InnerNeg, EltBits, DAG, /*IsRotate*/ N0 == N1)) { 6928 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT); 6929 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, N0, N1, 6930 HasPos ? Pos : Neg); 6931 } 6932 6933 // Matching the shift+xor cases, we can't easily use the xor'd shift amount 6934 // so for now just use the PosOpcode case if its legal. 6935 // TODO: When can we use the NegOpcode case? 6936 if (PosOpcode == ISD::FSHL && isPowerOf2_32(EltBits)) { 6937 auto IsBinOpImm = [](SDValue Op, unsigned BinOpc, unsigned Imm) { 6938 if (Op.getOpcode() != BinOpc) 6939 return false; 6940 ConstantSDNode *Cst = isConstOrConstSplat(Op.getOperand(1)); 6941 return Cst && (Cst->getAPIntValue() == Imm); 6942 }; 6943 6944 // fold (or (shl x0, y), (srl (srl x1, 1), (xor y, 31))) 6945 // -> (fshl x0, x1, y) 6946 if (IsBinOpImm(N1, ISD::SRL, 1) && 6947 IsBinOpImm(InnerNeg, ISD::XOR, EltBits - 1) && 6948 InnerPos == InnerNeg.getOperand(0) && 6949 TLI.isOperationLegalOrCustom(ISD::FSHL, VT)) { 6950 return DAG.getNode(ISD::FSHL, DL, VT, N0, N1.getOperand(0), Pos); 6951 } 6952 6953 // fold (or (shl (shl x0, 1), (xor y, 31)), (srl x1, y)) 6954 // -> (fshr x0, x1, y) 6955 if (IsBinOpImm(N0, ISD::SHL, 1) && 6956 IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) && 6957 InnerNeg == InnerPos.getOperand(0) && 6958 TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) { 6959 return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg); 6960 } 6961 6962 // fold (or (shl (add x0, x0), (xor y, 31)), (srl x1, y)) 6963 // -> (fshr x0, x1, y) 6964 // TODO: Should add(x,x) -> shl(x,1) be a general DAG canonicalization? 6965 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N0.getOperand(1) && 6966 IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) && 6967 InnerNeg == InnerPos.getOperand(0) && 6968 TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) { 6969 return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg); 6970 } 6971 } 6972 6973 return SDValue(); 6974 } 6975 6976 // MatchRotate - Handle an 'or' of two operands. If this is one of the many 6977 // idioms for rotate, and if the target supports rotation instructions, generate 6978 // a rot[lr]. This also matches funnel shift patterns, similar to rotation but 6979 // with different shifted sources. 6980 SDValue DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) { 6981 EVT VT = LHS.getValueType(); 6982 6983 // The target must have at least one rotate/funnel flavor. 6984 // We still try to match rotate by constant pre-legalization. 6985 // TODO: Support pre-legalization funnel-shift by constant. 6986 bool HasROTL = hasOperation(ISD::ROTL, VT); 6987 bool HasROTR = hasOperation(ISD::ROTR, VT); 6988 bool HasFSHL = hasOperation(ISD::FSHL, VT); 6989 bool HasFSHR = hasOperation(ISD::FSHR, VT); 6990 if (LegalOperations && !HasROTL && !HasROTR && !HasFSHL && !HasFSHR) 6991 return SDValue(); 6992 6993 // Check for truncated rotate. 6994 if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE && 6995 LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) { 6996 assert(LHS.getValueType() == RHS.getValueType()); 6997 if (SDValue Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) { 6998 return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), Rot); 6999 } 7000 } 7001 7002 // Match "(X shl/srl V1) & V2" where V2 may not be present. 7003 SDValue LHSShift; // The shift. 7004 SDValue LHSMask; // AND value if any. 7005 matchRotateHalf(DAG, LHS, LHSShift, LHSMask); 7006 7007 SDValue RHSShift; // The shift. 7008 SDValue RHSMask; // AND value if any. 7009 matchRotateHalf(DAG, RHS, RHSShift, RHSMask); 7010 7011 // If neither side matched a rotate half, bail 7012 if (!LHSShift && !RHSShift) 7013 return SDValue(); 7014 7015 // InstCombine may have combined a constant shl, srl, mul, or udiv with one 7016 // side of the rotate, so try to handle that here. In all cases we need to 7017 // pass the matched shift from the opposite side to compute the opcode and 7018 // needed shift amount to extract. We still want to do this if both sides 7019 // matched a rotate half because one half may be a potential overshift that 7020 // can be broken down (ie if InstCombine merged two shl or srl ops into a 7021 // single one). 7022 7023 // Have LHS side of the rotate, try to extract the needed shift from the RHS. 7024 if (LHSShift) 7025 if (SDValue NewRHSShift = 7026 extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL)) 7027 RHSShift = NewRHSShift; 7028 // Have RHS side of the rotate, try to extract the needed shift from the LHS. 7029 if (RHSShift) 7030 if (SDValue NewLHSShift = 7031 extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL)) 7032 LHSShift = NewLHSShift; 7033 7034 // If a side is still missing, nothing else we can do. 7035 if (!RHSShift || !LHSShift) 7036 return SDValue(); 7037 7038 // At this point we've matched or extracted a shift op on each side. 7039 7040 if (LHSShift.getOpcode() == RHSShift.getOpcode()) 7041 return SDValue(); // Shifts must disagree. 7042 7043 // TODO: Support pre-legalization funnel-shift by constant. 7044 bool IsRotate = LHSShift.getOperand(0) == RHSShift.getOperand(0); 7045 if (!IsRotate && !(HasFSHL || HasFSHR)) 7046 return SDValue(); // Requires funnel shift support. 7047 7048 // Canonicalize shl to left side in a shl/srl pair. 7049 if (RHSShift.getOpcode() == ISD::SHL) { 7050 std::swap(LHS, RHS); 7051 std::swap(LHSShift, RHSShift); 7052 std::swap(LHSMask, RHSMask); 7053 } 7054 7055 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 7056 SDValue LHSShiftArg = LHSShift.getOperand(0); 7057 SDValue LHSShiftAmt = LHSShift.getOperand(1); 7058 SDValue RHSShiftArg = RHSShift.getOperand(0); 7059 SDValue RHSShiftAmt = RHSShift.getOperand(1); 7060 7061 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1) 7062 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2) 7063 // fold (or (shl x, C1), (srl y, C2)) -> (fshl x, y, C1) 7064 // fold (or (shl x, C1), (srl y, C2)) -> (fshr x, y, C2) 7065 // iff C1+C2 == EltSizeInBits 7066 auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS, 7067 ConstantSDNode *RHS) { 7068 return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits; 7069 }; 7070 if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) { 7071 SDValue Res; 7072 if (IsRotate && (HasROTL || HasROTR || !(HasFSHL || HasFSHR))) { 7073 bool UseROTL = !LegalOperations || HasROTL; 7074 Res = DAG.getNode(UseROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg, 7075 UseROTL ? LHSShiftAmt : RHSShiftAmt); 7076 } else { 7077 bool UseFSHL = !LegalOperations || HasFSHL; 7078 Res = DAG.getNode(UseFSHL ? ISD::FSHL : ISD::FSHR, DL, VT, LHSShiftArg, 7079 RHSShiftArg, UseFSHL ? LHSShiftAmt : RHSShiftAmt); 7080 } 7081 7082 // If there is an AND of either shifted operand, apply it to the result. 7083 if (LHSMask.getNode() || RHSMask.getNode()) { 7084 SDValue AllOnes = DAG.getAllOnesConstant(DL, VT); 7085 SDValue Mask = AllOnes; 7086 7087 if (LHSMask.getNode()) { 7088 SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt); 7089 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 7090 DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits)); 7091 } 7092 if (RHSMask.getNode()) { 7093 SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt); 7094 Mask = DAG.getNode(ISD::AND, DL, VT, Mask, 7095 DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits)); 7096 } 7097 7098 Res = DAG.getNode(ISD::AND, DL, VT, Res, Mask); 7099 } 7100 7101 return Res; 7102 } 7103 7104 // Even pre-legalization, we can't easily rotate/funnel-shift by a variable 7105 // shift. 7106 if (!HasROTL && !HasROTR && !HasFSHL && !HasFSHR) 7107 return SDValue(); 7108 7109 // If there is a mask here, and we have a variable shift, we can't be sure 7110 // that we're masking out the right stuff. 7111 if (LHSMask.getNode() || RHSMask.getNode()) 7112 return SDValue(); 7113 7114 // If the shift amount is sign/zext/any-extended just peel it off. 7115 SDValue LExtOp0 = LHSShiftAmt; 7116 SDValue RExtOp0 = RHSShiftAmt; 7117 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 7118 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 7119 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 7120 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) && 7121 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND || 7122 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND || 7123 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND || 7124 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) { 7125 LExtOp0 = LHSShiftAmt.getOperand(0); 7126 RExtOp0 = RHSShiftAmt.getOperand(0); 7127 } 7128 7129 if (IsRotate && (HasROTL || HasROTR)) { 7130 SDValue TryL = 7131 MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, LExtOp0, 7132 RExtOp0, ISD::ROTL, ISD::ROTR, DL); 7133 if (TryL) 7134 return TryL; 7135 7136 SDValue TryR = 7137 MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, RExtOp0, 7138 LExtOp0, ISD::ROTR, ISD::ROTL, DL); 7139 if (TryR) 7140 return TryR; 7141 } 7142 7143 SDValue TryL = 7144 MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, LHSShiftAmt, RHSShiftAmt, 7145 LExtOp0, RExtOp0, ISD::FSHL, ISD::FSHR, DL); 7146 if (TryL) 7147 return TryL; 7148 7149 SDValue TryR = 7150 MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, RHSShiftAmt, LHSShiftAmt, 7151 RExtOp0, LExtOp0, ISD::FSHR, ISD::FSHL, DL); 7152 if (TryR) 7153 return TryR; 7154 7155 return SDValue(); 7156 } 7157 7158 namespace { 7159 7160 /// Represents known origin of an individual byte in load combine pattern. The 7161 /// value of the byte is either constant zero or comes from memory. 7162 struct ByteProvider { 7163 // For constant zero providers Load is set to nullptr. For memory providers 7164 // Load represents the node which loads the byte from memory. 7165 // ByteOffset is the offset of the byte in the value produced by the load. 7166 LoadSDNode *Load = nullptr; 7167 unsigned ByteOffset = 0; 7168 7169 ByteProvider() = default; 7170 7171 static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) { 7172 return ByteProvider(Load, ByteOffset); 7173 } 7174 7175 static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); } 7176 7177 bool isConstantZero() const { return !Load; } 7178 bool isMemory() const { return Load; } 7179 7180 bool operator==(const ByteProvider &Other) const { 7181 return Other.Load == Load && Other.ByteOffset == ByteOffset; 7182 } 7183 7184 private: 7185 ByteProvider(LoadSDNode *Load, unsigned ByteOffset) 7186 : Load(Load), ByteOffset(ByteOffset) {} 7187 }; 7188 7189 } // end anonymous namespace 7190 7191 /// Recursively traverses the expression calculating the origin of the requested 7192 /// byte of the given value. Returns None if the provider can't be calculated. 7193 /// 7194 /// For all the values except the root of the expression verifies that the value 7195 /// has exactly one use and if it's not true return None. This way if the origin 7196 /// of the byte is returned it's guaranteed that the values which contribute to 7197 /// the byte are not used outside of this expression. 7198 /// 7199 /// Because the parts of the expression are not allowed to have more than one 7200 /// use this function iterates over trees, not DAGs. So it never visits the same 7201 /// node more than once. 7202 static const Optional<ByteProvider> 7203 calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth, 7204 bool Root = false) { 7205 // Typical i64 by i8 pattern requires recursion up to 8 calls depth 7206 if (Depth == 10) 7207 return None; 7208 7209 if (!Root && !Op.hasOneUse()) 7210 return None; 7211 7212 assert(Op.getValueType().isScalarInteger() && "can't handle other types"); 7213 unsigned BitWidth = Op.getValueSizeInBits(); 7214 if (BitWidth % 8 != 0) 7215 return None; 7216 unsigned ByteWidth = BitWidth / 8; 7217 assert(Index < ByteWidth && "invalid index requested"); 7218 (void) ByteWidth; 7219 7220 switch (Op.getOpcode()) { 7221 case ISD::OR: { 7222 auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1); 7223 if (!LHS) 7224 return None; 7225 auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1); 7226 if (!RHS) 7227 return None; 7228 7229 if (LHS->isConstantZero()) 7230 return RHS; 7231 if (RHS->isConstantZero()) 7232 return LHS; 7233 return None; 7234 } 7235 case ISD::SHL: { 7236 auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 7237 if (!ShiftOp) 7238 return None; 7239 7240 uint64_t BitShift = ShiftOp->getZExtValue(); 7241 if (BitShift % 8 != 0) 7242 return None; 7243 uint64_t ByteShift = BitShift / 8; 7244 7245 return Index < ByteShift 7246 ? ByteProvider::getConstantZero() 7247 : calculateByteProvider(Op->getOperand(0), Index - ByteShift, 7248 Depth + 1); 7249 } 7250 case ISD::ANY_EXTEND: 7251 case ISD::SIGN_EXTEND: 7252 case ISD::ZERO_EXTEND: { 7253 SDValue NarrowOp = Op->getOperand(0); 7254 unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits(); 7255 if (NarrowBitWidth % 8 != 0) 7256 return None; 7257 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 7258 7259 if (Index >= NarrowByteWidth) 7260 return Op.getOpcode() == ISD::ZERO_EXTEND 7261 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 7262 : None; 7263 return calculateByteProvider(NarrowOp, Index, Depth + 1); 7264 } 7265 case ISD::BSWAP: 7266 return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1, 7267 Depth + 1); 7268 case ISD::LOAD: { 7269 auto L = cast<LoadSDNode>(Op.getNode()); 7270 if (!L->isSimple() || L->isIndexed()) 7271 return None; 7272 7273 unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits(); 7274 if (NarrowBitWidth % 8 != 0) 7275 return None; 7276 uint64_t NarrowByteWidth = NarrowBitWidth / 8; 7277 7278 if (Index >= NarrowByteWidth) 7279 return L->getExtensionType() == ISD::ZEXTLOAD 7280 ? Optional<ByteProvider>(ByteProvider::getConstantZero()) 7281 : None; 7282 return ByteProvider::getMemory(L, Index); 7283 } 7284 } 7285 7286 return None; 7287 } 7288 7289 static unsigned littleEndianByteAt(unsigned BW, unsigned i) { 7290 return i; 7291 } 7292 7293 static unsigned bigEndianByteAt(unsigned BW, unsigned i) { 7294 return BW - i - 1; 7295 } 7296 7297 // Check if the bytes offsets we are looking at match with either big or 7298 // little endian value loaded. Return true for big endian, false for little 7299 // endian, and None if match failed. 7300 static Optional<bool> isBigEndian(const ArrayRef<int64_t> ByteOffsets, 7301 int64_t FirstOffset) { 7302 // The endian can be decided only when it is 2 bytes at least. 7303 unsigned Width = ByteOffsets.size(); 7304 if (Width < 2) 7305 return None; 7306 7307 bool BigEndian = true, LittleEndian = true; 7308 for (unsigned i = 0; i < Width; i++) { 7309 int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset; 7310 LittleEndian &= CurrentByteOffset == littleEndianByteAt(Width, i); 7311 BigEndian &= CurrentByteOffset == bigEndianByteAt(Width, i); 7312 if (!BigEndian && !LittleEndian) 7313 return None; 7314 } 7315 7316 assert((BigEndian != LittleEndian) && "It should be either big endian or" 7317 "little endian"); 7318 return BigEndian; 7319 } 7320 7321 static SDValue stripTruncAndExt(SDValue Value) { 7322 switch (Value.getOpcode()) { 7323 case ISD::TRUNCATE: 7324 case ISD::ZERO_EXTEND: 7325 case ISD::SIGN_EXTEND: 7326 case ISD::ANY_EXTEND: 7327 return stripTruncAndExt(Value.getOperand(0)); 7328 } 7329 return Value; 7330 } 7331 7332 /// Match a pattern where a wide type scalar value is stored by several narrow 7333 /// stores. Fold it into a single store or a BSWAP and a store if the targets 7334 /// supports it. 7335 /// 7336 /// Assuming little endian target: 7337 /// i8 *p = ... 7338 /// i32 val = ... 7339 /// p[0] = (val >> 0) & 0xFF; 7340 /// p[1] = (val >> 8) & 0xFF; 7341 /// p[2] = (val >> 16) & 0xFF; 7342 /// p[3] = (val >> 24) & 0xFF; 7343 /// => 7344 /// *((i32)p) = val; 7345 /// 7346 /// i8 *p = ... 7347 /// i32 val = ... 7348 /// p[0] = (val >> 24) & 0xFF; 7349 /// p[1] = (val >> 16) & 0xFF; 7350 /// p[2] = (val >> 8) & 0xFF; 7351 /// p[3] = (val >> 0) & 0xFF; 7352 /// => 7353 /// *((i32)p) = BSWAP(val); 7354 SDValue DAGCombiner::mergeTruncStores(StoreSDNode *N) { 7355 // The matching looks for "store (trunc x)" patterns that appear early but are 7356 // likely to be replaced by truncating store nodes during combining. 7357 // TODO: If there is evidence that running this later would help, this 7358 // limitation could be removed. Legality checks may need to be added 7359 // for the created store and optional bswap/rotate. 7360 if (LegalOperations || OptLevel == CodeGenOpt::None) 7361 return SDValue(); 7362 7363 // We only handle merging simple stores of 1-4 bytes. 7364 // TODO: Allow unordered atomics when wider type is legal (see D66309) 7365 EVT MemVT = N->getMemoryVT(); 7366 if (!(MemVT == MVT::i8 || MemVT == MVT::i16 || MemVT == MVT::i32) || 7367 !N->isSimple() || N->isIndexed()) 7368 return SDValue(); 7369 7370 // Collect all of the stores in the chain. 7371 SDValue Chain = N->getChain(); 7372 SmallVector<StoreSDNode *, 8> Stores = {N}; 7373 while (auto *Store = dyn_cast<StoreSDNode>(Chain)) { 7374 // All stores must be the same size to ensure that we are writing all of the 7375 // bytes in the wide value. 7376 // TODO: We could allow multiple sizes by tracking each stored byte. 7377 if (Store->getMemoryVT() != MemVT || !Store->isSimple() || 7378 Store->isIndexed()) 7379 return SDValue(); 7380 Stores.push_back(Store); 7381 Chain = Store->getChain(); 7382 } 7383 // There is no reason to continue if we do not have at least a pair of stores. 7384 if (Stores.size() < 2) 7385 return SDValue(); 7386 7387 // Handle simple types only. 7388 LLVMContext &Context = *DAG.getContext(); 7389 unsigned NumStores = Stores.size(); 7390 unsigned NarrowNumBits = N->getMemoryVT().getScalarSizeInBits(); 7391 unsigned WideNumBits = NumStores * NarrowNumBits; 7392 EVT WideVT = EVT::getIntegerVT(Context, WideNumBits); 7393 if (WideVT != MVT::i16 && WideVT != MVT::i32 && WideVT != MVT::i64) 7394 return SDValue(); 7395 7396 // Check if all bytes of the source value that we are looking at are stored 7397 // to the same base address. Collect offsets from Base address into OffsetMap. 7398 SDValue SourceValue; 7399 SmallVector<int64_t, 8> OffsetMap(NumStores, INT64_MAX); 7400 int64_t FirstOffset = INT64_MAX; 7401 StoreSDNode *FirstStore = nullptr; 7402 Optional<BaseIndexOffset> Base; 7403 for (auto Store : Stores) { 7404 // All the stores store different parts of the CombinedValue. A truncate is 7405 // required to get the partial value. 7406 SDValue Trunc = Store->getValue(); 7407 if (Trunc.getOpcode() != ISD::TRUNCATE) 7408 return SDValue(); 7409 // Other than the first/last part, a shift operation is required to get the 7410 // offset. 7411 int64_t Offset = 0; 7412 SDValue WideVal = Trunc.getOperand(0); 7413 if ((WideVal.getOpcode() == ISD::SRL || WideVal.getOpcode() == ISD::SRA) && 7414 isa<ConstantSDNode>(WideVal.getOperand(1))) { 7415 // The shift amount must be a constant multiple of the narrow type. 7416 // It is translated to the offset address in the wide source value "y". 7417 // 7418 // x = srl y, ShiftAmtC 7419 // i8 z = trunc x 7420 // store z, ... 7421 uint64_t ShiftAmtC = WideVal.getConstantOperandVal(1); 7422 if (ShiftAmtC % NarrowNumBits != 0) 7423 return SDValue(); 7424 7425 Offset = ShiftAmtC / NarrowNumBits; 7426 WideVal = WideVal.getOperand(0); 7427 } 7428 7429 // Stores must share the same source value with different offsets. 7430 // Truncate and extends should be stripped to get the single source value. 7431 if (!SourceValue) 7432 SourceValue = WideVal; 7433 else if (stripTruncAndExt(SourceValue) != stripTruncAndExt(WideVal)) 7434 return SDValue(); 7435 else if (SourceValue.getValueType() != WideVT) { 7436 if (WideVal.getValueType() == WideVT || 7437 WideVal.getScalarValueSizeInBits() > 7438 SourceValue.getScalarValueSizeInBits()) 7439 SourceValue = WideVal; 7440 // Give up if the source value type is smaller than the store size. 7441 if (SourceValue.getScalarValueSizeInBits() < WideVT.getScalarSizeInBits()) 7442 return SDValue(); 7443 } 7444 7445 // Stores must share the same base address. 7446 BaseIndexOffset Ptr = BaseIndexOffset::match(Store, DAG); 7447 int64_t ByteOffsetFromBase = 0; 7448 if (!Base) 7449 Base = Ptr; 7450 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 7451 return SDValue(); 7452 7453 // Remember the first store. 7454 if (ByteOffsetFromBase < FirstOffset) { 7455 FirstStore = Store; 7456 FirstOffset = ByteOffsetFromBase; 7457 } 7458 // Map the offset in the store and the offset in the combined value, and 7459 // early return if it has been set before. 7460 if (Offset < 0 || Offset >= NumStores || OffsetMap[Offset] != INT64_MAX) 7461 return SDValue(); 7462 OffsetMap[Offset] = ByteOffsetFromBase; 7463 } 7464 7465 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 7466 assert(FirstStore && "First store must be set"); 7467 7468 // Check that a store of the wide type is both allowed and fast on the target 7469 const DataLayout &Layout = DAG.getDataLayout(); 7470 bool Fast = false; 7471 bool Allowed = TLI.allowsMemoryAccess(Context, Layout, WideVT, 7472 *FirstStore->getMemOperand(), &Fast); 7473 if (!Allowed || !Fast) 7474 return SDValue(); 7475 7476 // Check if the pieces of the value are going to the expected places in memory 7477 // to merge the stores. 7478 auto checkOffsets = [&](bool MatchLittleEndian) { 7479 if (MatchLittleEndian) { 7480 for (unsigned i = 0; i != NumStores; ++i) 7481 if (OffsetMap[i] != i * (NarrowNumBits / 8) + FirstOffset) 7482 return false; 7483 } else { // MatchBigEndian by reversing loop counter. 7484 for (unsigned i = 0, j = NumStores - 1; i != NumStores; ++i, --j) 7485 if (OffsetMap[j] != i * (NarrowNumBits / 8) + FirstOffset) 7486 return false; 7487 } 7488 return true; 7489 }; 7490 7491 // Check if the offsets line up for the native data layout of this target. 7492 bool NeedBswap = false; 7493 bool NeedRotate = false; 7494 if (!checkOffsets(Layout.isLittleEndian())) { 7495 // Special-case: check if byte offsets line up for the opposite endian. 7496 if (NarrowNumBits == 8 && checkOffsets(Layout.isBigEndian())) 7497 NeedBswap = true; 7498 else if (NumStores == 2 && checkOffsets(Layout.isBigEndian())) 7499 NeedRotate = true; 7500 else 7501 return SDValue(); 7502 } 7503 7504 SDLoc DL(N); 7505 if (WideVT != SourceValue.getValueType()) { 7506 assert(SourceValue.getValueType().getScalarSizeInBits() > WideNumBits && 7507 "Unexpected store value to merge"); 7508 SourceValue = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SourceValue); 7509 } 7510 7511 // Before legalize we can introduce illegal bswaps/rotates which will be later 7512 // converted to an explicit bswap sequence. This way we end up with a single 7513 // store and byte shuffling instead of several stores and byte shuffling. 7514 if (NeedBswap) { 7515 SourceValue = DAG.getNode(ISD::BSWAP, DL, WideVT, SourceValue); 7516 } else if (NeedRotate) { 7517 assert(WideNumBits % 2 == 0 && "Unexpected type for rotate"); 7518 SDValue RotAmt = DAG.getConstant(WideNumBits / 2, DL, WideVT); 7519 SourceValue = DAG.getNode(ISD::ROTR, DL, WideVT, SourceValue, RotAmt); 7520 } 7521 7522 SDValue NewStore = 7523 DAG.getStore(Chain, DL, SourceValue, FirstStore->getBasePtr(), 7524 FirstStore->getPointerInfo(), FirstStore->getAlign()); 7525 7526 // Rely on other DAG combine rules to remove the other individual stores. 7527 DAG.ReplaceAllUsesWith(N, NewStore.getNode()); 7528 return NewStore; 7529 } 7530 7531 /// Match a pattern where a wide type scalar value is loaded by several narrow 7532 /// loads and combined by shifts and ors. Fold it into a single load or a load 7533 /// and a BSWAP if the targets supports it. 7534 /// 7535 /// Assuming little endian target: 7536 /// i8 *a = ... 7537 /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24) 7538 /// => 7539 /// i32 val = *((i32)a) 7540 /// 7541 /// i8 *a = ... 7542 /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3] 7543 /// => 7544 /// i32 val = BSWAP(*((i32)a)) 7545 /// 7546 /// TODO: This rule matches complex patterns with OR node roots and doesn't 7547 /// interact well with the worklist mechanism. When a part of the pattern is 7548 /// updated (e.g. one of the loads) its direct users are put into the worklist, 7549 /// but the root node of the pattern which triggers the load combine is not 7550 /// necessarily a direct user of the changed node. For example, once the address 7551 /// of t28 load is reassociated load combine won't be triggered: 7552 /// t25: i32 = add t4, Constant:i32<2> 7553 /// t26: i64 = sign_extend t25 7554 /// t27: i64 = add t2, t26 7555 /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64 7556 /// t29: i32 = zero_extend t28 7557 /// t32: i32 = shl t29, Constant:i8<8> 7558 /// t33: i32 = or t23, t32 7559 /// As a possible fix visitLoad can check if the load can be a part of a load 7560 /// combine pattern and add corresponding OR roots to the worklist. 7561 SDValue DAGCombiner::MatchLoadCombine(SDNode *N) { 7562 assert(N->getOpcode() == ISD::OR && 7563 "Can only match load combining against OR nodes"); 7564 7565 // Handles simple types only 7566 EVT VT = N->getValueType(0); 7567 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64) 7568 return SDValue(); 7569 unsigned ByteWidth = VT.getSizeInBits() / 8; 7570 7571 bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian(); 7572 auto MemoryByteOffset = [&] (ByteProvider P) { 7573 assert(P.isMemory() && "Must be a memory byte provider"); 7574 unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits(); 7575 assert(LoadBitWidth % 8 == 0 && 7576 "can only analyze providers for individual bytes not bit"); 7577 unsigned LoadByteWidth = LoadBitWidth / 8; 7578 return IsBigEndianTarget 7579 ? bigEndianByteAt(LoadByteWidth, P.ByteOffset) 7580 : littleEndianByteAt(LoadByteWidth, P.ByteOffset); 7581 }; 7582 7583 Optional<BaseIndexOffset> Base; 7584 SDValue Chain; 7585 7586 SmallPtrSet<LoadSDNode *, 8> Loads; 7587 Optional<ByteProvider> FirstByteProvider; 7588 int64_t FirstOffset = INT64_MAX; 7589 7590 // Check if all the bytes of the OR we are looking at are loaded from the same 7591 // base address. Collect bytes offsets from Base address in ByteOffsets. 7592 SmallVector<int64_t, 8> ByteOffsets(ByteWidth); 7593 unsigned ZeroExtendedBytes = 0; 7594 for (int i = ByteWidth - 1; i >= 0; --i) { 7595 auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true); 7596 if (!P) 7597 return SDValue(); 7598 7599 if (P->isConstantZero()) { 7600 // It's OK for the N most significant bytes to be 0, we can just 7601 // zero-extend the load. 7602 if (++ZeroExtendedBytes != (ByteWidth - static_cast<unsigned>(i))) 7603 return SDValue(); 7604 continue; 7605 } 7606 assert(P->isMemory() && "provenance should either be memory or zero"); 7607 7608 LoadSDNode *L = P->Load; 7609 assert(L->hasNUsesOfValue(1, 0) && L->isSimple() && 7610 !L->isIndexed() && 7611 "Must be enforced by calculateByteProvider"); 7612 assert(L->getOffset().isUndef() && "Unindexed load must have undef offset"); 7613 7614 // All loads must share the same chain 7615 SDValue LChain = L->getChain(); 7616 if (!Chain) 7617 Chain = LChain; 7618 else if (Chain != LChain) 7619 return SDValue(); 7620 7621 // Loads must share the same base address 7622 BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG); 7623 int64_t ByteOffsetFromBase = 0; 7624 if (!Base) 7625 Base = Ptr; 7626 else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase)) 7627 return SDValue(); 7628 7629 // Calculate the offset of the current byte from the base address 7630 ByteOffsetFromBase += MemoryByteOffset(*P); 7631 ByteOffsets[i] = ByteOffsetFromBase; 7632 7633 // Remember the first byte load 7634 if (ByteOffsetFromBase < FirstOffset) { 7635 FirstByteProvider = P; 7636 FirstOffset = ByteOffsetFromBase; 7637 } 7638 7639 Loads.insert(L); 7640 } 7641 assert(!Loads.empty() && "All the bytes of the value must be loaded from " 7642 "memory, so there must be at least one load which produces the value"); 7643 assert(Base && "Base address of the accessed memory location must be set"); 7644 assert(FirstOffset != INT64_MAX && "First byte offset must be set"); 7645 7646 bool NeedsZext = ZeroExtendedBytes > 0; 7647 7648 EVT MemVT = 7649 EVT::getIntegerVT(*DAG.getContext(), (ByteWidth - ZeroExtendedBytes) * 8); 7650 7651 if (!MemVT.isSimple()) 7652 return SDValue(); 7653 7654 // Before legalize we can introduce too wide illegal loads which will be later 7655 // split into legal sized loads. This enables us to combine i64 load by i8 7656 // patterns to a couple of i32 loads on 32 bit targets. 7657 if (LegalOperations && 7658 !TLI.isOperationLegal(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, 7659 MemVT)) 7660 return SDValue(); 7661 7662 // Check if the bytes of the OR we are looking at match with either big or 7663 // little endian value load 7664 Optional<bool> IsBigEndian = isBigEndian( 7665 makeArrayRef(ByteOffsets).drop_back(ZeroExtendedBytes), FirstOffset); 7666 if (!IsBigEndian.hasValue()) 7667 return SDValue(); 7668 7669 assert(FirstByteProvider && "must be set"); 7670 7671 // Ensure that the first byte is loaded from zero offset of the first load. 7672 // So the combined value can be loaded from the first load address. 7673 if (MemoryByteOffset(*FirstByteProvider) != 0) 7674 return SDValue(); 7675 LoadSDNode *FirstLoad = FirstByteProvider->Load; 7676 7677 // The node we are looking at matches with the pattern, check if we can 7678 // replace it with a single (possibly zero-extended) load and bswap + shift if 7679 // needed. 7680 7681 // If the load needs byte swap check if the target supports it 7682 bool NeedsBswap = IsBigEndianTarget != *IsBigEndian; 7683 7684 // Before legalize we can introduce illegal bswaps which will be later 7685 // converted to an explicit bswap sequence. This way we end up with a single 7686 // load and byte shuffling instead of several loads and byte shuffling. 7687 // We do not introduce illegal bswaps when zero-extending as this tends to 7688 // introduce too many arithmetic instructions. 7689 if (NeedsBswap && (LegalOperations || NeedsZext) && 7690 !TLI.isOperationLegal(ISD::BSWAP, VT)) 7691 return SDValue(); 7692 7693 // If we need to bswap and zero extend, we have to insert a shift. Check that 7694 // it is legal. 7695 if (NeedsBswap && NeedsZext && LegalOperations && 7696 !TLI.isOperationLegal(ISD::SHL, VT)) 7697 return SDValue(); 7698 7699 // Check that a load of the wide type is both allowed and fast on the target 7700 bool Fast = false; 7701 bool Allowed = 7702 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 7703 *FirstLoad->getMemOperand(), &Fast); 7704 if (!Allowed || !Fast) 7705 return SDValue(); 7706 7707 SDValue NewLoad = 7708 DAG.getExtLoad(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, SDLoc(N), VT, 7709 Chain, FirstLoad->getBasePtr(), 7710 FirstLoad->getPointerInfo(), MemVT, FirstLoad->getAlign()); 7711 7712 // Transfer chain users from old loads to the new load. 7713 for (LoadSDNode *L : Loads) 7714 DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1)); 7715 7716 if (!NeedsBswap) 7717 return NewLoad; 7718 7719 SDValue ShiftedLoad = 7720 NeedsZext 7721 ? DAG.getNode(ISD::SHL, SDLoc(N), VT, NewLoad, 7722 DAG.getShiftAmountConstant(ZeroExtendedBytes * 8, VT, 7723 SDLoc(N), LegalOperations)) 7724 : NewLoad; 7725 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, ShiftedLoad); 7726 } 7727 7728 // If the target has andn, bsl, or a similar bit-select instruction, 7729 // we want to unfold masked merge, with canonical pattern of: 7730 // | A | |B| 7731 // ((x ^ y) & m) ^ y 7732 // | D | 7733 // Into: 7734 // (x & m) | (y & ~m) 7735 // If y is a constant, m is not a 'not', and the 'andn' does not work with 7736 // immediates, we unfold into a different pattern: 7737 // ~(~x & m) & (m | y) 7738 // If x is a constant, m is a 'not', and the 'andn' does not work with 7739 // immediates, we unfold into a different pattern: 7740 // (x | ~m) & ~(~m & ~y) 7741 // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at 7742 // the very least that breaks andnpd / andnps patterns, and because those 7743 // patterns are simplified in IR and shouldn't be created in the DAG 7744 SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) { 7745 assert(N->getOpcode() == ISD::XOR); 7746 7747 // Don't touch 'not' (i.e. where y = -1). 7748 if (isAllOnesOrAllOnesSplat(N->getOperand(1))) 7749 return SDValue(); 7750 7751 EVT VT = N->getValueType(0); 7752 7753 // There are 3 commutable operators in the pattern, 7754 // so we have to deal with 8 possible variants of the basic pattern. 7755 SDValue X, Y, M; 7756 auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) { 7757 if (And.getOpcode() != ISD::AND || !And.hasOneUse()) 7758 return false; 7759 SDValue Xor = And.getOperand(XorIdx); 7760 if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse()) 7761 return false; 7762 SDValue Xor0 = Xor.getOperand(0); 7763 SDValue Xor1 = Xor.getOperand(1); 7764 // Don't touch 'not' (i.e. where y = -1). 7765 if (isAllOnesOrAllOnesSplat(Xor1)) 7766 return false; 7767 if (Other == Xor0) 7768 std::swap(Xor0, Xor1); 7769 if (Other != Xor1) 7770 return false; 7771 X = Xor0; 7772 Y = Xor1; 7773 M = And.getOperand(XorIdx ? 0 : 1); 7774 return true; 7775 }; 7776 7777 SDValue N0 = N->getOperand(0); 7778 SDValue N1 = N->getOperand(1); 7779 if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) && 7780 !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0)) 7781 return SDValue(); 7782 7783 // Don't do anything if the mask is constant. This should not be reachable. 7784 // InstCombine should have already unfolded this pattern, and DAGCombiner 7785 // probably shouldn't produce it, too. 7786 if (isa<ConstantSDNode>(M.getNode())) 7787 return SDValue(); 7788 7789 // We can transform if the target has AndNot 7790 if (!TLI.hasAndNot(M)) 7791 return SDValue(); 7792 7793 SDLoc DL(N); 7794 7795 // If Y is a constant, check that 'andn' works with immediates. Unless M is 7796 // a bitwise not that would already allow ANDN to be used. 7797 if (!TLI.hasAndNot(Y) && !isBitwiseNot(M)) { 7798 assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable."); 7799 // If not, we need to do a bit more work to make sure andn is still used. 7800 SDValue NotX = DAG.getNOT(DL, X, VT); 7801 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M); 7802 SDValue NotLHS = DAG.getNOT(DL, LHS, VT); 7803 SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y); 7804 return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS); 7805 } 7806 7807 // If X is a constant and M is a bitwise not, check that 'andn' works with 7808 // immediates. 7809 if (!TLI.hasAndNot(X) && isBitwiseNot(M)) { 7810 assert(TLI.hasAndNot(Y) && "Only mask is a variable? Unreachable."); 7811 // If not, we need to do a bit more work to make sure andn is still used. 7812 SDValue NotM = M.getOperand(0); 7813 SDValue LHS = DAG.getNode(ISD::OR, DL, VT, X, NotM); 7814 SDValue NotY = DAG.getNOT(DL, Y, VT); 7815 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, NotM, NotY); 7816 SDValue NotRHS = DAG.getNOT(DL, RHS, VT); 7817 return DAG.getNode(ISD::AND, DL, VT, LHS, NotRHS); 7818 } 7819 7820 SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M); 7821 SDValue NotM = DAG.getNOT(DL, M, VT); 7822 SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM); 7823 7824 return DAG.getNode(ISD::OR, DL, VT, LHS, RHS); 7825 } 7826 7827 SDValue DAGCombiner::visitXOR(SDNode *N) { 7828 SDValue N0 = N->getOperand(0); 7829 SDValue N1 = N->getOperand(1); 7830 EVT VT = N0.getValueType(); 7831 SDLoc DL(N); 7832 7833 // fold vector ops 7834 if (VT.isVector()) { 7835 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL)) 7836 return FoldedVOp; 7837 7838 // fold (xor x, 0) -> x, vector edition 7839 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 7840 return N1; 7841 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) 7842 return N0; 7843 } 7844 7845 // fold (xor undef, undef) -> 0. This is a common idiom (misuse). 7846 if (N0.isUndef() && N1.isUndef()) 7847 return DAG.getConstant(0, DL, VT); 7848 7849 // fold (xor x, undef) -> undef 7850 if (N0.isUndef()) 7851 return N0; 7852 if (N1.isUndef()) 7853 return N1; 7854 7855 // fold (xor c1, c2) -> c1^c2 7856 if (SDValue C = DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, {N0, N1})) 7857 return C; 7858 7859 // canonicalize constant to RHS 7860 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 7861 !DAG.isConstantIntBuildVectorOrConstantInt(N1)) 7862 return DAG.getNode(ISD::XOR, DL, VT, N1, N0); 7863 7864 // fold (xor x, 0) -> x 7865 if (isNullConstant(N1)) 7866 return N0; 7867 7868 if (SDValue NewSel = foldBinOpIntoSelect(N)) 7869 return NewSel; 7870 7871 // reassociate xor 7872 if (SDValue RXOR = reassociateOps(ISD::XOR, DL, N0, N1, N->getFlags())) 7873 return RXOR; 7874 7875 // fold !(x cc y) -> (x !cc y) 7876 unsigned N0Opcode = N0.getOpcode(); 7877 SDValue LHS, RHS, CC; 7878 if (TLI.isConstTrueVal(N1.getNode()) && 7879 isSetCCEquivalent(N0, LHS, RHS, CC, /*MatchStrict*/true)) { 7880 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(), 7881 LHS.getValueType()); 7882 if (!LegalOperations || 7883 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) { 7884 switch (N0Opcode) { 7885 default: 7886 llvm_unreachable("Unhandled SetCC Equivalent!"); 7887 case ISD::SETCC: 7888 return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC); 7889 case ISD::SELECT_CC: 7890 return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2), 7891 N0.getOperand(3), NotCC); 7892 case ISD::STRICT_FSETCC: 7893 case ISD::STRICT_FSETCCS: { 7894 if (N0.hasOneUse()) { 7895 // FIXME Can we handle multiple uses? Could we token factor the chain 7896 // results from the new/old setcc? 7897 SDValue SetCC = 7898 DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC, 7899 N0.getOperand(0), N0Opcode == ISD::STRICT_FSETCCS); 7900 CombineTo(N, SetCC); 7901 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), SetCC.getValue(1)); 7902 recursivelyDeleteUnusedNodes(N0.getNode()); 7903 return SDValue(N, 0); // Return N so it doesn't get rechecked! 7904 } 7905 break; 7906 } 7907 } 7908 } 7909 } 7910 7911 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y))) 7912 if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() && 7913 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){ 7914 SDValue V = N0.getOperand(0); 7915 SDLoc DL0(N0); 7916 V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V, 7917 DAG.getConstant(1, DL0, V.getValueType())); 7918 AddToWorklist(V.getNode()); 7919 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V); 7920 } 7921 7922 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc 7923 if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() && 7924 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) { 7925 SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1); 7926 if (isOneUseSetCC(N01) || isOneUseSetCC(N00)) { 7927 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND; 7928 N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00 7929 N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01 7930 AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode()); 7931 return DAG.getNode(NewOpcode, DL, VT, N00, N01); 7932 } 7933 } 7934 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants 7935 if (isAllOnesConstant(N1) && N0.hasOneUse() && 7936 (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) { 7937 SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1); 7938 if (isa<ConstantSDNode>(N01) || isa<ConstantSDNode>(N00)) { 7939 unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND; 7940 N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00 7941 N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01 7942 AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode()); 7943 return DAG.getNode(NewOpcode, DL, VT, N00, N01); 7944 } 7945 } 7946 7947 // fold (not (neg x)) -> (add X, -1) 7948 // FIXME: This can be generalized to (not (sub Y, X)) -> (add X, ~Y) if 7949 // Y is a constant or the subtract has a single use. 7950 if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::SUB && 7951 isNullConstant(N0.getOperand(0))) { 7952 return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), 7953 DAG.getAllOnesConstant(DL, VT)); 7954 } 7955 7956 // fold (not (add X, -1)) -> (neg X) 7957 if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::ADD && 7958 isAllOnesOrAllOnesSplat(N0.getOperand(1))) { 7959 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 7960 N0.getOperand(0)); 7961 } 7962 7963 // fold (xor (and x, y), y) -> (and (not x), y) 7964 if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) { 7965 SDValue X = N0.getOperand(0); 7966 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT); 7967 AddToWorklist(NotX.getNode()); 7968 return DAG.getNode(ISD::AND, DL, VT, NotX, N1); 7969 } 7970 7971 if ((N0Opcode == ISD::SRL || N0Opcode == ISD::SHL) && N0.hasOneUse()) { 7972 ConstantSDNode *XorC = isConstOrConstSplat(N1); 7973 ConstantSDNode *ShiftC = isConstOrConstSplat(N0.getOperand(1)); 7974 unsigned BitWidth = VT.getScalarSizeInBits(); 7975 if (XorC && ShiftC) { 7976 // Don't crash on an oversized shift. We can not guarantee that a bogus 7977 // shift has been simplified to undef. 7978 uint64_t ShiftAmt = ShiftC->getLimitedValue(); 7979 if (ShiftAmt < BitWidth) { 7980 APInt Ones = APInt::getAllOnes(BitWidth); 7981 Ones = N0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) : Ones.lshr(ShiftAmt); 7982 if (XorC->getAPIntValue() == Ones) { 7983 // If the xor constant is a shifted -1, do a 'not' before the shift: 7984 // xor (X << ShiftC), XorC --> (not X) << ShiftC 7985 // xor (X >> ShiftC), XorC --> (not X) >> ShiftC 7986 SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT); 7987 return DAG.getNode(N0Opcode, DL, VT, Not, N0.getOperand(1)); 7988 } 7989 } 7990 } 7991 } 7992 7993 // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X) 7994 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) { 7995 SDValue A = N0Opcode == ISD::ADD ? N0 : N1; 7996 SDValue S = N0Opcode == ISD::SRA ? N0 : N1; 7997 if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) { 7998 SDValue A0 = A.getOperand(0), A1 = A.getOperand(1); 7999 SDValue S0 = S.getOperand(0); 8000 if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0)) 8001 if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1))) 8002 if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1)) 8003 return DAG.getNode(ISD::ABS, DL, VT, S0); 8004 } 8005 } 8006 8007 // fold (xor x, x) -> 0 8008 if (N0 == N1) 8009 return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations); 8010 8011 // fold (xor (shl 1, x), -1) -> (rotl ~1, x) 8012 // Here is a concrete example of this equivalence: 8013 // i16 x == 14 8014 // i16 shl == 1 << 14 == 16384 == 0b0100000000000000 8015 // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111 8016 // 8017 // => 8018 // 8019 // i16 ~1 == 0b1111111111111110 8020 // i16 rol(~1, 14) == 0b1011111111111111 8021 // 8022 // Some additional tips to help conceptualize this transform: 8023 // - Try to see the operation as placing a single zero in a value of all ones. 8024 // - There exists no value for x which would allow the result to contain zero. 8025 // - Values of x larger than the bitwidth are undefined and do not require a 8026 // consistent result. 8027 // - Pushing the zero left requires shifting one bits in from the right. 8028 // A rotate left of ~1 is a nice way of achieving the desired result. 8029 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL && 8030 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) { 8031 return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT), 8032 N0.getOperand(1)); 8033 } 8034 8035 // Simplify: xor (op x...), (op y...) -> (op (xor x, y)) 8036 if (N0Opcode == N1.getOpcode()) 8037 if (SDValue V = hoistLogicOpWithSameOpcodeHands(N)) 8038 return V; 8039 8040 // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable 8041 if (SDValue MM = unfoldMaskedMerge(N)) 8042 return MM; 8043 8044 // Simplify the expression using non-local knowledge. 8045 if (SimplifyDemandedBits(SDValue(N, 0))) 8046 return SDValue(N, 0); 8047 8048 if (SDValue Combined = combineCarryDiamond(*this, DAG, TLI, N0, N1, N)) 8049 return Combined; 8050 8051 return SDValue(); 8052 } 8053 8054 /// If we have a shift-by-constant of a bitwise logic op that itself has a 8055 /// shift-by-constant operand with identical opcode, we may be able to convert 8056 /// that into 2 independent shifts followed by the logic op. This is a 8057 /// throughput improvement. 8058 static SDValue combineShiftOfShiftedLogic(SDNode *Shift, SelectionDAG &DAG) { 8059 // Match a one-use bitwise logic op. 8060 SDValue LogicOp = Shift->getOperand(0); 8061 if (!LogicOp.hasOneUse()) 8062 return SDValue(); 8063 8064 unsigned LogicOpcode = LogicOp.getOpcode(); 8065 if (LogicOpcode != ISD::AND && LogicOpcode != ISD::OR && 8066 LogicOpcode != ISD::XOR) 8067 return SDValue(); 8068 8069 // Find a matching one-use shift by constant. 8070 unsigned ShiftOpcode = Shift->getOpcode(); 8071 SDValue C1 = Shift->getOperand(1); 8072 ConstantSDNode *C1Node = isConstOrConstSplat(C1); 8073 assert(C1Node && "Expected a shift with constant operand"); 8074 const APInt &C1Val = C1Node->getAPIntValue(); 8075 auto matchFirstShift = [&](SDValue V, SDValue &ShiftOp, 8076 const APInt *&ShiftAmtVal) { 8077 if (V.getOpcode() != ShiftOpcode || !V.hasOneUse()) 8078 return false; 8079 8080 ConstantSDNode *ShiftCNode = isConstOrConstSplat(V.getOperand(1)); 8081 if (!ShiftCNode) 8082 return false; 8083 8084 // Capture the shifted operand and shift amount value. 8085 ShiftOp = V.getOperand(0); 8086 ShiftAmtVal = &ShiftCNode->getAPIntValue(); 8087 8088 // Shift amount types do not have to match their operand type, so check that 8089 // the constants are the same width. 8090 if (ShiftAmtVal->getBitWidth() != C1Val.getBitWidth()) 8091 return false; 8092 8093 // The fold is not valid if the sum of the shift values exceeds bitwidth. 8094 if ((*ShiftAmtVal + C1Val).uge(V.getScalarValueSizeInBits())) 8095 return false; 8096 8097 return true; 8098 }; 8099 8100 // Logic ops are commutative, so check each operand for a match. 8101 SDValue X, Y; 8102 const APInt *C0Val; 8103 if (matchFirstShift(LogicOp.getOperand(0), X, C0Val)) 8104 Y = LogicOp.getOperand(1); 8105 else if (matchFirstShift(LogicOp.getOperand(1), X, C0Val)) 8106 Y = LogicOp.getOperand(0); 8107 else 8108 return SDValue(); 8109 8110 // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1) 8111 SDLoc DL(Shift); 8112 EVT VT = Shift->getValueType(0); 8113 EVT ShiftAmtVT = Shift->getOperand(1).getValueType(); 8114 SDValue ShiftSumC = DAG.getConstant(*C0Val + C1Val, DL, ShiftAmtVT); 8115 SDValue NewShift1 = DAG.getNode(ShiftOpcode, DL, VT, X, ShiftSumC); 8116 SDValue NewShift2 = DAG.getNode(ShiftOpcode, DL, VT, Y, C1); 8117 return DAG.getNode(LogicOpcode, DL, VT, NewShift1, NewShift2); 8118 } 8119 8120 /// Handle transforms common to the three shifts, when the shift amount is a 8121 /// constant. 8122 /// We are looking for: (shift being one of shl/sra/srl) 8123 /// shift (binop X, C0), C1 8124 /// And want to transform into: 8125 /// binop (shift X, C1), (shift C0, C1) 8126 SDValue DAGCombiner::visitShiftByConstant(SDNode *N) { 8127 assert(isConstOrConstSplat(N->getOperand(1)) && "Expected constant operand"); 8128 8129 // Do not turn a 'not' into a regular xor. 8130 if (isBitwiseNot(N->getOperand(0))) 8131 return SDValue(); 8132 8133 // The inner binop must be one-use, since we want to replace it. 8134 SDValue LHS = N->getOperand(0); 8135 if (!LHS.hasOneUse() || !TLI.isDesirableToCommuteWithShift(N, Level)) 8136 return SDValue(); 8137 8138 // TODO: This is limited to early combining because it may reveal regressions 8139 // otherwise. But since we just checked a target hook to see if this is 8140 // desirable, that should have filtered out cases where this interferes 8141 // with some other pattern matching. 8142 if (!LegalTypes) 8143 if (SDValue R = combineShiftOfShiftedLogic(N, DAG)) 8144 return R; 8145 8146 // We want to pull some binops through shifts, so that we have (and (shift)) 8147 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of 8148 // thing happens with address calculations, so it's important to canonicalize 8149 // it. 8150 switch (LHS.getOpcode()) { 8151 default: 8152 return SDValue(); 8153 case ISD::OR: 8154 case ISD::XOR: 8155 case ISD::AND: 8156 break; 8157 case ISD::ADD: 8158 if (N->getOpcode() != ISD::SHL) 8159 return SDValue(); // only shl(add) not sr[al](add). 8160 break; 8161 } 8162 8163 // We require the RHS of the binop to be a constant and not opaque as well. 8164 ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS.getOperand(1)); 8165 if (!BinOpCst) 8166 return SDValue(); 8167 8168 // FIXME: disable this unless the input to the binop is a shift by a constant 8169 // or is copy/select. Enable this in other cases when figure out it's exactly 8170 // profitable. 8171 SDValue BinOpLHSVal = LHS.getOperand(0); 8172 bool IsShiftByConstant = (BinOpLHSVal.getOpcode() == ISD::SHL || 8173 BinOpLHSVal.getOpcode() == ISD::SRA || 8174 BinOpLHSVal.getOpcode() == ISD::SRL) && 8175 isa<ConstantSDNode>(BinOpLHSVal.getOperand(1)); 8176 bool IsCopyOrSelect = BinOpLHSVal.getOpcode() == ISD::CopyFromReg || 8177 BinOpLHSVal.getOpcode() == ISD::SELECT; 8178 8179 if (!IsShiftByConstant && !IsCopyOrSelect) 8180 return SDValue(); 8181 8182 if (IsCopyOrSelect && N->hasOneUse()) 8183 return SDValue(); 8184 8185 // Fold the constants, shifting the binop RHS by the shift amount. 8186 SDLoc DL(N); 8187 EVT VT = N->getValueType(0); 8188 SDValue NewRHS = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(1), 8189 N->getOperand(1)); 8190 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!"); 8191 8192 SDValue NewShift = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(0), 8193 N->getOperand(1)); 8194 return DAG.getNode(LHS.getOpcode(), DL, VT, NewShift, NewRHS); 8195 } 8196 8197 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) { 8198 assert(N->getOpcode() == ISD::TRUNCATE); 8199 assert(N->getOperand(0).getOpcode() == ISD::AND); 8200 8201 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC) 8202 EVT TruncVT = N->getValueType(0); 8203 if (N->hasOneUse() && N->getOperand(0).hasOneUse() && 8204 TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) { 8205 SDValue N01 = N->getOperand(0).getOperand(1); 8206 if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) { 8207 SDLoc DL(N); 8208 SDValue N00 = N->getOperand(0).getOperand(0); 8209 SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00); 8210 SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01); 8211 AddToWorklist(Trunc00.getNode()); 8212 AddToWorklist(Trunc01.getNode()); 8213 return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01); 8214 } 8215 } 8216 8217 return SDValue(); 8218 } 8219 8220 SDValue DAGCombiner::visitRotate(SDNode *N) { 8221 SDLoc dl(N); 8222 SDValue N0 = N->getOperand(0); 8223 SDValue N1 = N->getOperand(1); 8224 EVT VT = N->getValueType(0); 8225 unsigned Bitsize = VT.getScalarSizeInBits(); 8226 8227 // fold (rot x, 0) -> x 8228 if (isNullOrNullSplat(N1)) 8229 return N0; 8230 8231 // fold (rot x, c) -> x iff (c % BitSize) == 0 8232 if (isPowerOf2_32(Bitsize) && Bitsize > 1) { 8233 APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1); 8234 if (DAG.MaskedValueIsZero(N1, ModuloMask)) 8235 return N0; 8236 } 8237 8238 // fold (rot x, c) -> (rot x, c % BitSize) 8239 bool OutOfRange = false; 8240 auto MatchOutOfRange = [Bitsize, &OutOfRange](ConstantSDNode *C) { 8241 OutOfRange |= C->getAPIntValue().uge(Bitsize); 8242 return true; 8243 }; 8244 if (ISD::matchUnaryPredicate(N1, MatchOutOfRange) && OutOfRange) { 8245 EVT AmtVT = N1.getValueType(); 8246 SDValue Bits = DAG.getConstant(Bitsize, dl, AmtVT); 8247 if (SDValue Amt = 8248 DAG.FoldConstantArithmetic(ISD::UREM, dl, AmtVT, {N1, Bits})) 8249 return DAG.getNode(N->getOpcode(), dl, VT, N0, Amt); 8250 } 8251 8252 // rot i16 X, 8 --> bswap X 8253 auto *RotAmtC = isConstOrConstSplat(N1); 8254 if (RotAmtC && RotAmtC->getAPIntValue() == 8 && 8255 VT.getScalarSizeInBits() == 16 && hasOperation(ISD::BSWAP, VT)) 8256 return DAG.getNode(ISD::BSWAP, dl, VT, N0); 8257 8258 // Simplify the operands using demanded-bits information. 8259 if (SimplifyDemandedBits(SDValue(N, 0))) 8260 return SDValue(N, 0); 8261 8262 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))). 8263 if (N1.getOpcode() == ISD::TRUNCATE && 8264 N1.getOperand(0).getOpcode() == ISD::AND) { 8265 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 8266 return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1); 8267 } 8268 8269 unsigned NextOp = N0.getOpcode(); 8270 // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize) 8271 if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) { 8272 SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1); 8273 SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)); 8274 if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) { 8275 EVT ShiftVT = C1->getValueType(0); 8276 bool SameSide = (N->getOpcode() == NextOp); 8277 unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB; 8278 if (SDValue CombinedShift = DAG.FoldConstantArithmetic( 8279 CombineOp, dl, ShiftVT, {N1, N0.getOperand(1)})) { 8280 SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT); 8281 SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic( 8282 ISD::SREM, dl, ShiftVT, {CombinedShift, BitsizeC}); 8283 return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0), 8284 CombinedShiftNorm); 8285 } 8286 } 8287 } 8288 return SDValue(); 8289 } 8290 8291 SDValue DAGCombiner::visitSHL(SDNode *N) { 8292 SDValue N0 = N->getOperand(0); 8293 SDValue N1 = N->getOperand(1); 8294 if (SDValue V = DAG.simplifyShift(N0, N1)) 8295 return V; 8296 8297 EVT VT = N0.getValueType(); 8298 EVT ShiftVT = N1.getValueType(); 8299 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 8300 8301 // fold vector ops 8302 if (VT.isVector()) { 8303 if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N))) 8304 return FoldedVOp; 8305 8306 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1); 8307 // If setcc produces all-one true value then: 8308 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV) 8309 if (N1CV && N1CV->isConstant()) { 8310 if (N0.getOpcode() == ISD::AND) { 8311 SDValue N00 = N0->getOperand(0); 8312 SDValue N01 = N0->getOperand(1); 8313 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01); 8314 8315 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC && 8316 TLI.getBooleanContents(N00.getOperand(0).getValueType()) == 8317 TargetLowering::ZeroOrNegativeOneBooleanContent) { 8318 if (SDValue C = 8319 DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N01, N1})) 8320 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C); 8321 } 8322 } 8323 } 8324 } 8325 8326 ConstantSDNode *N1C = isConstOrConstSplat(N1); 8327 8328 // fold (shl c1, c2) -> c1<<c2 8329 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N0, N1})) 8330 return C; 8331 8332 if (SDValue NewSel = foldBinOpIntoSelect(N)) 8333 return NewSel; 8334 8335 // if (shl x, c) is known to be zero, return 0 8336 if (DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits))) 8337 return DAG.getConstant(0, SDLoc(N), VT); 8338 8339 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))). 8340 if (N1.getOpcode() == ISD::TRUNCATE && 8341 N1.getOperand(0).getOpcode() == ISD::AND) { 8342 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 8343 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1); 8344 } 8345 8346 if (SimplifyDemandedBits(SDValue(N, 0))) 8347 return SDValue(N, 0); 8348 8349 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2)) 8350 if (N0.getOpcode() == ISD::SHL) { 8351 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 8352 ConstantSDNode *RHS) { 8353 APInt c1 = LHS->getAPIntValue(); 8354 APInt c2 = RHS->getAPIntValue(); 8355 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8356 return (c1 + c2).uge(OpSizeInBits); 8357 }; 8358 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 8359 return DAG.getConstant(0, SDLoc(N), VT); 8360 8361 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 8362 ConstantSDNode *RHS) { 8363 APInt c1 = LHS->getAPIntValue(); 8364 APInt c2 = RHS->getAPIntValue(); 8365 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8366 return (c1 + c2).ult(OpSizeInBits); 8367 }; 8368 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 8369 SDLoc DL(N); 8370 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 8371 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum); 8372 } 8373 } 8374 8375 // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2)) 8376 // For this to be valid, the second form must not preserve any of the bits 8377 // that are shifted out by the inner shift in the first form. This means 8378 // the outer shift size must be >= the number of bits added by the ext. 8379 // As a corollary, we don't care what kind of ext it is. 8380 if ((N0.getOpcode() == ISD::ZERO_EXTEND || 8381 N0.getOpcode() == ISD::ANY_EXTEND || 8382 N0.getOpcode() == ISD::SIGN_EXTEND) && 8383 N0.getOperand(0).getOpcode() == ISD::SHL) { 8384 SDValue N0Op0 = N0.getOperand(0); 8385 SDValue InnerShiftAmt = N0Op0.getOperand(1); 8386 EVT InnerVT = N0Op0.getValueType(); 8387 uint64_t InnerBitwidth = InnerVT.getScalarSizeInBits(); 8388 8389 auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS, 8390 ConstantSDNode *RHS) { 8391 APInt c1 = LHS->getAPIntValue(); 8392 APInt c2 = RHS->getAPIntValue(); 8393 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8394 return c2.uge(OpSizeInBits - InnerBitwidth) && 8395 (c1 + c2).uge(OpSizeInBits); 8396 }; 8397 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchOutOfRange, 8398 /*AllowUndefs*/ false, 8399 /*AllowTypeMismatch*/ true)) 8400 return DAG.getConstant(0, SDLoc(N), VT); 8401 8402 auto MatchInRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS, 8403 ConstantSDNode *RHS) { 8404 APInt c1 = LHS->getAPIntValue(); 8405 APInt c2 = RHS->getAPIntValue(); 8406 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8407 return c2.uge(OpSizeInBits - InnerBitwidth) && 8408 (c1 + c2).ult(OpSizeInBits); 8409 }; 8410 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchInRange, 8411 /*AllowUndefs*/ false, 8412 /*AllowTypeMismatch*/ true)) { 8413 SDLoc DL(N); 8414 SDValue Ext = DAG.getNode(N0.getOpcode(), DL, VT, N0Op0.getOperand(0)); 8415 SDValue Sum = DAG.getZExtOrTrunc(InnerShiftAmt, DL, ShiftVT); 8416 Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, Sum, N1); 8417 return DAG.getNode(ISD::SHL, DL, VT, Ext, Sum); 8418 } 8419 } 8420 8421 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C)) 8422 // Only fold this if the inner zext has no other uses to avoid increasing 8423 // the total number of instructions. 8424 if (N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() && 8425 N0.getOperand(0).getOpcode() == ISD::SRL) { 8426 SDValue N0Op0 = N0.getOperand(0); 8427 SDValue InnerShiftAmt = N0Op0.getOperand(1); 8428 8429 auto MatchEqual = [VT](ConstantSDNode *LHS, ConstantSDNode *RHS) { 8430 APInt c1 = LHS->getAPIntValue(); 8431 APInt c2 = RHS->getAPIntValue(); 8432 zeroExtendToMatch(c1, c2); 8433 return c1.ult(VT.getScalarSizeInBits()) && (c1 == c2); 8434 }; 8435 if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchEqual, 8436 /*AllowUndefs*/ false, 8437 /*AllowTypeMismatch*/ true)) { 8438 SDLoc DL(N); 8439 EVT InnerShiftAmtVT = N0Op0.getOperand(1).getValueType(); 8440 SDValue NewSHL = DAG.getZExtOrTrunc(N1, DL, InnerShiftAmtVT); 8441 NewSHL = DAG.getNode(ISD::SHL, DL, N0Op0.getValueType(), N0Op0, NewSHL); 8442 AddToWorklist(NewSHL.getNode()); 8443 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL); 8444 } 8445 } 8446 8447 // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2 8448 // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2 8449 // TODO - support non-uniform vector shift amounts. 8450 if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) && 8451 N0->getFlags().hasExact()) { 8452 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 8453 uint64_t C1 = N0C1->getZExtValue(); 8454 uint64_t C2 = N1C->getZExtValue(); 8455 SDLoc DL(N); 8456 if (C1 <= C2) 8457 return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 8458 DAG.getConstant(C2 - C1, DL, ShiftVT)); 8459 return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0), 8460 DAG.getConstant(C1 - C2, DL, ShiftVT)); 8461 } 8462 } 8463 8464 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or 8465 // (and (srl x, (sub c1, c2), MASK) 8466 // Only fold this if the inner shift has no other uses -- if it does, folding 8467 // this will increase the total number of instructions. 8468 // TODO - drop hasOneUse requirement if c1 == c2? 8469 // TODO - support non-uniform vector shift amounts. 8470 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() && 8471 TLI.shouldFoldConstantShiftPairToMask(N, Level)) { 8472 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) { 8473 if (N0C1->getAPIntValue().ult(OpSizeInBits)) { 8474 uint64_t c1 = N0C1->getZExtValue(); 8475 uint64_t c2 = N1C->getZExtValue(); 8476 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1); 8477 SDValue Shift; 8478 if (c2 > c1) { 8479 Mask <<= c2 - c1; 8480 SDLoc DL(N); 8481 Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), 8482 DAG.getConstant(c2 - c1, DL, ShiftVT)); 8483 } else { 8484 Mask.lshrInPlace(c1 - c2); 8485 SDLoc DL(N); 8486 Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), 8487 DAG.getConstant(c1 - c2, DL, ShiftVT)); 8488 } 8489 SDLoc DL(N0); 8490 return DAG.getNode(ISD::AND, DL, VT, Shift, 8491 DAG.getConstant(Mask, DL, VT)); 8492 } 8493 } 8494 } 8495 8496 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1)) 8497 if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) && 8498 isConstantOrConstantVector(N1, /* No Opaques */ true)) { 8499 SDLoc DL(N); 8500 SDValue AllBits = DAG.getAllOnesConstant(DL, VT); 8501 SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1); 8502 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask); 8503 } 8504 8505 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8506 // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8507 // Variant of version done on multiply, except mul by a power of 2 is turned 8508 // into a shift. 8509 if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) && 8510 N0.getNode()->hasOneUse() && 8511 isConstantOrConstantVector(N1, /* No Opaques */ true) && 8512 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) && 8513 TLI.isDesirableToCommuteWithShift(N, Level)) { 8514 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1); 8515 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 8516 AddToWorklist(Shl0.getNode()); 8517 AddToWorklist(Shl1.getNode()); 8518 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1); 8519 } 8520 8521 // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2) 8522 if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() && 8523 isConstantOrConstantVector(N1, /* No Opaques */ true) && 8524 isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) { 8525 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1); 8526 if (isConstantOrConstantVector(Shl)) 8527 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl); 8528 } 8529 8530 if (N1C && !N1C->isOpaque()) 8531 if (SDValue NewSHL = visitShiftByConstant(N)) 8532 return NewSHL; 8533 8534 // Fold (shl (vscale * C0), C1) to (vscale * (C0 << C1)). 8535 if (N0.getOpcode() == ISD::VSCALE) 8536 if (ConstantSDNode *NC1 = isConstOrConstSplat(N->getOperand(1))) { 8537 const APInt &C0 = N0.getConstantOperandAPInt(0); 8538 const APInt &C1 = NC1->getAPIntValue(); 8539 return DAG.getVScale(SDLoc(N), VT, C0 << C1); 8540 } 8541 8542 // Fold (shl step_vector(C0), C1) to (step_vector(C0 << C1)). 8543 APInt ShlVal; 8544 if (N0.getOpcode() == ISD::STEP_VECTOR) 8545 if (ISD::isConstantSplatVector(N1.getNode(), ShlVal)) { 8546 const APInt &C0 = N0.getConstantOperandAPInt(0); 8547 if (ShlVal.ult(C0.getBitWidth())) { 8548 APInt NewStep = C0 << ShlVal; 8549 return DAG.getStepVector(SDLoc(N), VT, NewStep); 8550 } 8551 } 8552 8553 return SDValue(); 8554 } 8555 8556 // Transform a right shift of a multiply into a multiply-high. 8557 // Examples: 8558 // (srl (mul (zext i32:$a to i64), (zext i32:$a to i64)), 32) -> (mulhu $a, $b) 8559 // (sra (mul (sext i32:$a to i64), (sext i32:$a to i64)), 32) -> (mulhs $a, $b) 8560 static SDValue combineShiftToMULH(SDNode *N, SelectionDAG &DAG, 8561 const TargetLowering &TLI) { 8562 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) && 8563 "SRL or SRA node is required here!"); 8564 8565 // Check the shift amount. Proceed with the transformation if the shift 8566 // amount is constant. 8567 ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1)); 8568 if (!ShiftAmtSrc) 8569 return SDValue(); 8570 8571 SDLoc DL(N); 8572 8573 // The operation feeding into the shift must be a multiply. 8574 SDValue ShiftOperand = N->getOperand(0); 8575 if (ShiftOperand.getOpcode() != ISD::MUL) 8576 return SDValue(); 8577 8578 // Both operands must be equivalent extend nodes. 8579 SDValue LeftOp = ShiftOperand.getOperand(0); 8580 SDValue RightOp = ShiftOperand.getOperand(1); 8581 8582 bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND; 8583 bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND; 8584 8585 if (!IsSignExt && !IsZeroExt) 8586 return SDValue(); 8587 8588 EVT NarrowVT = LeftOp.getOperand(0).getValueType(); 8589 unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits(); 8590 8591 SDValue MulhRightOp; 8592 if (ConstantSDNode *Constant = isConstOrConstSplat(RightOp)) { 8593 unsigned ActiveBits = IsSignExt 8594 ? Constant->getAPIntValue().getMinSignedBits() 8595 : Constant->getAPIntValue().getActiveBits(); 8596 if (ActiveBits > NarrowVTSize) 8597 return SDValue(); 8598 MulhRightOp = DAG.getConstant( 8599 Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL, 8600 NarrowVT); 8601 } else { 8602 if (LeftOp.getOpcode() != RightOp.getOpcode()) 8603 return SDValue(); 8604 // Check that the two extend nodes are the same type. 8605 if (NarrowVT != RightOp.getOperand(0).getValueType()) 8606 return SDValue(); 8607 MulhRightOp = RightOp.getOperand(0); 8608 } 8609 8610 EVT WideVT = LeftOp.getValueType(); 8611 // Proceed with the transformation if the wide types match. 8612 assert((WideVT == RightOp.getValueType()) && 8613 "Cannot have a multiply node with two different operand types."); 8614 8615 // Proceed with the transformation if the wide type is twice as large 8616 // as the narrow type. 8617 if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize) 8618 return SDValue(); 8619 8620 // Check the shift amount with the narrow type size. 8621 // Proceed with the transformation if the shift amount is the width 8622 // of the narrow type. 8623 unsigned ShiftAmt = ShiftAmtSrc->getZExtValue(); 8624 if (ShiftAmt != NarrowVTSize) 8625 return SDValue(); 8626 8627 // If the operation feeding into the MUL is a sign extend (sext), 8628 // we use mulhs. Othewise, zero extends (zext) use mulhu. 8629 unsigned MulhOpcode = IsSignExt ? ISD::MULHS : ISD::MULHU; 8630 8631 // Combine to mulh if mulh is legal/custom for the narrow type on the target. 8632 if (!TLI.isOperationLegalOrCustom(MulhOpcode, NarrowVT)) 8633 return SDValue(); 8634 8635 SDValue Result = 8636 DAG.getNode(MulhOpcode, DL, NarrowVT, LeftOp.getOperand(0), MulhRightOp); 8637 return (N->getOpcode() == ISD::SRA ? DAG.getSExtOrTrunc(Result, DL, WideVT) 8638 : DAG.getZExtOrTrunc(Result, DL, WideVT)); 8639 } 8640 8641 SDValue DAGCombiner::visitSRA(SDNode *N) { 8642 SDValue N0 = N->getOperand(0); 8643 SDValue N1 = N->getOperand(1); 8644 if (SDValue V = DAG.simplifyShift(N0, N1)) 8645 return V; 8646 8647 EVT VT = N0.getValueType(); 8648 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 8649 8650 // Arithmetic shifting an all-sign-bit value is a no-op. 8651 // fold (sra 0, x) -> 0 8652 // fold (sra -1, x) -> -1 8653 if (DAG.ComputeNumSignBits(N0) == OpSizeInBits) 8654 return N0; 8655 8656 // fold vector ops 8657 if (VT.isVector()) 8658 if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N))) 8659 return FoldedVOp; 8660 8661 ConstantSDNode *N1C = isConstOrConstSplat(N1); 8662 8663 // fold (sra c1, c2) -> (sra c1, c2) 8664 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, {N0, N1})) 8665 return C; 8666 8667 if (SDValue NewSel = foldBinOpIntoSelect(N)) 8668 return NewSel; 8669 8670 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports 8671 // sext_inreg. 8672 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) { 8673 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue(); 8674 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits); 8675 if (VT.isVector()) 8676 ExtVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, 8677 VT.getVectorElementCount()); 8678 if (!LegalOperations || 8679 TLI.getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) == 8680 TargetLowering::Legal) 8681 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, 8682 N0.getOperand(0), DAG.getValueType(ExtVT)); 8683 // Even if we can't convert to sext_inreg, we might be able to remove 8684 // this shift pair if the input is already sign extended. 8685 if (DAG.ComputeNumSignBits(N0.getOperand(0)) > N1C->getZExtValue()) 8686 return N0.getOperand(0); 8687 } 8688 8689 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2)) 8690 // clamp (add c1, c2) to max shift. 8691 if (N0.getOpcode() == ISD::SRA) { 8692 SDLoc DL(N); 8693 EVT ShiftVT = N1.getValueType(); 8694 EVT ShiftSVT = ShiftVT.getScalarType(); 8695 SmallVector<SDValue, 16> ShiftValues; 8696 8697 auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) { 8698 APInt c1 = LHS->getAPIntValue(); 8699 APInt c2 = RHS->getAPIntValue(); 8700 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8701 APInt Sum = c1 + c2; 8702 unsigned ShiftSum = 8703 Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue(); 8704 ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT)); 8705 return true; 8706 }; 8707 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) { 8708 SDValue ShiftValue; 8709 if (N1.getOpcode() == ISD::BUILD_VECTOR) 8710 ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues); 8711 else if (N1.getOpcode() == ISD::SPLAT_VECTOR) { 8712 assert(ShiftValues.size() == 1 && 8713 "Expected matchBinaryPredicate to return one element for " 8714 "SPLAT_VECTORs"); 8715 ShiftValue = DAG.getSplatVector(ShiftVT, DL, ShiftValues[0]); 8716 } else 8717 ShiftValue = ShiftValues[0]; 8718 return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue); 8719 } 8720 } 8721 8722 // fold (sra (shl X, m), (sub result_size, n)) 8723 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for 8724 // result_size - n != m. 8725 // If truncate is free for the target sext(shl) is likely to result in better 8726 // code. 8727 if (N0.getOpcode() == ISD::SHL && N1C) { 8728 // Get the two constanst of the shifts, CN0 = m, CN = n. 8729 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1)); 8730 if (N01C) { 8731 LLVMContext &Ctx = *DAG.getContext(); 8732 // Determine what the truncate's result bitsize and type would be. 8733 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue()); 8734 8735 if (VT.isVector()) 8736 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorElementCount()); 8737 8738 // Determine the residual right-shift amount. 8739 int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue(); 8740 8741 // If the shift is not a no-op (in which case this should be just a sign 8742 // extend already), the truncated to type is legal, sign_extend is legal 8743 // on that type, and the truncate to that type is both legal and free, 8744 // perform the transform. 8745 if ((ShiftAmt > 0) && 8746 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) && 8747 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) && 8748 TLI.isTruncateFree(VT, TruncVT)) { 8749 SDLoc DL(N); 8750 SDValue Amt = DAG.getConstant(ShiftAmt, DL, 8751 getShiftAmountTy(N0.getOperand(0).getValueType())); 8752 SDValue Shift = DAG.getNode(ISD::SRL, DL, VT, 8753 N0.getOperand(0), Amt); 8754 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, 8755 Shift); 8756 return DAG.getNode(ISD::SIGN_EXTEND, DL, 8757 N->getValueType(0), Trunc); 8758 } 8759 } 8760 } 8761 8762 // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper. 8763 // sra (add (shl X, N1C), AddC), N1C --> 8764 // sext (add (trunc X to (width - N1C)), AddC') 8765 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && N1C && 8766 N0.getOperand(0).getOpcode() == ISD::SHL && 8767 N0.getOperand(0).getOperand(1) == N1 && N0.getOperand(0).hasOneUse()) { 8768 if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) { 8769 SDValue Shl = N0.getOperand(0); 8770 // Determine what the truncate's type would be and ask the target if that 8771 // is a free operation. 8772 LLVMContext &Ctx = *DAG.getContext(); 8773 unsigned ShiftAmt = N1C->getZExtValue(); 8774 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - ShiftAmt); 8775 if (VT.isVector()) 8776 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorElementCount()); 8777 8778 // TODO: The simple type check probably belongs in the default hook 8779 // implementation and/or target-specific overrides (because 8780 // non-simple types likely require masking when legalized), but that 8781 // restriction may conflict with other transforms. 8782 if (TruncVT.isSimple() && isTypeLegal(TruncVT) && 8783 TLI.isTruncateFree(VT, TruncVT)) { 8784 SDLoc DL(N); 8785 SDValue Trunc = DAG.getZExtOrTrunc(Shl.getOperand(0), DL, TruncVT); 8786 SDValue ShiftC = DAG.getConstant(AddC->getAPIntValue().lshr(ShiftAmt). 8787 trunc(TruncVT.getScalarSizeInBits()), DL, TruncVT); 8788 SDValue Add = DAG.getNode(ISD::ADD, DL, TruncVT, Trunc, ShiftC); 8789 return DAG.getSExtOrTrunc(Add, DL, VT); 8790 } 8791 } 8792 } 8793 8794 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))). 8795 if (N1.getOpcode() == ISD::TRUNCATE && 8796 N1.getOperand(0).getOpcode() == ISD::AND) { 8797 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 8798 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1); 8799 } 8800 8801 // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2)) 8802 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2)) 8803 // if c1 is equal to the number of bits the trunc removes 8804 // TODO - support non-uniform vector shift amounts. 8805 if (N0.getOpcode() == ISD::TRUNCATE && 8806 (N0.getOperand(0).getOpcode() == ISD::SRL || 8807 N0.getOperand(0).getOpcode() == ISD::SRA) && 8808 N0.getOperand(0).hasOneUse() && 8809 N0.getOperand(0).getOperand(1).hasOneUse() && N1C) { 8810 SDValue N0Op0 = N0.getOperand(0); 8811 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) { 8812 EVT LargeVT = N0Op0.getValueType(); 8813 unsigned TruncBits = LargeVT.getScalarSizeInBits() - OpSizeInBits; 8814 if (LargeShift->getAPIntValue() == TruncBits) { 8815 SDLoc DL(N); 8816 SDValue Amt = DAG.getConstant(N1C->getZExtValue() + TruncBits, DL, 8817 getShiftAmountTy(LargeVT)); 8818 SDValue SRA = 8819 DAG.getNode(ISD::SRA, DL, LargeVT, N0Op0.getOperand(0), Amt); 8820 return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA); 8821 } 8822 } 8823 } 8824 8825 // Simplify, based on bits shifted out of the LHS. 8826 if (SimplifyDemandedBits(SDValue(N, 0))) 8827 return SDValue(N, 0); 8828 8829 // If the sign bit is known to be zero, switch this to a SRL. 8830 if (DAG.SignBitIsZero(N0)) 8831 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1); 8832 8833 if (N1C && !N1C->isOpaque()) 8834 if (SDValue NewSRA = visitShiftByConstant(N)) 8835 return NewSRA; 8836 8837 // Try to transform this shift into a multiply-high if 8838 // it matches the appropriate pattern detected in combineShiftToMULH. 8839 if (SDValue MULH = combineShiftToMULH(N, DAG, TLI)) 8840 return MULH; 8841 8842 return SDValue(); 8843 } 8844 8845 SDValue DAGCombiner::visitSRL(SDNode *N) { 8846 SDValue N0 = N->getOperand(0); 8847 SDValue N1 = N->getOperand(1); 8848 if (SDValue V = DAG.simplifyShift(N0, N1)) 8849 return V; 8850 8851 EVT VT = N0.getValueType(); 8852 unsigned OpSizeInBits = VT.getScalarSizeInBits(); 8853 8854 // fold vector ops 8855 if (VT.isVector()) 8856 if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N))) 8857 return FoldedVOp; 8858 8859 ConstantSDNode *N1C = isConstOrConstSplat(N1); 8860 8861 // fold (srl c1, c2) -> c1 >>u c2 8862 if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, {N0, N1})) 8863 return C; 8864 8865 if (SDValue NewSel = foldBinOpIntoSelect(N)) 8866 return NewSel; 8867 8868 // if (srl x, c) is known to be zero, return 0 8869 if (N1C && 8870 DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits))) 8871 return DAG.getConstant(0, SDLoc(N), VT); 8872 8873 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2)) 8874 if (N0.getOpcode() == ISD::SRL) { 8875 auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS, 8876 ConstantSDNode *RHS) { 8877 APInt c1 = LHS->getAPIntValue(); 8878 APInt c2 = RHS->getAPIntValue(); 8879 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8880 return (c1 + c2).uge(OpSizeInBits); 8881 }; 8882 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange)) 8883 return DAG.getConstant(0, SDLoc(N), VT); 8884 8885 auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS, 8886 ConstantSDNode *RHS) { 8887 APInt c1 = LHS->getAPIntValue(); 8888 APInt c2 = RHS->getAPIntValue(); 8889 zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */); 8890 return (c1 + c2).ult(OpSizeInBits); 8891 }; 8892 if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) { 8893 SDLoc DL(N); 8894 EVT ShiftVT = N1.getValueType(); 8895 SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1)); 8896 return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum); 8897 } 8898 } 8899 8900 if (N1C && N0.getOpcode() == ISD::TRUNCATE && 8901 N0.getOperand(0).getOpcode() == ISD::SRL) { 8902 SDValue InnerShift = N0.getOperand(0); 8903 // TODO - support non-uniform vector shift amounts. 8904 if (auto *N001C = isConstOrConstSplat(InnerShift.getOperand(1))) { 8905 uint64_t c1 = N001C->getZExtValue(); 8906 uint64_t c2 = N1C->getZExtValue(); 8907 EVT InnerShiftVT = InnerShift.getValueType(); 8908 EVT ShiftAmtVT = InnerShift.getOperand(1).getValueType(); 8909 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits(); 8910 // srl (trunc (srl x, c1)), c2 --> 0 or (trunc (srl x, (add c1, c2))) 8911 // This is only valid if the OpSizeInBits + c1 = size of inner shift. 8912 if (c1 + OpSizeInBits == InnerShiftSize) { 8913 SDLoc DL(N); 8914 if (c1 + c2 >= InnerShiftSize) 8915 return DAG.getConstant(0, DL, VT); 8916 SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT); 8917 SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT, 8918 InnerShift.getOperand(0), NewShiftAmt); 8919 return DAG.getNode(ISD::TRUNCATE, DL, VT, NewShift); 8920 } 8921 // In the more general case, we can clear the high bits after the shift: 8922 // srl (trunc (srl x, c1)), c2 --> trunc (and (srl x, (c1+c2)), Mask) 8923 if (N0.hasOneUse() && InnerShift.hasOneUse() && 8924 c1 + c2 < InnerShiftSize) { 8925 SDLoc DL(N); 8926 SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT); 8927 SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT, 8928 InnerShift.getOperand(0), NewShiftAmt); 8929 SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(InnerShiftSize, 8930 OpSizeInBits - c2), 8931 DL, InnerShiftVT); 8932 SDValue And = DAG.getNode(ISD::AND, DL, InnerShiftVT, NewShift, Mask); 8933 return DAG.getNode(ISD::TRUNCATE, DL, VT, And); 8934 } 8935 } 8936 } 8937 8938 // fold (srl (shl x, c), c) -> (and x, cst2) 8939 // TODO - (srl (shl x, c1), c2). 8940 if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 && 8941 isConstantOrConstantVector(N1, /* NoOpaques */ true)) { 8942 SDLoc DL(N); 8943 SDValue Mask = 8944 DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1); 8945 AddToWorklist(Mask.getNode()); 8946 return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask); 8947 } 8948 8949 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask) 8950 // TODO - support non-uniform vector shift amounts. 8951 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) { 8952 // Shifting in all undef bits? 8953 EVT SmallVT = N0.getOperand(0).getValueType(); 8954 unsigned BitSize = SmallVT.getScalarSizeInBits(); 8955 if (N1C->getAPIntValue().uge(BitSize)) 8956 return DAG.getUNDEF(VT); 8957 8958 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) { 8959 uint64_t ShiftAmt = N1C->getZExtValue(); 8960 SDLoc DL0(N0); 8961 SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT, 8962 N0.getOperand(0), 8963 DAG.getConstant(ShiftAmt, DL0, 8964 getShiftAmountTy(SmallVT))); 8965 AddToWorklist(SmallShift.getNode()); 8966 APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt); 8967 SDLoc DL(N); 8968 return DAG.getNode(ISD::AND, DL, VT, 8969 DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift), 8970 DAG.getConstant(Mask, DL, VT)); 8971 } 8972 } 8973 8974 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign 8975 // bit, which is unmodified by sra. 8976 if (N1C && N1C->getAPIntValue() == (OpSizeInBits - 1)) { 8977 if (N0.getOpcode() == ISD::SRA) 8978 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1); 8979 } 8980 8981 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit). 8982 if (N1C && N0.getOpcode() == ISD::CTLZ && 8983 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) { 8984 KnownBits Known = DAG.computeKnownBits(N0.getOperand(0)); 8985 8986 // If any of the input bits are KnownOne, then the input couldn't be all 8987 // zeros, thus the result of the srl will always be zero. 8988 if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT); 8989 8990 // If all of the bits input the to ctlz node are known to be zero, then 8991 // the result of the ctlz is "32" and the result of the shift is one. 8992 APInt UnknownBits = ~Known.Zero; 8993 if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT); 8994 8995 // Otherwise, check to see if there is exactly one bit input to the ctlz. 8996 if (UnknownBits.isPowerOf2()) { 8997 // Okay, we know that only that the single bit specified by UnknownBits 8998 // could be set on input to the CTLZ node. If this bit is set, the SRL 8999 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair 9000 // to an SRL/XOR pair, which is likely to simplify more. 9001 unsigned ShAmt = UnknownBits.countTrailingZeros(); 9002 SDValue Op = N0.getOperand(0); 9003 9004 if (ShAmt) { 9005 SDLoc DL(N0); 9006 Op = DAG.getNode(ISD::SRL, DL, VT, Op, 9007 DAG.getConstant(ShAmt, DL, 9008 getShiftAmountTy(Op.getValueType()))); 9009 AddToWorklist(Op.getNode()); 9010 } 9011 9012 SDLoc DL(N); 9013 return DAG.getNode(ISD::XOR, DL, VT, 9014 Op, DAG.getConstant(1, DL, VT)); 9015 } 9016 } 9017 9018 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))). 9019 if (N1.getOpcode() == ISD::TRUNCATE && 9020 N1.getOperand(0).getOpcode() == ISD::AND) { 9021 if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode())) 9022 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1); 9023 } 9024 9025 // fold operands of srl based on knowledge that the low bits are not 9026 // demanded. 9027 if (SimplifyDemandedBits(SDValue(N, 0))) 9028 return SDValue(N, 0); 9029 9030 if (N1C && !N1C->isOpaque()) 9031 if (SDValue NewSRL = visitShiftByConstant(N)) 9032 return NewSRL; 9033 9034 // Attempt to convert a srl of a load into a narrower zero-extending load. 9035 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 9036 return NarrowLoad; 9037 9038 // Here is a common situation. We want to optimize: 9039 // 9040 // %a = ... 9041 // %b = and i32 %a, 2 9042 // %c = srl i32 %b, 1 9043 // brcond i32 %c ... 9044 // 9045 // into 9046 // 9047 // %a = ... 9048 // %b = and %a, 2 9049 // %c = setcc eq %b, 0 9050 // brcond %c ... 9051 // 9052 // However when after the source operand of SRL is optimized into AND, the SRL 9053 // itself may not be optimized further. Look for it and add the BRCOND into 9054 // the worklist. 9055 if (N->hasOneUse()) { 9056 SDNode *Use = *N->use_begin(); 9057 if (Use->getOpcode() == ISD::BRCOND) 9058 AddToWorklist(Use); 9059 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) { 9060 // Also look pass the truncate. 9061 Use = *Use->use_begin(); 9062 if (Use->getOpcode() == ISD::BRCOND) 9063 AddToWorklist(Use); 9064 } 9065 } 9066 9067 // Try to transform this shift into a multiply-high if 9068 // it matches the appropriate pattern detected in combineShiftToMULH. 9069 if (SDValue MULH = combineShiftToMULH(N, DAG, TLI)) 9070 return MULH; 9071 9072 return SDValue(); 9073 } 9074 9075 SDValue DAGCombiner::visitFunnelShift(SDNode *N) { 9076 EVT VT = N->getValueType(0); 9077 SDValue N0 = N->getOperand(0); 9078 SDValue N1 = N->getOperand(1); 9079 SDValue N2 = N->getOperand(2); 9080 bool IsFSHL = N->getOpcode() == ISD::FSHL; 9081 unsigned BitWidth = VT.getScalarSizeInBits(); 9082 9083 // fold (fshl N0, N1, 0) -> N0 9084 // fold (fshr N0, N1, 0) -> N1 9085 if (isPowerOf2_32(BitWidth)) 9086 if (DAG.MaskedValueIsZero( 9087 N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1))) 9088 return IsFSHL ? N0 : N1; 9089 9090 auto IsUndefOrZero = [](SDValue V) { 9091 return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true); 9092 }; 9093 9094 // TODO - support non-uniform vector shift amounts. 9095 if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) { 9096 EVT ShAmtTy = N2.getValueType(); 9097 9098 // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth) 9099 if (Cst->getAPIntValue().uge(BitWidth)) { 9100 uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth); 9101 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N0, N1, 9102 DAG.getConstant(RotAmt, SDLoc(N), ShAmtTy)); 9103 } 9104 9105 unsigned ShAmt = Cst->getZExtValue(); 9106 if (ShAmt == 0) 9107 return IsFSHL ? N0 : N1; 9108 9109 // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C) 9110 // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C) 9111 // fold fshl(N0, undef_or_zero, C) -> shl(N0, C) 9112 // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C) 9113 if (IsUndefOrZero(N0)) 9114 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, 9115 DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt, 9116 SDLoc(N), ShAmtTy)); 9117 if (IsUndefOrZero(N1)) 9118 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, 9119 DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt, 9120 SDLoc(N), ShAmtTy)); 9121 9122 // fold (fshl ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive. 9123 // fold (fshr ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive. 9124 // TODO - bigendian support once we have test coverage. 9125 // TODO - can we merge this with CombineConseutiveLoads/MatchLoadCombine? 9126 // TODO - permit LHS EXTLOAD if extensions are shifted out. 9127 if ((BitWidth % 8) == 0 && (ShAmt % 8) == 0 && !VT.isVector() && 9128 !DAG.getDataLayout().isBigEndian()) { 9129 auto *LHS = dyn_cast<LoadSDNode>(N0); 9130 auto *RHS = dyn_cast<LoadSDNode>(N1); 9131 if (LHS && RHS && LHS->isSimple() && RHS->isSimple() && 9132 LHS->getAddressSpace() == RHS->getAddressSpace() && 9133 (LHS->hasOneUse() || RHS->hasOneUse()) && ISD::isNON_EXTLoad(RHS) && 9134 ISD::isNON_EXTLoad(LHS)) { 9135 if (DAG.areNonVolatileConsecutiveLoads(LHS, RHS, BitWidth / 8, 1)) { 9136 SDLoc DL(RHS); 9137 uint64_t PtrOff = 9138 IsFSHL ? (((BitWidth - ShAmt) % BitWidth) / 8) : (ShAmt / 8); 9139 Align NewAlign = commonAlignment(RHS->getAlign(), PtrOff); 9140 bool Fast = false; 9141 if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 9142 RHS->getAddressSpace(), NewAlign, 9143 RHS->getMemOperand()->getFlags(), &Fast) && 9144 Fast) { 9145 SDValue NewPtr = DAG.getMemBasePlusOffset( 9146 RHS->getBasePtr(), TypeSize::Fixed(PtrOff), DL); 9147 AddToWorklist(NewPtr.getNode()); 9148 SDValue Load = DAG.getLoad( 9149 VT, DL, RHS->getChain(), NewPtr, 9150 RHS->getPointerInfo().getWithOffset(PtrOff), NewAlign, 9151 RHS->getMemOperand()->getFlags(), RHS->getAAInfo()); 9152 // Replace the old load's chain with the new load's chain. 9153 WorklistRemover DeadNodes(*this); 9154 DAG.ReplaceAllUsesOfValueWith(N1.getValue(1), Load.getValue(1)); 9155 return Load; 9156 } 9157 } 9158 } 9159 } 9160 } 9161 9162 // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2) 9163 // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2) 9164 // iff We know the shift amount is in range. 9165 // TODO: when is it worth doing SUB(BW, N2) as well? 9166 if (isPowerOf2_32(BitWidth)) { 9167 APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1); 9168 if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits)) 9169 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, N2); 9170 if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits)) 9171 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N2); 9172 } 9173 9174 // fold (fshl N0, N0, N2) -> (rotl N0, N2) 9175 // fold (fshr N0, N0, N2) -> (rotr N0, N2) 9176 // TODO: Investigate flipping this rotate if only one is legal, if funnel shift 9177 // is legal as well we might be better off avoiding non-constant (BW - N2). 9178 unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR; 9179 if (N0 == N1 && hasOperation(RotOpc, VT)) 9180 return DAG.getNode(RotOpc, SDLoc(N), VT, N0, N2); 9181 9182 // Simplify, based on bits shifted out of N0/N1. 9183 if (SimplifyDemandedBits(SDValue(N, 0))) 9184 return SDValue(N, 0); 9185 9186 return SDValue(); 9187 } 9188 9189 // Given a ABS node, detect the following pattern: 9190 // (ABS (SUB (EXTEND a), (EXTEND b))). 9191 // Generates UABD/SABD instruction. 9192 static SDValue combineABSToABD(SDNode *N, SelectionDAG &DAG, 9193 const TargetLowering &TLI) { 9194 SDValue AbsOp1 = N->getOperand(0); 9195 SDValue Op0, Op1; 9196 9197 if (AbsOp1.getOpcode() != ISD::SUB) 9198 return SDValue(); 9199 9200 Op0 = AbsOp1.getOperand(0); 9201 Op1 = AbsOp1.getOperand(1); 9202 9203 unsigned Opc0 = Op0.getOpcode(); 9204 // Check if the operands of the sub are (zero|sign)-extended. 9205 if (Opc0 != Op1.getOpcode() || 9206 (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND)) 9207 return SDValue(); 9208 9209 EVT VT1 = Op0.getOperand(0).getValueType(); 9210 EVT VT2 = Op1.getOperand(0).getValueType(); 9211 // Check if the operands are of same type and valid size. 9212 unsigned ABDOpcode = (Opc0 == ISD::SIGN_EXTEND) ? ISD::ABDS : ISD::ABDU; 9213 if (VT1 != VT2 || !TLI.isOperationLegalOrCustom(ABDOpcode, VT1)) 9214 return SDValue(); 9215 9216 Op0 = Op0.getOperand(0); 9217 Op1 = Op1.getOperand(0); 9218 SDValue ABD = 9219 DAG.getNode(ABDOpcode, SDLoc(N), Op0->getValueType(0), Op0, Op1); 9220 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), ABD); 9221 } 9222 9223 SDValue DAGCombiner::visitABS(SDNode *N) { 9224 SDValue N0 = N->getOperand(0); 9225 EVT VT = N->getValueType(0); 9226 9227 // fold (abs c1) -> c2 9228 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9229 return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0); 9230 // fold (abs (abs x)) -> (abs x) 9231 if (N0.getOpcode() == ISD::ABS) 9232 return N0; 9233 // fold (abs x) -> x iff not-negative 9234 if (DAG.SignBitIsZero(N0)) 9235 return N0; 9236 9237 if (SDValue ABD = combineABSToABD(N, DAG, TLI)) 9238 return ABD; 9239 9240 return SDValue(); 9241 } 9242 9243 SDValue DAGCombiner::visitBSWAP(SDNode *N) { 9244 SDValue N0 = N->getOperand(0); 9245 EVT VT = N->getValueType(0); 9246 9247 // fold (bswap c1) -> c2 9248 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9249 return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0); 9250 // fold (bswap (bswap x)) -> x 9251 if (N0.getOpcode() == ISD::BSWAP) 9252 return N0->getOperand(0); 9253 return SDValue(); 9254 } 9255 9256 SDValue DAGCombiner::visitBITREVERSE(SDNode *N) { 9257 SDValue N0 = N->getOperand(0); 9258 EVT VT = N->getValueType(0); 9259 9260 // fold (bitreverse c1) -> c2 9261 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9262 return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0); 9263 // fold (bitreverse (bitreverse x)) -> x 9264 if (N0.getOpcode() == ISD::BITREVERSE) 9265 return N0.getOperand(0); 9266 return SDValue(); 9267 } 9268 9269 SDValue DAGCombiner::visitCTLZ(SDNode *N) { 9270 SDValue N0 = N->getOperand(0); 9271 EVT VT = N->getValueType(0); 9272 9273 // fold (ctlz c1) -> c2 9274 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9275 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0); 9276 9277 // If the value is known never to be zero, switch to the undef version. 9278 if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) { 9279 if (DAG.isKnownNeverZero(N0)) 9280 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 9281 } 9282 9283 return SDValue(); 9284 } 9285 9286 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) { 9287 SDValue N0 = N->getOperand(0); 9288 EVT VT = N->getValueType(0); 9289 9290 // fold (ctlz_zero_undef c1) -> c2 9291 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9292 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0); 9293 return SDValue(); 9294 } 9295 9296 SDValue DAGCombiner::visitCTTZ(SDNode *N) { 9297 SDValue N0 = N->getOperand(0); 9298 EVT VT = N->getValueType(0); 9299 9300 // fold (cttz c1) -> c2 9301 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9302 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0); 9303 9304 // If the value is known never to be zero, switch to the undef version. 9305 if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) { 9306 if (DAG.isKnownNeverZero(N0)) 9307 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 9308 } 9309 9310 return SDValue(); 9311 } 9312 9313 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) { 9314 SDValue N0 = N->getOperand(0); 9315 EVT VT = N->getValueType(0); 9316 9317 // fold (cttz_zero_undef c1) -> c2 9318 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9319 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0); 9320 return SDValue(); 9321 } 9322 9323 SDValue DAGCombiner::visitCTPOP(SDNode *N) { 9324 SDValue N0 = N->getOperand(0); 9325 EVT VT = N->getValueType(0); 9326 9327 // fold (ctpop c1) -> c2 9328 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 9329 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0); 9330 return SDValue(); 9331 } 9332 9333 // FIXME: This should be checking for no signed zeros on individual operands, as 9334 // well as no nans. 9335 static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS, 9336 SDValue RHS, 9337 const TargetLowering &TLI) { 9338 const TargetOptions &Options = DAG.getTarget().Options; 9339 EVT VT = LHS.getValueType(); 9340 9341 return Options.NoSignedZerosFPMath && VT.isFloatingPoint() && 9342 TLI.isProfitableToCombineMinNumMaxNum(VT) && 9343 DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS); 9344 } 9345 9346 /// Generate Min/Max node 9347 static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS, 9348 SDValue RHS, SDValue True, SDValue False, 9349 ISD::CondCode CC, const TargetLowering &TLI, 9350 SelectionDAG &DAG) { 9351 if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True)) 9352 return SDValue(); 9353 9354 EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 9355 switch (CC) { 9356 case ISD::SETOLT: 9357 case ISD::SETOLE: 9358 case ISD::SETLT: 9359 case ISD::SETLE: 9360 case ISD::SETULT: 9361 case ISD::SETULE: { 9362 // Since it's known never nan to get here already, either fminnum or 9363 // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is 9364 // expanded in terms of it. 9365 unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE; 9366 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT)) 9367 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS); 9368 9369 unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM; 9370 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) 9371 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 9372 return SDValue(); 9373 } 9374 case ISD::SETOGT: 9375 case ISD::SETOGE: 9376 case ISD::SETGT: 9377 case ISD::SETGE: 9378 case ISD::SETUGT: 9379 case ISD::SETUGE: { 9380 unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE; 9381 if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT)) 9382 return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS); 9383 9384 unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM; 9385 if (TLI.isOperationLegalOrCustom(Opcode, TransformVT)) 9386 return DAG.getNode(Opcode, DL, VT, LHS, RHS); 9387 return SDValue(); 9388 } 9389 default: 9390 return SDValue(); 9391 } 9392 } 9393 9394 /// If a (v)select has a condition value that is a sign-bit test, try to smear 9395 /// the condition operand sign-bit across the value width and use it as a mask. 9396 static SDValue foldSelectOfConstantsUsingSra(SDNode *N, SelectionDAG &DAG) { 9397 SDValue Cond = N->getOperand(0); 9398 SDValue C1 = N->getOperand(1); 9399 SDValue C2 = N->getOperand(2); 9400 if (!isConstantOrConstantVector(C1) || !isConstantOrConstantVector(C2)) 9401 return SDValue(); 9402 9403 EVT VT = N->getValueType(0); 9404 if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse() || 9405 VT != Cond.getOperand(0).getValueType()) 9406 return SDValue(); 9407 9408 // The inverted-condition + commuted-select variants of these patterns are 9409 // canonicalized to these forms in IR. 9410 SDValue X = Cond.getOperand(0); 9411 SDValue CondC = Cond.getOperand(1); 9412 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 9413 if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CondC) && 9414 isAllOnesOrAllOnesSplat(C2)) { 9415 // i32 X > -1 ? C1 : -1 --> (X >>s 31) | C1 9416 SDLoc DL(N); 9417 SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT); 9418 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC); 9419 return DAG.getNode(ISD::OR, DL, VT, Sra, C1); 9420 } 9421 if (CC == ISD::SETLT && isNullOrNullSplat(CondC) && isNullOrNullSplat(C2)) { 9422 // i8 X < 0 ? C1 : 0 --> (X >>s 7) & C1 9423 SDLoc DL(N); 9424 SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT); 9425 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC); 9426 return DAG.getNode(ISD::AND, DL, VT, Sra, C1); 9427 } 9428 return SDValue(); 9429 } 9430 9431 SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) { 9432 SDValue Cond = N->getOperand(0); 9433 SDValue N1 = N->getOperand(1); 9434 SDValue N2 = N->getOperand(2); 9435 EVT VT = N->getValueType(0); 9436 EVT CondVT = Cond.getValueType(); 9437 SDLoc DL(N); 9438 9439 if (!VT.isInteger()) 9440 return SDValue(); 9441 9442 auto *C1 = dyn_cast<ConstantSDNode>(N1); 9443 auto *C2 = dyn_cast<ConstantSDNode>(N2); 9444 if (!C1 || !C2) 9445 return SDValue(); 9446 9447 // Only do this before legalization to avoid conflicting with target-specific 9448 // transforms in the other direction (create a select from a zext/sext). There 9449 // is also a target-independent combine here in DAGCombiner in the other 9450 // direction for (select Cond, -1, 0) when the condition is not i1. 9451 if (CondVT == MVT::i1 && !LegalOperations) { 9452 if (C1->isZero() && C2->isOne()) { 9453 // select Cond, 0, 1 --> zext (!Cond) 9454 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 9455 if (VT != MVT::i1) 9456 NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond); 9457 return NotCond; 9458 } 9459 if (C1->isZero() && C2->isAllOnes()) { 9460 // select Cond, 0, -1 --> sext (!Cond) 9461 SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1); 9462 if (VT != MVT::i1) 9463 NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond); 9464 return NotCond; 9465 } 9466 if (C1->isOne() && C2->isZero()) { 9467 // select Cond, 1, 0 --> zext (Cond) 9468 if (VT != MVT::i1) 9469 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 9470 return Cond; 9471 } 9472 if (C1->isAllOnes() && C2->isZero()) { 9473 // select Cond, -1, 0 --> sext (Cond) 9474 if (VT != MVT::i1) 9475 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 9476 return Cond; 9477 } 9478 9479 // Use a target hook because some targets may prefer to transform in the 9480 // other direction. 9481 if (TLI.convertSelectOfConstantsToMath(VT)) { 9482 // For any constants that differ by 1, we can transform the select into an 9483 // extend and add. 9484 const APInt &C1Val = C1->getAPIntValue(); 9485 const APInt &C2Val = C2->getAPIntValue(); 9486 if (C1Val - 1 == C2Val) { 9487 // select Cond, C1, C1-1 --> add (zext Cond), C1-1 9488 if (VT != MVT::i1) 9489 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 9490 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 9491 } 9492 if (C1Val + 1 == C2Val) { 9493 // select Cond, C1, C1+1 --> add (sext Cond), C1+1 9494 if (VT != MVT::i1) 9495 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond); 9496 return DAG.getNode(ISD::ADD, DL, VT, Cond, N2); 9497 } 9498 9499 // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2) 9500 if (C1Val.isPowerOf2() && C2Val.isZero()) { 9501 if (VT != MVT::i1) 9502 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond); 9503 SDValue ShAmtC = DAG.getConstant(C1Val.exactLogBase2(), DL, VT); 9504 return DAG.getNode(ISD::SHL, DL, VT, Cond, ShAmtC); 9505 } 9506 9507 if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG)) 9508 return V; 9509 } 9510 9511 return SDValue(); 9512 } 9513 9514 // fold (select Cond, 0, 1) -> (xor Cond, 1) 9515 // We can't do this reliably if integer based booleans have different contents 9516 // to floating point based booleans. This is because we can't tell whether we 9517 // have an integer-based boolean or a floating-point-based boolean unless we 9518 // can find the SETCC that produced it and inspect its operands. This is 9519 // fairly easy if C is the SETCC node, but it can potentially be 9520 // undiscoverable (or not reasonably discoverable). For example, it could be 9521 // in another basic block or it could require searching a complicated 9522 // expression. 9523 if (CondVT.isInteger() && 9524 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) == 9525 TargetLowering::ZeroOrOneBooleanContent && 9526 TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) == 9527 TargetLowering::ZeroOrOneBooleanContent && 9528 C1->isZero() && C2->isOne()) { 9529 SDValue NotCond = 9530 DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT)); 9531 if (VT.bitsEq(CondVT)) 9532 return NotCond; 9533 return DAG.getZExtOrTrunc(NotCond, DL, VT); 9534 } 9535 9536 return SDValue(); 9537 } 9538 9539 static SDValue foldBoolSelectToLogic(SDNode *N, SelectionDAG &DAG) { 9540 assert((N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD::VSELECT) && 9541 "Expected a (v)select"); 9542 SDValue Cond = N->getOperand(0); 9543 SDValue T = N->getOperand(1), F = N->getOperand(2); 9544 EVT VT = N->getValueType(0); 9545 if (VT != Cond.getValueType() || VT.getScalarSizeInBits() != 1) 9546 return SDValue(); 9547 9548 // select Cond, Cond, F --> or Cond, F 9549 // select Cond, 1, F --> or Cond, F 9550 if (Cond == T || isOneOrOneSplat(T, /* AllowUndefs */ true)) 9551 return DAG.getNode(ISD::OR, SDLoc(N), VT, Cond, F); 9552 9553 // select Cond, T, Cond --> and Cond, T 9554 // select Cond, T, 0 --> and Cond, T 9555 if (Cond == F || isNullOrNullSplat(F, /* AllowUndefs */ true)) 9556 return DAG.getNode(ISD::AND, SDLoc(N), VT, Cond, T); 9557 9558 // select Cond, T, 1 --> or (not Cond), T 9559 if (isOneOrOneSplat(F, /* AllowUndefs */ true)) { 9560 SDValue NotCond = DAG.getNOT(SDLoc(N), Cond, VT); 9561 return DAG.getNode(ISD::OR, SDLoc(N), VT, NotCond, T); 9562 } 9563 9564 // select Cond, 0, F --> and (not Cond), F 9565 if (isNullOrNullSplat(T, /* AllowUndefs */ true)) { 9566 SDValue NotCond = DAG.getNOT(SDLoc(N), Cond, VT); 9567 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotCond, F); 9568 } 9569 9570 return SDValue(); 9571 } 9572 9573 static SDValue foldVSelectToSignBitSplatMask(SDNode *N, SelectionDAG &DAG) { 9574 SDValue N0 = N->getOperand(0); 9575 SDValue N1 = N->getOperand(1); 9576 SDValue N2 = N->getOperand(2); 9577 EVT VT = N->getValueType(0); 9578 if (N0.getOpcode() != ISD::SETCC || !N0.hasOneUse()) 9579 return SDValue(); 9580 9581 SDValue Cond0 = N0.getOperand(0); 9582 SDValue Cond1 = N0.getOperand(1); 9583 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 9584 if (VT != Cond0.getValueType()) 9585 return SDValue(); 9586 9587 // Match a signbit check of Cond0 as "Cond0 s<0". Swap select operands if the 9588 // compare is inverted from that pattern ("Cond0 s> -1"). 9589 if (CC == ISD::SETLT && isNullOrNullSplat(Cond1)) 9590 ; // This is the pattern we are looking for. 9591 else if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(Cond1)) 9592 std::swap(N1, N2); 9593 else 9594 return SDValue(); 9595 9596 // (Cond0 s< 0) ? N1 : 0 --> (Cond0 s>> BW-1) & N1 9597 if (isNullOrNullSplat(N2)) { 9598 SDLoc DL(N); 9599 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT); 9600 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt); 9601 return DAG.getNode(ISD::AND, DL, VT, Sra, N1); 9602 } 9603 9604 // (Cond0 s< 0) ? -1 : N2 --> (Cond0 s>> BW-1) | N2 9605 if (isAllOnesOrAllOnesSplat(N1)) { 9606 SDLoc DL(N); 9607 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT); 9608 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt); 9609 return DAG.getNode(ISD::OR, DL, VT, Sra, N2); 9610 } 9611 9612 // If we have to invert the sign bit mask, only do that transform if the 9613 // target has a bitwise 'and not' instruction (the invert is free). 9614 // (Cond0 s< -0) ? 0 : N2 --> ~(Cond0 s>> BW-1) & N2 9615 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9616 if (isNullOrNullSplat(N1) && TLI.hasAndNot(N1)) { 9617 SDLoc DL(N); 9618 SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT); 9619 SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt); 9620 SDValue Not = DAG.getNOT(DL, Sra, VT); 9621 return DAG.getNode(ISD::AND, DL, VT, Not, N2); 9622 } 9623 9624 // TODO: There's another pattern in this family, but it may require 9625 // implementing hasOrNot() to check for profitability: 9626 // (Cond0 s> -1) ? -1 : N2 --> ~(Cond0 s>> BW-1) | N2 9627 9628 return SDValue(); 9629 } 9630 9631 SDValue DAGCombiner::visitSELECT(SDNode *N) { 9632 SDValue N0 = N->getOperand(0); 9633 SDValue N1 = N->getOperand(1); 9634 SDValue N2 = N->getOperand(2); 9635 EVT VT = N->getValueType(0); 9636 EVT VT0 = N0.getValueType(); 9637 SDLoc DL(N); 9638 SDNodeFlags Flags = N->getFlags(); 9639 9640 if (SDValue V = DAG.simplifySelect(N0, N1, N2)) 9641 return V; 9642 9643 if (SDValue V = foldSelectOfConstants(N)) 9644 return V; 9645 9646 if (SDValue V = foldBoolSelectToLogic(N, DAG)) 9647 return V; 9648 9649 // If we can fold this based on the true/false value, do so. 9650 if (SimplifySelectOps(N, N1, N2)) 9651 return SDValue(N, 0); // Don't revisit N. 9652 9653 if (VT0 == MVT::i1) { 9654 // The code in this block deals with the following 2 equivalences: 9655 // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y)) 9656 // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y) 9657 // The target can specify its preferred form with the 9658 // shouldNormalizeToSelectSequence() callback. However we always transform 9659 // to the right anyway if we find the inner select exists in the DAG anyway 9660 // and we always transform to the left side if we know that we can further 9661 // optimize the combination of the conditions. 9662 bool normalizeToSequence = 9663 TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT); 9664 // select (and Cond0, Cond1), X, Y 9665 // -> select Cond0, (select Cond1, X, Y), Y 9666 if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) { 9667 SDValue Cond0 = N0->getOperand(0); 9668 SDValue Cond1 = N0->getOperand(1); 9669 SDValue InnerSelect = 9670 DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2, Flags); 9671 if (normalizeToSequence || !InnerSelect.use_empty()) 9672 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, 9673 InnerSelect, N2, Flags); 9674 // Cleanup on failure. 9675 if (InnerSelect.use_empty()) 9676 recursivelyDeleteUnusedNodes(InnerSelect.getNode()); 9677 } 9678 // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y) 9679 if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) { 9680 SDValue Cond0 = N0->getOperand(0); 9681 SDValue Cond1 = N0->getOperand(1); 9682 SDValue InnerSelect = DAG.getNode(ISD::SELECT, DL, N1.getValueType(), 9683 Cond1, N1, N2, Flags); 9684 if (normalizeToSequence || !InnerSelect.use_empty()) 9685 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1, 9686 InnerSelect, Flags); 9687 // Cleanup on failure. 9688 if (InnerSelect.use_empty()) 9689 recursivelyDeleteUnusedNodes(InnerSelect.getNode()); 9690 } 9691 9692 // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y 9693 if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) { 9694 SDValue N1_0 = N1->getOperand(0); 9695 SDValue N1_1 = N1->getOperand(1); 9696 SDValue N1_2 = N1->getOperand(2); 9697 if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) { 9698 // Create the actual and node if we can generate good code for it. 9699 if (!normalizeToSequence) { 9700 SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0); 9701 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1, 9702 N2, Flags); 9703 } 9704 // Otherwise see if we can optimize the "and" to a better pattern. 9705 if (SDValue Combined = visitANDLike(N0, N1_0, N)) { 9706 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1, 9707 N2, Flags); 9708 } 9709 } 9710 } 9711 // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y 9712 if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) { 9713 SDValue N2_0 = N2->getOperand(0); 9714 SDValue N2_1 = N2->getOperand(1); 9715 SDValue N2_2 = N2->getOperand(2); 9716 if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) { 9717 // Create the actual or node if we can generate good code for it. 9718 if (!normalizeToSequence) { 9719 SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0); 9720 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1, 9721 N2_2, Flags); 9722 } 9723 // Otherwise see if we can optimize to a better pattern. 9724 if (SDValue Combined = visitORLike(N0, N2_0, N)) 9725 return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1, 9726 N2_2, Flags); 9727 } 9728 } 9729 } 9730 9731 // select (not Cond), N1, N2 -> select Cond, N2, N1 9732 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false)) { 9733 SDValue SelectOp = DAG.getSelect(DL, VT, F, N2, N1); 9734 SelectOp->setFlags(Flags); 9735 return SelectOp; 9736 } 9737 9738 // Fold selects based on a setcc into other things, such as min/max/abs. 9739 if (N0.getOpcode() == ISD::SETCC) { 9740 SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1); 9741 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 9742 9743 // select (fcmp lt x, y), x, y -> fminnum x, y 9744 // select (fcmp gt x, y), x, y -> fmaxnum x, y 9745 // 9746 // This is OK if we don't care what happens if either operand is a NaN. 9747 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2, TLI)) 9748 if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2, 9749 CC, TLI, DAG)) 9750 return FMinMax; 9751 9752 // Use 'unsigned add with overflow' to optimize an unsigned saturating add. 9753 // This is conservatively limited to pre-legal-operations to give targets 9754 // a chance to reverse the transform if they want to do that. Also, it is 9755 // unlikely that the pattern would be formed late, so it's probably not 9756 // worth going through the other checks. 9757 if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) && 9758 CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) && 9759 N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) { 9760 auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1)); 9761 auto *NotC = dyn_cast<ConstantSDNode>(Cond1); 9762 if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) { 9763 // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) --> 9764 // uaddo Cond0, C; select uaddo.1, -1, uaddo.0 9765 // 9766 // The IR equivalent of this transform would have this form: 9767 // %a = add %x, C 9768 // %c = icmp ugt %x, ~C 9769 // %r = select %c, -1, %a 9770 // => 9771 // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C) 9772 // %u0 = extractvalue %u, 0 9773 // %u1 = extractvalue %u, 1 9774 // %r = select %u1, -1, %u0 9775 SDVTList VTs = DAG.getVTList(VT, VT0); 9776 SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1)); 9777 return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0)); 9778 } 9779 } 9780 9781 if (TLI.isOperationLegal(ISD::SELECT_CC, VT) || 9782 (!LegalOperations && 9783 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))) { 9784 // Any flags available in a select/setcc fold will be on the setcc as they 9785 // migrated from fcmp 9786 Flags = N0.getNode()->getFlags(); 9787 SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1, 9788 N2, N0.getOperand(2)); 9789 SelectNode->setFlags(Flags); 9790 return SelectNode; 9791 } 9792 9793 if (SDValue NewSel = SimplifySelect(DL, N0, N1, N2)) 9794 return NewSel; 9795 } 9796 9797 if (!VT.isVector()) 9798 if (SDValue BinOp = foldSelectOfBinops(N)) 9799 return BinOp; 9800 9801 return SDValue(); 9802 } 9803 9804 // This function assumes all the vselect's arguments are CONCAT_VECTOR 9805 // nodes and that the condition is a BV of ConstantSDNodes (or undefs). 9806 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) { 9807 SDLoc DL(N); 9808 SDValue Cond = N->getOperand(0); 9809 SDValue LHS = N->getOperand(1); 9810 SDValue RHS = N->getOperand(2); 9811 EVT VT = N->getValueType(0); 9812 int NumElems = VT.getVectorNumElements(); 9813 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS && 9814 RHS.getOpcode() == ISD::CONCAT_VECTORS && 9815 Cond.getOpcode() == ISD::BUILD_VECTOR); 9816 9817 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about 9818 // binary ones here. 9819 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2) 9820 return SDValue(); 9821 9822 // We're sure we have an even number of elements due to the 9823 // concat_vectors we have as arguments to vselect. 9824 // Skip BV elements until we find one that's not an UNDEF 9825 // After we find an UNDEF element, keep looping until we get to half the 9826 // length of the BV and see if all the non-undef nodes are the same. 9827 ConstantSDNode *BottomHalf = nullptr; 9828 for (int i = 0; i < NumElems / 2; ++i) { 9829 if (Cond->getOperand(i)->isUndef()) 9830 continue; 9831 9832 if (BottomHalf == nullptr) 9833 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 9834 else if (Cond->getOperand(i).getNode() != BottomHalf) 9835 return SDValue(); 9836 } 9837 9838 // Do the same for the second half of the BuildVector 9839 ConstantSDNode *TopHalf = nullptr; 9840 for (int i = NumElems / 2; i < NumElems; ++i) { 9841 if (Cond->getOperand(i)->isUndef()) 9842 continue; 9843 9844 if (TopHalf == nullptr) 9845 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i)); 9846 else if (Cond->getOperand(i).getNode() != TopHalf) 9847 return SDValue(); 9848 } 9849 9850 assert(TopHalf && BottomHalf && 9851 "One half of the selector was all UNDEFs and the other was all the " 9852 "same value. This should have been addressed before this function."); 9853 return DAG.getNode( 9854 ISD::CONCAT_VECTORS, DL, VT, 9855 BottomHalf->isZero() ? RHS->getOperand(0) : LHS->getOperand(0), 9856 TopHalf->isZero() ? RHS->getOperand(1) : LHS->getOperand(1)); 9857 } 9858 9859 bool refineUniformBase(SDValue &BasePtr, SDValue &Index, SelectionDAG &DAG) { 9860 if (!isNullConstant(BasePtr) || Index.getOpcode() != ISD::ADD) 9861 return false; 9862 9863 // For now we check only the LHS of the add. 9864 SDValue LHS = Index.getOperand(0); 9865 SDValue SplatVal = DAG.getSplatValue(LHS); 9866 if (!SplatVal) 9867 return false; 9868 9869 BasePtr = SplatVal; 9870 Index = Index.getOperand(1); 9871 return true; 9872 } 9873 9874 // Fold sext/zext of index into index type. 9875 bool refineIndexType(MaskedGatherScatterSDNode *MGS, SDValue &Index, 9876 bool Scaled, SelectionDAG &DAG) { 9877 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9878 9879 if (Index.getOpcode() == ISD::ZERO_EXTEND) { 9880 SDValue Op = Index.getOperand(0); 9881 MGS->setIndexType(Scaled ? ISD::UNSIGNED_SCALED : ISD::UNSIGNED_UNSCALED); 9882 if (TLI.shouldRemoveExtendFromGSIndex(Op.getValueType())) { 9883 Index = Op; 9884 return true; 9885 } 9886 } 9887 9888 if (Index.getOpcode() == ISD::SIGN_EXTEND) { 9889 SDValue Op = Index.getOperand(0); 9890 MGS->setIndexType(Scaled ? ISD::SIGNED_SCALED : ISD::SIGNED_UNSCALED); 9891 if (TLI.shouldRemoveExtendFromGSIndex(Op.getValueType())) { 9892 Index = Op; 9893 return true; 9894 } 9895 } 9896 9897 return false; 9898 } 9899 9900 SDValue DAGCombiner::visitMSCATTER(SDNode *N) { 9901 MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N); 9902 SDValue Mask = MSC->getMask(); 9903 SDValue Chain = MSC->getChain(); 9904 SDValue Index = MSC->getIndex(); 9905 SDValue Scale = MSC->getScale(); 9906 SDValue StoreVal = MSC->getValue(); 9907 SDValue BasePtr = MSC->getBasePtr(); 9908 SDLoc DL(N); 9909 9910 // Zap scatters with a zero mask. 9911 if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) 9912 return Chain; 9913 9914 if (refineUniformBase(BasePtr, Index, DAG)) { 9915 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale}; 9916 return DAG.getMaskedScatter( 9917 DAG.getVTList(MVT::Other), MSC->getMemoryVT(), DL, Ops, 9918 MSC->getMemOperand(), MSC->getIndexType(), MSC->isTruncatingStore()); 9919 } 9920 9921 if (refineIndexType(MSC, Index, MSC->isIndexScaled(), DAG)) { 9922 SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale}; 9923 return DAG.getMaskedScatter( 9924 DAG.getVTList(MVT::Other), MSC->getMemoryVT(), DL, Ops, 9925 MSC->getMemOperand(), MSC->getIndexType(), MSC->isTruncatingStore()); 9926 } 9927 9928 return SDValue(); 9929 } 9930 9931 SDValue DAGCombiner::visitMSTORE(SDNode *N) { 9932 MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N); 9933 SDValue Mask = MST->getMask(); 9934 SDValue Chain = MST->getChain(); 9935 SDLoc DL(N); 9936 9937 // Zap masked stores with a zero mask. 9938 if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) 9939 return Chain; 9940 9941 // If this is a masked load with an all ones mask, we can use a unmasked load. 9942 // FIXME: Can we do this for indexed, compressing, or truncating stores? 9943 if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && 9944 MST->isUnindexed() && !MST->isCompressingStore() && 9945 !MST->isTruncatingStore()) 9946 return DAG.getStore(MST->getChain(), SDLoc(N), MST->getValue(), 9947 MST->getBasePtr(), MST->getMemOperand()); 9948 9949 // Try transforming N to an indexed store. 9950 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 9951 return SDValue(N, 0); 9952 9953 return SDValue(); 9954 } 9955 9956 SDValue DAGCombiner::visitMGATHER(SDNode *N) { 9957 MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N); 9958 SDValue Mask = MGT->getMask(); 9959 SDValue Chain = MGT->getChain(); 9960 SDValue Index = MGT->getIndex(); 9961 SDValue Scale = MGT->getScale(); 9962 SDValue PassThru = MGT->getPassThru(); 9963 SDValue BasePtr = MGT->getBasePtr(); 9964 SDLoc DL(N); 9965 9966 // Zap gathers with a zero mask. 9967 if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) 9968 return CombineTo(N, PassThru, MGT->getChain()); 9969 9970 if (refineUniformBase(BasePtr, Index, DAG)) { 9971 SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale}; 9972 return DAG.getMaskedGather(DAG.getVTList(N->getValueType(0), MVT::Other), 9973 MGT->getMemoryVT(), DL, Ops, 9974 MGT->getMemOperand(), MGT->getIndexType(), 9975 MGT->getExtensionType()); 9976 } 9977 9978 if (refineIndexType(MGT, Index, MGT->isIndexScaled(), DAG)) { 9979 SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale}; 9980 return DAG.getMaskedGather(DAG.getVTList(N->getValueType(0), MVT::Other), 9981 MGT->getMemoryVT(), DL, Ops, 9982 MGT->getMemOperand(), MGT->getIndexType(), 9983 MGT->getExtensionType()); 9984 } 9985 9986 return SDValue(); 9987 } 9988 9989 SDValue DAGCombiner::visitMLOAD(SDNode *N) { 9990 MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N); 9991 SDValue Mask = MLD->getMask(); 9992 SDLoc DL(N); 9993 9994 // Zap masked loads with a zero mask. 9995 if (ISD::isConstantSplatVectorAllZeros(Mask.getNode())) 9996 return CombineTo(N, MLD->getPassThru(), MLD->getChain()); 9997 9998 // If this is a masked load with an all ones mask, we can use a unmasked load. 9999 // FIXME: Can we do this for indexed, expanding, or extending loads? 10000 if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && 10001 MLD->isUnindexed() && !MLD->isExpandingLoad() && 10002 MLD->getExtensionType() == ISD::NON_EXTLOAD) { 10003 SDValue NewLd = DAG.getLoad(N->getValueType(0), SDLoc(N), MLD->getChain(), 10004 MLD->getBasePtr(), MLD->getMemOperand()); 10005 return CombineTo(N, NewLd, NewLd.getValue(1)); 10006 } 10007 10008 // Try transforming N to an indexed load. 10009 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 10010 return SDValue(N, 0); 10011 10012 return SDValue(); 10013 } 10014 10015 /// A vector select of 2 constant vectors can be simplified to math/logic to 10016 /// avoid a variable select instruction and possibly avoid constant loads. 10017 SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) { 10018 SDValue Cond = N->getOperand(0); 10019 SDValue N1 = N->getOperand(1); 10020 SDValue N2 = N->getOperand(2); 10021 EVT VT = N->getValueType(0); 10022 if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 || 10023 !TLI.convertSelectOfConstantsToMath(VT) || 10024 !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) || 10025 !ISD::isBuildVectorOfConstantSDNodes(N2.getNode())) 10026 return SDValue(); 10027 10028 // Check if we can use the condition value to increment/decrement a single 10029 // constant value. This simplifies a select to an add and removes a constant 10030 // load/materialization from the general case. 10031 bool AllAddOne = true; 10032 bool AllSubOne = true; 10033 unsigned Elts = VT.getVectorNumElements(); 10034 for (unsigned i = 0; i != Elts; ++i) { 10035 SDValue N1Elt = N1.getOperand(i); 10036 SDValue N2Elt = N2.getOperand(i); 10037 if (N1Elt.isUndef() || N2Elt.isUndef()) 10038 continue; 10039 if (N1Elt.getValueType() != N2Elt.getValueType()) 10040 continue; 10041 10042 const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue(); 10043 const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue(); 10044 if (C1 != C2 + 1) 10045 AllAddOne = false; 10046 if (C1 != C2 - 1) 10047 AllSubOne = false; 10048 } 10049 10050 // Further simplifications for the extra-special cases where the constants are 10051 // all 0 or all -1 should be implemented as folds of these patterns. 10052 SDLoc DL(N); 10053 if (AllAddOne || AllSubOne) { 10054 // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C 10055 // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C 10056 auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND; 10057 SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond); 10058 return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2); 10059 } 10060 10061 // select Cond, Pow2C, 0 --> (zext Cond) << log2(Pow2C) 10062 APInt Pow2C; 10063 if (ISD::isConstantSplatVector(N1.getNode(), Pow2C) && Pow2C.isPowerOf2() && 10064 isNullOrNullSplat(N2)) { 10065 SDValue ZextCond = DAG.getZExtOrTrunc(Cond, DL, VT); 10066 SDValue ShAmtC = DAG.getConstant(Pow2C.exactLogBase2(), DL, VT); 10067 return DAG.getNode(ISD::SHL, DL, VT, ZextCond, ShAmtC); 10068 } 10069 10070 if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG)) 10071 return V; 10072 10073 // The general case for select-of-constants: 10074 // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2 10075 // ...but that only makes sense if a vselect is slower than 2 logic ops, so 10076 // leave that to a machine-specific pass. 10077 return SDValue(); 10078 } 10079 10080 SDValue DAGCombiner::visitVSELECT(SDNode *N) { 10081 SDValue N0 = N->getOperand(0); 10082 SDValue N1 = N->getOperand(1); 10083 SDValue N2 = N->getOperand(2); 10084 EVT VT = N->getValueType(0); 10085 SDLoc DL(N); 10086 10087 if (SDValue V = DAG.simplifySelect(N0, N1, N2)) 10088 return V; 10089 10090 if (SDValue V = foldBoolSelectToLogic(N, DAG)) 10091 return V; 10092 10093 // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1 10094 if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false)) 10095 return DAG.getSelect(DL, VT, F, N2, N1); 10096 10097 // Canonicalize integer abs. 10098 // vselect (setg[te] X, 0), X, -X -> 10099 // vselect (setgt X, -1), X, -X -> 10100 // vselect (setl[te] X, 0), -X, X -> 10101 // Y = sra (X, size(X)-1); xor (add (X, Y), Y) 10102 if (N0.getOpcode() == ISD::SETCC) { 10103 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1); 10104 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 10105 bool isAbs = false; 10106 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode()); 10107 10108 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) || 10109 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) && 10110 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1)) 10111 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode()); 10112 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) && 10113 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1)) 10114 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode()); 10115 10116 if (isAbs) { 10117 if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) 10118 return DAG.getNode(ISD::ABS, DL, VT, LHS); 10119 10120 SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, LHS, 10121 DAG.getConstant(VT.getScalarSizeInBits() - 1, 10122 DL, getShiftAmountTy(VT))); 10123 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift); 10124 AddToWorklist(Shift.getNode()); 10125 AddToWorklist(Add.getNode()); 10126 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift); 10127 } 10128 10129 // vselect x, y (fcmp lt x, y) -> fminnum x, y 10130 // vselect x, y (fcmp gt x, y) -> fmaxnum x, y 10131 // 10132 // This is OK if we don't care about what happens if either operand is a 10133 // NaN. 10134 // 10135 if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, LHS, RHS, TLI)) { 10136 if (SDValue FMinMax = 10137 combineMinNumMaxNum(DL, VT, LHS, RHS, N1, N2, CC, TLI, DAG)) 10138 return FMinMax; 10139 } 10140 10141 // If this select has a condition (setcc) with narrower operands than the 10142 // select, try to widen the compare to match the select width. 10143 // TODO: This should be extended to handle any constant. 10144 // TODO: This could be extended to handle non-loading patterns, but that 10145 // requires thorough testing to avoid regressions. 10146 if (isNullOrNullSplat(RHS)) { 10147 EVT NarrowVT = LHS.getValueType(); 10148 EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger(); 10149 EVT SetCCVT = getSetCCResultType(LHS.getValueType()); 10150 unsigned SetCCWidth = SetCCVT.getScalarSizeInBits(); 10151 unsigned WideWidth = WideVT.getScalarSizeInBits(); 10152 bool IsSigned = isSignedIntSetCC(CC); 10153 auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 10154 if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() && 10155 SetCCWidth != 1 && SetCCWidth < WideWidth && 10156 TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) && 10157 TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) { 10158 // Both compare operands can be widened for free. The LHS can use an 10159 // extended load, and the RHS is a constant: 10160 // vselect (ext (setcc load(X), C)), N1, N2 --> 10161 // vselect (setcc extload(X), C'), N1, N2 10162 auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 10163 SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS); 10164 SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS); 10165 EVT WideSetCCVT = getSetCCResultType(WideVT); 10166 SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC); 10167 return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2); 10168 } 10169 } 10170 10171 // Match VSELECTs into add with unsigned saturation. 10172 if (hasOperation(ISD::UADDSAT, VT)) { 10173 // Check if one of the arms of the VSELECT is vector with all bits set. 10174 // If it's on the left side invert the predicate to simplify logic below. 10175 SDValue Other; 10176 ISD::CondCode SatCC = CC; 10177 if (ISD::isConstantSplatVectorAllOnes(N1.getNode())) { 10178 Other = N2; 10179 SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType()); 10180 } else if (ISD::isConstantSplatVectorAllOnes(N2.getNode())) { 10181 Other = N1; 10182 } 10183 10184 if (Other && Other.getOpcode() == ISD::ADD) { 10185 SDValue CondLHS = LHS, CondRHS = RHS; 10186 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1); 10187 10188 // Canonicalize condition operands. 10189 if (SatCC == ISD::SETUGE) { 10190 std::swap(CondLHS, CondRHS); 10191 SatCC = ISD::SETULE; 10192 } 10193 10194 // We can test against either of the addition operands. 10195 // x <= x+y ? x+y : ~0 --> uaddsat x, y 10196 // x+y >= x ? x+y : ~0 --> uaddsat x, y 10197 if (SatCC == ISD::SETULE && Other == CondRHS && 10198 (OpLHS == CondLHS || OpRHS == CondLHS)) 10199 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS); 10200 10201 if (OpRHS.getOpcode() == CondRHS.getOpcode() && 10202 (OpRHS.getOpcode() == ISD::BUILD_VECTOR || 10203 OpRHS.getOpcode() == ISD::SPLAT_VECTOR) && 10204 CondLHS == OpLHS) { 10205 // If the RHS is a constant we have to reverse the const 10206 // canonicalization. 10207 // x >= ~C ? x+C : ~0 --> uaddsat x, C 10208 auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) { 10209 return Cond->getAPIntValue() == ~Op->getAPIntValue(); 10210 }; 10211 if (SatCC == ISD::SETULE && 10212 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT)) 10213 return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS); 10214 } 10215 } 10216 } 10217 10218 // Match VSELECTs into sub with unsigned saturation. 10219 if (hasOperation(ISD::USUBSAT, VT)) { 10220 // Check if one of the arms of the VSELECT is a zero vector. If it's on 10221 // the left side invert the predicate to simplify logic below. 10222 SDValue Other; 10223 ISD::CondCode SatCC = CC; 10224 if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) { 10225 Other = N2; 10226 SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType()); 10227 } else if (ISD::isConstantSplatVectorAllZeros(N2.getNode())) { 10228 Other = N1; 10229 } 10230 10231 if (Other && Other.getNumOperands() == 2) { 10232 SDValue CondRHS = RHS; 10233 SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1); 10234 10235 if (Other.getOpcode() == ISD::SUB && 10236 LHS.getOpcode() == ISD::ZERO_EXTEND && LHS.getOperand(0) == OpLHS && 10237 OpRHS.getOpcode() == ISD::TRUNCATE && OpRHS.getOperand(0) == RHS) { 10238 // Look for a general sub with unsigned saturation first. 10239 // zext(x) >= y ? x - trunc(y) : 0 10240 // --> usubsat(x,trunc(umin(y,SatLimit))) 10241 // zext(x) > y ? x - trunc(y) : 0 10242 // --> usubsat(x,trunc(umin(y,SatLimit))) 10243 if (SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) 10244 return getTruncatedUSUBSAT(VT, LHS.getValueType(), LHS, RHS, DAG, 10245 DL); 10246 } 10247 10248 if (OpLHS == LHS) { 10249 // Look for a general sub with unsigned saturation first. 10250 // x >= y ? x-y : 0 --> usubsat x, y 10251 // x > y ? x-y : 0 --> usubsat x, y 10252 if ((SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) && 10253 Other.getOpcode() == ISD::SUB && OpRHS == CondRHS) 10254 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS); 10255 10256 if (OpRHS.getOpcode() == ISD::BUILD_VECTOR || 10257 OpRHS.getOpcode() == ISD::SPLAT_VECTOR) { 10258 if (CondRHS.getOpcode() == ISD::BUILD_VECTOR || 10259 CondRHS.getOpcode() == ISD::SPLAT_VECTOR) { 10260 // If the RHS is a constant we have to reverse the const 10261 // canonicalization. 10262 // x > C-1 ? x+-C : 0 --> usubsat x, C 10263 auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) { 10264 return (!Op && !Cond) || 10265 (Op && Cond && 10266 Cond->getAPIntValue() == (-Op->getAPIntValue() - 1)); 10267 }; 10268 if (SatCC == ISD::SETUGT && Other.getOpcode() == ISD::ADD && 10269 ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT, 10270 /*AllowUndefs*/ true)) { 10271 OpRHS = DAG.getNode(ISD::SUB, DL, VT, 10272 DAG.getConstant(0, DL, VT), OpRHS); 10273 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS); 10274 } 10275 10276 // Another special case: If C was a sign bit, the sub has been 10277 // canonicalized into a xor. 10278 // FIXME: Would it be better to use computeKnownBits to determine 10279 // whether it's safe to decanonicalize the xor? 10280 // x s< 0 ? x^C : 0 --> usubsat x, C 10281 APInt SplatValue; 10282 if (SatCC == ISD::SETLT && Other.getOpcode() == ISD::XOR && 10283 ISD::isConstantSplatVector(OpRHS.getNode(), SplatValue) && 10284 ISD::isConstantSplatVectorAllZeros(CondRHS.getNode()) && 10285 SplatValue.isSignMask()) { 10286 // Note that we have to rebuild the RHS constant here to 10287 // ensure we don't rely on particular values of undef lanes. 10288 OpRHS = DAG.getConstant(SplatValue, DL, VT); 10289 return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS); 10290 } 10291 } 10292 } 10293 } 10294 } 10295 } 10296 } 10297 10298 if (SimplifySelectOps(N, N1, N2)) 10299 return SDValue(N, 0); // Don't revisit N. 10300 10301 // Fold (vselect all_ones, N1, N2) -> N1 10302 if (ISD::isConstantSplatVectorAllOnes(N0.getNode())) 10303 return N1; 10304 // Fold (vselect all_zeros, N1, N2) -> N2 10305 if (ISD::isConstantSplatVectorAllZeros(N0.getNode())) 10306 return N2; 10307 10308 // The ConvertSelectToConcatVector function is assuming both the above 10309 // checks for (vselect (build_vector all{ones,zeros) ...) have been made 10310 // and addressed. 10311 if (N1.getOpcode() == ISD::CONCAT_VECTORS && 10312 N2.getOpcode() == ISD::CONCAT_VECTORS && 10313 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) { 10314 if (SDValue CV = ConvertSelectToConcatVector(N, DAG)) 10315 return CV; 10316 } 10317 10318 if (SDValue V = foldVSelectOfConstants(N)) 10319 return V; 10320 10321 if (hasOperation(ISD::SRA, VT)) 10322 if (SDValue V = foldVSelectToSignBitSplatMask(N, DAG)) 10323 return V; 10324 10325 return SDValue(); 10326 } 10327 10328 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) { 10329 SDValue N0 = N->getOperand(0); 10330 SDValue N1 = N->getOperand(1); 10331 SDValue N2 = N->getOperand(2); 10332 SDValue N3 = N->getOperand(3); 10333 SDValue N4 = N->getOperand(4); 10334 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get(); 10335 10336 // fold select_cc lhs, rhs, x, x, cc -> x 10337 if (N2 == N3) 10338 return N2; 10339 10340 // Determine if the condition we're dealing with is constant 10341 if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1, 10342 CC, SDLoc(N), false)) { 10343 AddToWorklist(SCC.getNode()); 10344 10345 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) { 10346 if (!SCCC->isZero()) 10347 return N2; // cond always true -> true val 10348 else 10349 return N3; // cond always false -> false val 10350 } else if (SCC->isUndef()) { 10351 // When the condition is UNDEF, just return the first operand. This is 10352 // coherent the DAG creation, no setcc node is created in this case 10353 return N2; 10354 } else if (SCC.getOpcode() == ISD::SETCC) { 10355 // Fold to a simpler select_cc 10356 SDValue SelectOp = DAG.getNode( 10357 ISD::SELECT_CC, SDLoc(N), N2.getValueType(), SCC.getOperand(0), 10358 SCC.getOperand(1), N2, N3, SCC.getOperand(2)); 10359 SelectOp->setFlags(SCC->getFlags()); 10360 return SelectOp; 10361 } 10362 } 10363 10364 // If we can fold this based on the true/false value, do so. 10365 if (SimplifySelectOps(N, N2, N3)) 10366 return SDValue(N, 0); // Don't revisit N. 10367 10368 // fold select_cc into other things, such as min/max/abs 10369 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC); 10370 } 10371 10372 SDValue DAGCombiner::visitSETCC(SDNode *N) { 10373 // setcc is very commonly used as an argument to brcond. This pattern 10374 // also lend itself to numerous combines and, as a result, it is desired 10375 // we keep the argument to a brcond as a setcc as much as possible. 10376 bool PreferSetCC = 10377 N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND; 10378 10379 ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10380 EVT VT = N->getValueType(0); 10381 10382 // SETCC(FREEZE(X), CONST, Cond) 10383 // => 10384 // FREEZE(SETCC(X, CONST, Cond)) 10385 // This is correct if FREEZE(X) has one use and SETCC(FREEZE(X), CONST, Cond) 10386 // isn't equivalent to true or false. 10387 // For example, SETCC(FREEZE(X), -128, SETULT) cannot be folded to 10388 // FREEZE(SETCC(X, -128, SETULT)) because X can be poison. 10389 // 10390 // This transformation is beneficial because visitBRCOND can fold 10391 // BRCOND(FREEZE(X)) to BRCOND(X). 10392 10393 // Conservatively optimize integer comparisons only. 10394 if (PreferSetCC) { 10395 // Do this only when SETCC is going to be used by BRCOND. 10396 10397 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 10398 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0); 10399 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1); 10400 bool Updated = false; 10401 10402 // Is 'X Cond C' always true or false? 10403 auto IsAlwaysTrueOrFalse = [](ISD::CondCode Cond, ConstantSDNode *C) { 10404 bool False = (Cond == ISD::SETULT && C->isZero()) || 10405 (Cond == ISD::SETLT && C->isMinSignedValue()) || 10406 (Cond == ISD::SETUGT && C->isAllOnes()) || 10407 (Cond == ISD::SETGT && C->isMaxSignedValue()); 10408 bool True = (Cond == ISD::SETULE && C->isAllOnes()) || 10409 (Cond == ISD::SETLE && C->isMaxSignedValue()) || 10410 (Cond == ISD::SETUGE && C->isZero()) || 10411 (Cond == ISD::SETGE && C->isMinSignedValue()); 10412 return True || False; 10413 }; 10414 10415 if (N0->getOpcode() == ISD::FREEZE && N0.hasOneUse() && N1C) { 10416 if (!IsAlwaysTrueOrFalse(Cond, N1C)) { 10417 N0 = N0->getOperand(0); 10418 Updated = true; 10419 } 10420 } 10421 if (N1->getOpcode() == ISD::FREEZE && N1.hasOneUse() && N0C) { 10422 if (!IsAlwaysTrueOrFalse(ISD::getSetCCSwappedOperands(Cond), 10423 N0C)) { 10424 N1 = N1->getOperand(0); 10425 Updated = true; 10426 } 10427 } 10428 10429 if (Updated) 10430 return DAG.getFreeze(DAG.getSetCC(SDLoc(N), VT, N0, N1, Cond)); 10431 } 10432 10433 SDValue Combined = SimplifySetCC(VT, N->getOperand(0), N->getOperand(1), Cond, 10434 SDLoc(N), !PreferSetCC); 10435 10436 if (!Combined) 10437 return SDValue(); 10438 10439 // If we prefer to have a setcc, and we don't, we'll try our best to 10440 // recreate one using rebuildSetCC. 10441 if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) { 10442 SDValue NewSetCC = rebuildSetCC(Combined); 10443 10444 // We don't have anything interesting to combine to. 10445 if (NewSetCC.getNode() == N) 10446 return SDValue(); 10447 10448 if (NewSetCC) 10449 return NewSetCC; 10450 } 10451 10452 return Combined; 10453 } 10454 10455 SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) { 10456 SDValue LHS = N->getOperand(0); 10457 SDValue RHS = N->getOperand(1); 10458 SDValue Carry = N->getOperand(2); 10459 SDValue Cond = N->getOperand(3); 10460 10461 // If Carry is false, fold to a regular SETCC. 10462 if (isNullConstant(Carry)) 10463 return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond); 10464 10465 return SDValue(); 10466 } 10467 10468 /// Check if N satisfies: 10469 /// N is used once. 10470 /// N is a Load. 10471 /// The load is compatible with ExtOpcode. It means 10472 /// If load has explicit zero/sign extension, ExpOpcode must have the same 10473 /// extension. 10474 /// Otherwise returns true. 10475 static bool isCompatibleLoad(SDValue N, unsigned ExtOpcode) { 10476 if (!N.hasOneUse()) 10477 return false; 10478 10479 if (!isa<LoadSDNode>(N)) 10480 return false; 10481 10482 LoadSDNode *Load = cast<LoadSDNode>(N); 10483 ISD::LoadExtType LoadExt = Load->getExtensionType(); 10484 if (LoadExt == ISD::NON_EXTLOAD || LoadExt == ISD::EXTLOAD) 10485 return true; 10486 10487 // Now LoadExt is either SEXTLOAD or ZEXTLOAD, ExtOpcode must have the same 10488 // extension. 10489 if ((LoadExt == ISD::SEXTLOAD && ExtOpcode != ISD::SIGN_EXTEND) || 10490 (LoadExt == ISD::ZEXTLOAD && ExtOpcode != ISD::ZERO_EXTEND)) 10491 return false; 10492 10493 return true; 10494 } 10495 10496 /// Fold 10497 /// (sext (select c, load x, load y)) -> (select c, sextload x, sextload y) 10498 /// (zext (select c, load x, load y)) -> (select c, zextload x, zextload y) 10499 /// (aext (select c, load x, load y)) -> (select c, extload x, extload y) 10500 /// This function is called by the DAGCombiner when visiting sext/zext/aext 10501 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 10502 static SDValue tryToFoldExtendSelectLoad(SDNode *N, const TargetLowering &TLI, 10503 SelectionDAG &DAG) { 10504 unsigned Opcode = N->getOpcode(); 10505 SDValue N0 = N->getOperand(0); 10506 EVT VT = N->getValueType(0); 10507 SDLoc DL(N); 10508 10509 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 10510 Opcode == ISD::ANY_EXTEND) && 10511 "Expected EXTEND dag node in input!"); 10512 10513 if (!(N0->getOpcode() == ISD::SELECT || N0->getOpcode() == ISD::VSELECT) || 10514 !N0.hasOneUse()) 10515 return SDValue(); 10516 10517 SDValue Op1 = N0->getOperand(1); 10518 SDValue Op2 = N0->getOperand(2); 10519 if (!isCompatibleLoad(Op1, Opcode) || !isCompatibleLoad(Op2, Opcode)) 10520 return SDValue(); 10521 10522 auto ExtLoadOpcode = ISD::EXTLOAD; 10523 if (Opcode == ISD::SIGN_EXTEND) 10524 ExtLoadOpcode = ISD::SEXTLOAD; 10525 else if (Opcode == ISD::ZERO_EXTEND) 10526 ExtLoadOpcode = ISD::ZEXTLOAD; 10527 10528 LoadSDNode *Load1 = cast<LoadSDNode>(Op1); 10529 LoadSDNode *Load2 = cast<LoadSDNode>(Op2); 10530 if (!TLI.isLoadExtLegal(ExtLoadOpcode, VT, Load1->getMemoryVT()) || 10531 !TLI.isLoadExtLegal(ExtLoadOpcode, VT, Load2->getMemoryVT())) 10532 return SDValue(); 10533 10534 SDValue Ext1 = DAG.getNode(Opcode, DL, VT, Op1); 10535 SDValue Ext2 = DAG.getNode(Opcode, DL, VT, Op2); 10536 return DAG.getSelect(DL, VT, N0->getOperand(0), Ext1, Ext2); 10537 } 10538 10539 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or 10540 /// a build_vector of constants. 10541 /// This function is called by the DAGCombiner when visiting sext/zext/aext 10542 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 10543 /// Vector extends are not folded if operations are legal; this is to 10544 /// avoid introducing illegal build_vector dag nodes. 10545 static SDValue tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI, 10546 SelectionDAG &DAG, bool LegalTypes) { 10547 unsigned Opcode = N->getOpcode(); 10548 SDValue N0 = N->getOperand(0); 10549 EVT VT = N->getValueType(0); 10550 SDLoc DL(N); 10551 10552 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND || 10553 Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG || 10554 Opcode == ISD::ZERO_EXTEND_VECTOR_INREG) 10555 && "Expected EXTEND dag node in input!"); 10556 10557 // fold (sext c1) -> c1 10558 // fold (zext c1) -> c1 10559 // fold (aext c1) -> c1 10560 if (isa<ConstantSDNode>(N0)) 10561 return DAG.getNode(Opcode, DL, VT, N0); 10562 10563 // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2) 10564 // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2) 10565 // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2) 10566 if (N0->getOpcode() == ISD::SELECT) { 10567 SDValue Op1 = N0->getOperand(1); 10568 SDValue Op2 = N0->getOperand(2); 10569 if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) && 10570 (Opcode != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0.getValueType(), VT))) { 10571 // For any_extend, choose sign extension of the constants to allow a 10572 // possible further transform to sign_extend_inreg.i.e. 10573 // 10574 // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0> 10575 // t2: i64 = any_extend t1 10576 // --> 10577 // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0> 10578 // --> 10579 // t4: i64 = sign_extend_inreg t3 10580 unsigned FoldOpc = Opcode; 10581 if (FoldOpc == ISD::ANY_EXTEND) 10582 FoldOpc = ISD::SIGN_EXTEND; 10583 return DAG.getSelect(DL, VT, N0->getOperand(0), 10584 DAG.getNode(FoldOpc, DL, VT, Op1), 10585 DAG.getNode(FoldOpc, DL, VT, Op2)); 10586 } 10587 } 10588 10589 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants) 10590 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants) 10591 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants) 10592 EVT SVT = VT.getScalarType(); 10593 if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) && 10594 ISD::isBuildVectorOfConstantSDNodes(N0.getNode()))) 10595 return SDValue(); 10596 10597 // We can fold this node into a build_vector. 10598 unsigned VTBits = SVT.getSizeInBits(); 10599 unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits(); 10600 SmallVector<SDValue, 8> Elts; 10601 unsigned NumElts = VT.getVectorNumElements(); 10602 10603 // For zero-extensions, UNDEF elements still guarantee to have the upper 10604 // bits set to zero. 10605 bool IsZext = 10606 Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG; 10607 10608 for (unsigned i = 0; i != NumElts; ++i) { 10609 SDValue Op = N0.getOperand(i); 10610 if (Op.isUndef()) { 10611 Elts.push_back(IsZext ? DAG.getConstant(0, DL, SVT) : DAG.getUNDEF(SVT)); 10612 continue; 10613 } 10614 10615 SDLoc DL(Op); 10616 // Get the constant value and if needed trunc it to the size of the type. 10617 // Nodes like build_vector might have constants wider than the scalar type. 10618 APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits); 10619 if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG) 10620 Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT)); 10621 else 10622 Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT)); 10623 } 10624 10625 return DAG.getBuildVector(VT, DL, Elts); 10626 } 10627 10628 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this: 10629 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))" 10630 // transformation. Returns true if extension are possible and the above 10631 // mentioned transformation is profitable. 10632 static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0, 10633 unsigned ExtOpc, 10634 SmallVectorImpl<SDNode *> &ExtendNodes, 10635 const TargetLowering &TLI) { 10636 bool HasCopyToRegUses = false; 10637 bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType()); 10638 for (SDNode::use_iterator UI = N0.getNode()->use_begin(), 10639 UE = N0.getNode()->use_end(); 10640 UI != UE; ++UI) { 10641 SDNode *User = *UI; 10642 if (User == N) 10643 continue; 10644 if (UI.getUse().getResNo() != N0.getResNo()) 10645 continue; 10646 // FIXME: Only extend SETCC N, N and SETCC N, c for now. 10647 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) { 10648 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get(); 10649 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC)) 10650 // Sign bits will be lost after a zext. 10651 return false; 10652 bool Add = false; 10653 for (unsigned i = 0; i != 2; ++i) { 10654 SDValue UseOp = User->getOperand(i); 10655 if (UseOp == N0) 10656 continue; 10657 if (!isa<ConstantSDNode>(UseOp)) 10658 return false; 10659 Add = true; 10660 } 10661 if (Add) 10662 ExtendNodes.push_back(User); 10663 continue; 10664 } 10665 // If truncates aren't free and there are users we can't 10666 // extend, it isn't worthwhile. 10667 if (!isTruncFree) 10668 return false; 10669 // Remember if this value is live-out. 10670 if (User->getOpcode() == ISD::CopyToReg) 10671 HasCopyToRegUses = true; 10672 } 10673 10674 if (HasCopyToRegUses) { 10675 bool BothLiveOut = false; 10676 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 10677 UI != UE; ++UI) { 10678 SDUse &Use = UI.getUse(); 10679 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) { 10680 BothLiveOut = true; 10681 break; 10682 } 10683 } 10684 if (BothLiveOut) 10685 // Both unextended and extended values are live out. There had better be 10686 // a good reason for the transformation. 10687 return ExtendNodes.size(); 10688 } 10689 return true; 10690 } 10691 10692 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs, 10693 SDValue OrigLoad, SDValue ExtLoad, 10694 ISD::NodeType ExtType) { 10695 // Extend SetCC uses if necessary. 10696 SDLoc DL(ExtLoad); 10697 for (SDNode *SetCC : SetCCs) { 10698 SmallVector<SDValue, 4> Ops; 10699 10700 for (unsigned j = 0; j != 2; ++j) { 10701 SDValue SOp = SetCC->getOperand(j); 10702 if (SOp == OrigLoad) 10703 Ops.push_back(ExtLoad); 10704 else 10705 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp)); 10706 } 10707 10708 Ops.push_back(SetCC->getOperand(2)); 10709 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops)); 10710 } 10711 } 10712 10713 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?). 10714 SDValue DAGCombiner::CombineExtLoad(SDNode *N) { 10715 SDValue N0 = N->getOperand(0); 10716 EVT DstVT = N->getValueType(0); 10717 EVT SrcVT = N0.getValueType(); 10718 10719 assert((N->getOpcode() == ISD::SIGN_EXTEND || 10720 N->getOpcode() == ISD::ZERO_EXTEND) && 10721 "Unexpected node type (not an extend)!"); 10722 10723 // fold (sext (load x)) to multiple smaller sextloads; same for zext. 10724 // For example, on a target with legal v4i32, but illegal v8i32, turn: 10725 // (v8i32 (sext (v8i16 (load x)))) 10726 // into: 10727 // (v8i32 (concat_vectors (v4i32 (sextload x)), 10728 // (v4i32 (sextload (x + 16))))) 10729 // Where uses of the original load, i.e.: 10730 // (v8i16 (load x)) 10731 // are replaced with: 10732 // (v8i16 (truncate 10733 // (v8i32 (concat_vectors (v4i32 (sextload x)), 10734 // (v4i32 (sextload (x + 16))))))) 10735 // 10736 // This combine is only applicable to illegal, but splittable, vectors. 10737 // All legal types, and illegal non-vector types, are handled elsewhere. 10738 // This combine is controlled by TargetLowering::isVectorLoadExtDesirable. 10739 // 10740 if (N0->getOpcode() != ISD::LOAD) 10741 return SDValue(); 10742 10743 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10744 10745 if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) || 10746 !N0.hasOneUse() || !LN0->isSimple() || 10747 !DstVT.isVector() || !DstVT.isPow2VectorType() || 10748 !TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 10749 return SDValue(); 10750 10751 SmallVector<SDNode *, 4> SetCCs; 10752 if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI)) 10753 return SDValue(); 10754 10755 ISD::LoadExtType ExtType = 10756 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 10757 10758 // Try to split the vector types to get down to legal types. 10759 EVT SplitSrcVT = SrcVT; 10760 EVT SplitDstVT = DstVT; 10761 while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) && 10762 SplitSrcVT.getVectorNumElements() > 1) { 10763 SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first; 10764 SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first; 10765 } 10766 10767 if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT)) 10768 return SDValue(); 10769 10770 assert(!DstVT.isScalableVector() && "Unexpected scalable vector type"); 10771 10772 SDLoc DL(N); 10773 const unsigned NumSplits = 10774 DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements(); 10775 const unsigned Stride = SplitSrcVT.getStoreSize(); 10776 SmallVector<SDValue, 4> Loads; 10777 SmallVector<SDValue, 4> Chains; 10778 10779 SDValue BasePtr = LN0->getBasePtr(); 10780 for (unsigned Idx = 0; Idx < NumSplits; Idx++) { 10781 const unsigned Offset = Idx * Stride; 10782 const Align Align = commonAlignment(LN0->getAlign(), Offset); 10783 10784 SDValue SplitLoad = DAG.getExtLoad( 10785 ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr, 10786 LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align, 10787 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 10788 10789 BasePtr = DAG.getMemBasePlusOffset(BasePtr, TypeSize::Fixed(Stride), DL); 10790 10791 Loads.push_back(SplitLoad.getValue(0)); 10792 Chains.push_back(SplitLoad.getValue(1)); 10793 } 10794 10795 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 10796 SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads); 10797 10798 // Simplify TF. 10799 AddToWorklist(NewChain.getNode()); 10800 10801 CombineTo(N, NewValue); 10802 10803 // Replace uses of the original load (before extension) 10804 // with a truncate of the concatenated sextloaded vectors. 10805 SDValue Trunc = 10806 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue); 10807 ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode()); 10808 CombineTo(N0.getNode(), Trunc, NewChain); 10809 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10810 } 10811 10812 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 10813 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 10814 SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) { 10815 assert(N->getOpcode() == ISD::ZERO_EXTEND); 10816 EVT VT = N->getValueType(0); 10817 EVT OrigVT = N->getOperand(0).getValueType(); 10818 if (TLI.isZExtFree(OrigVT, VT)) 10819 return SDValue(); 10820 10821 // and/or/xor 10822 SDValue N0 = N->getOperand(0); 10823 if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 10824 N0.getOpcode() == ISD::XOR) || 10825 N0.getOperand(1).getOpcode() != ISD::Constant || 10826 (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT))) 10827 return SDValue(); 10828 10829 // shl/shr 10830 SDValue N1 = N0->getOperand(0); 10831 if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) || 10832 N1.getOperand(1).getOpcode() != ISD::Constant || 10833 (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT))) 10834 return SDValue(); 10835 10836 // load 10837 if (!isa<LoadSDNode>(N1.getOperand(0))) 10838 return SDValue(); 10839 LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0)); 10840 EVT MemVT = Load->getMemoryVT(); 10841 if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) || 10842 Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed()) 10843 return SDValue(); 10844 10845 10846 // If the shift op is SHL, the logic op must be AND, otherwise the result 10847 // will be wrong. 10848 if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND) 10849 return SDValue(); 10850 10851 if (!N0.hasOneUse() || !N1.hasOneUse()) 10852 return SDValue(); 10853 10854 SmallVector<SDNode*, 4> SetCCs; 10855 if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0), 10856 ISD::ZERO_EXTEND, SetCCs, TLI)) 10857 return SDValue(); 10858 10859 // Actually do the transformation. 10860 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT, 10861 Load->getChain(), Load->getBasePtr(), 10862 Load->getMemoryVT(), Load->getMemOperand()); 10863 10864 SDLoc DL1(N1); 10865 SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad, 10866 N1.getOperand(1)); 10867 10868 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); 10869 SDLoc DL0(N0); 10870 SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift, 10871 DAG.getConstant(Mask, DL0, VT)); 10872 10873 ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 10874 CombineTo(N, And); 10875 if (SDValue(Load, 0).hasOneUse()) { 10876 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1)); 10877 } else { 10878 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load), 10879 Load->getValueType(0), ExtLoad); 10880 CombineTo(Load, Trunc, ExtLoad.getValue(1)); 10881 } 10882 10883 // N0 is dead at this point. 10884 recursivelyDeleteUnusedNodes(N0.getNode()); 10885 10886 return SDValue(N,0); // Return N so it doesn't get rechecked! 10887 } 10888 10889 /// If we're narrowing or widening the result of a vector select and the final 10890 /// size is the same size as a setcc (compare) feeding the select, then try to 10891 /// apply the cast operation to the select's operands because matching vector 10892 /// sizes for a select condition and other operands should be more efficient. 10893 SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) { 10894 unsigned CastOpcode = Cast->getOpcode(); 10895 assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND || 10896 CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND || 10897 CastOpcode == ISD::FP_ROUND) && 10898 "Unexpected opcode for vector select narrowing/widening"); 10899 10900 // We only do this transform before legal ops because the pattern may be 10901 // obfuscated by target-specific operations after legalization. Do not create 10902 // an illegal select op, however, because that may be difficult to lower. 10903 EVT VT = Cast->getValueType(0); 10904 if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT)) 10905 return SDValue(); 10906 10907 SDValue VSel = Cast->getOperand(0); 10908 if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() || 10909 VSel.getOperand(0).getOpcode() != ISD::SETCC) 10910 return SDValue(); 10911 10912 // Does the setcc have the same vector size as the casted select? 10913 SDValue SetCC = VSel.getOperand(0); 10914 EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType()); 10915 if (SetCCVT.getSizeInBits() != VT.getSizeInBits()) 10916 return SDValue(); 10917 10918 // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B) 10919 SDValue A = VSel.getOperand(1); 10920 SDValue B = VSel.getOperand(2); 10921 SDValue CastA, CastB; 10922 SDLoc DL(Cast); 10923 if (CastOpcode == ISD::FP_ROUND) { 10924 // FP_ROUND (fptrunc) has an extra flag operand to pass along. 10925 CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1)); 10926 CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1)); 10927 } else { 10928 CastA = DAG.getNode(CastOpcode, DL, VT, A); 10929 CastB = DAG.getNode(CastOpcode, DL, VT, B); 10930 } 10931 return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB); 10932 } 10933 10934 // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 10935 // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x))) 10936 static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner, 10937 const TargetLowering &TLI, EVT VT, 10938 bool LegalOperations, SDNode *N, 10939 SDValue N0, ISD::LoadExtType ExtLoadType) { 10940 SDNode *N0Node = N0.getNode(); 10941 bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node) 10942 : ISD::isZEXTLoad(N0Node); 10943 if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) || 10944 !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse()) 10945 return SDValue(); 10946 10947 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10948 EVT MemVT = LN0->getMemoryVT(); 10949 if ((LegalOperations || !LN0->isSimple() || 10950 VT.isVector()) && 10951 !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT)) 10952 return SDValue(); 10953 10954 SDValue ExtLoad = 10955 DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 10956 LN0->getBasePtr(), MemVT, LN0->getMemOperand()); 10957 Combiner.CombineTo(N, ExtLoad); 10958 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 10959 if (LN0->use_empty()) 10960 Combiner.recursivelyDeleteUnusedNodes(LN0); 10961 return SDValue(N, 0); // Return N so it doesn't get rechecked! 10962 } 10963 10964 // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x))) 10965 // Only generate vector extloads when 1) they're legal, and 2) they are 10966 // deemed desirable by the target. 10967 static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner, 10968 const TargetLowering &TLI, EVT VT, 10969 bool LegalOperations, SDNode *N, SDValue N0, 10970 ISD::LoadExtType ExtLoadType, 10971 ISD::NodeType ExtOpc) { 10972 if (!ISD::isNON_EXTLoad(N0.getNode()) || 10973 !ISD::isUNINDEXEDLoad(N0.getNode()) || 10974 ((LegalOperations || VT.isVector() || 10975 !cast<LoadSDNode>(N0)->isSimple()) && 10976 !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType()))) 10977 return {}; 10978 10979 bool DoXform = true; 10980 SmallVector<SDNode *, 4> SetCCs; 10981 if (!N0.hasOneUse()) 10982 DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI); 10983 if (VT.isVector()) 10984 DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0)); 10985 if (!DoXform) 10986 return {}; 10987 10988 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10989 SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(), 10990 LN0->getBasePtr(), N0.getValueType(), 10991 LN0->getMemOperand()); 10992 Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc); 10993 // If the load value is used only by N, replace it via CombineTo N. 10994 bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse(); 10995 Combiner.CombineTo(N, ExtLoad); 10996 if (NoReplaceTrunc) { 10997 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 10998 Combiner.recursivelyDeleteUnusedNodes(LN0); 10999 } else { 11000 SDValue Trunc = 11001 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad); 11002 Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 11003 } 11004 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11005 } 11006 11007 static SDValue tryToFoldExtOfMaskedLoad(SelectionDAG &DAG, 11008 const TargetLowering &TLI, EVT VT, 11009 SDNode *N, SDValue N0, 11010 ISD::LoadExtType ExtLoadType, 11011 ISD::NodeType ExtOpc) { 11012 if (!N0.hasOneUse()) 11013 return SDValue(); 11014 11015 MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0); 11016 if (!Ld || Ld->getExtensionType() != ISD::NON_EXTLOAD) 11017 return SDValue(); 11018 11019 if (!TLI.isLoadExtLegalOrCustom(ExtLoadType, VT, Ld->getValueType(0))) 11020 return SDValue(); 11021 11022 if (!TLI.isVectorLoadExtDesirable(SDValue(N, 0))) 11023 return SDValue(); 11024 11025 SDLoc dl(Ld); 11026 SDValue PassThru = DAG.getNode(ExtOpc, dl, VT, Ld->getPassThru()); 11027 SDValue NewLoad = DAG.getMaskedLoad( 11028 VT, dl, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), Ld->getMask(), 11029 PassThru, Ld->getMemoryVT(), Ld->getMemOperand(), Ld->getAddressingMode(), 11030 ExtLoadType, Ld->isExpandingLoad()); 11031 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), SDValue(NewLoad.getNode(), 1)); 11032 return NewLoad; 11033 } 11034 11035 static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG, 11036 bool LegalOperations) { 11037 assert((N->getOpcode() == ISD::SIGN_EXTEND || 11038 N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext"); 11039 11040 SDValue SetCC = N->getOperand(0); 11041 if (LegalOperations || SetCC.getOpcode() != ISD::SETCC || 11042 !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1) 11043 return SDValue(); 11044 11045 SDValue X = SetCC.getOperand(0); 11046 SDValue Ones = SetCC.getOperand(1); 11047 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get(); 11048 EVT VT = N->getValueType(0); 11049 EVT XVT = X.getValueType(); 11050 // setge X, C is canonicalized to setgt, so we do not need to match that 11051 // pattern. The setlt sibling is folded in SimplifySelectCC() because it does 11052 // not require the 'not' op. 11053 if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) { 11054 // Invert and smear/shift the sign bit: 11055 // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1) 11056 // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1) 11057 SDLoc DL(N); 11058 unsigned ShCt = VT.getSizeInBits() - 1; 11059 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11060 if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) { 11061 SDValue NotX = DAG.getNOT(DL, X, VT); 11062 SDValue ShiftAmount = DAG.getConstant(ShCt, DL, VT); 11063 auto ShiftOpcode = 11064 N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL; 11065 return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount); 11066 } 11067 } 11068 return SDValue(); 11069 } 11070 11071 SDValue DAGCombiner::foldSextSetcc(SDNode *N) { 11072 SDValue N0 = N->getOperand(0); 11073 if (N0.getOpcode() != ISD::SETCC) 11074 return SDValue(); 11075 11076 SDValue N00 = N0.getOperand(0); 11077 SDValue N01 = N0.getOperand(1); 11078 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get(); 11079 EVT VT = N->getValueType(0); 11080 EVT N00VT = N00.getValueType(); 11081 SDLoc DL(N); 11082 11083 // On some architectures (such as SSE/NEON/etc) the SETCC result type is 11084 // the same size as the compared operands. Try to optimize sext(setcc()) 11085 // if this is the case. 11086 if (VT.isVector() && !LegalOperations && 11087 TLI.getBooleanContents(N00VT) == 11088 TargetLowering::ZeroOrNegativeOneBooleanContent) { 11089 EVT SVT = getSetCCResultType(N00VT); 11090 11091 // If we already have the desired type, don't change it. 11092 if (SVT != N0.getValueType()) { 11093 // We know that the # elements of the results is the same as the 11094 // # elements of the compare (and the # elements of the compare result 11095 // for that matter). Check to see that they are the same size. If so, 11096 // we know that the element size of the sext'd result matches the 11097 // element size of the compare operands. 11098 if (VT.getSizeInBits() == SVT.getSizeInBits()) 11099 return DAG.getSetCC(DL, VT, N00, N01, CC); 11100 11101 // If the desired elements are smaller or larger than the source 11102 // elements, we can use a matching integer vector type and then 11103 // truncate/sign extend. 11104 EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger(); 11105 if (SVT == MatchingVecType) { 11106 SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC); 11107 return DAG.getSExtOrTrunc(VsetCC, DL, VT); 11108 } 11109 } 11110 11111 // Try to eliminate the sext of a setcc by zexting the compare operands. 11112 if (N0.hasOneUse() && TLI.isOperationLegalOrCustom(ISD::SETCC, VT) && 11113 !TLI.isOperationLegalOrCustom(ISD::SETCC, SVT)) { 11114 bool IsSignedCmp = ISD::isSignedIntSetCC(CC); 11115 unsigned LoadOpcode = IsSignedCmp ? ISD::SEXTLOAD : ISD::ZEXTLOAD; 11116 unsigned ExtOpcode = IsSignedCmp ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 11117 11118 // We have an unsupported narrow vector compare op that would be legal 11119 // if extended to the destination type. See if the compare operands 11120 // can be freely extended to the destination type. 11121 auto IsFreeToExtend = [&](SDValue V) { 11122 if (isConstantOrConstantVector(V, /*NoOpaques*/ true)) 11123 return true; 11124 // Match a simple, non-extended load that can be converted to a 11125 // legal {z/s}ext-load. 11126 // TODO: Allow widening of an existing {z/s}ext-load? 11127 if (!(ISD::isNON_EXTLoad(V.getNode()) && 11128 ISD::isUNINDEXEDLoad(V.getNode()) && 11129 cast<LoadSDNode>(V)->isSimple() && 11130 TLI.isLoadExtLegal(LoadOpcode, VT, V.getValueType()))) 11131 return false; 11132 11133 // Non-chain users of this value must either be the setcc in this 11134 // sequence or extends that can be folded into the new {z/s}ext-load. 11135 for (SDNode::use_iterator UI = V->use_begin(), UE = V->use_end(); 11136 UI != UE; ++UI) { 11137 // Skip uses of the chain and the setcc. 11138 SDNode *User = *UI; 11139 if (UI.getUse().getResNo() != 0 || User == N0.getNode()) 11140 continue; 11141 // Extra users must have exactly the same cast we are about to create. 11142 // TODO: This restriction could be eased if ExtendUsesToFormExtLoad() 11143 // is enhanced similarly. 11144 if (User->getOpcode() != ExtOpcode || User->getValueType(0) != VT) 11145 return false; 11146 } 11147 return true; 11148 }; 11149 11150 if (IsFreeToExtend(N00) && IsFreeToExtend(N01)) { 11151 SDValue Ext0 = DAG.getNode(ExtOpcode, DL, VT, N00); 11152 SDValue Ext1 = DAG.getNode(ExtOpcode, DL, VT, N01); 11153 return DAG.getSetCC(DL, VT, Ext0, Ext1, CC); 11154 } 11155 } 11156 } 11157 11158 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0) 11159 // Here, T can be 1 or -1, depending on the type of the setcc and 11160 // getBooleanContents(). 11161 unsigned SetCCWidth = N0.getScalarValueSizeInBits(); 11162 11163 // To determine the "true" side of the select, we need to know the high bit 11164 // of the value returned by the setcc if it evaluates to true. 11165 // If the type of the setcc is i1, then the true case of the select is just 11166 // sext(i1 1), that is, -1. 11167 // If the type of the setcc is larger (say, i8) then the value of the high 11168 // bit depends on getBooleanContents(), so ask TLI for a real "true" value 11169 // of the appropriate width. 11170 SDValue ExtTrueVal = (SetCCWidth == 1) 11171 ? DAG.getAllOnesConstant(DL, VT) 11172 : DAG.getBoolConstant(true, DL, VT, N00VT); 11173 SDValue Zero = DAG.getConstant(0, DL, VT); 11174 if (SDValue SCC = SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true)) 11175 return SCC; 11176 11177 if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) { 11178 EVT SetCCVT = getSetCCResultType(N00VT); 11179 // Don't do this transform for i1 because there's a select transform 11180 // that would reverse it. 11181 // TODO: We should not do this transform at all without a target hook 11182 // because a sext is likely cheaper than a select? 11183 if (SetCCVT.getScalarSizeInBits() != 1 && 11184 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) { 11185 SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC); 11186 return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero); 11187 } 11188 } 11189 11190 return SDValue(); 11191 } 11192 11193 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) { 11194 SDValue N0 = N->getOperand(0); 11195 EVT VT = N->getValueType(0); 11196 SDLoc DL(N); 11197 11198 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 11199 return Res; 11200 11201 // fold (sext (sext x)) -> (sext x) 11202 // fold (sext (aext x)) -> (sext x) 11203 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 11204 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0)); 11205 11206 if (N0.getOpcode() == ISD::TRUNCATE) { 11207 // fold (sext (truncate (load x))) -> (sext (smaller load x)) 11208 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n))) 11209 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 11210 SDNode *oye = N0.getOperand(0).getNode(); 11211 if (NarrowLoad.getNode() != N0.getNode()) { 11212 CombineTo(N0.getNode(), NarrowLoad); 11213 // CombineTo deleted the truncate, if needed, but not what's under it. 11214 AddToWorklist(oye); 11215 } 11216 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11217 } 11218 11219 // See if the value being truncated is already sign extended. If so, just 11220 // eliminate the trunc/sext pair. 11221 SDValue Op = N0.getOperand(0); 11222 unsigned OpBits = Op.getScalarValueSizeInBits(); 11223 unsigned MidBits = N0.getScalarValueSizeInBits(); 11224 unsigned DestBits = VT.getScalarSizeInBits(); 11225 unsigned NumSignBits = DAG.ComputeNumSignBits(Op); 11226 11227 if (OpBits == DestBits) { 11228 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign 11229 // bits, it is already ready. 11230 if (NumSignBits > DestBits-MidBits) 11231 return Op; 11232 } else if (OpBits < DestBits) { 11233 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign 11234 // bits, just sext from i32. 11235 if (NumSignBits > OpBits-MidBits) 11236 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op); 11237 } else { 11238 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign 11239 // bits, just truncate to i32. 11240 if (NumSignBits > OpBits-MidBits) 11241 return DAG.getNode(ISD::TRUNCATE, DL, VT, Op); 11242 } 11243 11244 // fold (sext (truncate x)) -> (sextinreg x). 11245 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, 11246 N0.getValueType())) { 11247 if (OpBits < DestBits) 11248 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op); 11249 else if (OpBits > DestBits) 11250 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op); 11251 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op, 11252 DAG.getValueType(N0.getValueType())); 11253 } 11254 } 11255 11256 // Try to simplify (sext (load x)). 11257 if (SDValue foldedExt = 11258 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 11259 ISD::SEXTLOAD, ISD::SIGN_EXTEND)) 11260 return foldedExt; 11261 11262 if (SDValue foldedExt = 11263 tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::SEXTLOAD, 11264 ISD::SIGN_EXTEND)) 11265 return foldedExt; 11266 11267 // fold (sext (load x)) to multiple smaller sextloads. 11268 // Only on illegal but splittable vectors. 11269 if (SDValue ExtLoad = CombineExtLoad(N)) 11270 return ExtLoad; 11271 11272 // Try to simplify (sext (sextload x)). 11273 if (SDValue foldedExt = tryToFoldExtOfExtload( 11274 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD)) 11275 return foldedExt; 11276 11277 // fold (sext (and/or/xor (load x), cst)) -> 11278 // (and/or/xor (sextload x), (sext cst)) 11279 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 11280 N0.getOpcode() == ISD::XOR) && 11281 isa<LoadSDNode>(N0.getOperand(0)) && 11282 N0.getOperand(1).getOpcode() == ISD::Constant && 11283 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 11284 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 11285 EVT MemVT = LN00->getMemoryVT(); 11286 if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) && 11287 LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) { 11288 SmallVector<SDNode*, 4> SetCCs; 11289 bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 11290 ISD::SIGN_EXTEND, SetCCs, TLI); 11291 if (DoXform) { 11292 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT, 11293 LN00->getChain(), LN00->getBasePtr(), 11294 LN00->getMemoryVT(), 11295 LN00->getMemOperand()); 11296 APInt Mask = N0.getConstantOperandAPInt(1).sext(VT.getSizeInBits()); 11297 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 11298 ExtLoad, DAG.getConstant(Mask, DL, VT)); 11299 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND); 11300 bool NoReplaceTruncAnd = !N0.hasOneUse(); 11301 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 11302 CombineTo(N, And); 11303 // If N0 has multiple uses, change other uses as well. 11304 if (NoReplaceTruncAnd) { 11305 SDValue TruncAnd = 11306 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 11307 CombineTo(N0.getNode(), TruncAnd); 11308 } 11309 if (NoReplaceTrunc) { 11310 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 11311 } else { 11312 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 11313 LN00->getValueType(0), ExtLoad); 11314 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 11315 } 11316 return SDValue(N,0); // Return N so it doesn't get rechecked! 11317 } 11318 } 11319 } 11320 11321 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 11322 return V; 11323 11324 if (SDValue V = foldSextSetcc(N)) 11325 return V; 11326 11327 // fold (sext x) -> (zext x) if the sign bit is known zero. 11328 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) && 11329 DAG.SignBitIsZero(N0)) 11330 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0); 11331 11332 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 11333 return NewVSel; 11334 11335 // Eliminate this sign extend by doing a negation in the destination type: 11336 // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64) 11337 if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() && 11338 isNullOrNullSplat(N0.getOperand(0)) && 11339 N0.getOperand(1).getOpcode() == ISD::ZERO_EXTEND && 11340 TLI.isOperationLegalOrCustom(ISD::SUB, VT)) { 11341 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT); 11342 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Zext); 11343 } 11344 // Eliminate this sign extend by doing a decrement in the destination type: 11345 // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1) 11346 if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && 11347 isAllOnesOrAllOnesSplat(N0.getOperand(1)) && 11348 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 11349 TLI.isOperationLegalOrCustom(ISD::ADD, VT)) { 11350 SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT); 11351 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT)); 11352 } 11353 11354 // fold sext (not i1 X) -> add (zext i1 X), -1 11355 // TODO: This could be extended to handle bool vectors. 11356 if (N0.getValueType() == MVT::i1 && isBitwiseNot(N0) && N0.hasOneUse() && 11357 (!LegalOperations || (TLI.isOperationLegal(ISD::ZERO_EXTEND, VT) && 11358 TLI.isOperationLegal(ISD::ADD, VT)))) { 11359 // If we can eliminate the 'not', the sext form should be better 11360 if (SDValue NewXor = visitXOR(N0.getNode())) { 11361 // Returning N0 is a form of in-visit replacement that may have 11362 // invalidated N0. 11363 if (NewXor.getNode() == N0.getNode()) { 11364 // Return SDValue here as the xor should have already been replaced in 11365 // this sext. 11366 return SDValue(); 11367 } else { 11368 // Return a new sext with the new xor. 11369 return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NewXor); 11370 } 11371 } 11372 11373 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)); 11374 return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT)); 11375 } 11376 11377 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG)) 11378 return Res; 11379 11380 return SDValue(); 11381 } 11382 11383 // isTruncateOf - If N is a truncate of some other value, return true, record 11384 // the value being truncated in Op and which of Op's bits are zero/one in Known. 11385 // This function computes KnownBits to avoid a duplicated call to 11386 // computeKnownBits in the caller. 11387 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op, 11388 KnownBits &Known) { 11389 if (N->getOpcode() == ISD::TRUNCATE) { 11390 Op = N->getOperand(0); 11391 Known = DAG.computeKnownBits(Op); 11392 return true; 11393 } 11394 11395 if (N.getOpcode() != ISD::SETCC || 11396 N.getValueType().getScalarType() != MVT::i1 || 11397 cast<CondCodeSDNode>(N.getOperand(2))->get() != ISD::SETNE) 11398 return false; 11399 11400 SDValue Op0 = N->getOperand(0); 11401 SDValue Op1 = N->getOperand(1); 11402 assert(Op0.getValueType() == Op1.getValueType()); 11403 11404 if (isNullOrNullSplat(Op0)) 11405 Op = Op1; 11406 else if (isNullOrNullSplat(Op1)) 11407 Op = Op0; 11408 else 11409 return false; 11410 11411 Known = DAG.computeKnownBits(Op); 11412 11413 return (Known.Zero | 1).isAllOnes(); 11414 } 11415 11416 /// Given an extending node with a pop-count operand, if the target does not 11417 /// support a pop-count in the narrow source type but does support it in the 11418 /// destination type, widen the pop-count to the destination type. 11419 static SDValue widenCtPop(SDNode *Extend, SelectionDAG &DAG) { 11420 assert((Extend->getOpcode() == ISD::ZERO_EXTEND || 11421 Extend->getOpcode() == ISD::ANY_EXTEND) && "Expected extend op"); 11422 11423 SDValue CtPop = Extend->getOperand(0); 11424 if (CtPop.getOpcode() != ISD::CTPOP || !CtPop.hasOneUse()) 11425 return SDValue(); 11426 11427 EVT VT = Extend->getValueType(0); 11428 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11429 if (TLI.isOperationLegalOrCustom(ISD::CTPOP, CtPop.getValueType()) || 11430 !TLI.isOperationLegalOrCustom(ISD::CTPOP, VT)) 11431 return SDValue(); 11432 11433 // zext (ctpop X) --> ctpop (zext X) 11434 SDLoc DL(Extend); 11435 SDValue NewZext = DAG.getZExtOrTrunc(CtPop.getOperand(0), DL, VT); 11436 return DAG.getNode(ISD::CTPOP, DL, VT, NewZext); 11437 } 11438 11439 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) { 11440 SDValue N0 = N->getOperand(0); 11441 EVT VT = N->getValueType(0); 11442 11443 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 11444 return Res; 11445 11446 // fold (zext (zext x)) -> (zext x) 11447 // fold (zext (aext x)) -> (zext x) 11448 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) 11449 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, 11450 N0.getOperand(0)); 11451 11452 // fold (zext (truncate x)) -> (zext x) or 11453 // (zext (truncate x)) -> (truncate x) 11454 // This is valid when the truncated bits of x are already zero. 11455 SDValue Op; 11456 KnownBits Known; 11457 if (isTruncateOf(DAG, N0, Op, Known)) { 11458 APInt TruncatedBits = 11459 (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ? 11460 APInt(Op.getScalarValueSizeInBits(), 0) : 11461 APInt::getBitsSet(Op.getScalarValueSizeInBits(), 11462 N0.getScalarValueSizeInBits(), 11463 std::min(Op.getScalarValueSizeInBits(), 11464 VT.getScalarSizeInBits())); 11465 if (TruncatedBits.isSubsetOf(Known.Zero)) 11466 return DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 11467 } 11468 11469 // fold (zext (truncate x)) -> (and x, mask) 11470 if (N0.getOpcode() == ISD::TRUNCATE) { 11471 // fold (zext (truncate (load x))) -> (zext (smaller load x)) 11472 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n))) 11473 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 11474 SDNode *oye = N0.getOperand(0).getNode(); 11475 if (NarrowLoad.getNode() != N0.getNode()) { 11476 CombineTo(N0.getNode(), NarrowLoad); 11477 // CombineTo deleted the truncate, if needed, but not what's under it. 11478 AddToWorklist(oye); 11479 } 11480 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11481 } 11482 11483 EVT SrcVT = N0.getOperand(0).getValueType(); 11484 EVT MinVT = N0.getValueType(); 11485 11486 // Try to mask before the extension to avoid having to generate a larger mask, 11487 // possibly over several sub-vectors. 11488 if (SrcVT.bitsLT(VT) && VT.isVector()) { 11489 if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) && 11490 TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) { 11491 SDValue Op = N0.getOperand(0); 11492 Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT); 11493 AddToWorklist(Op.getNode()); 11494 SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT); 11495 // Transfer the debug info; the new node is equivalent to N0. 11496 DAG.transferDbgValues(N0, ZExtOrTrunc); 11497 return ZExtOrTrunc; 11498 } 11499 } 11500 11501 if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) { 11502 SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 11503 AddToWorklist(Op.getNode()); 11504 SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT); 11505 // We may safely transfer the debug info describing the truncate node over 11506 // to the equivalent and operation. 11507 DAG.transferDbgValues(N0, And); 11508 return And; 11509 } 11510 } 11511 11512 // Fold (zext (and (trunc x), cst)) -> (and x, cst), 11513 // if either of the casts is not free. 11514 if (N0.getOpcode() == ISD::AND && 11515 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 11516 N0.getOperand(1).getOpcode() == ISD::Constant && 11517 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 11518 N0.getValueType()) || 11519 !TLI.isZExtFree(N0.getValueType(), VT))) { 11520 SDValue X = N0.getOperand(0).getOperand(0); 11521 X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT); 11522 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); 11523 SDLoc DL(N); 11524 return DAG.getNode(ISD::AND, DL, VT, 11525 X, DAG.getConstant(Mask, DL, VT)); 11526 } 11527 11528 // Try to simplify (zext (load x)). 11529 if (SDValue foldedExt = 11530 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 11531 ISD::ZEXTLOAD, ISD::ZERO_EXTEND)) 11532 return foldedExt; 11533 11534 if (SDValue foldedExt = 11535 tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::ZEXTLOAD, 11536 ISD::ZERO_EXTEND)) 11537 return foldedExt; 11538 11539 // fold (zext (load x)) to multiple smaller zextloads. 11540 // Only on illegal but splittable vectors. 11541 if (SDValue ExtLoad = CombineExtLoad(N)) 11542 return ExtLoad; 11543 11544 // fold (zext (and/or/xor (load x), cst)) -> 11545 // (and/or/xor (zextload x), (zext cst)) 11546 // Unless (and (load x) cst) will match as a zextload already and has 11547 // additional users. 11548 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR || 11549 N0.getOpcode() == ISD::XOR) && 11550 isa<LoadSDNode>(N0.getOperand(0)) && 11551 N0.getOperand(1).getOpcode() == ISD::Constant && 11552 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) { 11553 LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0)); 11554 EVT MemVT = LN00->getMemoryVT(); 11555 if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) && 11556 LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) { 11557 bool DoXform = true; 11558 SmallVector<SDNode*, 4> SetCCs; 11559 if (!N0.hasOneUse()) { 11560 if (N0.getOpcode() == ISD::AND) { 11561 auto *AndC = cast<ConstantSDNode>(N0.getOperand(1)); 11562 EVT LoadResultTy = AndC->getValueType(0); 11563 EVT ExtVT; 11564 if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT)) 11565 DoXform = false; 11566 } 11567 } 11568 if (DoXform) 11569 DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0), 11570 ISD::ZERO_EXTEND, SetCCs, TLI); 11571 if (DoXform) { 11572 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT, 11573 LN00->getChain(), LN00->getBasePtr(), 11574 LN00->getMemoryVT(), 11575 LN00->getMemOperand()); 11576 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); 11577 SDLoc DL(N); 11578 SDValue And = DAG.getNode(N0.getOpcode(), DL, VT, 11579 ExtLoad, DAG.getConstant(Mask, DL, VT)); 11580 ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND); 11581 bool NoReplaceTruncAnd = !N0.hasOneUse(); 11582 bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse(); 11583 CombineTo(N, And); 11584 // If N0 has multiple uses, change other uses as well. 11585 if (NoReplaceTruncAnd) { 11586 SDValue TruncAnd = 11587 DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And); 11588 CombineTo(N0.getNode(), TruncAnd); 11589 } 11590 if (NoReplaceTrunc) { 11591 DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1)); 11592 } else { 11593 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00), 11594 LN00->getValueType(0), ExtLoad); 11595 CombineTo(LN00, Trunc, ExtLoad.getValue(1)); 11596 } 11597 return SDValue(N,0); // Return N so it doesn't get rechecked! 11598 } 11599 } 11600 } 11601 11602 // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) -> 11603 // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst)) 11604 if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N)) 11605 return ZExtLoad; 11606 11607 // Try to simplify (zext (zextload x)). 11608 if (SDValue foldedExt = tryToFoldExtOfExtload( 11609 DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD)) 11610 return foldedExt; 11611 11612 if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations)) 11613 return V; 11614 11615 if (N0.getOpcode() == ISD::SETCC) { 11616 // Only do this before legalize for now. 11617 if (!LegalOperations && VT.isVector() && 11618 N0.getValueType().getVectorElementType() == MVT::i1) { 11619 EVT N00VT = N0.getOperand(0).getValueType(); 11620 if (getSetCCResultType(N00VT) == N0.getValueType()) 11621 return SDValue(); 11622 11623 // We know that the # elements of the results is the same as the # 11624 // elements of the compare (and the # elements of the compare result for 11625 // that matter). Check to see that they are the same size. If so, we know 11626 // that the element size of the sext'd result matches the element size of 11627 // the compare operands. 11628 SDLoc DL(N); 11629 if (VT.getSizeInBits() == N00VT.getSizeInBits()) { 11630 // zext(setcc) -> zext_in_reg(vsetcc) for vectors. 11631 SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0), 11632 N0.getOperand(1), N0.getOperand(2)); 11633 return DAG.getZeroExtendInReg(VSetCC, DL, N0.getValueType()); 11634 } 11635 11636 // If the desired elements are smaller or larger than the source 11637 // elements we can use a matching integer vector type and then 11638 // truncate/any extend followed by zext_in_reg. 11639 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 11640 SDValue VsetCC = 11641 DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0), 11642 N0.getOperand(1), N0.getOperand(2)); 11643 return DAG.getZeroExtendInReg(DAG.getAnyExtOrTrunc(VsetCC, DL, VT), DL, 11644 N0.getValueType()); 11645 } 11646 11647 // zext(setcc x,y,cc) -> zext(select x, y, true, false, cc) 11648 SDLoc DL(N); 11649 EVT N0VT = N0.getValueType(); 11650 EVT N00VT = N0.getOperand(0).getValueType(); 11651 if (SDValue SCC = SimplifySelectCC( 11652 DL, N0.getOperand(0), N0.getOperand(1), 11653 DAG.getBoolConstant(true, DL, N0VT, N00VT), 11654 DAG.getBoolConstant(false, DL, N0VT, N00VT), 11655 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 11656 return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, SCC); 11657 } 11658 11659 // (zext (shl (zext x), cst)) -> (shl (zext x), cst) 11660 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) && 11661 isa<ConstantSDNode>(N0.getOperand(1)) && 11662 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 11663 N0.hasOneUse()) { 11664 SDValue ShAmt = N0.getOperand(1); 11665 if (N0.getOpcode() == ISD::SHL) { 11666 SDValue InnerZExt = N0.getOperand(0); 11667 // If the original shl may be shifting out bits, do not perform this 11668 // transformation. 11669 unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() - 11670 InnerZExt.getOperand(0).getValueSizeInBits(); 11671 if (cast<ConstantSDNode>(ShAmt)->getAPIntValue().ugt(KnownZeroBits)) 11672 return SDValue(); 11673 } 11674 11675 SDLoc DL(N); 11676 11677 // Ensure that the shift amount is wide enough for the shifted value. 11678 if (Log2_32_Ceil(VT.getSizeInBits()) > ShAmt.getValueSizeInBits()) 11679 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt); 11680 11681 return DAG.getNode(N0.getOpcode(), DL, VT, 11682 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)), 11683 ShAmt); 11684 } 11685 11686 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 11687 return NewVSel; 11688 11689 if (SDValue NewCtPop = widenCtPop(N, DAG)) 11690 return NewCtPop; 11691 11692 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG)) 11693 return Res; 11694 11695 return SDValue(); 11696 } 11697 11698 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) { 11699 SDValue N0 = N->getOperand(0); 11700 EVT VT = N->getValueType(0); 11701 11702 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 11703 return Res; 11704 11705 // fold (aext (aext x)) -> (aext x) 11706 // fold (aext (zext x)) -> (zext x) 11707 // fold (aext (sext x)) -> (sext x) 11708 if (N0.getOpcode() == ISD::ANY_EXTEND || 11709 N0.getOpcode() == ISD::ZERO_EXTEND || 11710 N0.getOpcode() == ISD::SIGN_EXTEND) 11711 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 11712 11713 // fold (aext (truncate (load x))) -> (aext (smaller load x)) 11714 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n))) 11715 if (N0.getOpcode() == ISD::TRUNCATE) { 11716 if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) { 11717 SDNode *oye = N0.getOperand(0).getNode(); 11718 if (NarrowLoad.getNode() != N0.getNode()) { 11719 CombineTo(N0.getNode(), NarrowLoad); 11720 // CombineTo deleted the truncate, if needed, but not what's under it. 11721 AddToWorklist(oye); 11722 } 11723 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11724 } 11725 } 11726 11727 // fold (aext (truncate x)) 11728 if (N0.getOpcode() == ISD::TRUNCATE) 11729 return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT); 11730 11731 // Fold (aext (and (trunc x), cst)) -> (and x, cst) 11732 // if the trunc is not free. 11733 if (N0.getOpcode() == ISD::AND && 11734 N0.getOperand(0).getOpcode() == ISD::TRUNCATE && 11735 N0.getOperand(1).getOpcode() == ISD::Constant && 11736 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(), 11737 N0.getValueType())) { 11738 SDLoc DL(N); 11739 SDValue X = N0.getOperand(0).getOperand(0); 11740 X = DAG.getAnyExtOrTrunc(X, DL, VT); 11741 APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits()); 11742 return DAG.getNode(ISD::AND, DL, VT, 11743 X, DAG.getConstant(Mask, DL, VT)); 11744 } 11745 11746 // fold (aext (load x)) -> (aext (truncate (extload x))) 11747 // None of the supported targets knows how to perform load and any_ext 11748 // on vectors in one instruction, so attempt to fold to zext instead. 11749 if (VT.isVector()) { 11750 // Try to simplify (zext (load x)). 11751 if (SDValue foldedExt = 11752 tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0, 11753 ISD::ZEXTLOAD, ISD::ZERO_EXTEND)) 11754 return foldedExt; 11755 } else if (ISD::isNON_EXTLoad(N0.getNode()) && 11756 ISD::isUNINDEXEDLoad(N0.getNode()) && 11757 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 11758 bool DoXform = true; 11759 SmallVector<SDNode *, 4> SetCCs; 11760 if (!N0.hasOneUse()) 11761 DoXform = 11762 ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, TLI); 11763 if (DoXform) { 11764 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 11765 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 11766 LN0->getChain(), LN0->getBasePtr(), 11767 N0.getValueType(), LN0->getMemOperand()); 11768 ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND); 11769 // If the load value is used only by N, replace it via CombineTo N. 11770 bool NoReplaceTrunc = N0.hasOneUse(); 11771 CombineTo(N, ExtLoad); 11772 if (NoReplaceTrunc) { 11773 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 11774 recursivelyDeleteUnusedNodes(LN0); 11775 } else { 11776 SDValue Trunc = 11777 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad); 11778 CombineTo(LN0, Trunc, ExtLoad.getValue(1)); 11779 } 11780 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11781 } 11782 } 11783 11784 // fold (aext (zextload x)) -> (aext (truncate (zextload x))) 11785 // fold (aext (sextload x)) -> (aext (truncate (sextload x))) 11786 // fold (aext ( extload x)) -> (aext (truncate (extload x))) 11787 if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) && 11788 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) { 11789 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 11790 ISD::LoadExtType ExtType = LN0->getExtensionType(); 11791 EVT MemVT = LN0->getMemoryVT(); 11792 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) { 11793 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N), 11794 VT, LN0->getChain(), LN0->getBasePtr(), 11795 MemVT, LN0->getMemOperand()); 11796 CombineTo(N, ExtLoad); 11797 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1)); 11798 recursivelyDeleteUnusedNodes(LN0); 11799 return SDValue(N, 0); // Return N so it doesn't get rechecked! 11800 } 11801 } 11802 11803 if (N0.getOpcode() == ISD::SETCC) { 11804 // For vectors: 11805 // aext(setcc) -> vsetcc 11806 // aext(setcc) -> truncate(vsetcc) 11807 // aext(setcc) -> aext(vsetcc) 11808 // Only do this before legalize for now. 11809 if (VT.isVector() && !LegalOperations) { 11810 EVT N00VT = N0.getOperand(0).getValueType(); 11811 if (getSetCCResultType(N00VT) == N0.getValueType()) 11812 return SDValue(); 11813 11814 // We know that the # elements of the results is the same as the 11815 // # elements of the compare (and the # elements of the compare result 11816 // for that matter). Check to see that they are the same size. If so, 11817 // we know that the element size of the sext'd result matches the 11818 // element size of the compare operands. 11819 if (VT.getSizeInBits() == N00VT.getSizeInBits()) 11820 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0), 11821 N0.getOperand(1), 11822 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 11823 11824 // If the desired elements are smaller or larger than the source 11825 // elements we can use a matching integer vector type and then 11826 // truncate/any extend 11827 EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger(); 11828 SDValue VsetCC = 11829 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0), 11830 N0.getOperand(1), 11831 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 11832 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT); 11833 } 11834 11835 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc 11836 SDLoc DL(N); 11837 if (SDValue SCC = SimplifySelectCC( 11838 DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT), 11839 DAG.getConstant(0, DL, VT), 11840 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true)) 11841 return SCC; 11842 } 11843 11844 if (SDValue NewCtPop = widenCtPop(N, DAG)) 11845 return NewCtPop; 11846 11847 if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG)) 11848 return Res; 11849 11850 return SDValue(); 11851 } 11852 11853 SDValue DAGCombiner::visitAssertExt(SDNode *N) { 11854 unsigned Opcode = N->getOpcode(); 11855 SDValue N0 = N->getOperand(0); 11856 SDValue N1 = N->getOperand(1); 11857 EVT AssertVT = cast<VTSDNode>(N1)->getVT(); 11858 11859 // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt) 11860 if (N0.getOpcode() == Opcode && 11861 AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT()) 11862 return N0; 11863 11864 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 11865 N0.getOperand(0).getOpcode() == Opcode) { 11866 // We have an assert, truncate, assert sandwich. Make one stronger assert 11867 // by asserting on the smallest asserted type to the larger source type. 11868 // This eliminates the later assert: 11869 // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN 11870 // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN 11871 SDValue BigA = N0.getOperand(0); 11872 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 11873 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 11874 "Asserting zero/sign-extended bits to a type larger than the " 11875 "truncated destination does not provide information"); 11876 11877 SDLoc DL(N); 11878 EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT; 11879 SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT); 11880 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 11881 BigA.getOperand(0), MinAssertVTVal); 11882 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 11883 } 11884 11885 // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller 11886 // than X. Just move the AssertZext in front of the truncate and drop the 11887 // AssertSExt. 11888 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && 11889 N0.getOperand(0).getOpcode() == ISD::AssertSext && 11890 Opcode == ISD::AssertZext) { 11891 SDValue BigA = N0.getOperand(0); 11892 EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT(); 11893 assert(BigA_AssertVT.bitsLE(N0.getValueType()) && 11894 "Asserting zero/sign-extended bits to a type larger than the " 11895 "truncated destination does not provide information"); 11896 11897 if (AssertVT.bitsLT(BigA_AssertVT)) { 11898 SDLoc DL(N); 11899 SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(), 11900 BigA.getOperand(0), N1); 11901 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert); 11902 } 11903 } 11904 11905 return SDValue(); 11906 } 11907 11908 SDValue DAGCombiner::visitAssertAlign(SDNode *N) { 11909 SDLoc DL(N); 11910 11911 Align AL = cast<AssertAlignSDNode>(N)->getAlign(); 11912 SDValue N0 = N->getOperand(0); 11913 11914 // Fold (assertalign (assertalign x, AL0), AL1) -> 11915 // (assertalign x, max(AL0, AL1)) 11916 if (auto *AAN = dyn_cast<AssertAlignSDNode>(N0)) 11917 return DAG.getAssertAlign(DL, N0.getOperand(0), 11918 std::max(AL, AAN->getAlign())); 11919 11920 // In rare cases, there are trivial arithmetic ops in source operands. Sink 11921 // this assert down to source operands so that those arithmetic ops could be 11922 // exposed to the DAG combining. 11923 switch (N0.getOpcode()) { 11924 default: 11925 break; 11926 case ISD::ADD: 11927 case ISD::SUB: { 11928 unsigned AlignShift = Log2(AL); 11929 SDValue LHS = N0.getOperand(0); 11930 SDValue RHS = N0.getOperand(1); 11931 unsigned LHSAlignShift = DAG.computeKnownBits(LHS).countMinTrailingZeros(); 11932 unsigned RHSAlignShift = DAG.computeKnownBits(RHS).countMinTrailingZeros(); 11933 if (LHSAlignShift >= AlignShift || RHSAlignShift >= AlignShift) { 11934 if (LHSAlignShift < AlignShift) 11935 LHS = DAG.getAssertAlign(DL, LHS, AL); 11936 if (RHSAlignShift < AlignShift) 11937 RHS = DAG.getAssertAlign(DL, RHS, AL); 11938 return DAG.getNode(N0.getOpcode(), DL, N0.getValueType(), LHS, RHS); 11939 } 11940 break; 11941 } 11942 } 11943 11944 return SDValue(); 11945 } 11946 11947 /// If the result of a wider load is shifted to right of N bits and then 11948 /// truncated to a narrower type and where N is a multiple of number of bits of 11949 /// the narrower type, transform it to a narrower load from address + N / num of 11950 /// bits of new type. Also narrow the load if the result is masked with an AND 11951 /// to effectively produce a smaller type. If the result is to be extended, also 11952 /// fold the extension to form a extending load. 11953 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) { 11954 unsigned Opc = N->getOpcode(); 11955 11956 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 11957 SDValue N0 = N->getOperand(0); 11958 EVT VT = N->getValueType(0); 11959 EVT ExtVT = VT; 11960 11961 // This transformation isn't valid for vector loads. 11962 if (VT.isVector()) 11963 return SDValue(); 11964 11965 unsigned ShAmt = 0; 11966 bool HasShiftedOffset = false; 11967 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then 11968 // extended to VT. 11969 if (Opc == ISD::SIGN_EXTEND_INREG) { 11970 ExtType = ISD::SEXTLOAD; 11971 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 11972 } else if (Opc == ISD::SRL) { 11973 // Another special-case: SRL is basically zero-extending a narrower value, 11974 // or it maybe shifting a higher subword, half or byte into the lowest 11975 // bits. 11976 ExtType = ISD::ZEXTLOAD; 11977 N0 = SDValue(N, 0); 11978 11979 auto *LN0 = dyn_cast<LoadSDNode>(N0.getOperand(0)); 11980 auto *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 11981 if (!N01 || !LN0) 11982 return SDValue(); 11983 11984 uint64_t ShiftAmt = N01->getZExtValue(); 11985 uint64_t MemoryWidth = LN0->getMemoryVT().getScalarSizeInBits(); 11986 if (LN0->getExtensionType() != ISD::SEXTLOAD && MemoryWidth > ShiftAmt) 11987 ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShiftAmt); 11988 else 11989 ExtVT = EVT::getIntegerVT(*DAG.getContext(), 11990 VT.getScalarSizeInBits() - ShiftAmt); 11991 } else if (Opc == ISD::AND) { 11992 // An AND with a constant mask is the same as a truncate + zero-extend. 11993 auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11994 if (!AndC) 11995 return SDValue(); 11996 11997 const APInt &Mask = AndC->getAPIntValue(); 11998 unsigned ActiveBits = 0; 11999 if (Mask.isMask()) { 12000 ActiveBits = Mask.countTrailingOnes(); 12001 } else if (Mask.isShiftedMask()) { 12002 ShAmt = Mask.countTrailingZeros(); 12003 APInt ShiftedMask = Mask.lshr(ShAmt); 12004 ActiveBits = ShiftedMask.countTrailingOnes(); 12005 HasShiftedOffset = true; 12006 } else 12007 return SDValue(); 12008 12009 ExtType = ISD::ZEXTLOAD; 12010 ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits); 12011 } 12012 12013 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) { 12014 SDValue SRL = N0; 12015 if (auto *ConstShift = dyn_cast<ConstantSDNode>(SRL.getOperand(1))) { 12016 ShAmt = ConstShift->getZExtValue(); 12017 unsigned EVTBits = ExtVT.getScalarSizeInBits(); 12018 // Is the shift amount a multiple of size of VT? 12019 if ((ShAmt & (EVTBits-1)) == 0) { 12020 N0 = N0.getOperand(0); 12021 // Is the load width a multiple of size of VT? 12022 if ((N0.getScalarValueSizeInBits() & (EVTBits - 1)) != 0) 12023 return SDValue(); 12024 } 12025 12026 // At this point, we must have a load or else we can't do the transform. 12027 auto *LN0 = dyn_cast<LoadSDNode>(N0); 12028 if (!LN0) return SDValue(); 12029 12030 // Because a SRL must be assumed to *need* to zero-extend the high bits 12031 // (as opposed to anyext the high bits), we can't combine the zextload 12032 // lowering of SRL and an sextload. 12033 if (LN0->getExtensionType() == ISD::SEXTLOAD) 12034 return SDValue(); 12035 12036 // If the shift amount is larger than the input type then we're not 12037 // accessing any of the loaded bytes. If the load was a zextload/extload 12038 // then the result of the shift+trunc is zero/undef (handled elsewhere). 12039 if (ShAmt >= LN0->getMemoryVT().getSizeInBits()) 12040 return SDValue(); 12041 12042 // If the SRL is only used by a masking AND, we may be able to adjust 12043 // the ExtVT to make the AND redundant. 12044 SDNode *Mask = *(SRL->use_begin()); 12045 if (Mask->getOpcode() == ISD::AND && 12046 isa<ConstantSDNode>(Mask->getOperand(1))) { 12047 const APInt& ShiftMask = Mask->getConstantOperandAPInt(1); 12048 if (ShiftMask.isMask()) { 12049 EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(), 12050 ShiftMask.countTrailingOnes()); 12051 // If the mask is smaller, recompute the type. 12052 if ((ExtVT.getScalarSizeInBits() > MaskedVT.getScalarSizeInBits()) && 12053 TLI.isLoadExtLegal(ExtType, N0.getValueType(), MaskedVT)) 12054 ExtVT = MaskedVT; 12055 } 12056 } 12057 } 12058 } 12059 12060 // If the load is shifted left (and the result isn't shifted back right), 12061 // we can fold the truncate through the shift. 12062 unsigned ShLeftAmt = 0; 12063 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 12064 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) { 12065 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) { 12066 ShLeftAmt = N01->getZExtValue(); 12067 N0 = N0.getOperand(0); 12068 } 12069 } 12070 12071 // If we haven't found a load, we can't narrow it. 12072 if (!isa<LoadSDNode>(N0)) 12073 return SDValue(); 12074 12075 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12076 // Reducing the width of a volatile load is illegal. For atomics, we may be 12077 // able to reduce the width provided we never widen again. (see D66309) 12078 if (!LN0->isSimple() || 12079 !isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt)) 12080 return SDValue(); 12081 12082 auto AdjustBigEndianShift = [&](unsigned ShAmt) { 12083 unsigned LVTStoreBits = 12084 LN0->getMemoryVT().getStoreSizeInBits().getFixedSize(); 12085 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits().getFixedSize(); 12086 return LVTStoreBits - EVTStoreBits - ShAmt; 12087 }; 12088 12089 // For big endian targets, we need to adjust the offset to the pointer to 12090 // load the correct bytes. 12091 if (DAG.getDataLayout().isBigEndian()) 12092 ShAmt = AdjustBigEndianShift(ShAmt); 12093 12094 uint64_t PtrOff = ShAmt / 8; 12095 Align NewAlign = commonAlignment(LN0->getAlign(), PtrOff); 12096 SDLoc DL(LN0); 12097 // The original load itself didn't wrap, so an offset within it doesn't. 12098 SDNodeFlags Flags; 12099 Flags.setNoUnsignedWrap(true); 12100 SDValue NewPtr = DAG.getMemBasePlusOffset(LN0->getBasePtr(), 12101 TypeSize::Fixed(PtrOff), DL, Flags); 12102 AddToWorklist(NewPtr.getNode()); 12103 12104 SDValue Load; 12105 if (ExtType == ISD::NON_EXTLOAD) 12106 Load = DAG.getLoad(VT, DL, LN0->getChain(), NewPtr, 12107 LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign, 12108 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 12109 else 12110 Load = DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), NewPtr, 12111 LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT, 12112 NewAlign, LN0->getMemOperand()->getFlags(), 12113 LN0->getAAInfo()); 12114 12115 // Replace the old load's chain with the new load's chain. 12116 WorklistRemover DeadNodes(*this); 12117 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 12118 12119 // Shift the result left, if we've swallowed a left shift. 12120 SDValue Result = Load; 12121 if (ShLeftAmt != 0) { 12122 EVT ShImmTy = getShiftAmountTy(Result.getValueType()); 12123 if (!isUIntN(ShImmTy.getScalarSizeInBits(), ShLeftAmt)) 12124 ShImmTy = VT; 12125 // If the shift amount is as large as the result size (but, presumably, 12126 // no larger than the source) then the useful bits of the result are 12127 // zero; we can't simply return the shortened shift, because the result 12128 // of that operation is undefined. 12129 if (ShLeftAmt >= VT.getScalarSizeInBits()) 12130 Result = DAG.getConstant(0, DL, VT); 12131 else 12132 Result = DAG.getNode(ISD::SHL, DL, VT, 12133 Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy)); 12134 } 12135 12136 if (HasShiftedOffset) { 12137 // Recalculate the shift amount after it has been altered to calculate 12138 // the offset. 12139 if (DAG.getDataLayout().isBigEndian()) 12140 ShAmt = AdjustBigEndianShift(ShAmt); 12141 12142 // We're using a shifted mask, so the load now has an offset. This means 12143 // that data has been loaded into the lower bytes than it would have been 12144 // before, so we need to shl the loaded data into the correct position in the 12145 // register. 12146 SDValue ShiftC = DAG.getConstant(ShAmt, DL, VT); 12147 Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC); 12148 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 12149 } 12150 12151 // Return the new loaded value. 12152 return Result; 12153 } 12154 12155 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) { 12156 SDValue N0 = N->getOperand(0); 12157 SDValue N1 = N->getOperand(1); 12158 EVT VT = N->getValueType(0); 12159 EVT ExtVT = cast<VTSDNode>(N1)->getVT(); 12160 unsigned VTBits = VT.getScalarSizeInBits(); 12161 unsigned ExtVTBits = ExtVT.getScalarSizeInBits(); 12162 12163 // sext_vector_inreg(undef) = 0 because the top bit will all be the same. 12164 if (N0.isUndef()) 12165 return DAG.getConstant(0, SDLoc(N), VT); 12166 12167 // fold (sext_in_reg c1) -> c1 12168 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) 12169 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1); 12170 12171 // If the input is already sign extended, just drop the extension. 12172 if (ExtVTBits >= DAG.ComputeMinSignedBits(N0)) 12173 return N0; 12174 12175 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2 12176 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG && 12177 ExtVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) 12178 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0.getOperand(0), 12179 N1); 12180 12181 // fold (sext_in_reg (sext x)) -> (sext x) 12182 // fold (sext_in_reg (aext x)) -> (sext x) 12183 // if x is small enough or if we know that x has more than 1 sign bit and the 12184 // sign_extend_inreg is extending from one of them. 12185 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) { 12186 SDValue N00 = N0.getOperand(0); 12187 unsigned N00Bits = N00.getScalarValueSizeInBits(); 12188 if ((N00Bits <= ExtVTBits || DAG.ComputeMinSignedBits(N00) <= ExtVTBits) && 12189 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 12190 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00); 12191 } 12192 12193 // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x) 12194 // if x is small enough or if we know that x has more than 1 sign bit and the 12195 // sign_extend_inreg is extending from one of them. 12196 if (N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG || 12197 N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG || 12198 N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) { 12199 SDValue N00 = N0.getOperand(0); 12200 unsigned N00Bits = N00.getScalarValueSizeInBits(); 12201 unsigned DstElts = N0.getValueType().getVectorMinNumElements(); 12202 unsigned SrcElts = N00.getValueType().getVectorMinNumElements(); 12203 bool IsZext = N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG; 12204 APInt DemandedSrcElts = APInt::getLowBitsSet(SrcElts, DstElts); 12205 if ((N00Bits == ExtVTBits || 12206 (!IsZext && (N00Bits < ExtVTBits || 12207 DAG.ComputeMinSignedBits(N00) <= ExtVTBits))) && 12208 (!LegalOperations || 12209 TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT))) 12210 return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT, N00); 12211 } 12212 12213 // fold (sext_in_reg (zext x)) -> (sext x) 12214 // iff we are extending the source sign bit. 12215 if (N0.getOpcode() == ISD::ZERO_EXTEND) { 12216 SDValue N00 = N0.getOperand(0); 12217 if (N00.getScalarValueSizeInBits() == ExtVTBits && 12218 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT))) 12219 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1); 12220 } 12221 12222 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero. 12223 if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, ExtVTBits - 1))) 12224 return DAG.getZeroExtendInReg(N0, SDLoc(N), ExtVT); 12225 12226 // fold operands of sext_in_reg based on knowledge that the top bits are not 12227 // demanded. 12228 if (SimplifyDemandedBits(SDValue(N, 0))) 12229 return SDValue(N, 0); 12230 12231 // fold (sext_in_reg (load x)) -> (smaller sextload x) 12232 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits)) 12233 if (SDValue NarrowLoad = ReduceLoadWidth(N)) 12234 return NarrowLoad; 12235 12236 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24) 12237 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible. 12238 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above. 12239 if (N0.getOpcode() == ISD::SRL) { 12240 if (auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1))) 12241 if (ShAmt->getAPIntValue().ule(VTBits - ExtVTBits)) { 12242 // We can turn this into an SRA iff the input to the SRL is already sign 12243 // extended enough. 12244 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0)); 12245 if (((VTBits - ExtVTBits) - ShAmt->getZExtValue()) < InSignBits) 12246 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0), 12247 N0.getOperand(1)); 12248 } 12249 } 12250 12251 // fold (sext_inreg (extload x)) -> (sextload x) 12252 // If sextload is not supported by target, we can only do the combine when 12253 // load has one use. Doing otherwise can block folding the extload with other 12254 // extends that the target does support. 12255 if (ISD::isEXTLoad(N0.getNode()) && 12256 ISD::isUNINDEXEDLoad(N0.getNode()) && 12257 ExtVT == cast<LoadSDNode>(N0)->getMemoryVT() && 12258 ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple() && 12259 N0.hasOneUse()) || 12260 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT))) { 12261 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12262 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 12263 LN0->getChain(), 12264 LN0->getBasePtr(), ExtVT, 12265 LN0->getMemOperand()); 12266 CombineTo(N, ExtLoad); 12267 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 12268 AddToWorklist(ExtLoad.getNode()); 12269 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12270 } 12271 12272 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use 12273 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) && 12274 N0.hasOneUse() && 12275 ExtVT == cast<LoadSDNode>(N0)->getMemoryVT() && 12276 ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) && 12277 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT))) { 12278 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12279 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT, 12280 LN0->getChain(), 12281 LN0->getBasePtr(), ExtVT, 12282 LN0->getMemOperand()); 12283 CombineTo(N, ExtLoad); 12284 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 12285 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12286 } 12287 12288 // fold (sext_inreg (masked_load x)) -> (sext_masked_load x) 12289 // ignore it if the masked load is already sign extended 12290 if (MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0)) { 12291 if (ExtVT == Ld->getMemoryVT() && N0.hasOneUse() && 12292 Ld->getExtensionType() != ISD::LoadExtType::NON_EXTLOAD && 12293 TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT)) { 12294 SDValue ExtMaskedLoad = DAG.getMaskedLoad( 12295 VT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), 12296 Ld->getMask(), Ld->getPassThru(), ExtVT, Ld->getMemOperand(), 12297 Ld->getAddressingMode(), ISD::SEXTLOAD, Ld->isExpandingLoad()); 12298 CombineTo(N, ExtMaskedLoad); 12299 CombineTo(N0.getNode(), ExtMaskedLoad, ExtMaskedLoad.getValue(1)); 12300 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12301 } 12302 } 12303 12304 // fold (sext_inreg (masked_gather x)) -> (sext_masked_gather x) 12305 if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) { 12306 if (SDValue(GN0, 0).hasOneUse() && 12307 ExtVT == GN0->getMemoryVT() && 12308 TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) { 12309 SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(), 12310 GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()}; 12311 12312 SDValue ExtLoad = DAG.getMaskedGather( 12313 DAG.getVTList(VT, MVT::Other), ExtVT, SDLoc(N), Ops, 12314 GN0->getMemOperand(), GN0->getIndexType(), ISD::SEXTLOAD); 12315 12316 CombineTo(N, ExtLoad); 12317 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1)); 12318 AddToWorklist(ExtLoad.getNode()); 12319 return SDValue(N, 0); // Return N so it doesn't get rechecked! 12320 } 12321 } 12322 12323 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16)) 12324 if (ExtVTBits <= 16 && N0.getOpcode() == ISD::OR) { 12325 if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0), 12326 N0.getOperand(1), false)) 12327 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, BSwap, N1); 12328 } 12329 12330 return SDValue(); 12331 } 12332 12333 SDValue DAGCombiner::visitEXTEND_VECTOR_INREG(SDNode *N) { 12334 SDValue N0 = N->getOperand(0); 12335 EVT VT = N->getValueType(0); 12336 12337 // {s/z}ext_vector_inreg(undef) = 0 because the top bits must be the same. 12338 if (N0.isUndef()) 12339 return DAG.getConstant(0, SDLoc(N), VT); 12340 12341 if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes)) 12342 return Res; 12343 12344 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 12345 return SDValue(N, 0); 12346 12347 return SDValue(); 12348 } 12349 12350 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) { 12351 SDValue N0 = N->getOperand(0); 12352 EVT VT = N->getValueType(0); 12353 EVT SrcVT = N0.getValueType(); 12354 bool isLE = DAG.getDataLayout().isLittleEndian(); 12355 12356 // noop truncate 12357 if (SrcVT == VT) 12358 return N0; 12359 12360 // fold (truncate (truncate x)) -> (truncate x) 12361 if (N0.getOpcode() == ISD::TRUNCATE) 12362 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 12363 12364 // fold (truncate c1) -> c1 12365 if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) { 12366 SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0); 12367 if (C.getNode() != N) 12368 return C; 12369 } 12370 12371 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x 12372 if (N0.getOpcode() == ISD::ZERO_EXTEND || 12373 N0.getOpcode() == ISD::SIGN_EXTEND || 12374 N0.getOpcode() == ISD::ANY_EXTEND) { 12375 // if the source is smaller than the dest, we still need an extend. 12376 if (N0.getOperand(0).getValueType().bitsLT(VT)) 12377 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0)); 12378 // if the source is larger than the dest, than we just need the truncate. 12379 if (N0.getOperand(0).getValueType().bitsGT(VT)) 12380 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0)); 12381 // if the source and dest are the same type, we can drop both the extend 12382 // and the truncate. 12383 return N0.getOperand(0); 12384 } 12385 12386 // If this is anyext(trunc), don't fold it, allow ourselves to be folded. 12387 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND)) 12388 return SDValue(); 12389 12390 // Fold extract-and-trunc into a narrow extract. For example: 12391 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1) 12392 // i32 y = TRUNCATE(i64 x) 12393 // -- becomes -- 12394 // v16i8 b = BITCAST (v2i64 val) 12395 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8) 12396 // 12397 // Note: We only run this optimization after type legalization (which often 12398 // creates this pattern) and before operation legalization after which 12399 // we need to be more careful about the vector instructions that we generate. 12400 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 12401 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) { 12402 EVT VecTy = N0.getOperand(0).getValueType(); 12403 EVT ExTy = N0.getValueType(); 12404 EVT TrTy = N->getValueType(0); 12405 12406 auto EltCnt = VecTy.getVectorElementCount(); 12407 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits(); 12408 auto NewEltCnt = EltCnt * SizeRatio; 12409 12410 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, NewEltCnt); 12411 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size"); 12412 12413 SDValue EltNo = N0->getOperand(1); 12414 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) { 12415 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue(); 12416 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1)); 12417 12418 SDLoc DL(N); 12419 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy, 12420 DAG.getBitcast(NVT, N0.getOperand(0)), 12421 DAG.getVectorIdxConstant(Index, DL)); 12422 } 12423 } 12424 12425 // trunc (select c, a, b) -> select c, (trunc a), (trunc b) 12426 if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) { 12427 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) && 12428 TLI.isTruncateFree(SrcVT, VT)) { 12429 SDLoc SL(N0); 12430 SDValue Cond = N0.getOperand(0); 12431 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 12432 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2)); 12433 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1); 12434 } 12435 } 12436 12437 // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits() 12438 if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() && 12439 (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) && 12440 TLI.isTypeDesirableForOp(ISD::SHL, VT)) { 12441 SDValue Amt = N0.getOperand(1); 12442 KnownBits Known = DAG.computeKnownBits(Amt); 12443 unsigned Size = VT.getScalarSizeInBits(); 12444 if (Known.countMaxActiveBits() <= Log2_32(Size)) { 12445 SDLoc SL(N); 12446 EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout()); 12447 12448 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 12449 if (AmtVT != Amt.getValueType()) { 12450 Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT); 12451 AddToWorklist(Amt.getNode()); 12452 } 12453 return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt); 12454 } 12455 } 12456 12457 if (SDValue V = foldSubToUSubSat(VT, N0.getNode())) 12458 return V; 12459 12460 // Attempt to pre-truncate BUILD_VECTOR sources. 12461 if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations && 12462 TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType()) && 12463 // Avoid creating illegal types if running after type legalizer. 12464 (!LegalTypes || TLI.isTypeLegal(VT.getScalarType()))) { 12465 SDLoc DL(N); 12466 EVT SVT = VT.getScalarType(); 12467 SmallVector<SDValue, 8> TruncOps; 12468 for (const SDValue &Op : N0->op_values()) { 12469 SDValue TruncOp = DAG.getNode(ISD::TRUNCATE, DL, SVT, Op); 12470 TruncOps.push_back(TruncOp); 12471 } 12472 return DAG.getBuildVector(VT, DL, TruncOps); 12473 } 12474 12475 // Fold a series of buildvector, bitcast, and truncate if possible. 12476 // For example fold 12477 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to 12478 // (2xi32 (buildvector x, y)). 12479 if (Level == AfterLegalizeVectorOps && VT.isVector() && 12480 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 12481 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR && 12482 N0.getOperand(0).hasOneUse()) { 12483 SDValue BuildVect = N0.getOperand(0); 12484 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType(); 12485 EVT TruncVecEltTy = VT.getVectorElementType(); 12486 12487 // Check that the element types match. 12488 if (BuildVectEltTy == TruncVecEltTy) { 12489 // Now we only need to compute the offset of the truncated elements. 12490 unsigned BuildVecNumElts = BuildVect.getNumOperands(); 12491 unsigned TruncVecNumElts = VT.getVectorNumElements(); 12492 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts; 12493 12494 assert((BuildVecNumElts % TruncVecNumElts) == 0 && 12495 "Invalid number of elements"); 12496 12497 SmallVector<SDValue, 8> Opnds; 12498 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset) 12499 Opnds.push_back(BuildVect.getOperand(i)); 12500 12501 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 12502 } 12503 } 12504 12505 // See if we can simplify the input to this truncate through knowledge that 12506 // only the low bits are being used. 12507 // For example "trunc (or (shl x, 8), y)" // -> trunc y 12508 // Currently we only perform this optimization on scalars because vectors 12509 // may have different active low bits. 12510 if (!VT.isVector()) { 12511 APInt Mask = 12512 APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits()); 12513 if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask)) 12514 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter); 12515 } 12516 12517 // fold (truncate (load x)) -> (smaller load x) 12518 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits)) 12519 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) { 12520 if (SDValue Reduced = ReduceLoadWidth(N)) 12521 return Reduced; 12522 12523 // Handle the case where the load remains an extending load even 12524 // after truncation. 12525 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) { 12526 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12527 if (LN0->isSimple() && LN0->getMemoryVT().bitsLT(VT)) { 12528 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0), 12529 VT, LN0->getChain(), LN0->getBasePtr(), 12530 LN0->getMemoryVT(), 12531 LN0->getMemOperand()); 12532 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1)); 12533 return NewLoad; 12534 } 12535 } 12536 } 12537 12538 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)), 12539 // where ... are all 'undef'. 12540 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) { 12541 SmallVector<EVT, 8> VTs; 12542 SDValue V; 12543 unsigned Idx = 0; 12544 unsigned NumDefs = 0; 12545 12546 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) { 12547 SDValue X = N0.getOperand(i); 12548 if (!X.isUndef()) { 12549 V = X; 12550 Idx = i; 12551 NumDefs++; 12552 } 12553 // Stop if more than one members are non-undef. 12554 if (NumDefs > 1) 12555 break; 12556 12557 VTs.push_back(EVT::getVectorVT(*DAG.getContext(), 12558 VT.getVectorElementType(), 12559 X.getValueType().getVectorElementCount())); 12560 } 12561 12562 if (NumDefs == 0) 12563 return DAG.getUNDEF(VT); 12564 12565 if (NumDefs == 1) { 12566 assert(V.getNode() && "The single defined operand is empty!"); 12567 SmallVector<SDValue, 8> Opnds; 12568 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 12569 if (i != Idx) { 12570 Opnds.push_back(DAG.getUNDEF(VTs[i])); 12571 continue; 12572 } 12573 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V); 12574 AddToWorklist(NV.getNode()); 12575 Opnds.push_back(NV); 12576 } 12577 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds); 12578 } 12579 } 12580 12581 // Fold truncate of a bitcast of a vector to an extract of the low vector 12582 // element. 12583 // 12584 // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx 12585 if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) { 12586 SDValue VecSrc = N0.getOperand(0); 12587 EVT VecSrcVT = VecSrc.getValueType(); 12588 if (VecSrcVT.isVector() && VecSrcVT.getScalarType() == VT && 12589 (!LegalOperations || 12590 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecSrcVT))) { 12591 SDLoc SL(N); 12592 12593 unsigned Idx = isLE ? 0 : VecSrcVT.getVectorNumElements() - 1; 12594 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, VecSrc, 12595 DAG.getVectorIdxConstant(Idx, SL)); 12596 } 12597 } 12598 12599 // Simplify the operands using demanded-bits information. 12600 if (SimplifyDemandedBits(SDValue(N, 0))) 12601 return SDValue(N, 0); 12602 12603 // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry) 12604 // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry) 12605 // When the adde's carry is not used. 12606 if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) && 12607 N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) && 12608 // We only do for addcarry before legalize operation 12609 ((!LegalOperations && N0.getOpcode() == ISD::ADDCARRY) || 12610 TLI.isOperationLegal(N0.getOpcode(), VT))) { 12611 SDLoc SL(N); 12612 auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0)); 12613 auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1)); 12614 auto VTs = DAG.getVTList(VT, N0->getValueType(1)); 12615 return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2)); 12616 } 12617 12618 // fold (truncate (extract_subvector(ext x))) -> 12619 // (extract_subvector x) 12620 // TODO: This can be generalized to cover cases where the truncate and extract 12621 // do not fully cancel each other out. 12622 if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 12623 SDValue N00 = N0.getOperand(0); 12624 if (N00.getOpcode() == ISD::SIGN_EXTEND || 12625 N00.getOpcode() == ISD::ZERO_EXTEND || 12626 N00.getOpcode() == ISD::ANY_EXTEND) { 12627 if (N00.getOperand(0)->getValueType(0).getVectorElementType() == 12628 VT.getVectorElementType()) 12629 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT, 12630 N00.getOperand(0), N0.getOperand(1)); 12631 } 12632 } 12633 12634 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 12635 return NewVSel; 12636 12637 // Narrow a suitable binary operation with a non-opaque constant operand by 12638 // moving it ahead of the truncate. This is limited to pre-legalization 12639 // because targets may prefer a wider type during later combines and invert 12640 // this transform. 12641 switch (N0.getOpcode()) { 12642 case ISD::ADD: 12643 case ISD::SUB: 12644 case ISD::MUL: 12645 case ISD::AND: 12646 case ISD::OR: 12647 case ISD::XOR: 12648 if (!LegalOperations && N0.hasOneUse() && 12649 (isConstantOrConstantVector(N0.getOperand(0), true) || 12650 isConstantOrConstantVector(N0.getOperand(1), true))) { 12651 // TODO: We already restricted this to pre-legalization, but for vectors 12652 // we are extra cautious to not create an unsupported operation. 12653 // Target-specific changes are likely needed to avoid regressions here. 12654 if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) { 12655 SDLoc DL(N); 12656 SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0)); 12657 SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1)); 12658 return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR); 12659 } 12660 } 12661 break; 12662 case ISD::USUBSAT: 12663 // Truncate the USUBSAT only if LHS is a known zero-extension, its not 12664 // enough to know that the upper bits are zero we must ensure that we don't 12665 // introduce an extra truncate. 12666 if (!LegalOperations && N0.hasOneUse() && 12667 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND && 12668 N0.getOperand(0).getOperand(0).getScalarValueSizeInBits() <= 12669 VT.getScalarSizeInBits() && 12670 hasOperation(N0.getOpcode(), VT)) { 12671 return getTruncatedUSUBSAT(VT, SrcVT, N0.getOperand(0), N0.getOperand(1), 12672 DAG, SDLoc(N)); 12673 } 12674 break; 12675 } 12676 12677 return SDValue(); 12678 } 12679 12680 static SDNode *getBuildPairElt(SDNode *N, unsigned i) { 12681 SDValue Elt = N->getOperand(i); 12682 if (Elt.getOpcode() != ISD::MERGE_VALUES) 12683 return Elt.getNode(); 12684 return Elt.getOperand(Elt.getResNo()).getNode(); 12685 } 12686 12687 /// build_pair (load, load) -> load 12688 /// if load locations are consecutive. 12689 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) { 12690 assert(N->getOpcode() == ISD::BUILD_PAIR); 12691 12692 auto *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0)); 12693 auto *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1)); 12694 12695 // A BUILD_PAIR is always having the least significant part in elt 0 and the 12696 // most significant part in elt 1. So when combining into one large load, we 12697 // need to consider the endianness. 12698 if (DAG.getDataLayout().isBigEndian()) 12699 std::swap(LD1, LD2); 12700 12701 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !ISD::isNON_EXTLoad(LD2) || 12702 !LD1->hasOneUse() || !LD2->hasOneUse() || 12703 LD1->getAddressSpace() != LD2->getAddressSpace()) 12704 return SDValue(); 12705 12706 bool LD1Fast = false; 12707 EVT LD1VT = LD1->getValueType(0); 12708 unsigned LD1Bytes = LD1VT.getStoreSize(); 12709 if ((!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) && 12710 DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1) && 12711 TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 12712 *LD1->getMemOperand(), &LD1Fast) && LD1Fast) 12713 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(), 12714 LD1->getPointerInfo(), LD1->getAlign()); 12715 12716 return SDValue(); 12717 } 12718 12719 static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) { 12720 // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi 12721 // and Lo parts; on big-endian machines it doesn't. 12722 return DAG.getDataLayout().isBigEndian() ? 1 : 0; 12723 } 12724 12725 static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG, 12726 const TargetLowering &TLI) { 12727 // If this is not a bitcast to an FP type or if the target doesn't have 12728 // IEEE754-compliant FP logic, we're done. 12729 EVT VT = N->getValueType(0); 12730 if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT)) 12731 return SDValue(); 12732 12733 // TODO: Handle cases where the integer constant is a different scalar 12734 // bitwidth to the FP. 12735 SDValue N0 = N->getOperand(0); 12736 EVT SourceVT = N0.getValueType(); 12737 if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits()) 12738 return SDValue(); 12739 12740 unsigned FPOpcode; 12741 APInt SignMask; 12742 switch (N0.getOpcode()) { 12743 case ISD::AND: 12744 FPOpcode = ISD::FABS; 12745 SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits()); 12746 break; 12747 case ISD::XOR: 12748 FPOpcode = ISD::FNEG; 12749 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits()); 12750 break; 12751 case ISD::OR: 12752 FPOpcode = ISD::FABS; 12753 SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits()); 12754 break; 12755 default: 12756 return SDValue(); 12757 } 12758 12759 // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X 12760 // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X 12761 // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) -> 12762 // fneg (fabs X) 12763 SDValue LogicOp0 = N0.getOperand(0); 12764 ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true); 12765 if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask && 12766 LogicOp0.getOpcode() == ISD::BITCAST && 12767 LogicOp0.getOperand(0).getValueType() == VT) { 12768 SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0.getOperand(0)); 12769 NumFPLogicOpsConv++; 12770 if (N0.getOpcode() == ISD::OR) 12771 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp); 12772 return FPOp; 12773 } 12774 12775 return SDValue(); 12776 } 12777 12778 SDValue DAGCombiner::visitBITCAST(SDNode *N) { 12779 SDValue N0 = N->getOperand(0); 12780 EVT VT = N->getValueType(0); 12781 12782 if (N0.isUndef()) 12783 return DAG.getUNDEF(VT); 12784 12785 // If the input is a BUILD_VECTOR with all constant elements, fold this now. 12786 // Only do this before legalize types, unless both types are integer and the 12787 // scalar type is legal. Only do this before legalize ops, since the target 12788 // maybe depending on the bitcast. 12789 // First check to see if this is all constant. 12790 // TODO: Support FP bitcasts after legalize types. 12791 if (VT.isVector() && 12792 (!LegalTypes || 12793 (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() && 12794 TLI.isTypeLegal(VT.getVectorElementType()))) && 12795 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() && 12796 cast<BuildVectorSDNode>(N0)->isConstant()) 12797 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), 12798 VT.getVectorElementType()); 12799 12800 // If the input is a constant, let getNode fold it. 12801 if (isIntOrFPConstant(N0)) { 12802 // If we can't allow illegal operations, we need to check that this is just 12803 // a fp -> int or int -> conversion and that the resulting operation will 12804 // be legal. 12805 if (!LegalOperations || 12806 (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() && 12807 TLI.isOperationLegal(ISD::ConstantFP, VT)) || 12808 (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() && 12809 TLI.isOperationLegal(ISD::Constant, VT))) { 12810 SDValue C = DAG.getBitcast(VT, N0); 12811 if (C.getNode() != N) 12812 return C; 12813 } 12814 } 12815 12816 // (conv (conv x, t1), t2) -> (conv x, t2) 12817 if (N0.getOpcode() == ISD::BITCAST) 12818 return DAG.getBitcast(VT, N0.getOperand(0)); 12819 12820 // fold (conv (load x)) -> (load (conv*)x) 12821 // If the resultant load doesn't need a higher alignment than the original! 12822 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 12823 // Do not remove the cast if the types differ in endian layout. 12824 TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) == 12825 TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) && 12826 // If the load is volatile, we only want to change the load type if the 12827 // resulting load is legal. Otherwise we might increase the number of 12828 // memory accesses. We don't care if the original type was legal or not 12829 // as we assume software couldn't rely on the number of accesses of an 12830 // illegal type. 12831 ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) || 12832 TLI.isOperationLegal(ISD::LOAD, VT))) { 12833 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 12834 12835 if (TLI.isLoadBitCastBeneficial(N0.getValueType(), VT, DAG, 12836 *LN0->getMemOperand())) { 12837 SDValue Load = 12838 DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 12839 LN0->getPointerInfo(), LN0->getAlign(), 12840 LN0->getMemOperand()->getFlags(), LN0->getAAInfo()); 12841 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1)); 12842 return Load; 12843 } 12844 } 12845 12846 if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI)) 12847 return V; 12848 12849 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 12850 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 12851 // 12852 // For ppc_fp128: 12853 // fold (bitcast (fneg x)) -> 12854 // flipbit = signbit 12855 // (xor (bitcast x) (build_pair flipbit, flipbit)) 12856 // 12857 // fold (bitcast (fabs x)) -> 12858 // flipbit = (and (extract_element (bitcast x), 0), signbit) 12859 // (xor (bitcast x) (build_pair flipbit, flipbit)) 12860 // This often reduces constant pool loads. 12861 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) || 12862 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) && 12863 N0.getNode()->hasOneUse() && VT.isInteger() && 12864 !VT.isVector() && !N0.getValueType().isVector()) { 12865 SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0)); 12866 AddToWorklist(NewConv.getNode()); 12867 12868 SDLoc DL(N); 12869 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 12870 assert(VT.getSizeInBits() == 128); 12871 SDValue SignBit = DAG.getConstant( 12872 APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64); 12873 SDValue FlipBit; 12874 if (N0.getOpcode() == ISD::FNEG) { 12875 FlipBit = SignBit; 12876 AddToWorklist(FlipBit.getNode()); 12877 } else { 12878 assert(N0.getOpcode() == ISD::FABS); 12879 SDValue Hi = 12880 DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv, 12881 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 12882 SDLoc(NewConv))); 12883 AddToWorklist(Hi.getNode()); 12884 FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit); 12885 AddToWorklist(FlipBit.getNode()); 12886 } 12887 SDValue FlipBits = 12888 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 12889 AddToWorklist(FlipBits.getNode()); 12890 return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits); 12891 } 12892 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 12893 if (N0.getOpcode() == ISD::FNEG) 12894 return DAG.getNode(ISD::XOR, DL, VT, 12895 NewConv, DAG.getConstant(SignBit, DL, VT)); 12896 assert(N0.getOpcode() == ISD::FABS); 12897 return DAG.getNode(ISD::AND, DL, VT, 12898 NewConv, DAG.getConstant(~SignBit, DL, VT)); 12899 } 12900 12901 // fold (bitconvert (fcopysign cst, x)) -> 12902 // (or (and (bitconvert x), sign), (and cst, (not sign))) 12903 // Note that we don't handle (copysign x, cst) because this can always be 12904 // folded to an fneg or fabs. 12905 // 12906 // For ppc_fp128: 12907 // fold (bitcast (fcopysign cst, x)) -> 12908 // flipbit = (and (extract_element 12909 // (xor (bitcast cst), (bitcast x)), 0), 12910 // signbit) 12911 // (xor (bitcast cst) (build_pair flipbit, flipbit)) 12912 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() && 12913 isa<ConstantFPSDNode>(N0.getOperand(0)) && 12914 VT.isInteger() && !VT.isVector()) { 12915 unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits(); 12916 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth); 12917 if (isTypeLegal(IntXVT)) { 12918 SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1)); 12919 AddToWorklist(X.getNode()); 12920 12921 // If X has a different width than the result/lhs, sext it or truncate it. 12922 unsigned VTWidth = VT.getSizeInBits(); 12923 if (OrigXWidth < VTWidth) { 12924 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X); 12925 AddToWorklist(X.getNode()); 12926 } else if (OrigXWidth > VTWidth) { 12927 // To get the sign bit in the right place, we have to shift it right 12928 // before truncating. 12929 SDLoc DL(X); 12930 X = DAG.getNode(ISD::SRL, DL, 12931 X.getValueType(), X, 12932 DAG.getConstant(OrigXWidth-VTWidth, DL, 12933 X.getValueType())); 12934 AddToWorklist(X.getNode()); 12935 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X); 12936 AddToWorklist(X.getNode()); 12937 } 12938 12939 if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) { 12940 APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2); 12941 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 12942 AddToWorklist(Cst.getNode()); 12943 SDValue X = DAG.getBitcast(VT, N0.getOperand(1)); 12944 AddToWorklist(X.getNode()); 12945 SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X); 12946 AddToWorklist(XorResult.getNode()); 12947 SDValue XorResult64 = DAG.getNode( 12948 ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult, 12949 DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG), 12950 SDLoc(XorResult))); 12951 AddToWorklist(XorResult64.getNode()); 12952 SDValue FlipBit = 12953 DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64, 12954 DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64)); 12955 AddToWorklist(FlipBit.getNode()); 12956 SDValue FlipBits = 12957 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit); 12958 AddToWorklist(FlipBits.getNode()); 12959 return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits); 12960 } 12961 APInt SignBit = APInt::getSignMask(VT.getSizeInBits()); 12962 X = DAG.getNode(ISD::AND, SDLoc(X), VT, 12963 X, DAG.getConstant(SignBit, SDLoc(X), VT)); 12964 AddToWorklist(X.getNode()); 12965 12966 SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0)); 12967 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT, 12968 Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT)); 12969 AddToWorklist(Cst.getNode()); 12970 12971 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst); 12972 } 12973 } 12974 12975 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 12976 if (N0.getOpcode() == ISD::BUILD_PAIR) 12977 if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT)) 12978 return CombineLD; 12979 12980 // Remove double bitcasts from shuffles - this is often a legacy of 12981 // XformToShuffleWithZero being used to combine bitmaskings (of 12982 // float vectors bitcast to integer vectors) into shuffles. 12983 // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1) 12984 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() && 12985 N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() && 12986 VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() && 12987 !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) { 12988 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0); 12989 12990 // If operands are a bitcast, peek through if it casts the original VT. 12991 // If operands are a constant, just bitcast back to original VT. 12992 auto PeekThroughBitcast = [&](SDValue Op) { 12993 if (Op.getOpcode() == ISD::BITCAST && 12994 Op.getOperand(0).getValueType() == VT) 12995 return SDValue(Op.getOperand(0)); 12996 if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) || 12997 ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode())) 12998 return DAG.getBitcast(VT, Op); 12999 return SDValue(); 13000 }; 13001 13002 // FIXME: If either input vector is bitcast, try to convert the shuffle to 13003 // the result type of this bitcast. This would eliminate at least one 13004 // bitcast. See the transform in InstCombine. 13005 SDValue SV0 = PeekThroughBitcast(N0->getOperand(0)); 13006 SDValue SV1 = PeekThroughBitcast(N0->getOperand(1)); 13007 if (!(SV0 && SV1)) 13008 return SDValue(); 13009 13010 int MaskScale = 13011 VT.getVectorNumElements() / N0.getValueType().getVectorNumElements(); 13012 SmallVector<int, 8> NewMask; 13013 for (int M : SVN->getMask()) 13014 for (int i = 0; i != MaskScale; ++i) 13015 NewMask.push_back(M < 0 ? -1 : M * MaskScale + i); 13016 13017 SDValue LegalShuffle = 13018 TLI.buildLegalVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask, DAG); 13019 if (LegalShuffle) 13020 return LegalShuffle; 13021 } 13022 13023 return SDValue(); 13024 } 13025 13026 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) { 13027 EVT VT = N->getValueType(0); 13028 return CombineConsecutiveLoads(N, VT); 13029 } 13030 13031 SDValue DAGCombiner::visitFREEZE(SDNode *N) { 13032 SDValue N0 = N->getOperand(0); 13033 13034 if (DAG.isGuaranteedNotToBeUndefOrPoison(N0, /*PoisonOnly*/ false)) 13035 return N0; 13036 13037 return SDValue(); 13038 } 13039 13040 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef 13041 /// operands. DstEltVT indicates the destination element value type. 13042 SDValue DAGCombiner:: 13043 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) { 13044 EVT SrcEltVT = BV->getValueType(0).getVectorElementType(); 13045 13046 // If this is already the right type, we're done. 13047 if (SrcEltVT == DstEltVT) return SDValue(BV, 0); 13048 13049 unsigned SrcBitSize = SrcEltVT.getSizeInBits(); 13050 unsigned DstBitSize = DstEltVT.getSizeInBits(); 13051 13052 // If this is a conversion of N elements of one type to N elements of another 13053 // type, convert each element. This handles FP<->INT cases. 13054 if (SrcBitSize == DstBitSize) { 13055 SmallVector<SDValue, 8> Ops; 13056 for (SDValue Op : BV->op_values()) { 13057 // If the vector element type is not legal, the BUILD_VECTOR operands 13058 // are promoted and implicitly truncated. Make that explicit here. 13059 if (Op.getValueType() != SrcEltVT) 13060 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op); 13061 Ops.push_back(DAG.getBitcast(DstEltVT, Op)); 13062 AddToWorklist(Ops.back().getNode()); 13063 } 13064 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, 13065 BV->getValueType(0).getVectorNumElements()); 13066 return DAG.getBuildVector(VT, SDLoc(BV), Ops); 13067 } 13068 13069 // Otherwise, we're growing or shrinking the elements. To avoid having to 13070 // handle annoying details of growing/shrinking FP values, we convert them to 13071 // int first. 13072 if (SrcEltVT.isFloatingPoint()) { 13073 // Convert the input float vector to a int vector where the elements are the 13074 // same sizes. 13075 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits()); 13076 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode(); 13077 SrcEltVT = IntVT; 13078 } 13079 13080 // Now we know the input is an integer vector. If the output is a FP type, 13081 // convert to integer first, then to FP of the right size. 13082 if (DstEltVT.isFloatingPoint()) { 13083 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits()); 13084 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode(); 13085 13086 // Next, convert to FP elements of the same size. 13087 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT); 13088 } 13089 13090 // Okay, we know the src/dst types are both integers of differing types. 13091 assert(SrcEltVT.isInteger() && DstEltVT.isInteger()); 13092 13093 // TODO: Should ConstantFoldBITCASTofBUILD_VECTOR always take a 13094 // BuildVectorSDNode? 13095 auto *BVN = cast<BuildVectorSDNode>(BV); 13096 13097 // Extract the constant raw bit data. 13098 BitVector UndefElements; 13099 SmallVector<APInt> RawBits; 13100 bool IsLE = DAG.getDataLayout().isLittleEndian(); 13101 if (!BVN->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements)) 13102 return SDValue(); 13103 13104 SDLoc DL(BV); 13105 SmallVector<SDValue, 8> Ops; 13106 for (unsigned I = 0, E = RawBits.size(); I != E; ++I) { 13107 if (UndefElements[I]) 13108 Ops.push_back(DAG.getUNDEF(DstEltVT)); 13109 else 13110 Ops.push_back(DAG.getConstant(RawBits[I], DL, DstEltVT)); 13111 } 13112 13113 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size()); 13114 return DAG.getBuildVector(VT, DL, Ops); 13115 } 13116 13117 // Returns true if floating point contraction is allowed on the FMUL-SDValue 13118 // `N` 13119 static bool isContractableFMUL(const TargetOptions &Options, SDValue N) { 13120 assert(N.getOpcode() == ISD::FMUL); 13121 13122 return Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 13123 N->getFlags().hasAllowContract(); 13124 } 13125 13126 // Returns true if `N` can assume no infinities involved in its computation. 13127 static bool hasNoInfs(const TargetOptions &Options, SDValue N) { 13128 return Options.NoInfsFPMath || N.getNode()->getFlags().hasNoInfs(); 13129 } 13130 13131 /// Try to perform FMA combining on a given FADD node. 13132 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) { 13133 SDValue N0 = N->getOperand(0); 13134 SDValue N1 = N->getOperand(1); 13135 EVT VT = N->getValueType(0); 13136 SDLoc SL(N); 13137 13138 const TargetOptions &Options = DAG.getTarget().Options; 13139 13140 // Floating-point multiply-add with intermediate rounding. 13141 bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N)); 13142 13143 // Floating-point multiply-add without intermediate rounding. 13144 bool HasFMA = 13145 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) && 13146 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 13147 13148 // No valid opcode, do not combine. 13149 if (!HasFMAD && !HasFMA) 13150 return SDValue(); 13151 13152 bool CanReassociate = 13153 Options.UnsafeFPMath || N->getFlags().hasAllowReassociation(); 13154 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 13155 Options.UnsafeFPMath || HasFMAD); 13156 // If the addition is not contractable, do not combine. 13157 if (!AllowFusionGlobally && !N->getFlags().hasAllowContract()) 13158 return SDValue(); 13159 13160 if (TLI.generateFMAsInMachineCombiner(VT, OptLevel)) 13161 return SDValue(); 13162 13163 // Always prefer FMAD to FMA for precision. 13164 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 13165 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 13166 13167 auto isFusedOp = [&](SDValue N) { 13168 unsigned Opcode = N.getOpcode(); 13169 return Opcode == ISD::FMA || Opcode == ISD::FMAD; 13170 }; 13171 13172 // Is the node an FMUL and contractable either due to global flags or 13173 // SDNodeFlags. 13174 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 13175 if (N.getOpcode() != ISD::FMUL) 13176 return false; 13177 return AllowFusionGlobally || N->getFlags().hasAllowContract(); 13178 }; 13179 // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)), 13180 // prefer to fold the multiply with fewer uses. 13181 if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) { 13182 if (N0.getNode()->use_size() > N1.getNode()->use_size()) 13183 std::swap(N0, N1); 13184 } 13185 13186 // fold (fadd (fmul x, y), z) -> (fma x, y, z) 13187 if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) { 13188 return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0), 13189 N0.getOperand(1), N1); 13190 } 13191 13192 // fold (fadd x, (fmul y, z)) -> (fma y, z, x) 13193 // Note: Commutes FADD operands. 13194 if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) { 13195 return DAG.getNode(PreferredFusedOpcode, SL, VT, N1.getOperand(0), 13196 N1.getOperand(1), N0); 13197 } 13198 13199 // fadd (fma A, B, (fmul C, D)), E --> fma A, B, (fma C, D, E) 13200 // fadd E, (fma A, B, (fmul C, D)) --> fma A, B, (fma C, D, E) 13201 // This requires reassociation because it changes the order of operations. 13202 SDValue FMA, E; 13203 if (CanReassociate && isFusedOp(N0) && 13204 N0.getOperand(2).getOpcode() == ISD::FMUL && N0.hasOneUse() && 13205 N0.getOperand(2).hasOneUse()) { 13206 FMA = N0; 13207 E = N1; 13208 } else if (CanReassociate && isFusedOp(N1) && 13209 N1.getOperand(2).getOpcode() == ISD::FMUL && N1.hasOneUse() && 13210 N1.getOperand(2).hasOneUse()) { 13211 FMA = N1; 13212 E = N0; 13213 } 13214 if (FMA && E) { 13215 SDValue A = FMA.getOperand(0); 13216 SDValue B = FMA.getOperand(1); 13217 SDValue C = FMA.getOperand(2).getOperand(0); 13218 SDValue D = FMA.getOperand(2).getOperand(1); 13219 SDValue CDE = DAG.getNode(PreferredFusedOpcode, SL, VT, C, D, E); 13220 return DAG.getNode(PreferredFusedOpcode, SL, VT, A, B, CDE); 13221 } 13222 13223 // Look through FP_EXTEND nodes to do more combining. 13224 13225 // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z) 13226 if (N0.getOpcode() == ISD::FP_EXTEND) { 13227 SDValue N00 = N0.getOperand(0); 13228 if (isContractableFMUL(N00) && 13229 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13230 N00.getValueType())) { 13231 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13232 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)), 13233 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)), 13234 N1); 13235 } 13236 } 13237 13238 // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x) 13239 // Note: Commutes FADD operands. 13240 if (N1.getOpcode() == ISD::FP_EXTEND) { 13241 SDValue N10 = N1.getOperand(0); 13242 if (isContractableFMUL(N10) && 13243 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13244 N10.getValueType())) { 13245 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13246 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0)), 13247 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), 13248 N0); 13249 } 13250 } 13251 13252 // More folding opportunities when target permits. 13253 if (Aggressive) { 13254 // fold (fadd (fma x, y, (fpext (fmul u, v))), z) 13255 // -> (fma x, y, (fma (fpext u), (fpext v), z)) 13256 auto FoldFAddFMAFPExtFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V, 13257 SDValue Z) { 13258 return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y, 13259 DAG.getNode(PreferredFusedOpcode, SL, VT, 13260 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 13261 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), 13262 Z)); 13263 }; 13264 if (isFusedOp(N0)) { 13265 SDValue N02 = N0.getOperand(2); 13266 if (N02.getOpcode() == ISD::FP_EXTEND) { 13267 SDValue N020 = N02.getOperand(0); 13268 if (isContractableFMUL(N020) && 13269 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13270 N020.getValueType())) { 13271 return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1), 13272 N020.getOperand(0), N020.getOperand(1), 13273 N1); 13274 } 13275 } 13276 } 13277 13278 // fold (fadd (fpext (fma x, y, (fmul u, v))), z) 13279 // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z)) 13280 // FIXME: This turns two single-precision and one double-precision 13281 // operation into two double-precision operations, which might not be 13282 // interesting for all targets, especially GPUs. 13283 auto FoldFAddFPExtFMAFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V, 13284 SDValue Z) { 13285 return DAG.getNode( 13286 PreferredFusedOpcode, SL, VT, DAG.getNode(ISD::FP_EXTEND, SL, VT, X), 13287 DAG.getNode(ISD::FP_EXTEND, SL, VT, Y), 13288 DAG.getNode(PreferredFusedOpcode, SL, VT, 13289 DAG.getNode(ISD::FP_EXTEND, SL, VT, U), 13290 DAG.getNode(ISD::FP_EXTEND, SL, VT, V), Z)); 13291 }; 13292 if (N0.getOpcode() == ISD::FP_EXTEND) { 13293 SDValue N00 = N0.getOperand(0); 13294 if (isFusedOp(N00)) { 13295 SDValue N002 = N00.getOperand(2); 13296 if (isContractableFMUL(N002) && 13297 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13298 N00.getValueType())) { 13299 return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1), 13300 N002.getOperand(0), N002.getOperand(1), 13301 N1); 13302 } 13303 } 13304 } 13305 13306 // fold (fadd x, (fma y, z, (fpext (fmul u, v))) 13307 // -> (fma y, z, (fma (fpext u), (fpext v), x)) 13308 if (isFusedOp(N1)) { 13309 SDValue N12 = N1.getOperand(2); 13310 if (N12.getOpcode() == ISD::FP_EXTEND) { 13311 SDValue N120 = N12.getOperand(0); 13312 if (isContractableFMUL(N120) && 13313 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13314 N120.getValueType())) { 13315 return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1), 13316 N120.getOperand(0), N120.getOperand(1), 13317 N0); 13318 } 13319 } 13320 } 13321 13322 // fold (fadd x, (fpext (fma y, z, (fmul u, v))) 13323 // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x)) 13324 // FIXME: This turns two single-precision and one double-precision 13325 // operation into two double-precision operations, which might not be 13326 // interesting for all targets, especially GPUs. 13327 if (N1.getOpcode() == ISD::FP_EXTEND) { 13328 SDValue N10 = N1.getOperand(0); 13329 if (isFusedOp(N10)) { 13330 SDValue N102 = N10.getOperand(2); 13331 if (isContractableFMUL(N102) && 13332 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13333 N10.getValueType())) { 13334 return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1), 13335 N102.getOperand(0), N102.getOperand(1), 13336 N0); 13337 } 13338 } 13339 } 13340 } 13341 13342 return SDValue(); 13343 } 13344 13345 /// Try to perform FMA combining on a given FSUB node. 13346 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) { 13347 SDValue N0 = N->getOperand(0); 13348 SDValue N1 = N->getOperand(1); 13349 EVT VT = N->getValueType(0); 13350 SDLoc SL(N); 13351 13352 const TargetOptions &Options = DAG.getTarget().Options; 13353 // Floating-point multiply-add with intermediate rounding. 13354 bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N)); 13355 13356 // Floating-point multiply-add without intermediate rounding. 13357 bool HasFMA = 13358 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) && 13359 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 13360 13361 // No valid opcode, do not combine. 13362 if (!HasFMAD && !HasFMA) 13363 return SDValue(); 13364 13365 const SDNodeFlags Flags = N->getFlags(); 13366 bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast || 13367 Options.UnsafeFPMath || HasFMAD); 13368 13369 // If the subtraction is not contractable, do not combine. 13370 if (!AllowFusionGlobally && !N->getFlags().hasAllowContract()) 13371 return SDValue(); 13372 13373 if (TLI.generateFMAsInMachineCombiner(VT, OptLevel)) 13374 return SDValue(); 13375 13376 // Always prefer FMAD to FMA for precision. 13377 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 13378 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 13379 bool NoSignedZero = Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros(); 13380 13381 // Is the node an FMUL and contractable either due to global flags or 13382 // SDNodeFlags. 13383 auto isContractableFMUL = [AllowFusionGlobally](SDValue N) { 13384 if (N.getOpcode() != ISD::FMUL) 13385 return false; 13386 return AllowFusionGlobally || N->getFlags().hasAllowContract(); 13387 }; 13388 13389 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 13390 auto tryToFoldXYSubZ = [&](SDValue XY, SDValue Z) { 13391 if (isContractableFMUL(XY) && (Aggressive || XY->hasOneUse())) { 13392 return DAG.getNode(PreferredFusedOpcode, SL, VT, XY.getOperand(0), 13393 XY.getOperand(1), DAG.getNode(ISD::FNEG, SL, VT, Z)); 13394 } 13395 return SDValue(); 13396 }; 13397 13398 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 13399 // Note: Commutes FSUB operands. 13400 auto tryToFoldXSubYZ = [&](SDValue X, SDValue YZ) { 13401 if (isContractableFMUL(YZ) && (Aggressive || YZ->hasOneUse())) { 13402 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13403 DAG.getNode(ISD::FNEG, SL, VT, YZ.getOperand(0)), 13404 YZ.getOperand(1), X); 13405 } 13406 return SDValue(); 13407 }; 13408 13409 // If we have two choices trying to fold (fsub (fmul u, v), (fmul x, y)), 13410 // prefer to fold the multiply with fewer uses. 13411 if (isContractableFMUL(N0) && isContractableFMUL(N1) && 13412 (N0.getNode()->use_size() > N1.getNode()->use_size())) { 13413 // fold (fsub (fmul a, b), (fmul c, d)) -> (fma (fneg c), d, (fmul a, b)) 13414 if (SDValue V = tryToFoldXSubYZ(N0, N1)) 13415 return V; 13416 // fold (fsub (fmul a, b), (fmul c, d)) -> (fma a, b, (fneg (fmul c, d))) 13417 if (SDValue V = tryToFoldXYSubZ(N0, N1)) 13418 return V; 13419 } else { 13420 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z)) 13421 if (SDValue V = tryToFoldXYSubZ(N0, N1)) 13422 return V; 13423 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x) 13424 if (SDValue V = tryToFoldXSubYZ(N0, N1)) 13425 return V; 13426 } 13427 13428 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z)) 13429 if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) && 13430 (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) { 13431 SDValue N00 = N0.getOperand(0).getOperand(0); 13432 SDValue N01 = N0.getOperand(0).getOperand(1); 13433 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13434 DAG.getNode(ISD::FNEG, SL, VT, N00), N01, 13435 DAG.getNode(ISD::FNEG, SL, VT, N1)); 13436 } 13437 13438 // Look through FP_EXTEND nodes to do more combining. 13439 13440 // fold (fsub (fpext (fmul x, y)), z) 13441 // -> (fma (fpext x), (fpext y), (fneg z)) 13442 if (N0.getOpcode() == ISD::FP_EXTEND) { 13443 SDValue N00 = N0.getOperand(0); 13444 if (isContractableFMUL(N00) && 13445 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13446 N00.getValueType())) { 13447 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13448 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)), 13449 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)), 13450 DAG.getNode(ISD::FNEG, SL, VT, N1)); 13451 } 13452 } 13453 13454 // fold (fsub x, (fpext (fmul y, z))) 13455 // -> (fma (fneg (fpext y)), (fpext z), x) 13456 // Note: Commutes FSUB operands. 13457 if (N1.getOpcode() == ISD::FP_EXTEND) { 13458 SDValue N10 = N1.getOperand(0); 13459 if (isContractableFMUL(N10) && 13460 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13461 N10.getValueType())) { 13462 return DAG.getNode( 13463 PreferredFusedOpcode, SL, VT, 13464 DAG.getNode(ISD::FNEG, SL, VT, 13465 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0))), 13466 DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), N0); 13467 } 13468 } 13469 13470 // fold (fsub (fpext (fneg (fmul, x, y))), z) 13471 // -> (fneg (fma (fpext x), (fpext y), z)) 13472 // Note: This could be removed with appropriate canonicalization of the 13473 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 13474 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 13475 // from implementing the canonicalization in visitFSUB. 13476 if (N0.getOpcode() == ISD::FP_EXTEND) { 13477 SDValue N00 = N0.getOperand(0); 13478 if (N00.getOpcode() == ISD::FNEG) { 13479 SDValue N000 = N00.getOperand(0); 13480 if (isContractableFMUL(N000) && 13481 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13482 N00.getValueType())) { 13483 return DAG.getNode( 13484 ISD::FNEG, SL, VT, 13485 DAG.getNode(PreferredFusedOpcode, SL, VT, 13486 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)), 13487 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)), 13488 N1)); 13489 } 13490 } 13491 } 13492 13493 // fold (fsub (fneg (fpext (fmul, x, y))), z) 13494 // -> (fneg (fma (fpext x)), (fpext y), z) 13495 // Note: This could be removed with appropriate canonicalization of the 13496 // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the 13497 // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent 13498 // from implementing the canonicalization in visitFSUB. 13499 if (N0.getOpcode() == ISD::FNEG) { 13500 SDValue N00 = N0.getOperand(0); 13501 if (N00.getOpcode() == ISD::FP_EXTEND) { 13502 SDValue N000 = N00.getOperand(0); 13503 if (isContractableFMUL(N000) && 13504 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13505 N000.getValueType())) { 13506 return DAG.getNode( 13507 ISD::FNEG, SL, VT, 13508 DAG.getNode(PreferredFusedOpcode, SL, VT, 13509 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)), 13510 DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)), 13511 N1)); 13512 } 13513 } 13514 } 13515 13516 auto isReassociable = [Options](SDNode *N) { 13517 return Options.UnsafeFPMath || N->getFlags().hasAllowReassociation(); 13518 }; 13519 13520 auto isContractableAndReassociableFMUL = [isContractableFMUL, 13521 isReassociable](SDValue N) { 13522 return isContractableFMUL(N) && isReassociable(N.getNode()); 13523 }; 13524 13525 auto isFusedOp = [&](SDValue N) { 13526 unsigned Opcode = N.getOpcode(); 13527 return Opcode == ISD::FMA || Opcode == ISD::FMAD; 13528 }; 13529 13530 // More folding opportunities when target permits. 13531 if (Aggressive && isReassociable(N)) { 13532 bool CanFuse = Options.UnsafeFPMath || N->getFlags().hasAllowContract(); 13533 // fold (fsub (fma x, y, (fmul u, v)), z) 13534 // -> (fma x, y (fma u, v, (fneg z))) 13535 if (CanFuse && isFusedOp(N0) && 13536 isContractableAndReassociableFMUL(N0.getOperand(2)) && 13537 N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) { 13538 return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0), 13539 N0.getOperand(1), 13540 DAG.getNode(PreferredFusedOpcode, SL, VT, 13541 N0.getOperand(2).getOperand(0), 13542 N0.getOperand(2).getOperand(1), 13543 DAG.getNode(ISD::FNEG, SL, VT, N1))); 13544 } 13545 13546 // fold (fsub x, (fma y, z, (fmul u, v))) 13547 // -> (fma (fneg y), z, (fma (fneg u), v, x)) 13548 if (CanFuse && isFusedOp(N1) && 13549 isContractableAndReassociableFMUL(N1.getOperand(2)) && 13550 N1->hasOneUse() && NoSignedZero) { 13551 SDValue N20 = N1.getOperand(2).getOperand(0); 13552 SDValue N21 = N1.getOperand(2).getOperand(1); 13553 return DAG.getNode( 13554 PreferredFusedOpcode, SL, VT, 13555 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1), 13556 DAG.getNode(PreferredFusedOpcode, SL, VT, 13557 DAG.getNode(ISD::FNEG, SL, VT, N20), N21, N0)); 13558 } 13559 13560 // fold (fsub (fma x, y, (fpext (fmul u, v))), z) 13561 // -> (fma x, y (fma (fpext u), (fpext v), (fneg z))) 13562 if (isFusedOp(N0) && N0->hasOneUse()) { 13563 SDValue N02 = N0.getOperand(2); 13564 if (N02.getOpcode() == ISD::FP_EXTEND) { 13565 SDValue N020 = N02.getOperand(0); 13566 if (isContractableAndReassociableFMUL(N020) && 13567 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13568 N020.getValueType())) { 13569 return DAG.getNode( 13570 PreferredFusedOpcode, SL, VT, N0.getOperand(0), N0.getOperand(1), 13571 DAG.getNode( 13572 PreferredFusedOpcode, SL, VT, 13573 DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(0)), 13574 DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(1)), 13575 DAG.getNode(ISD::FNEG, SL, VT, N1))); 13576 } 13577 } 13578 } 13579 13580 // fold (fsub (fpext (fma x, y, (fmul u, v))), z) 13581 // -> (fma (fpext x), (fpext y), 13582 // (fma (fpext u), (fpext v), (fneg z))) 13583 // FIXME: This turns two single-precision and one double-precision 13584 // operation into two double-precision operations, which might not be 13585 // interesting for all targets, especially GPUs. 13586 if (N0.getOpcode() == ISD::FP_EXTEND) { 13587 SDValue N00 = N0.getOperand(0); 13588 if (isFusedOp(N00)) { 13589 SDValue N002 = N00.getOperand(2); 13590 if (isContractableAndReassociableFMUL(N002) && 13591 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13592 N00.getValueType())) { 13593 return DAG.getNode( 13594 PreferredFusedOpcode, SL, VT, 13595 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)), 13596 DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)), 13597 DAG.getNode( 13598 PreferredFusedOpcode, SL, VT, 13599 DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(0)), 13600 DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(1)), 13601 DAG.getNode(ISD::FNEG, SL, VT, N1))); 13602 } 13603 } 13604 } 13605 13606 // fold (fsub x, (fma y, z, (fpext (fmul u, v)))) 13607 // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x)) 13608 if (isFusedOp(N1) && N1.getOperand(2).getOpcode() == ISD::FP_EXTEND && 13609 N1->hasOneUse()) { 13610 SDValue N120 = N1.getOperand(2).getOperand(0); 13611 if (isContractableAndReassociableFMUL(N120) && 13612 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13613 N120.getValueType())) { 13614 SDValue N1200 = N120.getOperand(0); 13615 SDValue N1201 = N120.getOperand(1); 13616 return DAG.getNode( 13617 PreferredFusedOpcode, SL, VT, 13618 DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1), 13619 DAG.getNode(PreferredFusedOpcode, SL, VT, 13620 DAG.getNode(ISD::FNEG, SL, VT, 13621 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1200)), 13622 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1201), N0)); 13623 } 13624 } 13625 13626 // fold (fsub x, (fpext (fma y, z, (fmul u, v)))) 13627 // -> (fma (fneg (fpext y)), (fpext z), 13628 // (fma (fneg (fpext u)), (fpext v), x)) 13629 // FIXME: This turns two single-precision and one double-precision 13630 // operation into two double-precision operations, which might not be 13631 // interesting for all targets, especially GPUs. 13632 if (N1.getOpcode() == ISD::FP_EXTEND && isFusedOp(N1.getOperand(0))) { 13633 SDValue CvtSrc = N1.getOperand(0); 13634 SDValue N100 = CvtSrc.getOperand(0); 13635 SDValue N101 = CvtSrc.getOperand(1); 13636 SDValue N102 = CvtSrc.getOperand(2); 13637 if (isContractableAndReassociableFMUL(N102) && 13638 TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT, 13639 CvtSrc.getValueType())) { 13640 SDValue N1020 = N102.getOperand(0); 13641 SDValue N1021 = N102.getOperand(1); 13642 return DAG.getNode( 13643 PreferredFusedOpcode, SL, VT, 13644 DAG.getNode(ISD::FNEG, SL, VT, 13645 DAG.getNode(ISD::FP_EXTEND, SL, VT, N100)), 13646 DAG.getNode(ISD::FP_EXTEND, SL, VT, N101), 13647 DAG.getNode(PreferredFusedOpcode, SL, VT, 13648 DAG.getNode(ISD::FNEG, SL, VT, 13649 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1020)), 13650 DAG.getNode(ISD::FP_EXTEND, SL, VT, N1021), N0)); 13651 } 13652 } 13653 } 13654 13655 return SDValue(); 13656 } 13657 13658 /// Try to perform FMA combining on a given FMUL node based on the distributive 13659 /// law x * (y + 1) = x * y + x and variants thereof (commuted versions, 13660 /// subtraction instead of addition). 13661 SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) { 13662 SDValue N0 = N->getOperand(0); 13663 SDValue N1 = N->getOperand(1); 13664 EVT VT = N->getValueType(0); 13665 SDLoc SL(N); 13666 13667 assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation"); 13668 13669 const TargetOptions &Options = DAG.getTarget().Options; 13670 13671 // The transforms below are incorrect when x == 0 and y == inf, because the 13672 // intermediate multiplication produces a nan. 13673 SDValue FAdd = N0.getOpcode() == ISD::FADD ? N0 : N1; 13674 if (!hasNoInfs(Options, FAdd)) 13675 return SDValue(); 13676 13677 // Floating-point multiply-add without intermediate rounding. 13678 bool HasFMA = 13679 isContractableFMUL(Options, SDValue(N, 0)) && 13680 TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) && 13681 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT)); 13682 13683 // Floating-point multiply-add with intermediate rounding. This can result 13684 // in a less precise result due to the changed rounding order. 13685 bool HasFMAD = Options.UnsafeFPMath && 13686 (LegalOperations && TLI.isFMADLegal(DAG, N)); 13687 13688 // No valid opcode, do not combine. 13689 if (!HasFMAD && !HasFMA) 13690 return SDValue(); 13691 13692 // Always prefer FMAD to FMA for precision. 13693 unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA; 13694 bool Aggressive = TLI.enableAggressiveFMAFusion(VT); 13695 13696 // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y) 13697 // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y)) 13698 auto FuseFADD = [&](SDValue X, SDValue Y) { 13699 if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) { 13700 if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) { 13701 if (C->isExactlyValue(+1.0)) 13702 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 13703 Y); 13704 if (C->isExactlyValue(-1.0)) 13705 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 13706 DAG.getNode(ISD::FNEG, SL, VT, Y)); 13707 } 13708 } 13709 return SDValue(); 13710 }; 13711 13712 if (SDValue FMA = FuseFADD(N0, N1)) 13713 return FMA; 13714 if (SDValue FMA = FuseFADD(N1, N0)) 13715 return FMA; 13716 13717 // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y) 13718 // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y)) 13719 // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y)) 13720 // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y) 13721 auto FuseFSUB = [&](SDValue X, SDValue Y) { 13722 if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) { 13723 if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) { 13724 if (C0->isExactlyValue(+1.0)) 13725 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13726 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 13727 Y); 13728 if (C0->isExactlyValue(-1.0)) 13729 return DAG.getNode(PreferredFusedOpcode, SL, VT, 13730 DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y, 13731 DAG.getNode(ISD::FNEG, SL, VT, Y)); 13732 } 13733 if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) { 13734 if (C1->isExactlyValue(+1.0)) 13735 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 13736 DAG.getNode(ISD::FNEG, SL, VT, Y)); 13737 if (C1->isExactlyValue(-1.0)) 13738 return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, 13739 Y); 13740 } 13741 } 13742 return SDValue(); 13743 }; 13744 13745 if (SDValue FMA = FuseFSUB(N0, N1)) 13746 return FMA; 13747 if (SDValue FMA = FuseFSUB(N1, N0)) 13748 return FMA; 13749 13750 return SDValue(); 13751 } 13752 13753 SDValue DAGCombiner::visitFADD(SDNode *N) { 13754 SDValue N0 = N->getOperand(0); 13755 SDValue N1 = N->getOperand(1); 13756 bool N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0); 13757 bool N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1); 13758 EVT VT = N->getValueType(0); 13759 SDLoc DL(N); 13760 const TargetOptions &Options = DAG.getTarget().Options; 13761 SDNodeFlags Flags = N->getFlags(); 13762 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 13763 13764 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) 13765 return R; 13766 13767 // fold vector ops 13768 if (VT.isVector()) 13769 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL)) 13770 return FoldedVOp; 13771 13772 // fold (fadd c1, c2) -> c1 + c2 13773 if (N0CFP && N1CFP) 13774 return DAG.getNode(ISD::FADD, DL, VT, N0, N1); 13775 13776 // canonicalize constant to RHS 13777 if (N0CFP && !N1CFP) 13778 return DAG.getNode(ISD::FADD, DL, VT, N1, N0); 13779 13780 // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math) 13781 ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true); 13782 if (N1C && N1C->isZero()) 13783 if (N1C->isNegative() || Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) 13784 return N0; 13785 13786 if (SDValue NewSel = foldBinOpIntoSelect(N)) 13787 return NewSel; 13788 13789 // fold (fadd A, (fneg B)) -> (fsub A, B) 13790 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) 13791 if (SDValue NegN1 = TLI.getCheaperNegatedExpression( 13792 N1, DAG, LegalOperations, ForCodeSize)) 13793 return DAG.getNode(ISD::FSUB, DL, VT, N0, NegN1); 13794 13795 // fold (fadd (fneg A), B) -> (fsub B, A) 13796 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) 13797 if (SDValue NegN0 = TLI.getCheaperNegatedExpression( 13798 N0, DAG, LegalOperations, ForCodeSize)) 13799 return DAG.getNode(ISD::FSUB, DL, VT, N1, NegN0); 13800 13801 auto isFMulNegTwo = [](SDValue FMul) { 13802 if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL) 13803 return false; 13804 auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true); 13805 return C && C->isExactlyValue(-2.0); 13806 }; 13807 13808 // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B) 13809 if (isFMulNegTwo(N0)) { 13810 SDValue B = N0.getOperand(0); 13811 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B); 13812 return DAG.getNode(ISD::FSUB, DL, VT, N1, Add); 13813 } 13814 // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B) 13815 if (isFMulNegTwo(N1)) { 13816 SDValue B = N1.getOperand(0); 13817 SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B); 13818 return DAG.getNode(ISD::FSUB, DL, VT, N0, Add); 13819 } 13820 13821 // No FP constant should be created after legalization as Instruction 13822 // Selection pass has a hard time dealing with FP constants. 13823 bool AllowNewConst = (Level < AfterLegalizeDAG); 13824 13825 // If nnan is enabled, fold lots of things. 13826 if ((Options.NoNaNsFPMath || Flags.hasNoNaNs()) && AllowNewConst) { 13827 // If allowed, fold (fadd (fneg x), x) -> 0.0 13828 if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) 13829 return DAG.getConstantFP(0.0, DL, VT); 13830 13831 // If allowed, fold (fadd x, (fneg x)) -> 0.0 13832 if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) 13833 return DAG.getConstantFP(0.0, DL, VT); 13834 } 13835 13836 // If 'unsafe math' or reassoc and nsz, fold lots of things. 13837 // TODO: break out portions of the transformations below for which Unsafe is 13838 // considered and which do not require both nsz and reassoc 13839 if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) || 13840 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) && 13841 AllowNewConst) { 13842 // fadd (fadd x, c1), c2 -> fadd x, c1 + c2 13843 if (N1CFP && N0.getOpcode() == ISD::FADD && 13844 DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 13845 SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1); 13846 return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC); 13847 } 13848 13849 // We can fold chains of FADD's of the same value into multiplications. 13850 // This transform is not safe in general because we are reducing the number 13851 // of rounding steps. 13852 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) { 13853 if (N0.getOpcode() == ISD::FMUL) { 13854 bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 13855 bool CFP01 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)); 13856 13857 // (fadd (fmul x, c), x) -> (fmul x, c+1) 13858 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) { 13859 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 13860 DAG.getConstantFP(1.0, DL, VT)); 13861 return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP); 13862 } 13863 13864 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2) 13865 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD && 13866 N1.getOperand(0) == N1.getOperand(1) && 13867 N0.getOperand(0) == N1.getOperand(0)) { 13868 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), 13869 DAG.getConstantFP(2.0, DL, VT)); 13870 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP); 13871 } 13872 } 13873 13874 if (N1.getOpcode() == ISD::FMUL) { 13875 bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 13876 bool CFP11 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(1)); 13877 13878 // (fadd x, (fmul x, c)) -> (fmul x, c+1) 13879 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) { 13880 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 13881 DAG.getConstantFP(1.0, DL, VT)); 13882 return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP); 13883 } 13884 13885 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2) 13886 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD && 13887 N0.getOperand(0) == N0.getOperand(1) && 13888 N1.getOperand(0) == N0.getOperand(0)) { 13889 SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1), 13890 DAG.getConstantFP(2.0, DL, VT)); 13891 return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP); 13892 } 13893 } 13894 13895 if (N0.getOpcode() == ISD::FADD) { 13896 bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0)); 13897 // (fadd (fadd x, x), x) -> (fmul x, 3.0) 13898 if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) && 13899 (N0.getOperand(0) == N1)) { 13900 return DAG.getNode(ISD::FMUL, DL, VT, N1, 13901 DAG.getConstantFP(3.0, DL, VT)); 13902 } 13903 } 13904 13905 if (N1.getOpcode() == ISD::FADD) { 13906 bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0)); 13907 // (fadd x, (fadd x, x)) -> (fmul x, 3.0) 13908 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) && 13909 N1.getOperand(0) == N0) { 13910 return DAG.getNode(ISD::FMUL, DL, VT, N0, 13911 DAG.getConstantFP(3.0, DL, VT)); 13912 } 13913 } 13914 13915 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0) 13916 if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD && 13917 N0.getOperand(0) == N0.getOperand(1) && 13918 N1.getOperand(0) == N1.getOperand(1) && 13919 N0.getOperand(0) == N1.getOperand(0)) { 13920 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), 13921 DAG.getConstantFP(4.0, DL, VT)); 13922 } 13923 } 13924 } // enable-unsafe-fp-math 13925 13926 // FADD -> FMA combines: 13927 if (SDValue Fused = visitFADDForFMACombine(N)) { 13928 AddToWorklist(Fused.getNode()); 13929 return Fused; 13930 } 13931 return SDValue(); 13932 } 13933 13934 SDValue DAGCombiner::visitSTRICT_FADD(SDNode *N) { 13935 SDValue Chain = N->getOperand(0); 13936 SDValue N0 = N->getOperand(1); 13937 SDValue N1 = N->getOperand(2); 13938 EVT VT = N->getValueType(0); 13939 EVT ChainVT = N->getValueType(1); 13940 SDLoc DL(N); 13941 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 13942 13943 // fold (strict_fadd A, (fneg B)) -> (strict_fsub A, B) 13944 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT)) 13945 if (SDValue NegN1 = TLI.getCheaperNegatedExpression( 13946 N1, DAG, LegalOperations, ForCodeSize)) { 13947 return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT), 13948 {Chain, N0, NegN1}); 13949 } 13950 13951 // fold (strict_fadd (fneg A), B) -> (strict_fsub B, A) 13952 if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT)) 13953 if (SDValue NegN0 = TLI.getCheaperNegatedExpression( 13954 N0, DAG, LegalOperations, ForCodeSize)) { 13955 return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT), 13956 {Chain, N1, NegN0}); 13957 } 13958 return SDValue(); 13959 } 13960 13961 SDValue DAGCombiner::visitFSUB(SDNode *N) { 13962 SDValue N0 = N->getOperand(0); 13963 SDValue N1 = N->getOperand(1); 13964 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true); 13965 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true); 13966 EVT VT = N->getValueType(0); 13967 SDLoc DL(N); 13968 const TargetOptions &Options = DAG.getTarget().Options; 13969 const SDNodeFlags Flags = N->getFlags(); 13970 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 13971 13972 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) 13973 return R; 13974 13975 // fold vector ops 13976 if (VT.isVector()) 13977 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL)) 13978 return FoldedVOp; 13979 13980 // fold (fsub c1, c2) -> c1-c2 13981 if (N0CFP && N1CFP) 13982 return DAG.getNode(ISD::FSUB, DL, VT, N0, N1); 13983 13984 if (SDValue NewSel = foldBinOpIntoSelect(N)) 13985 return NewSel; 13986 13987 // (fsub A, 0) -> A 13988 if (N1CFP && N1CFP->isZero()) { 13989 if (!N1CFP->isNegative() || Options.NoSignedZerosFPMath || 13990 Flags.hasNoSignedZeros()) { 13991 return N0; 13992 } 13993 } 13994 13995 if (N0 == N1) { 13996 // (fsub x, x) -> 0.0 13997 if (Options.NoNaNsFPMath || Flags.hasNoNaNs()) 13998 return DAG.getConstantFP(0.0f, DL, VT); 13999 } 14000 14001 // (fsub -0.0, N1) -> -N1 14002 if (N0CFP && N0CFP->isZero()) { 14003 if (N0CFP->isNegative() || 14004 (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())) { 14005 // We cannot replace an FSUB(+-0.0,X) with FNEG(X) when denormals are 14006 // flushed to zero, unless all users treat denorms as zero (DAZ). 14007 // FIXME: This transform will change the sign of a NaN and the behavior 14008 // of a signaling NaN. It is only valid when a NoNaN flag is present. 14009 DenormalMode DenormMode = DAG.getDenormalMode(VT); 14010 if (DenormMode == DenormalMode::getIEEE()) { 14011 if (SDValue NegN1 = 14012 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize)) 14013 return NegN1; 14014 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 14015 return DAG.getNode(ISD::FNEG, DL, VT, N1); 14016 } 14017 } 14018 } 14019 14020 if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) || 14021 (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) && 14022 N1.getOpcode() == ISD::FADD) { 14023 // X - (X + Y) -> -Y 14024 if (N0 == N1->getOperand(0)) 14025 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1)); 14026 // X - (Y + X) -> -Y 14027 if (N0 == N1->getOperand(1)) 14028 return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0)); 14029 } 14030 14031 // fold (fsub A, (fneg B)) -> (fadd A, B) 14032 if (SDValue NegN1 = 14033 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize)) 14034 return DAG.getNode(ISD::FADD, DL, VT, N0, NegN1); 14035 14036 // FSUB -> FMA combines: 14037 if (SDValue Fused = visitFSUBForFMACombine(N)) { 14038 AddToWorklist(Fused.getNode()); 14039 return Fused; 14040 } 14041 14042 return SDValue(); 14043 } 14044 14045 SDValue DAGCombiner::visitFMUL(SDNode *N) { 14046 SDValue N0 = N->getOperand(0); 14047 SDValue N1 = N->getOperand(1); 14048 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true); 14049 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true); 14050 EVT VT = N->getValueType(0); 14051 SDLoc DL(N); 14052 const TargetOptions &Options = DAG.getTarget().Options; 14053 const SDNodeFlags Flags = N->getFlags(); 14054 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 14055 14056 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) 14057 return R; 14058 14059 // fold vector ops 14060 if (VT.isVector()) { 14061 // This just handles C1 * C2 for vectors. Other vector folds are below. 14062 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL)) 14063 return FoldedVOp; 14064 } 14065 14066 // fold (fmul c1, c2) -> c1*c2 14067 if (N0CFP && N1CFP) 14068 return DAG.getNode(ISD::FMUL, DL, VT, N0, N1); 14069 14070 // canonicalize constant to RHS 14071 if (DAG.isConstantFPBuildVectorOrConstantFP(N0) && 14072 !DAG.isConstantFPBuildVectorOrConstantFP(N1)) 14073 return DAG.getNode(ISD::FMUL, DL, VT, N1, N0); 14074 14075 if (SDValue NewSel = foldBinOpIntoSelect(N)) 14076 return NewSel; 14077 14078 if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) { 14079 // fmul (fmul X, C1), C2 -> fmul X, C1 * C2 14080 if (DAG.isConstantFPBuildVectorOrConstantFP(N1) && 14081 N0.getOpcode() == ISD::FMUL) { 14082 SDValue N00 = N0.getOperand(0); 14083 SDValue N01 = N0.getOperand(1); 14084 // Avoid an infinite loop by making sure that N00 is not a constant 14085 // (the inner multiply has not been constant folded yet). 14086 if (DAG.isConstantFPBuildVectorOrConstantFP(N01) && 14087 !DAG.isConstantFPBuildVectorOrConstantFP(N00)) { 14088 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1); 14089 return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts); 14090 } 14091 } 14092 14093 // Match a special-case: we convert X * 2.0 into fadd. 14094 // fmul (fadd X, X), C -> fmul X, 2.0 * C 14095 if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() && 14096 N0.getOperand(0) == N0.getOperand(1)) { 14097 const SDValue Two = DAG.getConstantFP(2.0, DL, VT); 14098 SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1); 14099 return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts); 14100 } 14101 } 14102 14103 // fold (fmul X, 2.0) -> (fadd X, X) 14104 if (N1CFP && N1CFP->isExactlyValue(+2.0)) 14105 return DAG.getNode(ISD::FADD, DL, VT, N0, N0); 14106 14107 // fold (fmul X, -1.0) -> (fsub -0.0, X) 14108 if (N1CFP && N1CFP->isExactlyValue(-1.0)) { 14109 if (!LegalOperations || TLI.isOperationLegal(ISD::FSUB, VT)) { 14110 return DAG.getNode(ISD::FSUB, DL, VT, 14111 DAG.getConstantFP(-0.0, DL, VT), N0, Flags); 14112 } 14113 } 14114 14115 // -N0 * -N1 --> N0 * N1 14116 TargetLowering::NegatibleCost CostN0 = 14117 TargetLowering::NegatibleCost::Expensive; 14118 TargetLowering::NegatibleCost CostN1 = 14119 TargetLowering::NegatibleCost::Expensive; 14120 SDValue NegN0 = 14121 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0); 14122 SDValue NegN1 = 14123 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1); 14124 if (NegN0 && NegN1 && 14125 (CostN0 == TargetLowering::NegatibleCost::Cheaper || 14126 CostN1 == TargetLowering::NegatibleCost::Cheaper)) 14127 return DAG.getNode(ISD::FMUL, DL, VT, NegN0, NegN1); 14128 14129 // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X)) 14130 // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X) 14131 if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() && 14132 (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) && 14133 TLI.isOperationLegal(ISD::FABS, VT)) { 14134 SDValue Select = N0, X = N1; 14135 if (Select.getOpcode() != ISD::SELECT) 14136 std::swap(Select, X); 14137 14138 SDValue Cond = Select.getOperand(0); 14139 auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1)); 14140 auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2)); 14141 14142 if (TrueOpnd && FalseOpnd && 14143 Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X && 14144 isa<ConstantFPSDNode>(Cond.getOperand(1)) && 14145 cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) { 14146 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get(); 14147 switch (CC) { 14148 default: break; 14149 case ISD::SETOLT: 14150 case ISD::SETULT: 14151 case ISD::SETOLE: 14152 case ISD::SETULE: 14153 case ISD::SETLT: 14154 case ISD::SETLE: 14155 std::swap(TrueOpnd, FalseOpnd); 14156 LLVM_FALLTHROUGH; 14157 case ISD::SETOGT: 14158 case ISD::SETUGT: 14159 case ISD::SETOGE: 14160 case ISD::SETUGE: 14161 case ISD::SETGT: 14162 case ISD::SETGE: 14163 if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) && 14164 TLI.isOperationLegal(ISD::FNEG, VT)) 14165 return DAG.getNode(ISD::FNEG, DL, VT, 14166 DAG.getNode(ISD::FABS, DL, VT, X)); 14167 if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0)) 14168 return DAG.getNode(ISD::FABS, DL, VT, X); 14169 14170 break; 14171 } 14172 } 14173 } 14174 14175 // FMUL -> FMA combines: 14176 if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) { 14177 AddToWorklist(Fused.getNode()); 14178 return Fused; 14179 } 14180 14181 return SDValue(); 14182 } 14183 14184 SDValue DAGCombiner::visitFMA(SDNode *N) { 14185 SDValue N0 = N->getOperand(0); 14186 SDValue N1 = N->getOperand(1); 14187 SDValue N2 = N->getOperand(2); 14188 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 14189 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 14190 EVT VT = N->getValueType(0); 14191 SDLoc DL(N); 14192 const TargetOptions &Options = DAG.getTarget().Options; 14193 // FMA nodes have flags that propagate to the created nodes. 14194 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 14195 14196 bool UnsafeFPMath = 14197 Options.UnsafeFPMath || N->getFlags().hasAllowReassociation(); 14198 14199 // Constant fold FMA. 14200 if (isa<ConstantFPSDNode>(N0) && 14201 isa<ConstantFPSDNode>(N1) && 14202 isa<ConstantFPSDNode>(N2)) { 14203 return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2); 14204 } 14205 14206 // (-N0 * -N1) + N2 --> (N0 * N1) + N2 14207 TargetLowering::NegatibleCost CostN0 = 14208 TargetLowering::NegatibleCost::Expensive; 14209 TargetLowering::NegatibleCost CostN1 = 14210 TargetLowering::NegatibleCost::Expensive; 14211 SDValue NegN0 = 14212 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0); 14213 SDValue NegN1 = 14214 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1); 14215 if (NegN0 && NegN1 && 14216 (CostN0 == TargetLowering::NegatibleCost::Cheaper || 14217 CostN1 == TargetLowering::NegatibleCost::Cheaper)) 14218 return DAG.getNode(ISD::FMA, DL, VT, NegN0, NegN1, N2); 14219 14220 if (UnsafeFPMath) { 14221 if (N0CFP && N0CFP->isZero()) 14222 return N2; 14223 if (N1CFP && N1CFP->isZero()) 14224 return N2; 14225 } 14226 14227 if (N0CFP && N0CFP->isExactlyValue(1.0)) 14228 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2); 14229 if (N1CFP && N1CFP->isExactlyValue(1.0)) 14230 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2); 14231 14232 // Canonicalize (fma c, x, y) -> (fma x, c, y) 14233 if (DAG.isConstantFPBuildVectorOrConstantFP(N0) && 14234 !DAG.isConstantFPBuildVectorOrConstantFP(N1)) 14235 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2); 14236 14237 if (UnsafeFPMath) { 14238 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2) 14239 if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) && 14240 DAG.isConstantFPBuildVectorOrConstantFP(N1) && 14241 DAG.isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) { 14242 return DAG.getNode(ISD::FMUL, DL, VT, N0, 14243 DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1))); 14244 } 14245 14246 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y) 14247 if (N0.getOpcode() == ISD::FMUL && 14248 DAG.isConstantFPBuildVectorOrConstantFP(N1) && 14249 DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) { 14250 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 14251 DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1)), 14252 N2); 14253 } 14254 } 14255 14256 // (fma x, -1, y) -> (fadd (fneg x), y) 14257 if (N1CFP) { 14258 if (N1CFP->isExactlyValue(1.0)) 14259 return DAG.getNode(ISD::FADD, DL, VT, N0, N2); 14260 14261 if (N1CFP->isExactlyValue(-1.0) && 14262 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) { 14263 SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0); 14264 AddToWorklist(RHSNeg.getNode()); 14265 return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg); 14266 } 14267 14268 // fma (fneg x), K, y -> fma x -K, y 14269 if (N0.getOpcode() == ISD::FNEG && 14270 (TLI.isOperationLegal(ISD::ConstantFP, VT) || 14271 (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT, 14272 ForCodeSize)))) { 14273 return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0), 14274 DAG.getNode(ISD::FNEG, DL, VT, N1), N2); 14275 } 14276 } 14277 14278 if (UnsafeFPMath) { 14279 // (fma x, c, x) -> (fmul x, (c+1)) 14280 if (N1CFP && N0 == N2) { 14281 return DAG.getNode( 14282 ISD::FMUL, DL, VT, N0, 14283 DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(1.0, DL, VT))); 14284 } 14285 14286 // (fma x, c, (fneg x)) -> (fmul x, (c-1)) 14287 if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) { 14288 return DAG.getNode( 14289 ISD::FMUL, DL, VT, N0, 14290 DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(-1.0, DL, VT))); 14291 } 14292 } 14293 14294 // fold ((fma (fneg X), Y, (fneg Z)) -> fneg (fma X, Y, Z)) 14295 // fold ((fma X, (fneg Y), (fneg Z)) -> fneg (fma X, Y, Z)) 14296 if (!TLI.isFNegFree(VT)) 14297 if (SDValue Neg = TLI.getCheaperNegatedExpression( 14298 SDValue(N, 0), DAG, LegalOperations, ForCodeSize)) 14299 return DAG.getNode(ISD::FNEG, DL, VT, Neg); 14300 return SDValue(); 14301 } 14302 14303 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 14304 // reciprocal. 14305 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip) 14306 // Notice that this is not always beneficial. One reason is different targets 14307 // may have different costs for FDIV and FMUL, so sometimes the cost of two 14308 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason 14309 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL". 14310 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) { 14311 // TODO: Limit this transform based on optsize/minsize - it always creates at 14312 // least 1 extra instruction. But the perf win may be substantial enough 14313 // that only minsize should restrict this. 14314 bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath; 14315 const SDNodeFlags Flags = N->getFlags(); 14316 if (LegalDAG || (!UnsafeMath && !Flags.hasAllowReciprocal())) 14317 return SDValue(); 14318 14319 // Skip if current node is a reciprocal/fneg-reciprocal. 14320 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 14321 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, /* AllowUndefs */ true); 14322 if (N0CFP && (N0CFP->isExactlyValue(1.0) || N0CFP->isExactlyValue(-1.0))) 14323 return SDValue(); 14324 14325 // Exit early if the target does not want this transform or if there can't 14326 // possibly be enough uses of the divisor to make the transform worthwhile. 14327 unsigned MinUses = TLI.combineRepeatedFPDivisors(); 14328 14329 // For splat vectors, scale the number of uses by the splat factor. If we can 14330 // convert the division into a scalar op, that will likely be much faster. 14331 unsigned NumElts = 1; 14332 EVT VT = N->getValueType(0); 14333 if (VT.isVector() && DAG.isSplatValue(N1)) 14334 NumElts = VT.getVectorNumElements(); 14335 14336 if (!MinUses || (N1->use_size() * NumElts) < MinUses) 14337 return SDValue(); 14338 14339 // Find all FDIV users of the same divisor. 14340 // Use a set because duplicates may be present in the user list. 14341 SetVector<SDNode *> Users; 14342 for (auto *U : N1->uses()) { 14343 if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) { 14344 // Skip X/sqrt(X) that has not been simplified to sqrt(X) yet. 14345 if (U->getOperand(1).getOpcode() == ISD::FSQRT && 14346 U->getOperand(0) == U->getOperand(1).getOperand(0) && 14347 U->getFlags().hasAllowReassociation() && 14348 U->getFlags().hasNoSignedZeros()) 14349 continue; 14350 14351 // This division is eligible for optimization only if global unsafe math 14352 // is enabled or if this division allows reciprocal formation. 14353 if (UnsafeMath || U->getFlags().hasAllowReciprocal()) 14354 Users.insert(U); 14355 } 14356 } 14357 14358 // Now that we have the actual number of divisor uses, make sure it meets 14359 // the minimum threshold specified by the target. 14360 if ((Users.size() * NumElts) < MinUses) 14361 return SDValue(); 14362 14363 SDLoc DL(N); 14364 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 14365 SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags); 14366 14367 // Dividend / Divisor -> Dividend * Reciprocal 14368 for (auto *U : Users) { 14369 SDValue Dividend = U->getOperand(0); 14370 if (Dividend != FPOne) { 14371 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend, 14372 Reciprocal, Flags); 14373 CombineTo(U, NewNode); 14374 } else if (U != Reciprocal.getNode()) { 14375 // In the absence of fast-math-flags, this user node is always the 14376 // same node as Reciprocal, but with FMF they may be different nodes. 14377 CombineTo(U, Reciprocal); 14378 } 14379 } 14380 return SDValue(N, 0); // N was replaced. 14381 } 14382 14383 SDValue DAGCombiner::visitFDIV(SDNode *N) { 14384 SDValue N0 = N->getOperand(0); 14385 SDValue N1 = N->getOperand(1); 14386 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 14387 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 14388 EVT VT = N->getValueType(0); 14389 SDLoc DL(N); 14390 const TargetOptions &Options = DAG.getTarget().Options; 14391 SDNodeFlags Flags = N->getFlags(); 14392 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 14393 14394 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) 14395 return R; 14396 14397 // fold vector ops 14398 if (VT.isVector()) 14399 if (SDValue FoldedVOp = SimplifyVBinOp(N, DL)) 14400 return FoldedVOp; 14401 14402 // fold (fdiv c1, c2) -> c1/c2 14403 if (N0CFP && N1CFP) 14404 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1); 14405 14406 if (SDValue NewSel = foldBinOpIntoSelect(N)) 14407 return NewSel; 14408 14409 if (SDValue V = combineRepeatedFPDivisors(N)) 14410 return V; 14411 14412 if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) { 14413 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable. 14414 if (N1CFP) { 14415 // Compute the reciprocal 1.0 / c2. 14416 const APFloat &N1APF = N1CFP->getValueAPF(); 14417 APFloat Recip(N1APF.getSemantics(), 1); // 1.0 14418 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven); 14419 // Only do the transform if the reciprocal is a legal fp immediate that 14420 // isn't too nasty (eg NaN, denormal, ...). 14421 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty 14422 (!LegalOperations || 14423 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM 14424 // backend)... we should handle this gracefully after Legalize. 14425 // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) || 14426 TLI.isOperationLegal(ISD::ConstantFP, VT) || 14427 TLI.isFPImmLegal(Recip, VT, ForCodeSize))) 14428 return DAG.getNode(ISD::FMUL, DL, VT, N0, 14429 DAG.getConstantFP(Recip, DL, VT)); 14430 } 14431 14432 // If this FDIV is part of a reciprocal square root, it may be folded 14433 // into a target-specific square root estimate instruction. 14434 if (N1.getOpcode() == ISD::FSQRT) { 14435 if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags)) 14436 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 14437 } else if (N1.getOpcode() == ISD::FP_EXTEND && 14438 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 14439 if (SDValue RV = 14440 buildRsqrtEstimate(N1.getOperand(0).getOperand(0), Flags)) { 14441 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV); 14442 AddToWorklist(RV.getNode()); 14443 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 14444 } 14445 } else if (N1.getOpcode() == ISD::FP_ROUND && 14446 N1.getOperand(0).getOpcode() == ISD::FSQRT) { 14447 if (SDValue RV = 14448 buildRsqrtEstimate(N1.getOperand(0).getOperand(0), Flags)) { 14449 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1)); 14450 AddToWorklist(RV.getNode()); 14451 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV); 14452 } 14453 } else if (N1.getOpcode() == ISD::FMUL) { 14454 // Look through an FMUL. Even though this won't remove the FDIV directly, 14455 // it's still worthwhile to get rid of the FSQRT if possible. 14456 SDValue Sqrt, Y; 14457 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) { 14458 Sqrt = N1.getOperand(0); 14459 Y = N1.getOperand(1); 14460 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) { 14461 Sqrt = N1.getOperand(1); 14462 Y = N1.getOperand(0); 14463 } 14464 if (Sqrt.getNode()) { 14465 // If the other multiply operand is known positive, pull it into the 14466 // sqrt. That will eliminate the division if we convert to an estimate. 14467 if (Flags.hasAllowReassociation() && N1.hasOneUse() && 14468 N1->getFlags().hasAllowReassociation() && Sqrt.hasOneUse()) { 14469 SDValue A; 14470 if (Y.getOpcode() == ISD::FABS && Y.hasOneUse()) 14471 A = Y.getOperand(0); 14472 else if (Y == Sqrt.getOperand(0)) 14473 A = Y; 14474 if (A) { 14475 // X / (fabs(A) * sqrt(Z)) --> X / sqrt(A*A*Z) --> X * rsqrt(A*A*Z) 14476 // X / (A * sqrt(A)) --> X / sqrt(A*A*A) --> X * rsqrt(A*A*A) 14477 SDValue AA = DAG.getNode(ISD::FMUL, DL, VT, A, A); 14478 SDValue AAZ = 14479 DAG.getNode(ISD::FMUL, DL, VT, AA, Sqrt.getOperand(0)); 14480 if (SDValue Rsqrt = buildRsqrtEstimate(AAZ, Flags)) 14481 return DAG.getNode(ISD::FMUL, DL, VT, N0, Rsqrt); 14482 14483 // Estimate creation failed. Clean up speculatively created nodes. 14484 recursivelyDeleteUnusedNodes(AAZ.getNode()); 14485 } 14486 } 14487 14488 // We found a FSQRT, so try to make this fold: 14489 // X / (Y * sqrt(Z)) -> X * (rsqrt(Z) / Y) 14490 if (SDValue Rsqrt = buildRsqrtEstimate(Sqrt.getOperand(0), Flags)) { 14491 SDValue Div = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, Rsqrt, Y); 14492 AddToWorklist(Div.getNode()); 14493 return DAG.getNode(ISD::FMUL, DL, VT, N0, Div); 14494 } 14495 } 14496 } 14497 14498 // Fold into a reciprocal estimate and multiply instead of a real divide. 14499 if (Options.NoInfsFPMath || Flags.hasNoInfs()) 14500 if (SDValue RV = BuildDivEstimate(N0, N1, Flags)) 14501 return RV; 14502 } 14503 14504 // Fold X/Sqrt(X) -> Sqrt(X) 14505 if ((Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) && 14506 (Options.UnsafeFPMath || Flags.hasAllowReassociation())) 14507 if (N1.getOpcode() == ISD::FSQRT && N0 == N1.getOperand(0)) 14508 return N1; 14509 14510 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y) 14511 TargetLowering::NegatibleCost CostN0 = 14512 TargetLowering::NegatibleCost::Expensive; 14513 TargetLowering::NegatibleCost CostN1 = 14514 TargetLowering::NegatibleCost::Expensive; 14515 SDValue NegN0 = 14516 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0); 14517 SDValue NegN1 = 14518 TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1); 14519 if (NegN0 && NegN1 && 14520 (CostN0 == TargetLowering::NegatibleCost::Cheaper || 14521 CostN1 == TargetLowering::NegatibleCost::Cheaper)) 14522 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, NegN0, NegN1); 14523 14524 return SDValue(); 14525 } 14526 14527 SDValue DAGCombiner::visitFREM(SDNode *N) { 14528 SDValue N0 = N->getOperand(0); 14529 SDValue N1 = N->getOperand(1); 14530 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 14531 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1); 14532 EVT VT = N->getValueType(0); 14533 SDNodeFlags Flags = N->getFlags(); 14534 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 14535 14536 if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags)) 14537 return R; 14538 14539 // fold (frem c1, c2) -> fmod(c1,c2) 14540 if (N0CFP && N1CFP) 14541 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1); 14542 14543 if (SDValue NewSel = foldBinOpIntoSelect(N)) 14544 return NewSel; 14545 14546 return SDValue(); 14547 } 14548 14549 SDValue DAGCombiner::visitFSQRT(SDNode *N) { 14550 SDNodeFlags Flags = N->getFlags(); 14551 const TargetOptions &Options = DAG.getTarget().Options; 14552 14553 // Require 'ninf' flag since sqrt(+Inf) = +Inf, but the estimation goes as: 14554 // sqrt(+Inf) == rsqrt(+Inf) * +Inf = 0 * +Inf = NaN 14555 if (!Flags.hasApproximateFuncs() || 14556 (!Options.NoInfsFPMath && !Flags.hasNoInfs())) 14557 return SDValue(); 14558 14559 SDValue N0 = N->getOperand(0); 14560 if (TLI.isFsqrtCheap(N0, DAG)) 14561 return SDValue(); 14562 14563 // FSQRT nodes have flags that propagate to the created nodes. 14564 // TODO: If this is N0/sqrt(N0), and we reach this node before trying to 14565 // transform the fdiv, we may produce a sub-optimal estimate sequence 14566 // because the reciprocal calculation may not have to filter out a 14567 // 0.0 input. 14568 return buildSqrtEstimate(N0, Flags); 14569 } 14570 14571 /// copysign(x, fp_extend(y)) -> copysign(x, y) 14572 /// copysign(x, fp_round(y)) -> copysign(x, y) 14573 static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) { 14574 SDValue N1 = N->getOperand(1); 14575 if ((N1.getOpcode() == ISD::FP_EXTEND || 14576 N1.getOpcode() == ISD::FP_ROUND)) { 14577 EVT N1VT = N1->getValueType(0); 14578 EVT N1Op0VT = N1->getOperand(0).getValueType(); 14579 14580 // Always fold no-op FP casts. 14581 if (N1VT == N1Op0VT) 14582 return true; 14583 14584 // Do not optimize out type conversion of f128 type yet. 14585 // For some targets like x86_64, configuration is changed to keep one f128 14586 // value in one SSE register, but instruction selection cannot handle 14587 // FCOPYSIGN on SSE registers yet. 14588 if (N1Op0VT == MVT::f128) 14589 return false; 14590 14591 // Avoid mismatched vector operand types, for better instruction selection. 14592 if (N1Op0VT.isVector()) 14593 return false; 14594 14595 return true; 14596 } 14597 return false; 14598 } 14599 14600 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) { 14601 SDValue N0 = N->getOperand(0); 14602 SDValue N1 = N->getOperand(1); 14603 bool N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0); 14604 bool N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1); 14605 EVT VT = N->getValueType(0); 14606 14607 if (N0CFP && N1CFP) // Constant fold 14608 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1); 14609 14610 if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N->getOperand(1))) { 14611 const APFloat &V = N1C->getValueAPF(); 14612 // copysign(x, c1) -> fabs(x) iff ispos(c1) 14613 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1) 14614 if (!V.isNegative()) { 14615 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT)) 14616 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 14617 } else { 14618 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT)) 14619 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, 14620 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0)); 14621 } 14622 } 14623 14624 // copysign(fabs(x), y) -> copysign(x, y) 14625 // copysign(fneg(x), y) -> copysign(x, y) 14626 // copysign(copysign(x,z), y) -> copysign(x, y) 14627 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG || 14628 N0.getOpcode() == ISD::FCOPYSIGN) 14629 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1); 14630 14631 // copysign(x, abs(y)) -> abs(x) 14632 if (N1.getOpcode() == ISD::FABS) 14633 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 14634 14635 // copysign(x, copysign(y,z)) -> copysign(x, z) 14636 if (N1.getOpcode() == ISD::FCOPYSIGN) 14637 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1)); 14638 14639 // copysign(x, fp_extend(y)) -> copysign(x, y) 14640 // copysign(x, fp_round(y)) -> copysign(x, y) 14641 if (CanCombineFCOPYSIGN_EXTEND_ROUND(N)) 14642 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0)); 14643 14644 return SDValue(); 14645 } 14646 14647 SDValue DAGCombiner::visitFPOW(SDNode *N) { 14648 ConstantFPSDNode *ExponentC = isConstOrConstSplatFP(N->getOperand(1)); 14649 if (!ExponentC) 14650 return SDValue(); 14651 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 14652 14653 // Try to convert x ** (1/3) into cube root. 14654 // TODO: Handle the various flavors of long double. 14655 // TODO: Since we're approximating, we don't need an exact 1/3 exponent. 14656 // Some range near 1/3 should be fine. 14657 EVT VT = N->getValueType(0); 14658 if ((VT == MVT::f32 && ExponentC->getValueAPF().isExactlyValue(1.0f/3.0f)) || 14659 (VT == MVT::f64 && ExponentC->getValueAPF().isExactlyValue(1.0/3.0))) { 14660 // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0. 14661 // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf. 14662 // pow(-val, 1/3) = nan; cbrt(-val) = -num. 14663 // For regular numbers, rounding may cause the results to differ. 14664 // Therefore, we require { nsz ninf nnan afn } for this transform. 14665 // TODO: We could select out the special cases if we don't have nsz/ninf. 14666 SDNodeFlags Flags = N->getFlags(); 14667 if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || !Flags.hasNoNaNs() || 14668 !Flags.hasApproximateFuncs()) 14669 return SDValue(); 14670 14671 // Do not create a cbrt() libcall if the target does not have it, and do not 14672 // turn a pow that has lowering support into a cbrt() libcall. 14673 if (!DAG.getLibInfo().has(LibFunc_cbrt) || 14674 (!DAG.getTargetLoweringInfo().isOperationExpand(ISD::FPOW, VT) && 14675 DAG.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT, VT))) 14676 return SDValue(); 14677 14678 return DAG.getNode(ISD::FCBRT, SDLoc(N), VT, N->getOperand(0)); 14679 } 14680 14681 // Try to convert x ** (1/4) and x ** (3/4) into square roots. 14682 // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case. 14683 // TODO: This could be extended (using a target hook) to handle smaller 14684 // power-of-2 fractional exponents. 14685 bool ExponentIs025 = ExponentC->getValueAPF().isExactlyValue(0.25); 14686 bool ExponentIs075 = ExponentC->getValueAPF().isExactlyValue(0.75); 14687 if (ExponentIs025 || ExponentIs075) { 14688 // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0. 14689 // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN. 14690 // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0. 14691 // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) = NaN. 14692 // For regular numbers, rounding may cause the results to differ. 14693 // Therefore, we require { nsz ninf afn } for this transform. 14694 // TODO: We could select out the special cases if we don't have nsz/ninf. 14695 SDNodeFlags Flags = N->getFlags(); 14696 14697 // We only need no signed zeros for the 0.25 case. 14698 if ((!Flags.hasNoSignedZeros() && ExponentIs025) || !Flags.hasNoInfs() || 14699 !Flags.hasApproximateFuncs()) 14700 return SDValue(); 14701 14702 // Don't double the number of libcalls. We are trying to inline fast code. 14703 if (!DAG.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT, VT)) 14704 return SDValue(); 14705 14706 // Assume that libcalls are the smallest code. 14707 // TODO: This restriction should probably be lifted for vectors. 14708 if (ForCodeSize) 14709 return SDValue(); 14710 14711 // pow(X, 0.25) --> sqrt(sqrt(X)) 14712 SDLoc DL(N); 14713 SDValue Sqrt = DAG.getNode(ISD::FSQRT, DL, VT, N->getOperand(0)); 14714 SDValue SqrtSqrt = DAG.getNode(ISD::FSQRT, DL, VT, Sqrt); 14715 if (ExponentIs025) 14716 return SqrtSqrt; 14717 // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X)) 14718 return DAG.getNode(ISD::FMUL, DL, VT, Sqrt, SqrtSqrt); 14719 } 14720 14721 return SDValue(); 14722 } 14723 14724 static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG, 14725 const TargetLowering &TLI) { 14726 // This optimization is guarded by a function attribute because it may produce 14727 // unexpected results. Ie, programs may be relying on the platform-specific 14728 // undefined behavior when the float-to-int conversion overflows. 14729 const Function &F = DAG.getMachineFunction().getFunction(); 14730 Attribute StrictOverflow = F.getFnAttribute("strict-float-cast-overflow"); 14731 if (StrictOverflow.getValueAsString().equals("false")) 14732 return SDValue(); 14733 14734 // We only do this if the target has legal ftrunc. Otherwise, we'd likely be 14735 // replacing casts with a libcall. We also must be allowed to ignore -0.0 14736 // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer 14737 // conversions would return +0.0. 14738 // FIXME: We should be able to use node-level FMF here. 14739 // TODO: If strict math, should we use FABS (+ range check for signed cast)? 14740 EVT VT = N->getValueType(0); 14741 if (!TLI.isOperationLegal(ISD::FTRUNC, VT) || 14742 !DAG.getTarget().Options.NoSignedZerosFPMath) 14743 return SDValue(); 14744 14745 // fptosi/fptoui round towards zero, so converting from FP to integer and 14746 // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X 14747 SDValue N0 = N->getOperand(0); 14748 if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT && 14749 N0.getOperand(0).getValueType() == VT) 14750 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 14751 14752 if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT && 14753 N0.getOperand(0).getValueType() == VT) 14754 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0)); 14755 14756 return SDValue(); 14757 } 14758 14759 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) { 14760 SDValue N0 = N->getOperand(0); 14761 EVT VT = N->getValueType(0); 14762 EVT OpVT = N0.getValueType(); 14763 14764 // [us]itofp(undef) = 0, because the result value is bounded. 14765 if (N0.isUndef()) 14766 return DAG.getConstantFP(0.0, SDLoc(N), VT); 14767 14768 // fold (sint_to_fp c1) -> c1fp 14769 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 14770 // ...but only if the target supports immediate floating-point values 14771 (!LegalOperations || 14772 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 14773 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 14774 14775 // If the input is a legal type, and SINT_TO_FP is not legal on this target, 14776 // but UINT_TO_FP is legal on this target, try to convert. 14777 if (!hasOperation(ISD::SINT_TO_FP, OpVT) && 14778 hasOperation(ISD::UINT_TO_FP, OpVT)) { 14779 // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 14780 if (DAG.SignBitIsZero(N0)) 14781 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 14782 } 14783 14784 // The next optimizations are desirable only if SELECT_CC can be lowered. 14785 // fold (sint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), -1.0, 0.0) 14786 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 && 14787 !VT.isVector() && 14788 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 14789 SDLoc DL(N); 14790 return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(-1.0, DL, VT), 14791 DAG.getConstantFP(0.0, DL, VT)); 14792 } 14793 14794 // fold (sint_to_fp (zext (setcc x, y, cc))) -> 14795 // (select (setcc x, y, cc), 1.0, 0.0) 14796 if (N0.getOpcode() == ISD::ZERO_EXTEND && 14797 N0.getOperand(0).getOpcode() == ISD::SETCC && !VT.isVector() && 14798 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 14799 SDLoc DL(N); 14800 return DAG.getSelect(DL, VT, N0.getOperand(0), 14801 DAG.getConstantFP(1.0, DL, VT), 14802 DAG.getConstantFP(0.0, DL, VT)); 14803 } 14804 14805 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 14806 return FTrunc; 14807 14808 return SDValue(); 14809 } 14810 14811 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) { 14812 SDValue N0 = N->getOperand(0); 14813 EVT VT = N->getValueType(0); 14814 EVT OpVT = N0.getValueType(); 14815 14816 // [us]itofp(undef) = 0, because the result value is bounded. 14817 if (N0.isUndef()) 14818 return DAG.getConstantFP(0.0, SDLoc(N), VT); 14819 14820 // fold (uint_to_fp c1) -> c1fp 14821 if (DAG.isConstantIntBuildVectorOrConstantInt(N0) && 14822 // ...but only if the target supports immediate floating-point values 14823 (!LegalOperations || 14824 TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) 14825 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0); 14826 14827 // If the input is a legal type, and UINT_TO_FP is not legal on this target, 14828 // but SINT_TO_FP is legal on this target, try to convert. 14829 if (!hasOperation(ISD::UINT_TO_FP, OpVT) && 14830 hasOperation(ISD::SINT_TO_FP, OpVT)) { 14831 // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 14832 if (DAG.SignBitIsZero(N0)) 14833 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0); 14834 } 14835 14836 // fold (uint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), 1.0, 0.0) 14837 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() && 14838 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) { 14839 SDLoc DL(N); 14840 return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(1.0, DL, VT), 14841 DAG.getConstantFP(0.0, DL, VT)); 14842 } 14843 14844 if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI)) 14845 return FTrunc; 14846 14847 return SDValue(); 14848 } 14849 14850 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x 14851 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) { 14852 SDValue N0 = N->getOperand(0); 14853 EVT VT = N->getValueType(0); 14854 14855 if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP) 14856 return SDValue(); 14857 14858 SDValue Src = N0.getOperand(0); 14859 EVT SrcVT = Src.getValueType(); 14860 bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP; 14861 bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT; 14862 14863 // We can safely assume the conversion won't overflow the output range, 14864 // because (for example) (uint8_t)18293.f is undefined behavior. 14865 14866 // Since we can assume the conversion won't overflow, our decision as to 14867 // whether the input will fit in the float should depend on the minimum 14868 // of the input range and output range. 14869 14870 // This means this is also safe for a signed input and unsigned output, since 14871 // a negative input would lead to undefined behavior. 14872 unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned; 14873 unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned; 14874 unsigned ActualSize = std::min(InputSize, OutputSize); 14875 const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType()); 14876 14877 // We can only fold away the float conversion if the input range can be 14878 // represented exactly in the float range. 14879 if (APFloat::semanticsPrecision(sem) >= ActualSize) { 14880 if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) { 14881 unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND 14882 : ISD::ZERO_EXTEND; 14883 return DAG.getNode(ExtOp, SDLoc(N), VT, Src); 14884 } 14885 if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits()) 14886 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src); 14887 return DAG.getBitcast(VT, Src); 14888 } 14889 return SDValue(); 14890 } 14891 14892 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) { 14893 SDValue N0 = N->getOperand(0); 14894 EVT VT = N->getValueType(0); 14895 14896 // fold (fp_to_sint undef) -> undef 14897 if (N0.isUndef()) 14898 return DAG.getUNDEF(VT); 14899 14900 // fold (fp_to_sint c1fp) -> c1 14901 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14902 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0); 14903 14904 return FoldIntToFPToInt(N, DAG); 14905 } 14906 14907 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) { 14908 SDValue N0 = N->getOperand(0); 14909 EVT VT = N->getValueType(0); 14910 14911 // fold (fp_to_uint undef) -> undef 14912 if (N0.isUndef()) 14913 return DAG.getUNDEF(VT); 14914 14915 // fold (fp_to_uint c1fp) -> c1 14916 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14917 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0); 14918 14919 return FoldIntToFPToInt(N, DAG); 14920 } 14921 14922 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) { 14923 SDValue N0 = N->getOperand(0); 14924 SDValue N1 = N->getOperand(1); 14925 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0); 14926 EVT VT = N->getValueType(0); 14927 14928 // fold (fp_round c1fp) -> c1fp 14929 if (N0CFP) 14930 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1); 14931 14932 // fold (fp_round (fp_extend x)) -> x 14933 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType()) 14934 return N0.getOperand(0); 14935 14936 // fold (fp_round (fp_round x)) -> (fp_round x) 14937 if (N0.getOpcode() == ISD::FP_ROUND) { 14938 const bool NIsTrunc = N->getConstantOperandVal(1) == 1; 14939 const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1; 14940 14941 // Skip this folding if it results in an fp_round from f80 to f16. 14942 // 14943 // f80 to f16 always generates an expensive (and as yet, unimplemented) 14944 // libcall to __truncxfhf2 instead of selecting native f16 conversion 14945 // instructions from f32 or f64. Moreover, the first (value-preserving) 14946 // fp_round from f80 to either f32 or f64 may become a NOP in platforms like 14947 // x86. 14948 if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16) 14949 return SDValue(); 14950 14951 // If the first fp_round isn't a value preserving truncation, it might 14952 // introduce a tie in the second fp_round, that wouldn't occur in the 14953 // single-step fp_round we want to fold to. 14954 // In other words, double rounding isn't the same as rounding. 14955 // Also, this is a value preserving truncation iff both fp_round's are. 14956 if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) { 14957 SDLoc DL(N); 14958 return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0), 14959 DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL)); 14960 } 14961 } 14962 14963 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y) 14964 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) { 14965 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT, 14966 N0.getOperand(0), N1); 14967 AddToWorklist(Tmp.getNode()); 14968 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, 14969 Tmp, N0.getOperand(1)); 14970 } 14971 14972 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 14973 return NewVSel; 14974 14975 return SDValue(); 14976 } 14977 14978 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) { 14979 SDValue N0 = N->getOperand(0); 14980 EVT VT = N->getValueType(0); 14981 14982 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded. 14983 if (N->hasOneUse() && 14984 N->use_begin()->getOpcode() == ISD::FP_ROUND) 14985 return SDValue(); 14986 14987 // fold (fp_extend c1fp) -> c1fp 14988 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 14989 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0); 14990 14991 // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op) 14992 if (N0.getOpcode() == ISD::FP16_TO_FP && 14993 TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal) 14994 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0)); 14995 14996 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the 14997 // value of X. 14998 if (N0.getOpcode() == ISD::FP_ROUND 14999 && N0.getConstantOperandVal(1) == 1) { 15000 SDValue In = N0.getOperand(0); 15001 if (In.getValueType() == VT) return In; 15002 if (VT.bitsLT(In.getValueType())) 15003 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, 15004 In, N0.getOperand(1)); 15005 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In); 15006 } 15007 15008 // fold (fpext (load x)) -> (fpext (fptrunc (extload x))) 15009 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 15010 TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) { 15011 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 15012 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT, 15013 LN0->getChain(), 15014 LN0->getBasePtr(), N0.getValueType(), 15015 LN0->getMemOperand()); 15016 CombineTo(N, ExtLoad); 15017 CombineTo(N0.getNode(), 15018 DAG.getNode(ISD::FP_ROUND, SDLoc(N0), 15019 N0.getValueType(), ExtLoad, 15020 DAG.getIntPtrConstant(1, SDLoc(N0))), 15021 ExtLoad.getValue(1)); 15022 return SDValue(N, 0); // Return N so it doesn't get rechecked! 15023 } 15024 15025 if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N)) 15026 return NewVSel; 15027 15028 return SDValue(); 15029 } 15030 15031 SDValue DAGCombiner::visitFCEIL(SDNode *N) { 15032 SDValue N0 = N->getOperand(0); 15033 EVT VT = N->getValueType(0); 15034 15035 // fold (fceil c1) -> fceil(c1) 15036 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 15037 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0); 15038 15039 return SDValue(); 15040 } 15041 15042 SDValue DAGCombiner::visitFTRUNC(SDNode *N) { 15043 SDValue N0 = N->getOperand(0); 15044 EVT VT = N->getValueType(0); 15045 15046 // fold (ftrunc c1) -> ftrunc(c1) 15047 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 15048 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0); 15049 15050 // fold ftrunc (known rounded int x) -> x 15051 // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is 15052 // likely to be generated to extract integer from a rounded floating value. 15053 switch (N0.getOpcode()) { 15054 default: break; 15055 case ISD::FRINT: 15056 case ISD::FTRUNC: 15057 case ISD::FNEARBYINT: 15058 case ISD::FFLOOR: 15059 case ISD::FCEIL: 15060 return N0; 15061 } 15062 15063 return SDValue(); 15064 } 15065 15066 SDValue DAGCombiner::visitFFLOOR(SDNode *N) { 15067 SDValue N0 = N->getOperand(0); 15068 EVT VT = N->getValueType(0); 15069 15070 // fold (ffloor c1) -> ffloor(c1) 15071 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 15072 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0); 15073 15074 return SDValue(); 15075 } 15076 15077 SDValue DAGCombiner::visitFNEG(SDNode *N) { 15078 SDValue N0 = N->getOperand(0); 15079 EVT VT = N->getValueType(0); 15080 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 15081 15082 // Constant fold FNEG. 15083 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 15084 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0); 15085 15086 if (SDValue NegN0 = 15087 TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize)) 15088 return NegN0; 15089 15090 // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0 15091 // FIXME: This is duplicated in getNegatibleCost, but getNegatibleCost doesn't 15092 // know it was called from a context with a nsz flag if the input fsub does 15093 // not. 15094 if (N0.getOpcode() == ISD::FSUB && 15095 (DAG.getTarget().Options.NoSignedZerosFPMath || 15096 N->getFlags().hasNoSignedZeros()) && N0.hasOneUse()) { 15097 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0.getOperand(1), 15098 N0.getOperand(0)); 15099 } 15100 15101 if (SDValue Cast = foldSignChangeInBitcast(N)) 15102 return Cast; 15103 15104 return SDValue(); 15105 } 15106 15107 static SDValue visitFMinMax(SelectionDAG &DAG, SDNode *N, 15108 APFloat (*Op)(const APFloat &, const APFloat &)) { 15109 SDValue N0 = N->getOperand(0); 15110 SDValue N1 = N->getOperand(1); 15111 EVT VT = N->getValueType(0); 15112 const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0); 15113 const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1); 15114 const SDNodeFlags Flags = N->getFlags(); 15115 unsigned Opc = N->getOpcode(); 15116 bool PropagatesNaN = Opc == ISD::FMINIMUM || Opc == ISD::FMAXIMUM; 15117 bool IsMin = Opc == ISD::FMINNUM || Opc == ISD::FMINIMUM; 15118 SelectionDAG::FlagInserter FlagsInserter(DAG, N); 15119 15120 if (N0CFP && N1CFP) { 15121 const APFloat &C0 = N0CFP->getValueAPF(); 15122 const APFloat &C1 = N1CFP->getValueAPF(); 15123 return DAG.getConstantFP(Op(C0, C1), SDLoc(N), VT); 15124 } 15125 15126 // Canonicalize to constant on RHS. 15127 if (DAG.isConstantFPBuildVectorOrConstantFP(N0) && 15128 !DAG.isConstantFPBuildVectorOrConstantFP(N1)) 15129 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0); 15130 15131 if (N1CFP) { 15132 const APFloat &AF = N1CFP->getValueAPF(); 15133 15134 // minnum(X, nan) -> X 15135 // maxnum(X, nan) -> X 15136 // minimum(X, nan) -> nan 15137 // maximum(X, nan) -> nan 15138 if (AF.isNaN()) 15139 return PropagatesNaN ? N->getOperand(1) : N->getOperand(0); 15140 15141 // In the following folds, inf can be replaced with the largest finite 15142 // float, if the ninf flag is set. 15143 if (AF.isInfinity() || (Flags.hasNoInfs() && AF.isLargest())) { 15144 // minnum(X, -inf) -> -inf 15145 // maxnum(X, +inf) -> +inf 15146 // minimum(X, -inf) -> -inf if nnan 15147 // maximum(X, +inf) -> +inf if nnan 15148 if (IsMin == AF.isNegative() && (!PropagatesNaN || Flags.hasNoNaNs())) 15149 return N->getOperand(1); 15150 15151 // minnum(X, +inf) -> X if nnan 15152 // maxnum(X, -inf) -> X if nnan 15153 // minimum(X, +inf) -> X 15154 // maximum(X, -inf) -> X 15155 if (IsMin != AF.isNegative() && (PropagatesNaN || Flags.hasNoNaNs())) 15156 return N->getOperand(0); 15157 } 15158 } 15159 15160 return SDValue(); 15161 } 15162 15163 SDValue DAGCombiner::visitFMINNUM(SDNode *N) { 15164 return visitFMinMax(DAG, N, minnum); 15165 } 15166 15167 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) { 15168 return visitFMinMax(DAG, N, maxnum); 15169 } 15170 15171 SDValue DAGCombiner::visitFMINIMUM(SDNode *N) { 15172 return visitFMinMax(DAG, N, minimum); 15173 } 15174 15175 SDValue DAGCombiner::visitFMAXIMUM(SDNode *N) { 15176 return visitFMinMax(DAG, N, maximum); 15177 } 15178 15179 SDValue DAGCombiner::visitFABS(SDNode *N) { 15180 SDValue N0 = N->getOperand(0); 15181 EVT VT = N->getValueType(0); 15182 15183 // fold (fabs c1) -> fabs(c1) 15184 if (DAG.isConstantFPBuildVectorOrConstantFP(N0)) 15185 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0); 15186 15187 // fold (fabs (fabs x)) -> (fabs x) 15188 if (N0.getOpcode() == ISD::FABS) 15189 return N->getOperand(0); 15190 15191 // fold (fabs (fneg x)) -> (fabs x) 15192 // fold (fabs (fcopysign x, y)) -> (fabs x) 15193 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN) 15194 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0)); 15195 15196 if (SDValue Cast = foldSignChangeInBitcast(N)) 15197 return Cast; 15198 15199 return SDValue(); 15200 } 15201 15202 SDValue DAGCombiner::visitBRCOND(SDNode *N) { 15203 SDValue Chain = N->getOperand(0); 15204 SDValue N1 = N->getOperand(1); 15205 SDValue N2 = N->getOperand(2); 15206 15207 // BRCOND(FREEZE(cond)) is equivalent to BRCOND(cond) (both are 15208 // nondeterministic jumps). 15209 if (N1->getOpcode() == ISD::FREEZE && N1.hasOneUse()) { 15210 return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain, 15211 N1->getOperand(0), N2); 15212 } 15213 15214 // If N is a constant we could fold this into a fallthrough or unconditional 15215 // branch. However that doesn't happen very often in normal code, because 15216 // Instcombine/SimplifyCFG should have handled the available opportunities. 15217 // If we did this folding here, it would be necessary to update the 15218 // MachineBasicBlock CFG, which is awkward. 15219 15220 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal 15221 // on the target. 15222 if (N1.getOpcode() == ISD::SETCC && 15223 TLI.isOperationLegalOrCustom(ISD::BR_CC, 15224 N1.getOperand(0).getValueType())) { 15225 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 15226 Chain, N1.getOperand(2), 15227 N1.getOperand(0), N1.getOperand(1), N2); 15228 } 15229 15230 if (N1.hasOneUse()) { 15231 // rebuildSetCC calls visitXor which may change the Chain when there is a 15232 // STRICT_FSETCC/STRICT_FSETCCS involved. Use a handle to track changes. 15233 HandleSDNode ChainHandle(Chain); 15234 if (SDValue NewN1 = rebuildSetCC(N1)) 15235 return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, 15236 ChainHandle.getValue(), NewN1, N2); 15237 } 15238 15239 return SDValue(); 15240 } 15241 15242 SDValue DAGCombiner::rebuildSetCC(SDValue N) { 15243 if (N.getOpcode() == ISD::SRL || 15244 (N.getOpcode() == ISD::TRUNCATE && 15245 (N.getOperand(0).hasOneUse() && 15246 N.getOperand(0).getOpcode() == ISD::SRL))) { 15247 // Look pass the truncate. 15248 if (N.getOpcode() == ISD::TRUNCATE) 15249 N = N.getOperand(0); 15250 15251 // Match this pattern so that we can generate simpler code: 15252 // 15253 // %a = ... 15254 // %b = and i32 %a, 2 15255 // %c = srl i32 %b, 1 15256 // brcond i32 %c ... 15257 // 15258 // into 15259 // 15260 // %a = ... 15261 // %b = and i32 %a, 2 15262 // %c = setcc eq %b, 0 15263 // brcond %c ... 15264 // 15265 // This applies only when the AND constant value has one bit set and the 15266 // SRL constant is equal to the log2 of the AND constant. The back-end is 15267 // smart enough to convert the result into a TEST/JMP sequence. 15268 SDValue Op0 = N.getOperand(0); 15269 SDValue Op1 = N.getOperand(1); 15270 15271 if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) { 15272 SDValue AndOp1 = Op0.getOperand(1); 15273 15274 if (AndOp1.getOpcode() == ISD::Constant) { 15275 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue(); 15276 15277 if (AndConst.isPowerOf2() && 15278 cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) { 15279 SDLoc DL(N); 15280 return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()), 15281 Op0, DAG.getConstant(0, DL, Op0.getValueType()), 15282 ISD::SETNE); 15283 } 15284 } 15285 } 15286 } 15287 15288 // Transform (brcond (xor x, y)) -> (brcond (setcc, x, y, ne)) 15289 // Transform (brcond (xor (xor x, y), -1)) -> (brcond (setcc, x, y, eq)) 15290 if (N.getOpcode() == ISD::XOR) { 15291 // Because we may call this on a speculatively constructed 15292 // SimplifiedSetCC Node, we need to simplify this node first. 15293 // Ideally this should be folded into SimplifySetCC and not 15294 // here. For now, grab a handle to N so we don't lose it from 15295 // replacements interal to the visit. 15296 HandleSDNode XORHandle(N); 15297 while (N.getOpcode() == ISD::XOR) { 15298 SDValue Tmp = visitXOR(N.getNode()); 15299 // No simplification done. 15300 if (!Tmp.getNode()) 15301 break; 15302 // Returning N is form in-visit replacement that may invalidated 15303 // N. Grab value from Handle. 15304 if (Tmp.getNode() == N.getNode()) 15305 N = XORHandle.getValue(); 15306 else // Node simplified. Try simplifying again. 15307 N = Tmp; 15308 } 15309 15310 if (N.getOpcode() != ISD::XOR) 15311 return N; 15312 15313 SDValue Op0 = N->getOperand(0); 15314 SDValue Op1 = N->getOperand(1); 15315 15316 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) { 15317 bool Equal = false; 15318 // (brcond (xor (xor x, y), -1)) -> (brcond (setcc x, y, eq)) 15319 if (isBitwiseNot(N) && Op0.hasOneUse() && Op0.getOpcode() == ISD::XOR && 15320 Op0.getValueType() == MVT::i1) { 15321 N = Op0; 15322 Op0 = N->getOperand(0); 15323 Op1 = N->getOperand(1); 15324 Equal = true; 15325 } 15326 15327 EVT SetCCVT = N.getValueType(); 15328 if (LegalTypes) 15329 SetCCVT = getSetCCResultType(SetCCVT); 15330 // Replace the uses of XOR with SETCC 15331 return DAG.getSetCC(SDLoc(N), SetCCVT, Op0, Op1, 15332 Equal ? ISD::SETEQ : ISD::SETNE); 15333 } 15334 } 15335 15336 return SDValue(); 15337 } 15338 15339 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB. 15340 // 15341 SDValue DAGCombiner::visitBR_CC(SDNode *N) { 15342 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1)); 15343 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3); 15344 15345 // If N is a constant we could fold this into a fallthrough or unconditional 15346 // branch. However that doesn't happen very often in normal code, because 15347 // Instcombine/SimplifyCFG should have handled the available opportunities. 15348 // If we did this folding here, it would be necessary to update the 15349 // MachineBasicBlock CFG, which is awkward. 15350 15351 // Use SimplifySetCC to simplify SETCC's. 15352 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()), 15353 CondLHS, CondRHS, CC->get(), SDLoc(N), 15354 false); 15355 if (Simp.getNode()) AddToWorklist(Simp.getNode()); 15356 15357 // fold to a simpler setcc 15358 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC) 15359 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other, 15360 N->getOperand(0), Simp.getOperand(2), 15361 Simp.getOperand(0), Simp.getOperand(1), 15362 N->getOperand(4)); 15363 15364 return SDValue(); 15365 } 15366 15367 static bool getCombineLoadStoreParts(SDNode *N, unsigned Inc, unsigned Dec, 15368 bool &IsLoad, bool &IsMasked, SDValue &Ptr, 15369 const TargetLowering &TLI) { 15370 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 15371 if (LD->isIndexed()) 15372 return false; 15373 EVT VT = LD->getMemoryVT(); 15374 if (!TLI.isIndexedLoadLegal(Inc, VT) && !TLI.isIndexedLoadLegal(Dec, VT)) 15375 return false; 15376 Ptr = LD->getBasePtr(); 15377 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 15378 if (ST->isIndexed()) 15379 return false; 15380 EVT VT = ST->getMemoryVT(); 15381 if (!TLI.isIndexedStoreLegal(Inc, VT) && !TLI.isIndexedStoreLegal(Dec, VT)) 15382 return false; 15383 Ptr = ST->getBasePtr(); 15384 IsLoad = false; 15385 } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) { 15386 if (LD->isIndexed()) 15387 return false; 15388 EVT VT = LD->getMemoryVT(); 15389 if (!TLI.isIndexedMaskedLoadLegal(Inc, VT) && 15390 !TLI.isIndexedMaskedLoadLegal(Dec, VT)) 15391 return false; 15392 Ptr = LD->getBasePtr(); 15393 IsMasked = true; 15394 } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) { 15395 if (ST->isIndexed()) 15396 return false; 15397 EVT VT = ST->getMemoryVT(); 15398 if (!TLI.isIndexedMaskedStoreLegal(Inc, VT) && 15399 !TLI.isIndexedMaskedStoreLegal(Dec, VT)) 15400 return false; 15401 Ptr = ST->getBasePtr(); 15402 IsLoad = false; 15403 IsMasked = true; 15404 } else { 15405 return false; 15406 } 15407 return true; 15408 } 15409 15410 /// Try turning a load/store into a pre-indexed load/store when the base 15411 /// pointer is an add or subtract and it has other uses besides the load/store. 15412 /// After the transformation, the new indexed load/store has effectively folded 15413 /// the add/subtract in and all of its other uses are redirected to the 15414 /// new load/store. 15415 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) { 15416 if (Level < AfterLegalizeDAG) 15417 return false; 15418 15419 bool IsLoad = true; 15420 bool IsMasked = false; 15421 SDValue Ptr; 15422 if (!getCombineLoadStoreParts(N, ISD::PRE_INC, ISD::PRE_DEC, IsLoad, IsMasked, 15423 Ptr, TLI)) 15424 return false; 15425 15426 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail 15427 // out. There is no reason to make this a preinc/predec. 15428 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) || 15429 Ptr.getNode()->hasOneUse()) 15430 return false; 15431 15432 // Ask the target to do addressing mode selection. 15433 SDValue BasePtr; 15434 SDValue Offset; 15435 ISD::MemIndexedMode AM = ISD::UNINDEXED; 15436 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG)) 15437 return false; 15438 15439 // Backends without true r+i pre-indexed forms may need to pass a 15440 // constant base with a variable offset so that constant coercion 15441 // will work with the patterns in canonical form. 15442 bool Swapped = false; 15443 if (isa<ConstantSDNode>(BasePtr)) { 15444 std::swap(BasePtr, Offset); 15445 Swapped = true; 15446 } 15447 15448 // Don't create a indexed load / store with zero offset. 15449 if (isNullConstant(Offset)) 15450 return false; 15451 15452 // Try turning it into a pre-indexed load / store except when: 15453 // 1) The new base ptr is a frame index. 15454 // 2) If N is a store and the new base ptr is either the same as or is a 15455 // predecessor of the value being stored. 15456 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded 15457 // that would create a cycle. 15458 // 4) All uses are load / store ops that use it as old base ptr. 15459 15460 // Check #1. Preinc'ing a frame index would require copying the stack pointer 15461 // (plus the implicit offset) to a register to preinc anyway. 15462 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 15463 return false; 15464 15465 // Check #2. 15466 if (!IsLoad) { 15467 SDValue Val = IsMasked ? cast<MaskedStoreSDNode>(N)->getValue() 15468 : cast<StoreSDNode>(N)->getValue(); 15469 15470 // Would require a copy. 15471 if (Val == BasePtr) 15472 return false; 15473 15474 // Would create a cycle. 15475 if (Val == Ptr || Ptr->isPredecessorOf(Val.getNode())) 15476 return false; 15477 } 15478 15479 // Caches for hasPredecessorHelper. 15480 SmallPtrSet<const SDNode *, 32> Visited; 15481 SmallVector<const SDNode *, 16> Worklist; 15482 Worklist.push_back(N); 15483 15484 // If the offset is a constant, there may be other adds of constants that 15485 // can be folded with this one. We should do this to avoid having to keep 15486 // a copy of the original base pointer. 15487 SmallVector<SDNode *, 16> OtherUses; 15488 if (isa<ConstantSDNode>(Offset)) 15489 for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(), 15490 UE = BasePtr.getNode()->use_end(); 15491 UI != UE; ++UI) { 15492 SDUse &Use = UI.getUse(); 15493 // Skip the use that is Ptr and uses of other results from BasePtr's 15494 // node (important for nodes that return multiple results). 15495 if (Use.getUser() == Ptr.getNode() || Use != BasePtr) 15496 continue; 15497 15498 if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist)) 15499 continue; 15500 15501 if (Use.getUser()->getOpcode() != ISD::ADD && 15502 Use.getUser()->getOpcode() != ISD::SUB) { 15503 OtherUses.clear(); 15504 break; 15505 } 15506 15507 SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1); 15508 if (!isa<ConstantSDNode>(Op1)) { 15509 OtherUses.clear(); 15510 break; 15511 } 15512 15513 // FIXME: In some cases, we can be smarter about this. 15514 if (Op1.getValueType() != Offset.getValueType()) { 15515 OtherUses.clear(); 15516 break; 15517 } 15518 15519 OtherUses.push_back(Use.getUser()); 15520 } 15521 15522 if (Swapped) 15523 std::swap(BasePtr, Offset); 15524 15525 // Now check for #3 and #4. 15526 bool RealUse = false; 15527 15528 for (SDNode *Use : Ptr.getNode()->uses()) { 15529 if (Use == N) 15530 continue; 15531 if (SDNode::hasPredecessorHelper(Use, Visited, Worklist)) 15532 return false; 15533 15534 // If Ptr may be folded in addressing mode of other use, then it's 15535 // not profitable to do this transformation. 15536 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI)) 15537 RealUse = true; 15538 } 15539 15540 if (!RealUse) 15541 return false; 15542 15543 SDValue Result; 15544 if (!IsMasked) { 15545 if (IsLoad) 15546 Result = DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM); 15547 else 15548 Result = 15549 DAG.getIndexedStore(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM); 15550 } else { 15551 if (IsLoad) 15552 Result = DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N), BasePtr, 15553 Offset, AM); 15554 else 15555 Result = DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N), BasePtr, 15556 Offset, AM); 15557 } 15558 ++PreIndexedNodes; 15559 ++NodesCombined; 15560 LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: "; 15561 Result.getNode()->dump(&DAG); dbgs() << '\n'); 15562 WorklistRemover DeadNodes(*this); 15563 if (IsLoad) { 15564 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 15565 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 15566 } else { 15567 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 15568 } 15569 15570 // Finally, since the node is now dead, remove it from the graph. 15571 deleteAndRecombine(N); 15572 15573 if (Swapped) 15574 std::swap(BasePtr, Offset); 15575 15576 // Replace other uses of BasePtr that can be updated to use Ptr 15577 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) { 15578 unsigned OffsetIdx = 1; 15579 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode()) 15580 OffsetIdx = 0; 15581 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() == 15582 BasePtr.getNode() && "Expected BasePtr operand"); 15583 15584 // We need to replace ptr0 in the following expression: 15585 // x0 * offset0 + y0 * ptr0 = t0 15586 // knowing that 15587 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store) 15588 // 15589 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the 15590 // indexed load/store and the expression that needs to be re-written. 15591 // 15592 // Therefore, we have: 15593 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1 15594 15595 auto *CN = cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx)); 15596 const APInt &Offset0 = CN->getAPIntValue(); 15597 const APInt &Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue(); 15598 int X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1; 15599 int Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1; 15600 int X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1; 15601 int Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1; 15602 15603 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD; 15604 15605 APInt CNV = Offset0; 15606 if (X0 < 0) CNV = -CNV; 15607 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1; 15608 else CNV = CNV - Offset1; 15609 15610 SDLoc DL(OtherUses[i]); 15611 15612 // We can now generate the new expression. 15613 SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0)); 15614 SDValue NewOp2 = Result.getValue(IsLoad ? 1 : 0); 15615 15616 SDValue NewUse = DAG.getNode(Opcode, 15617 DL, 15618 OtherUses[i]->getValueType(0), NewOp1, NewOp2); 15619 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse); 15620 deleteAndRecombine(OtherUses[i]); 15621 } 15622 15623 // Replace the uses of Ptr with uses of the updated base value. 15624 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(IsLoad ? 1 : 0)); 15625 deleteAndRecombine(Ptr.getNode()); 15626 AddToWorklist(Result.getNode()); 15627 15628 return true; 15629 } 15630 15631 static bool shouldCombineToPostInc(SDNode *N, SDValue Ptr, SDNode *PtrUse, 15632 SDValue &BasePtr, SDValue &Offset, 15633 ISD::MemIndexedMode &AM, 15634 SelectionDAG &DAG, 15635 const TargetLowering &TLI) { 15636 if (PtrUse == N || 15637 (PtrUse->getOpcode() != ISD::ADD && PtrUse->getOpcode() != ISD::SUB)) 15638 return false; 15639 15640 if (!TLI.getPostIndexedAddressParts(N, PtrUse, BasePtr, Offset, AM, DAG)) 15641 return false; 15642 15643 // Don't create a indexed load / store with zero offset. 15644 if (isNullConstant(Offset)) 15645 return false; 15646 15647 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr)) 15648 return false; 15649 15650 SmallPtrSet<const SDNode *, 32> Visited; 15651 for (SDNode *Use : BasePtr.getNode()->uses()) { 15652 if (Use == Ptr.getNode()) 15653 continue; 15654 15655 // No if there's a later user which could perform the index instead. 15656 if (isa<MemSDNode>(Use)) { 15657 bool IsLoad = true; 15658 bool IsMasked = false; 15659 SDValue OtherPtr; 15660 if (getCombineLoadStoreParts(Use, ISD::POST_INC, ISD::POST_DEC, IsLoad, 15661 IsMasked, OtherPtr, TLI)) { 15662 SmallVector<const SDNode *, 2> Worklist; 15663 Worklist.push_back(Use); 15664 if (SDNode::hasPredecessorHelper(N, Visited, Worklist)) 15665 return false; 15666 } 15667 } 15668 15669 // If all the uses are load / store addresses, then don't do the 15670 // transformation. 15671 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB) { 15672 for (SDNode *UseUse : Use->uses()) 15673 if (canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 15674 return false; 15675 } 15676 } 15677 return true; 15678 } 15679 15680 static SDNode *getPostIndexedLoadStoreOp(SDNode *N, bool &IsLoad, 15681 bool &IsMasked, SDValue &Ptr, 15682 SDValue &BasePtr, SDValue &Offset, 15683 ISD::MemIndexedMode &AM, 15684 SelectionDAG &DAG, 15685 const TargetLowering &TLI) { 15686 if (!getCombineLoadStoreParts(N, ISD::POST_INC, ISD::POST_DEC, IsLoad, 15687 IsMasked, Ptr, TLI) || 15688 Ptr.getNode()->hasOneUse()) 15689 return nullptr; 15690 15691 // Try turning it into a post-indexed load / store except when 15692 // 1) All uses are load / store ops that use it as base ptr (and 15693 // it may be folded as addressing mmode). 15694 // 2) Op must be independent of N, i.e. Op is neither a predecessor 15695 // nor a successor of N. Otherwise, if Op is folded that would 15696 // create a cycle. 15697 for (SDNode *Op : Ptr->uses()) { 15698 // Check for #1. 15699 if (!shouldCombineToPostInc(N, Ptr, Op, BasePtr, Offset, AM, DAG, TLI)) 15700 continue; 15701 15702 // Check for #2. 15703 SmallPtrSet<const SDNode *, 32> Visited; 15704 SmallVector<const SDNode *, 8> Worklist; 15705 // Ptr is predecessor to both N and Op. 15706 Visited.insert(Ptr.getNode()); 15707 Worklist.push_back(N); 15708 Worklist.push_back(Op); 15709 if (!SDNode::hasPredecessorHelper(N, Visited, Worklist) && 15710 !SDNode::hasPredecessorHelper(Op, Visited, Worklist)) 15711 return Op; 15712 } 15713 return nullptr; 15714 } 15715 15716 /// Try to combine a load/store with a add/sub of the base pointer node into a 15717 /// post-indexed load/store. The transformation folded the add/subtract into the 15718 /// new indexed load/store effectively and all of its uses are redirected to the 15719 /// new load/store. 15720 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) { 15721 if (Level < AfterLegalizeDAG) 15722 return false; 15723 15724 bool IsLoad = true; 15725 bool IsMasked = false; 15726 SDValue Ptr; 15727 SDValue BasePtr; 15728 SDValue Offset; 15729 ISD::MemIndexedMode AM = ISD::UNINDEXED; 15730 SDNode *Op = getPostIndexedLoadStoreOp(N, IsLoad, IsMasked, Ptr, BasePtr, 15731 Offset, AM, DAG, TLI); 15732 if (!Op) 15733 return false; 15734 15735 SDValue Result; 15736 if (!IsMasked) 15737 Result = IsLoad ? DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr, 15738 Offset, AM) 15739 : DAG.getIndexedStore(SDValue(N, 0), SDLoc(N), 15740 BasePtr, Offset, AM); 15741 else 15742 Result = IsLoad ? DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N), 15743 BasePtr, Offset, AM) 15744 : DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N), 15745 BasePtr, Offset, AM); 15746 ++PostIndexedNodes; 15747 ++NodesCombined; 15748 LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG); 15749 dbgs() << "\nWith: "; Result.getNode()->dump(&DAG); 15750 dbgs() << '\n'); 15751 WorklistRemover DeadNodes(*this); 15752 if (IsLoad) { 15753 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0)); 15754 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2)); 15755 } else { 15756 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1)); 15757 } 15758 15759 // Finally, since the node is now dead, remove it from the graph. 15760 deleteAndRecombine(N); 15761 15762 // Replace the uses of Use with uses of the updated base value. 15763 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0), 15764 Result.getValue(IsLoad ? 1 : 0)); 15765 deleteAndRecombine(Op); 15766 return true; 15767 } 15768 15769 /// Return the base-pointer arithmetic from an indexed \p LD. 15770 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) { 15771 ISD::MemIndexedMode AM = LD->getAddressingMode(); 15772 assert(AM != ISD::UNINDEXED); 15773 SDValue BP = LD->getOperand(1); 15774 SDValue Inc = LD->getOperand(2); 15775 15776 // Some backends use TargetConstants for load offsets, but don't expect 15777 // TargetConstants in general ADD nodes. We can convert these constants into 15778 // regular Constants (if the constant is not opaque). 15779 assert((Inc.getOpcode() != ISD::TargetConstant || 15780 !cast<ConstantSDNode>(Inc)->isOpaque()) && 15781 "Cannot split out indexing using opaque target constants"); 15782 if (Inc.getOpcode() == ISD::TargetConstant) { 15783 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc); 15784 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc), 15785 ConstInc->getValueType(0)); 15786 } 15787 15788 unsigned Opc = 15789 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB); 15790 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc); 15791 } 15792 15793 static inline ElementCount numVectorEltsOrZero(EVT T) { 15794 return T.isVector() ? T.getVectorElementCount() : ElementCount::getFixed(0); 15795 } 15796 15797 bool DAGCombiner::getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val) { 15798 Val = ST->getValue(); 15799 EVT STType = Val.getValueType(); 15800 EVT STMemType = ST->getMemoryVT(); 15801 if (STType == STMemType) 15802 return true; 15803 if (isTypeLegal(STMemType)) 15804 return false; // fail. 15805 if (STType.isFloatingPoint() && STMemType.isFloatingPoint() && 15806 TLI.isOperationLegal(ISD::FTRUNC, STMemType)) { 15807 Val = DAG.getNode(ISD::FTRUNC, SDLoc(ST), STMemType, Val); 15808 return true; 15809 } 15810 if (numVectorEltsOrZero(STType) == numVectorEltsOrZero(STMemType) && 15811 STType.isInteger() && STMemType.isInteger()) { 15812 Val = DAG.getNode(ISD::TRUNCATE, SDLoc(ST), STMemType, Val); 15813 return true; 15814 } 15815 if (STType.getSizeInBits() == STMemType.getSizeInBits()) { 15816 Val = DAG.getBitcast(STMemType, Val); 15817 return true; 15818 } 15819 return false; // fail. 15820 } 15821 15822 bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val) { 15823 EVT LDMemType = LD->getMemoryVT(); 15824 EVT LDType = LD->getValueType(0); 15825 assert(Val.getValueType() == LDMemType && 15826 "Attempting to extend value of non-matching type"); 15827 if (LDType == LDMemType) 15828 return true; 15829 if (LDMemType.isInteger() && LDType.isInteger()) { 15830 switch (LD->getExtensionType()) { 15831 case ISD::NON_EXTLOAD: 15832 Val = DAG.getBitcast(LDType, Val); 15833 return true; 15834 case ISD::EXTLOAD: 15835 Val = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LD), LDType, Val); 15836 return true; 15837 case ISD::SEXTLOAD: 15838 Val = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(LD), LDType, Val); 15839 return true; 15840 case ISD::ZEXTLOAD: 15841 Val = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(LD), LDType, Val); 15842 return true; 15843 } 15844 } 15845 return false; 15846 } 15847 15848 SDValue DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode *LD) { 15849 if (OptLevel == CodeGenOpt::None || !LD->isSimple()) 15850 return SDValue(); 15851 SDValue Chain = LD->getOperand(0); 15852 StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain.getNode()); 15853 // TODO: Relax this restriction for unordered atomics (see D66309) 15854 if (!ST || !ST->isSimple()) 15855 return SDValue(); 15856 15857 EVT LDType = LD->getValueType(0); 15858 EVT LDMemType = LD->getMemoryVT(); 15859 EVT STMemType = ST->getMemoryVT(); 15860 EVT STType = ST->getValue().getValueType(); 15861 15862 // There are two cases to consider here: 15863 // 1. The store is fixed width and the load is scalable. In this case we 15864 // don't know at compile time if the store completely envelops the load 15865 // so we abandon the optimisation. 15866 // 2. The store is scalable and the load is fixed width. We could 15867 // potentially support a limited number of cases here, but there has been 15868 // no cost-benefit analysis to prove it's worth it. 15869 bool LdStScalable = LDMemType.isScalableVector(); 15870 if (LdStScalable != STMemType.isScalableVector()) 15871 return SDValue(); 15872 15873 // If we are dealing with scalable vectors on a big endian platform the 15874 // calculation of offsets below becomes trickier, since we do not know at 15875 // compile time the absolute size of the vector. Until we've done more 15876 // analysis on big-endian platforms it seems better to bail out for now. 15877 if (LdStScalable && DAG.getDataLayout().isBigEndian()) 15878 return SDValue(); 15879 15880 BaseIndexOffset BasePtrLD = BaseIndexOffset::match(LD, DAG); 15881 BaseIndexOffset BasePtrST = BaseIndexOffset::match(ST, DAG); 15882 int64_t Offset; 15883 if (!BasePtrST.equalBaseIndex(BasePtrLD, DAG, Offset)) 15884 return SDValue(); 15885 15886 // Normalize for Endianness. After this Offset=0 will denote that the least 15887 // significant bit in the loaded value maps to the least significant bit in 15888 // the stored value). With Offset=n (for n > 0) the loaded value starts at the 15889 // n:th least significant byte of the stored value. 15890 if (DAG.getDataLayout().isBigEndian()) 15891 Offset = ((int64_t)STMemType.getStoreSizeInBits().getFixedSize() - 15892 (int64_t)LDMemType.getStoreSizeInBits().getFixedSize()) / 15893 8 - 15894 Offset; 15895 15896 // Check that the stored value cover all bits that are loaded. 15897 bool STCoversLD; 15898 15899 TypeSize LdMemSize = LDMemType.getSizeInBits(); 15900 TypeSize StMemSize = STMemType.getSizeInBits(); 15901 if (LdStScalable) 15902 STCoversLD = (Offset == 0) && LdMemSize == StMemSize; 15903 else 15904 STCoversLD = (Offset >= 0) && (Offset * 8 + LdMemSize.getFixedSize() <= 15905 StMemSize.getFixedSize()); 15906 15907 auto ReplaceLd = [&](LoadSDNode *LD, SDValue Val, SDValue Chain) -> SDValue { 15908 if (LD->isIndexed()) { 15909 // Cannot handle opaque target constants and we must respect the user's 15910 // request not to split indexes from loads. 15911 if (!canSplitIdx(LD)) 15912 return SDValue(); 15913 SDValue Idx = SplitIndexingFromLoad(LD); 15914 SDValue Ops[] = {Val, Idx, Chain}; 15915 return CombineTo(LD, Ops, 3); 15916 } 15917 return CombineTo(LD, Val, Chain); 15918 }; 15919 15920 if (!STCoversLD) 15921 return SDValue(); 15922 15923 // Memory as copy space (potentially masked). 15924 if (Offset == 0 && LDType == STType && STMemType == LDMemType) { 15925 // Simple case: Direct non-truncating forwarding 15926 if (LDType.getSizeInBits() == LdMemSize) 15927 return ReplaceLd(LD, ST->getValue(), Chain); 15928 // Can we model the truncate and extension with an and mask? 15929 if (STType.isInteger() && LDMemType.isInteger() && !STType.isVector() && 15930 !LDMemType.isVector() && LD->getExtensionType() != ISD::SEXTLOAD) { 15931 // Mask to size of LDMemType 15932 auto Mask = 15933 DAG.getConstant(APInt::getLowBitsSet(STType.getFixedSizeInBits(), 15934 StMemSize.getFixedSize()), 15935 SDLoc(ST), STType); 15936 auto Val = DAG.getNode(ISD::AND, SDLoc(LD), LDType, ST->getValue(), Mask); 15937 return ReplaceLd(LD, Val, Chain); 15938 } 15939 } 15940 15941 // TODO: Deal with nonzero offset. 15942 if (LD->getBasePtr().isUndef() || Offset != 0) 15943 return SDValue(); 15944 // Model necessary truncations / extenstions. 15945 SDValue Val; 15946 // Truncate Value To Stored Memory Size. 15947 do { 15948 if (!getTruncatedStoreValue(ST, Val)) 15949 continue; 15950 if (!isTypeLegal(LDMemType)) 15951 continue; 15952 if (STMemType != LDMemType) { 15953 // TODO: Support vectors? This requires extract_subvector/bitcast. 15954 if (!STMemType.isVector() && !LDMemType.isVector() && 15955 STMemType.isInteger() && LDMemType.isInteger()) 15956 Val = DAG.getNode(ISD::TRUNCATE, SDLoc(LD), LDMemType, Val); 15957 else 15958 continue; 15959 } 15960 if (!extendLoadedValueToExtension(LD, Val)) 15961 continue; 15962 return ReplaceLd(LD, Val, Chain); 15963 } while (false); 15964 15965 // On failure, cleanup dead nodes we may have created. 15966 if (Val->use_empty()) 15967 deleteAndRecombine(Val.getNode()); 15968 return SDValue(); 15969 } 15970 15971 SDValue DAGCombiner::visitLOAD(SDNode *N) { 15972 LoadSDNode *LD = cast<LoadSDNode>(N); 15973 SDValue Chain = LD->getChain(); 15974 SDValue Ptr = LD->getBasePtr(); 15975 15976 // If load is not volatile and there are no uses of the loaded value (and 15977 // the updated indexed value in case of indexed loads), change uses of the 15978 // chain value into uses of the chain input (i.e. delete the dead load). 15979 // TODO: Allow this for unordered atomics (see D66309) 15980 if (LD->isSimple()) { 15981 if (N->getValueType(1) == MVT::Other) { 15982 // Unindexed loads. 15983 if (!N->hasAnyUseOfValue(0)) { 15984 // It's not safe to use the two value CombineTo variant here. e.g. 15985 // v1, chain2 = load chain1, loc 15986 // v2, chain3 = load chain2, loc 15987 // v3 = add v2, c 15988 // Now we replace use of chain2 with chain1. This makes the second load 15989 // isomorphic to the one we are deleting, and thus makes this load live. 15990 LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG); 15991 dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG); 15992 dbgs() << "\n"); 15993 WorklistRemover DeadNodes(*this); 15994 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 15995 AddUsersToWorklist(Chain.getNode()); 15996 if (N->use_empty()) 15997 deleteAndRecombine(N); 15998 15999 return SDValue(N, 0); // Return N so it doesn't get rechecked! 16000 } 16001 } else { 16002 // Indexed loads. 16003 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?"); 16004 16005 // If this load has an opaque TargetConstant offset, then we cannot split 16006 // the indexing into an add/sub directly (that TargetConstant may not be 16007 // valid for a different type of node, and we cannot convert an opaque 16008 // target constant into a regular constant). 16009 bool CanSplitIdx = canSplitIdx(LD); 16010 16011 if (!N->hasAnyUseOfValue(0) && (CanSplitIdx || !N->hasAnyUseOfValue(1))) { 16012 SDValue Undef = DAG.getUNDEF(N->getValueType(0)); 16013 SDValue Index; 16014 if (N->hasAnyUseOfValue(1) && CanSplitIdx) { 16015 Index = SplitIndexingFromLoad(LD); 16016 // Try to fold the base pointer arithmetic into subsequent loads and 16017 // stores. 16018 AddUsersToWorklist(N); 16019 } else 16020 Index = DAG.getUNDEF(N->getValueType(1)); 16021 LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG); 16022 dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG); 16023 dbgs() << " and 2 other values\n"); 16024 WorklistRemover DeadNodes(*this); 16025 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef); 16026 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index); 16027 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain); 16028 deleteAndRecombine(N); 16029 return SDValue(N, 0); // Return N so it doesn't get rechecked! 16030 } 16031 } 16032 } 16033 16034 // If this load is directly stored, replace the load value with the stored 16035 // value. 16036 if (auto V = ForwardStoreValueToDirectLoad(LD)) 16037 return V; 16038 16039 // Try to infer better alignment information than the load already has. 16040 if (OptLevel != CodeGenOpt::None && LD->isUnindexed() && !LD->isAtomic()) { 16041 if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) { 16042 if (*Alignment > LD->getAlign() && 16043 isAligned(*Alignment, LD->getSrcValueOffset())) { 16044 SDValue NewLoad = DAG.getExtLoad( 16045 LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr, 16046 LD->getPointerInfo(), LD->getMemoryVT(), *Alignment, 16047 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 16048 // NewLoad will always be N as we are only refining the alignment 16049 assert(NewLoad.getNode() == N); 16050 (void)NewLoad; 16051 } 16052 } 16053 } 16054 16055 if (LD->isUnindexed()) { 16056 // Walk up chain skipping non-aliasing memory nodes. 16057 SDValue BetterChain = FindBetterChain(LD, Chain); 16058 16059 // If there is a better chain. 16060 if (Chain != BetterChain) { 16061 SDValue ReplLoad; 16062 16063 // Replace the chain to void dependency. 16064 if (LD->getExtensionType() == ISD::NON_EXTLOAD) { 16065 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD), 16066 BetterChain, Ptr, LD->getMemOperand()); 16067 } else { 16068 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), 16069 LD->getValueType(0), 16070 BetterChain, Ptr, LD->getMemoryVT(), 16071 LD->getMemOperand()); 16072 } 16073 16074 // Create token factor to keep old chain connected. 16075 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N), 16076 MVT::Other, Chain, ReplLoad.getValue(1)); 16077 16078 // Replace uses with load result and token factor 16079 return CombineTo(N, ReplLoad.getValue(0), Token); 16080 } 16081 } 16082 16083 // Try transforming N to an indexed load. 16084 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 16085 return SDValue(N, 0); 16086 16087 // Try to slice up N to more direct loads if the slices are mapped to 16088 // different register banks or pairing can take place. 16089 if (SliceUpLoad(N)) 16090 return SDValue(N, 0); 16091 16092 return SDValue(); 16093 } 16094 16095 namespace { 16096 16097 /// Helper structure used to slice a load in smaller loads. 16098 /// Basically a slice is obtained from the following sequence: 16099 /// Origin = load Ty1, Base 16100 /// Shift = srl Ty1 Origin, CstTy Amount 16101 /// Inst = trunc Shift to Ty2 16102 /// 16103 /// Then, it will be rewritten into: 16104 /// Slice = load SliceTy, Base + SliceOffset 16105 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2 16106 /// 16107 /// SliceTy is deduced from the number of bits that are actually used to 16108 /// build Inst. 16109 struct LoadedSlice { 16110 /// Helper structure used to compute the cost of a slice. 16111 struct Cost { 16112 /// Are we optimizing for code size. 16113 bool ForCodeSize = false; 16114 16115 /// Various cost. 16116 unsigned Loads = 0; 16117 unsigned Truncates = 0; 16118 unsigned CrossRegisterBanksCopies = 0; 16119 unsigned ZExts = 0; 16120 unsigned Shift = 0; 16121 16122 explicit Cost(bool ForCodeSize) : ForCodeSize(ForCodeSize) {} 16123 16124 /// Get the cost of one isolated slice. 16125 Cost(const LoadedSlice &LS, bool ForCodeSize) 16126 : ForCodeSize(ForCodeSize), Loads(1) { 16127 EVT TruncType = LS.Inst->getValueType(0); 16128 EVT LoadedType = LS.getLoadedType(); 16129 if (TruncType != LoadedType && 16130 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType)) 16131 ZExts = 1; 16132 } 16133 16134 /// Account for slicing gain in the current cost. 16135 /// Slicing provide a few gains like removing a shift or a 16136 /// truncate. This method allows to grow the cost of the original 16137 /// load with the gain from this slice. 16138 void addSliceGain(const LoadedSlice &LS) { 16139 // Each slice saves a truncate. 16140 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo(); 16141 if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(), 16142 LS.Inst->getValueType(0))) 16143 ++Truncates; 16144 // If there is a shift amount, this slice gets rid of it. 16145 if (LS.Shift) 16146 ++Shift; 16147 // If this slice can merge a cross register bank copy, account for it. 16148 if (LS.canMergeExpensiveCrossRegisterBankCopy()) 16149 ++CrossRegisterBanksCopies; 16150 } 16151 16152 Cost &operator+=(const Cost &RHS) { 16153 Loads += RHS.Loads; 16154 Truncates += RHS.Truncates; 16155 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies; 16156 ZExts += RHS.ZExts; 16157 Shift += RHS.Shift; 16158 return *this; 16159 } 16160 16161 bool operator==(const Cost &RHS) const { 16162 return Loads == RHS.Loads && Truncates == RHS.Truncates && 16163 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies && 16164 ZExts == RHS.ZExts && Shift == RHS.Shift; 16165 } 16166 16167 bool operator!=(const Cost &RHS) const { return !(*this == RHS); } 16168 16169 bool operator<(const Cost &RHS) const { 16170 // Assume cross register banks copies are as expensive as loads. 16171 // FIXME: Do we want some more target hooks? 16172 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies; 16173 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies; 16174 // Unless we are optimizing for code size, consider the 16175 // expensive operation first. 16176 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS) 16177 return ExpensiveOpsLHS < ExpensiveOpsRHS; 16178 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) < 16179 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS); 16180 } 16181 16182 bool operator>(const Cost &RHS) const { return RHS < *this; } 16183 16184 bool operator<=(const Cost &RHS) const { return !(RHS < *this); } 16185 16186 bool operator>=(const Cost &RHS) const { return !(*this < RHS); } 16187 }; 16188 16189 // The last instruction that represent the slice. This should be a 16190 // truncate instruction. 16191 SDNode *Inst; 16192 16193 // The original load instruction. 16194 LoadSDNode *Origin; 16195 16196 // The right shift amount in bits from the original load. 16197 unsigned Shift; 16198 16199 // The DAG from which Origin came from. 16200 // This is used to get some contextual information about legal types, etc. 16201 SelectionDAG *DAG; 16202 16203 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr, 16204 unsigned Shift = 0, SelectionDAG *DAG = nullptr) 16205 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {} 16206 16207 /// Get the bits used in a chunk of bits \p BitWidth large. 16208 /// \return Result is \p BitWidth and has used bits set to 1 and 16209 /// not used bits set to 0. 16210 APInt getUsedBits() const { 16211 // Reproduce the trunc(lshr) sequence: 16212 // - Start from the truncated value. 16213 // - Zero extend to the desired bit width. 16214 // - Shift left. 16215 assert(Origin && "No original load to compare against."); 16216 unsigned BitWidth = Origin->getValueSizeInBits(0); 16217 assert(Inst && "This slice is not bound to an instruction"); 16218 assert(Inst->getValueSizeInBits(0) <= BitWidth && 16219 "Extracted slice is bigger than the whole type!"); 16220 APInt UsedBits(Inst->getValueSizeInBits(0), 0); 16221 UsedBits.setAllBits(); 16222 UsedBits = UsedBits.zext(BitWidth); 16223 UsedBits <<= Shift; 16224 return UsedBits; 16225 } 16226 16227 /// Get the size of the slice to be loaded in bytes. 16228 unsigned getLoadedSize() const { 16229 unsigned SliceSize = getUsedBits().countPopulation(); 16230 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte."); 16231 return SliceSize / 8; 16232 } 16233 16234 /// Get the type that will be loaded for this slice. 16235 /// Note: This may not be the final type for the slice. 16236 EVT getLoadedType() const { 16237 assert(DAG && "Missing context"); 16238 LLVMContext &Ctxt = *DAG->getContext(); 16239 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8); 16240 } 16241 16242 /// Get the alignment of the load used for this slice. 16243 Align getAlign() const { 16244 Align Alignment = Origin->getAlign(); 16245 uint64_t Offset = getOffsetFromBase(); 16246 if (Offset != 0) 16247 Alignment = commonAlignment(Alignment, Alignment.value() + Offset); 16248 return Alignment; 16249 } 16250 16251 /// Check if this slice can be rewritten with legal operations. 16252 bool isLegal() const { 16253 // An invalid slice is not legal. 16254 if (!Origin || !Inst || !DAG) 16255 return false; 16256 16257 // Offsets are for indexed load only, we do not handle that. 16258 if (!Origin->getOffset().isUndef()) 16259 return false; 16260 16261 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 16262 16263 // Check that the type is legal. 16264 EVT SliceType = getLoadedType(); 16265 if (!TLI.isTypeLegal(SliceType)) 16266 return false; 16267 16268 // Check that the load is legal for this type. 16269 if (!TLI.isOperationLegal(ISD::LOAD, SliceType)) 16270 return false; 16271 16272 // Check that the offset can be computed. 16273 // 1. Check its type. 16274 EVT PtrType = Origin->getBasePtr().getValueType(); 16275 if (PtrType == MVT::Untyped || PtrType.isExtended()) 16276 return false; 16277 16278 // 2. Check that it fits in the immediate. 16279 if (!TLI.isLegalAddImmediate(getOffsetFromBase())) 16280 return false; 16281 16282 // 3. Check that the computation is legal. 16283 if (!TLI.isOperationLegal(ISD::ADD, PtrType)) 16284 return false; 16285 16286 // Check that the zext is legal if it needs one. 16287 EVT TruncateType = Inst->getValueType(0); 16288 if (TruncateType != SliceType && 16289 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType)) 16290 return false; 16291 16292 return true; 16293 } 16294 16295 /// Get the offset in bytes of this slice in the original chunk of 16296 /// bits. 16297 /// \pre DAG != nullptr. 16298 uint64_t getOffsetFromBase() const { 16299 assert(DAG && "Missing context."); 16300 bool IsBigEndian = DAG->getDataLayout().isBigEndian(); 16301 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported."); 16302 uint64_t Offset = Shift / 8; 16303 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8; 16304 assert(!(Origin->getValueSizeInBits(0) & 0x7) && 16305 "The size of the original loaded type is not a multiple of a" 16306 " byte."); 16307 // If Offset is bigger than TySizeInBytes, it means we are loading all 16308 // zeros. This should have been optimized before in the process. 16309 assert(TySizeInBytes > Offset && 16310 "Invalid shift amount for given loaded size"); 16311 if (IsBigEndian) 16312 Offset = TySizeInBytes - Offset - getLoadedSize(); 16313 return Offset; 16314 } 16315 16316 /// Generate the sequence of instructions to load the slice 16317 /// represented by this object and redirect the uses of this slice to 16318 /// this new sequence of instructions. 16319 /// \pre this->Inst && this->Origin are valid Instructions and this 16320 /// object passed the legal check: LoadedSlice::isLegal returned true. 16321 /// \return The last instruction of the sequence used to load the slice. 16322 SDValue loadSlice() const { 16323 assert(Inst && Origin && "Unable to replace a non-existing slice."); 16324 const SDValue &OldBaseAddr = Origin->getBasePtr(); 16325 SDValue BaseAddr = OldBaseAddr; 16326 // Get the offset in that chunk of bytes w.r.t. the endianness. 16327 int64_t Offset = static_cast<int64_t>(getOffsetFromBase()); 16328 assert(Offset >= 0 && "Offset too big to fit in int64_t!"); 16329 if (Offset) { 16330 // BaseAddr = BaseAddr + Offset. 16331 EVT ArithType = BaseAddr.getValueType(); 16332 SDLoc DL(Origin); 16333 BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr, 16334 DAG->getConstant(Offset, DL, ArithType)); 16335 } 16336 16337 // Create the type of the loaded slice according to its size. 16338 EVT SliceType = getLoadedType(); 16339 16340 // Create the load for the slice. 16341 SDValue LastInst = 16342 DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr, 16343 Origin->getPointerInfo().getWithOffset(Offset), getAlign(), 16344 Origin->getMemOperand()->getFlags()); 16345 // If the final type is not the same as the loaded type, this means that 16346 // we have to pad with zero. Create a zero extend for that. 16347 EVT FinalType = Inst->getValueType(0); 16348 if (SliceType != FinalType) 16349 LastInst = 16350 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst); 16351 return LastInst; 16352 } 16353 16354 /// Check if this slice can be merged with an expensive cross register 16355 /// bank copy. E.g., 16356 /// i = load i32 16357 /// f = bitcast i32 i to float 16358 bool canMergeExpensiveCrossRegisterBankCopy() const { 16359 if (!Inst || !Inst->hasOneUse()) 16360 return false; 16361 SDNode *Use = *Inst->use_begin(); 16362 if (Use->getOpcode() != ISD::BITCAST) 16363 return false; 16364 assert(DAG && "Missing context"); 16365 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 16366 EVT ResVT = Use->getValueType(0); 16367 const TargetRegisterClass *ResRC = 16368 TLI.getRegClassFor(ResVT.getSimpleVT(), Use->isDivergent()); 16369 const TargetRegisterClass *ArgRC = 16370 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT(), 16371 Use->getOperand(0)->isDivergent()); 16372 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT)) 16373 return false; 16374 16375 // At this point, we know that we perform a cross-register-bank copy. 16376 // Check if it is expensive. 16377 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo(); 16378 // Assume bitcasts are cheap, unless both register classes do not 16379 // explicitly share a common sub class. 16380 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC)) 16381 return false; 16382 16383 // Check if it will be merged with the load. 16384 // 1. Check the alignment / fast memory access constraint. 16385 bool IsFast = false; 16386 if (!TLI.allowsMemoryAccess(*DAG->getContext(), DAG->getDataLayout(), ResVT, 16387 Origin->getAddressSpace(), getAlign(), 16388 Origin->getMemOperand()->getFlags(), &IsFast) || 16389 !IsFast) 16390 return false; 16391 16392 // 2. Check that the load is a legal operation for that type. 16393 if (!TLI.isOperationLegal(ISD::LOAD, ResVT)) 16394 return false; 16395 16396 // 3. Check that we do not have a zext in the way. 16397 if (Inst->getValueType(0) != getLoadedType()) 16398 return false; 16399 16400 return true; 16401 } 16402 }; 16403 16404 } // end anonymous namespace 16405 16406 /// Check that all bits set in \p UsedBits form a dense region, i.e., 16407 /// \p UsedBits looks like 0..0 1..1 0..0. 16408 static bool areUsedBitsDense(const APInt &UsedBits) { 16409 // If all the bits are one, this is dense! 16410 if (UsedBits.isAllOnes()) 16411 return true; 16412 16413 // Get rid of the unused bits on the right. 16414 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros()); 16415 // Get rid of the unused bits on the left. 16416 if (NarrowedUsedBits.countLeadingZeros()) 16417 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits()); 16418 // Check that the chunk of bits is completely used. 16419 return NarrowedUsedBits.isAllOnes(); 16420 } 16421 16422 /// Check whether or not \p First and \p Second are next to each other 16423 /// in memory. This means that there is no hole between the bits loaded 16424 /// by \p First and the bits loaded by \p Second. 16425 static bool areSlicesNextToEachOther(const LoadedSlice &First, 16426 const LoadedSlice &Second) { 16427 assert(First.Origin == Second.Origin && First.Origin && 16428 "Unable to match different memory origins."); 16429 APInt UsedBits = First.getUsedBits(); 16430 assert((UsedBits & Second.getUsedBits()) == 0 && 16431 "Slices are not supposed to overlap."); 16432 UsedBits |= Second.getUsedBits(); 16433 return areUsedBitsDense(UsedBits); 16434 } 16435 16436 /// Adjust the \p GlobalLSCost according to the target 16437 /// paring capabilities and the layout of the slices. 16438 /// \pre \p GlobalLSCost should account for at least as many loads as 16439 /// there is in the slices in \p LoadedSlices. 16440 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices, 16441 LoadedSlice::Cost &GlobalLSCost) { 16442 unsigned NumberOfSlices = LoadedSlices.size(); 16443 // If there is less than 2 elements, no pairing is possible. 16444 if (NumberOfSlices < 2) 16445 return; 16446 16447 // Sort the slices so that elements that are likely to be next to each 16448 // other in memory are next to each other in the list. 16449 llvm::sort(LoadedSlices, [](const LoadedSlice &LHS, const LoadedSlice &RHS) { 16450 assert(LHS.Origin == RHS.Origin && "Different bases not implemented."); 16451 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase(); 16452 }); 16453 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo(); 16454 // First (resp. Second) is the first (resp. Second) potentially candidate 16455 // to be placed in a paired load. 16456 const LoadedSlice *First = nullptr; 16457 const LoadedSlice *Second = nullptr; 16458 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice, 16459 // Set the beginning of the pair. 16460 First = Second) { 16461 Second = &LoadedSlices[CurrSlice]; 16462 16463 // If First is NULL, it means we start a new pair. 16464 // Get to the next slice. 16465 if (!First) 16466 continue; 16467 16468 EVT LoadedType = First->getLoadedType(); 16469 16470 // If the types of the slices are different, we cannot pair them. 16471 if (LoadedType != Second->getLoadedType()) 16472 continue; 16473 16474 // Check if the target supplies paired loads for this type. 16475 Align RequiredAlignment; 16476 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) { 16477 // move to the next pair, this type is hopeless. 16478 Second = nullptr; 16479 continue; 16480 } 16481 // Check if we meet the alignment requirement. 16482 if (First->getAlign() < RequiredAlignment) 16483 continue; 16484 16485 // Check that both loads are next to each other in memory. 16486 if (!areSlicesNextToEachOther(*First, *Second)) 16487 continue; 16488 16489 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!"); 16490 --GlobalLSCost.Loads; 16491 // Move to the next pair. 16492 Second = nullptr; 16493 } 16494 } 16495 16496 /// Check the profitability of all involved LoadedSlice. 16497 /// Currently, it is considered profitable if there is exactly two 16498 /// involved slices (1) which are (2) next to each other in memory, and 16499 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3). 16500 /// 16501 /// Note: The order of the elements in \p LoadedSlices may be modified, but not 16502 /// the elements themselves. 16503 /// 16504 /// FIXME: When the cost model will be mature enough, we can relax 16505 /// constraints (1) and (2). 16506 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices, 16507 const APInt &UsedBits, bool ForCodeSize) { 16508 unsigned NumberOfSlices = LoadedSlices.size(); 16509 if (StressLoadSlicing) 16510 return NumberOfSlices > 1; 16511 16512 // Check (1). 16513 if (NumberOfSlices != 2) 16514 return false; 16515 16516 // Check (2). 16517 if (!areUsedBitsDense(UsedBits)) 16518 return false; 16519 16520 // Check (3). 16521 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize); 16522 // The original code has one big load. 16523 OrigCost.Loads = 1; 16524 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) { 16525 const LoadedSlice &LS = LoadedSlices[CurrSlice]; 16526 // Accumulate the cost of all the slices. 16527 LoadedSlice::Cost SliceCost(LS, ForCodeSize); 16528 GlobalSlicingCost += SliceCost; 16529 16530 // Account as cost in the original configuration the gain obtained 16531 // with the current slices. 16532 OrigCost.addSliceGain(LS); 16533 } 16534 16535 // If the target supports paired load, adjust the cost accordingly. 16536 adjustCostForPairing(LoadedSlices, GlobalSlicingCost); 16537 return OrigCost > GlobalSlicingCost; 16538 } 16539 16540 /// If the given load, \p LI, is used only by trunc or trunc(lshr) 16541 /// operations, split it in the various pieces being extracted. 16542 /// 16543 /// This sort of thing is introduced by SROA. 16544 /// This slicing takes care not to insert overlapping loads. 16545 /// \pre LI is a simple load (i.e., not an atomic or volatile load). 16546 bool DAGCombiner::SliceUpLoad(SDNode *N) { 16547 if (Level < AfterLegalizeDAG) 16548 return false; 16549 16550 LoadSDNode *LD = cast<LoadSDNode>(N); 16551 if (!LD->isSimple() || !ISD::isNormalLoad(LD) || 16552 !LD->getValueType(0).isInteger()) 16553 return false; 16554 16555 // The algorithm to split up a load of a scalable vector into individual 16556 // elements currently requires knowing the length of the loaded type, 16557 // so will need adjusting to work on scalable vectors. 16558 if (LD->getValueType(0).isScalableVector()) 16559 return false; 16560 16561 // Keep track of already used bits to detect overlapping values. 16562 // In that case, we will just abort the transformation. 16563 APInt UsedBits(LD->getValueSizeInBits(0), 0); 16564 16565 SmallVector<LoadedSlice, 4> LoadedSlices; 16566 16567 // Check if this load is used as several smaller chunks of bits. 16568 // Basically, look for uses in trunc or trunc(lshr) and record a new chain 16569 // of computation for each trunc. 16570 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end(); 16571 UI != UIEnd; ++UI) { 16572 // Skip the uses of the chain. 16573 if (UI.getUse().getResNo() != 0) 16574 continue; 16575 16576 SDNode *User = *UI; 16577 unsigned Shift = 0; 16578 16579 // Check if this is a trunc(lshr). 16580 if (User->getOpcode() == ISD::SRL && User->hasOneUse() && 16581 isa<ConstantSDNode>(User->getOperand(1))) { 16582 Shift = User->getConstantOperandVal(1); 16583 User = *User->use_begin(); 16584 } 16585 16586 // At this point, User is a Truncate, iff we encountered, trunc or 16587 // trunc(lshr). 16588 if (User->getOpcode() != ISD::TRUNCATE) 16589 return false; 16590 16591 // The width of the type must be a power of 2 and greater than 8-bits. 16592 // Otherwise the load cannot be represented in LLVM IR. 16593 // Moreover, if we shifted with a non-8-bits multiple, the slice 16594 // will be across several bytes. We do not support that. 16595 unsigned Width = User->getValueSizeInBits(0); 16596 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7)) 16597 return false; 16598 16599 // Build the slice for this chain of computations. 16600 LoadedSlice LS(User, LD, Shift, &DAG); 16601 APInt CurrentUsedBits = LS.getUsedBits(); 16602 16603 // Check if this slice overlaps with another. 16604 if ((CurrentUsedBits & UsedBits) != 0) 16605 return false; 16606 // Update the bits used globally. 16607 UsedBits |= CurrentUsedBits; 16608 16609 // Check if the new slice would be legal. 16610 if (!LS.isLegal()) 16611 return false; 16612 16613 // Record the slice. 16614 LoadedSlices.push_back(LS); 16615 } 16616 16617 // Abort slicing if it does not seem to be profitable. 16618 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize)) 16619 return false; 16620 16621 ++SlicedLoads; 16622 16623 // Rewrite each chain to use an independent load. 16624 // By construction, each chain can be represented by a unique load. 16625 16626 // Prepare the argument for the new token factor for all the slices. 16627 SmallVector<SDValue, 8> ArgChains; 16628 for (const LoadedSlice &LS : LoadedSlices) { 16629 SDValue SliceInst = LS.loadSlice(); 16630 CombineTo(LS.Inst, SliceInst, true); 16631 if (SliceInst.getOpcode() != ISD::LOAD) 16632 SliceInst = SliceInst.getOperand(0); 16633 assert(SliceInst->getOpcode() == ISD::LOAD && 16634 "It takes more than a zext to get to the loaded slice!!"); 16635 ArgChains.push_back(SliceInst.getValue(1)); 16636 } 16637 16638 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, 16639 ArgChains); 16640 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain); 16641 AddToWorklist(Chain.getNode()); 16642 return true; 16643 } 16644 16645 /// Check to see if V is (and load (ptr), imm), where the load is having 16646 /// specific bytes cleared out. If so, return the byte size being masked out 16647 /// and the shift amount. 16648 static std::pair<unsigned, unsigned> 16649 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) { 16650 std::pair<unsigned, unsigned> Result(0, 0); 16651 16652 // Check for the structure we're looking for. 16653 if (V->getOpcode() != ISD::AND || 16654 !isa<ConstantSDNode>(V->getOperand(1)) || 16655 !ISD::isNormalLoad(V->getOperand(0).getNode())) 16656 return Result; 16657 16658 // Check the chain and pointer. 16659 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0)); 16660 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer. 16661 16662 // This only handles simple types. 16663 if (V.getValueType() != MVT::i16 && 16664 V.getValueType() != MVT::i32 && 16665 V.getValueType() != MVT::i64) 16666 return Result; 16667 16668 // Check the constant mask. Invert it so that the bits being masked out are 16669 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits 16670 // follow the sign bit for uniformity. 16671 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue(); 16672 unsigned NotMaskLZ = countLeadingZeros(NotMask); 16673 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte. 16674 unsigned NotMaskTZ = countTrailingZeros(NotMask); 16675 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte. 16676 if (NotMaskLZ == 64) return Result; // All zero mask. 16677 16678 // See if we have a continuous run of bits. If so, we have 0*1+0* 16679 if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64) 16680 return Result; 16681 16682 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64. 16683 if (V.getValueType() != MVT::i64 && NotMaskLZ) 16684 NotMaskLZ -= 64-V.getValueSizeInBits(); 16685 16686 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8; 16687 switch (MaskedBytes) { 16688 case 1: 16689 case 2: 16690 case 4: break; 16691 default: return Result; // All one mask, or 5-byte mask. 16692 } 16693 16694 // Verify that the first bit starts at a multiple of mask so that the access 16695 // is aligned the same as the access width. 16696 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result; 16697 16698 // For narrowing to be valid, it must be the case that the load the 16699 // immediately preceding memory operation before the store. 16700 if (LD == Chain.getNode()) 16701 ; // ok. 16702 else if (Chain->getOpcode() == ISD::TokenFactor && 16703 SDValue(LD, 1).hasOneUse()) { 16704 // LD has only 1 chain use so they are no indirect dependencies. 16705 if (!LD->isOperandOf(Chain.getNode())) 16706 return Result; 16707 } else 16708 return Result; // Fail. 16709 16710 Result.first = MaskedBytes; 16711 Result.second = NotMaskTZ/8; 16712 return Result; 16713 } 16714 16715 /// Check to see if IVal is something that provides a value as specified by 16716 /// MaskInfo. If so, replace the specified store with a narrower store of 16717 /// truncated IVal. 16718 static SDValue 16719 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo, 16720 SDValue IVal, StoreSDNode *St, 16721 DAGCombiner *DC) { 16722 unsigned NumBytes = MaskInfo.first; 16723 unsigned ByteShift = MaskInfo.second; 16724 SelectionDAG &DAG = DC->getDAG(); 16725 16726 // Check to see if IVal is all zeros in the part being masked in by the 'or' 16727 // that uses this. If not, this is not a replacement. 16728 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(), 16729 ByteShift*8, (ByteShift+NumBytes)*8); 16730 if (!DAG.MaskedValueIsZero(IVal, Mask)) return SDValue(); 16731 16732 // Check that it is legal on the target to do this. It is legal if the new 16733 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type 16734 // legalization (and the target doesn't explicitly think this is a bad idea). 16735 MVT VT = MVT::getIntegerVT(NumBytes * 8); 16736 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 16737 if (!DC->isTypeLegal(VT)) 16738 return SDValue(); 16739 if (St->getMemOperand() && 16740 !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 16741 *St->getMemOperand())) 16742 return SDValue(); 16743 16744 // Okay, we can do this! Replace the 'St' store with a store of IVal that is 16745 // shifted by ByteShift and truncated down to NumBytes. 16746 if (ByteShift) { 16747 SDLoc DL(IVal); 16748 IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal, 16749 DAG.getConstant(ByteShift*8, DL, 16750 DC->getShiftAmountTy(IVal.getValueType()))); 16751 } 16752 16753 // Figure out the offset for the store and the alignment of the access. 16754 unsigned StOffset; 16755 if (DAG.getDataLayout().isLittleEndian()) 16756 StOffset = ByteShift; 16757 else 16758 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes; 16759 16760 SDValue Ptr = St->getBasePtr(); 16761 if (StOffset) { 16762 SDLoc DL(IVal); 16763 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(StOffset), DL); 16764 } 16765 16766 // Truncate down to the new size. 16767 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal); 16768 16769 ++OpsNarrowed; 16770 return DAG 16771 .getStore(St->getChain(), SDLoc(St), IVal, Ptr, 16772 St->getPointerInfo().getWithOffset(StOffset), 16773 St->getOriginalAlign()); 16774 } 16775 16776 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and 16777 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try 16778 /// narrowing the load and store if it would end up being a win for performance 16779 /// or code size. 16780 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) { 16781 StoreSDNode *ST = cast<StoreSDNode>(N); 16782 if (!ST->isSimple()) 16783 return SDValue(); 16784 16785 SDValue Chain = ST->getChain(); 16786 SDValue Value = ST->getValue(); 16787 SDValue Ptr = ST->getBasePtr(); 16788 EVT VT = Value.getValueType(); 16789 16790 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse()) 16791 return SDValue(); 16792 16793 unsigned Opc = Value.getOpcode(); 16794 16795 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst 16796 // is a byte mask indicating a consecutive number of bytes, check to see if 16797 // Y is known to provide just those bytes. If so, we try to replace the 16798 // load + replace + store sequence with a single (narrower) store, which makes 16799 // the load dead. 16800 if (Opc == ISD::OR && EnableShrinkLoadReplaceStoreWithStore) { 16801 std::pair<unsigned, unsigned> MaskedLoad; 16802 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain); 16803 if (MaskedLoad.first) 16804 if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 16805 Value.getOperand(1), ST,this)) 16806 return NewST; 16807 16808 // Or is commutative, so try swapping X and Y. 16809 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain); 16810 if (MaskedLoad.first) 16811 if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad, 16812 Value.getOperand(0), ST,this)) 16813 return NewST; 16814 } 16815 16816 if (!EnableReduceLoadOpStoreWidth) 16817 return SDValue(); 16818 16819 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) || 16820 Value.getOperand(1).getOpcode() != ISD::Constant) 16821 return SDValue(); 16822 16823 SDValue N0 = Value.getOperand(0); 16824 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 16825 Chain == SDValue(N0.getNode(), 1)) { 16826 LoadSDNode *LD = cast<LoadSDNode>(N0); 16827 if (LD->getBasePtr() != Ptr || 16828 LD->getPointerInfo().getAddrSpace() != 16829 ST->getPointerInfo().getAddrSpace()) 16830 return SDValue(); 16831 16832 // Find the type to narrow it the load / op / store to. 16833 SDValue N1 = Value.getOperand(1); 16834 unsigned BitWidth = N1.getValueSizeInBits(); 16835 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue(); 16836 if (Opc == ISD::AND) 16837 Imm ^= APInt::getAllOnes(BitWidth); 16838 if (Imm == 0 || Imm.isAllOnes()) 16839 return SDValue(); 16840 unsigned ShAmt = Imm.countTrailingZeros(); 16841 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1; 16842 unsigned NewBW = NextPowerOf2(MSB - ShAmt); 16843 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 16844 // The narrowing should be profitable, the load/store operation should be 16845 // legal (or custom) and the store size should be equal to the NewVT width. 16846 while (NewBW < BitWidth && 16847 (NewVT.getStoreSizeInBits() != NewBW || 16848 !TLI.isOperationLegalOrCustom(Opc, NewVT) || 16849 !TLI.isNarrowingProfitable(VT, NewVT))) { 16850 NewBW = NextPowerOf2(NewBW); 16851 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW); 16852 } 16853 if (NewBW >= BitWidth) 16854 return SDValue(); 16855 16856 // If the lsb changed does not start at the type bitwidth boundary, 16857 // start at the previous one. 16858 if (ShAmt % NewBW) 16859 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW; 16860 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, 16861 std::min(BitWidth, ShAmt + NewBW)); 16862 if ((Imm & Mask) == Imm) { 16863 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW); 16864 if (Opc == ISD::AND) 16865 NewImm ^= APInt::getAllOnes(NewBW); 16866 uint64_t PtrOff = ShAmt / 8; 16867 // For big endian targets, we need to adjust the offset to the pointer to 16868 // load the correct bytes. 16869 if (DAG.getDataLayout().isBigEndian()) 16870 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff; 16871 16872 bool IsFast = false; 16873 Align NewAlign = commonAlignment(LD->getAlign(), PtrOff); 16874 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), NewVT, 16875 LD->getAddressSpace(), NewAlign, 16876 LD->getMemOperand()->getFlags(), &IsFast) || 16877 !IsFast) 16878 return SDValue(); 16879 16880 SDValue NewPtr = 16881 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(PtrOff), SDLoc(LD)); 16882 SDValue NewLD = 16883 DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr, 16884 LD->getPointerInfo().getWithOffset(PtrOff), NewAlign, 16885 LD->getMemOperand()->getFlags(), LD->getAAInfo()); 16886 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD, 16887 DAG.getConstant(NewImm, SDLoc(Value), 16888 NewVT)); 16889 SDValue NewST = 16890 DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr, 16891 ST->getPointerInfo().getWithOffset(PtrOff), NewAlign); 16892 16893 AddToWorklist(NewPtr.getNode()); 16894 AddToWorklist(NewLD.getNode()); 16895 AddToWorklist(NewVal.getNode()); 16896 WorklistRemover DeadNodes(*this); 16897 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1)); 16898 ++OpsNarrowed; 16899 return NewST; 16900 } 16901 } 16902 16903 return SDValue(); 16904 } 16905 16906 /// For a given floating point load / store pair, if the load value isn't used 16907 /// by any other operations, then consider transforming the pair to integer 16908 /// load / store operations if the target deems the transformation profitable. 16909 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) { 16910 StoreSDNode *ST = cast<StoreSDNode>(N); 16911 SDValue Value = ST->getValue(); 16912 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) && 16913 Value.hasOneUse()) { 16914 LoadSDNode *LD = cast<LoadSDNode>(Value); 16915 EVT VT = LD->getMemoryVT(); 16916 if (!VT.isFloatingPoint() || 16917 VT != ST->getMemoryVT() || 16918 LD->isNonTemporal() || 16919 ST->isNonTemporal() || 16920 LD->getPointerInfo().getAddrSpace() != 0 || 16921 ST->getPointerInfo().getAddrSpace() != 0) 16922 return SDValue(); 16923 16924 TypeSize VTSize = VT.getSizeInBits(); 16925 16926 // We don't know the size of scalable types at compile time so we cannot 16927 // create an integer of the equivalent size. 16928 if (VTSize.isScalable()) 16929 return SDValue(); 16930 16931 bool FastLD = false, FastST = false; 16932 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VTSize.getFixedSize()); 16933 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) || 16934 !TLI.isOperationLegal(ISD::STORE, IntVT) || 16935 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) || 16936 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT) || 16937 !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), IntVT, 16938 *LD->getMemOperand(), &FastLD) || 16939 !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), IntVT, 16940 *ST->getMemOperand(), &FastST) || 16941 !FastLD || !FastST) 16942 return SDValue(); 16943 16944 SDValue NewLD = 16945 DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(), 16946 LD->getPointerInfo(), LD->getAlign()); 16947 16948 SDValue NewST = 16949 DAG.getStore(ST->getChain(), SDLoc(N), NewLD, ST->getBasePtr(), 16950 ST->getPointerInfo(), ST->getAlign()); 16951 16952 AddToWorklist(NewLD.getNode()); 16953 AddToWorklist(NewST.getNode()); 16954 WorklistRemover DeadNodes(*this); 16955 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1)); 16956 ++LdStFP2Int; 16957 return NewST; 16958 } 16959 16960 return SDValue(); 16961 } 16962 16963 // This is a helper function for visitMUL to check the profitability 16964 // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2). 16965 // MulNode is the original multiply, AddNode is (add x, c1), 16966 // and ConstNode is c2. 16967 // 16968 // If the (add x, c1) has multiple uses, we could increase 16969 // the number of adds if we make this transformation. 16970 // It would only be worth doing this if we can remove a 16971 // multiply in the process. Check for that here. 16972 // To illustrate: 16973 // (A + c1) * c3 16974 // (A + c2) * c3 16975 // We're checking for cases where we have common "c3 * A" expressions. 16976 bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode, 16977 SDValue &AddNode, 16978 SDValue &ConstNode) { 16979 APInt Val; 16980 16981 // If the add only has one use, and the target thinks the folding is 16982 // profitable or does not lead to worse code, this would be OK to do. 16983 if (AddNode.getNode()->hasOneUse() && 16984 TLI.isMulAddWithConstProfitable(AddNode, ConstNode)) 16985 return true; 16986 16987 // Walk all the users of the constant with which we're multiplying. 16988 for (SDNode *Use : ConstNode->uses()) { 16989 if (Use == MulNode) // This use is the one we're on right now. Skip it. 16990 continue; 16991 16992 if (Use->getOpcode() == ISD::MUL) { // We have another multiply use. 16993 SDNode *OtherOp; 16994 SDNode *MulVar = AddNode.getOperand(0).getNode(); 16995 16996 // OtherOp is what we're multiplying against the constant. 16997 if (Use->getOperand(0) == ConstNode) 16998 OtherOp = Use->getOperand(1).getNode(); 16999 else 17000 OtherOp = Use->getOperand(0).getNode(); 17001 17002 // Check to see if multiply is with the same operand of our "add". 17003 // 17004 // ConstNode = CONST 17005 // Use = ConstNode * A <-- visiting Use. OtherOp is A. 17006 // ... 17007 // AddNode = (A + c1) <-- MulVar is A. 17008 // = AddNode * ConstNode <-- current visiting instruction. 17009 // 17010 // If we make this transformation, we will have a common 17011 // multiply (ConstNode * A) that we can save. 17012 if (OtherOp == MulVar) 17013 return true; 17014 17015 // Now check to see if a future expansion will give us a common 17016 // multiply. 17017 // 17018 // ConstNode = CONST 17019 // AddNode = (A + c1) 17020 // ... = AddNode * ConstNode <-- current visiting instruction. 17021 // ... 17022 // OtherOp = (A + c2) 17023 // Use = OtherOp * ConstNode <-- visiting Use. 17024 // 17025 // If we make this transformation, we will have a common 17026 // multiply (CONST * A) after we also do the same transformation 17027 // to the "t2" instruction. 17028 if (OtherOp->getOpcode() == ISD::ADD && 17029 DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) && 17030 OtherOp->getOperand(0).getNode() == MulVar) 17031 return true; 17032 } 17033 } 17034 17035 // Didn't find a case where this would be profitable. 17036 return false; 17037 } 17038 17039 SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes, 17040 unsigned NumStores) { 17041 SmallVector<SDValue, 8> Chains; 17042 SmallPtrSet<const SDNode *, 8> Visited; 17043 SDLoc StoreDL(StoreNodes[0].MemNode); 17044 17045 for (unsigned i = 0; i < NumStores; ++i) { 17046 Visited.insert(StoreNodes[i].MemNode); 17047 } 17048 17049 // don't include nodes that are children or repeated nodes. 17050 for (unsigned i = 0; i < NumStores; ++i) { 17051 if (Visited.insert(StoreNodes[i].MemNode->getChain().getNode()).second) 17052 Chains.push_back(StoreNodes[i].MemNode->getChain()); 17053 } 17054 17055 assert(Chains.size() > 0 && "Chain should have generated a chain"); 17056 return DAG.getTokenFactor(StoreDL, Chains); 17057 } 17058 17059 bool DAGCombiner::mergeStoresOfConstantsOrVecElts( 17060 SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores, 17061 bool IsConstantSrc, bool UseVector, bool UseTrunc) { 17062 // Make sure we have something to merge. 17063 if (NumStores < 2) 17064 return false; 17065 17066 assert((!UseTrunc || !UseVector) && 17067 "This optimization cannot emit a vector truncating store"); 17068 17069 // The latest Node in the DAG. 17070 SDLoc DL(StoreNodes[0].MemNode); 17071 17072 TypeSize ElementSizeBits = MemVT.getStoreSizeInBits(); 17073 unsigned SizeInBits = NumStores * ElementSizeBits; 17074 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 17075 17076 Optional<MachineMemOperand::Flags> Flags; 17077 AAMDNodes AAInfo; 17078 for (unsigned I = 0; I != NumStores; ++I) { 17079 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 17080 if (!Flags) { 17081 Flags = St->getMemOperand()->getFlags(); 17082 AAInfo = St->getAAInfo(); 17083 continue; 17084 } 17085 // Skip merging if there's an inconsistent flag. 17086 if (Flags != St->getMemOperand()->getFlags()) 17087 return false; 17088 // Concatenate AA metadata. 17089 AAInfo = AAInfo.concat(St->getAAInfo()); 17090 } 17091 17092 EVT StoreTy; 17093 if (UseVector) { 17094 unsigned Elts = NumStores * NumMemElts; 17095 // Get the type for the merged vector store. 17096 StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 17097 } else 17098 StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits); 17099 17100 SDValue StoredVal; 17101 if (UseVector) { 17102 if (IsConstantSrc) { 17103 SmallVector<SDValue, 8> BuildVector; 17104 for (unsigned I = 0; I != NumStores; ++I) { 17105 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode); 17106 SDValue Val = St->getValue(); 17107 // If constant is of the wrong type, convert it now. 17108 if (MemVT != Val.getValueType()) { 17109 Val = peekThroughBitcasts(Val); 17110 // Deal with constants of wrong size. 17111 if (ElementSizeBits != Val.getValueSizeInBits()) { 17112 EVT IntMemVT = 17113 EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 17114 if (isa<ConstantFPSDNode>(Val)) { 17115 // Not clear how to truncate FP values. 17116 return false; 17117 } else if (auto *C = dyn_cast<ConstantSDNode>(Val)) 17118 Val = DAG.getConstant(C->getAPIntValue() 17119 .zextOrTrunc(Val.getValueSizeInBits()) 17120 .zextOrTrunc(ElementSizeBits), 17121 SDLoc(C), IntMemVT); 17122 } 17123 // Make sure correctly size type is the correct type. 17124 Val = DAG.getBitcast(MemVT, Val); 17125 } 17126 BuildVector.push_back(Val); 17127 } 17128 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 17129 : ISD::BUILD_VECTOR, 17130 DL, StoreTy, BuildVector); 17131 } else { 17132 SmallVector<SDValue, 8> Ops; 17133 for (unsigned i = 0; i < NumStores; ++i) { 17134 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 17135 SDValue Val = peekThroughBitcasts(St->getValue()); 17136 // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of 17137 // type MemVT. If the underlying value is not the correct 17138 // type, but it is an extraction of an appropriate vector we 17139 // can recast Val to be of the correct type. This may require 17140 // converting between EXTRACT_VECTOR_ELT and 17141 // EXTRACT_SUBVECTOR. 17142 if ((MemVT != Val.getValueType()) && 17143 (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT || 17144 Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) { 17145 EVT MemVTScalarTy = MemVT.getScalarType(); 17146 // We may need to add a bitcast here to get types to line up. 17147 if (MemVTScalarTy != Val.getValueType().getScalarType()) { 17148 Val = DAG.getBitcast(MemVT, Val); 17149 } else { 17150 unsigned OpC = MemVT.isVector() ? ISD::EXTRACT_SUBVECTOR 17151 : ISD::EXTRACT_VECTOR_ELT; 17152 SDValue Vec = Val.getOperand(0); 17153 SDValue Idx = Val.getOperand(1); 17154 Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Idx); 17155 } 17156 } 17157 Ops.push_back(Val); 17158 } 17159 17160 // Build the extracted vector elements back into a vector. 17161 StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS 17162 : ISD::BUILD_VECTOR, 17163 DL, StoreTy, Ops); 17164 } 17165 } else { 17166 // We should always use a vector store when merging extracted vector 17167 // elements, so this path implies a store of constants. 17168 assert(IsConstantSrc && "Merged vector elements should use vector store"); 17169 17170 APInt StoreInt(SizeInBits, 0); 17171 17172 // Construct a single integer constant which is made of the smaller 17173 // constant inputs. 17174 bool IsLE = DAG.getDataLayout().isLittleEndian(); 17175 for (unsigned i = 0; i < NumStores; ++i) { 17176 unsigned Idx = IsLE ? (NumStores - 1 - i) : i; 17177 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode); 17178 17179 SDValue Val = St->getValue(); 17180 Val = peekThroughBitcasts(Val); 17181 StoreInt <<= ElementSizeBits; 17182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) { 17183 StoreInt |= C->getAPIntValue() 17184 .zextOrTrunc(ElementSizeBits) 17185 .zextOrTrunc(SizeInBits); 17186 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) { 17187 StoreInt |= C->getValueAPF() 17188 .bitcastToAPInt() 17189 .zextOrTrunc(ElementSizeBits) 17190 .zextOrTrunc(SizeInBits); 17191 // If fp truncation is necessary give up for now. 17192 if (MemVT.getSizeInBits() != ElementSizeBits) 17193 return false; 17194 } else { 17195 llvm_unreachable("Invalid constant element type"); 17196 } 17197 } 17198 17199 // Create the new Load and Store operations. 17200 StoredVal = DAG.getConstant(StoreInt, DL, StoreTy); 17201 } 17202 17203 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 17204 SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores); 17205 17206 // make sure we use trunc store if it's necessary to be legal. 17207 SDValue NewStore; 17208 if (!UseTrunc) { 17209 NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(), 17210 FirstInChain->getPointerInfo(), 17211 FirstInChain->getAlign(), Flags.getValue(), AAInfo); 17212 } else { // Must be realized as a trunc store 17213 EVT LegalizedStoredValTy = 17214 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType()); 17215 unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits(); 17216 ConstantSDNode *C = cast<ConstantSDNode>(StoredVal); 17217 SDValue ExtendedStoreVal = 17218 DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL, 17219 LegalizedStoredValTy); 17220 NewStore = DAG.getTruncStore( 17221 NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(), 17222 FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/, 17223 FirstInChain->getAlign(), Flags.getValue(), AAInfo); 17224 } 17225 17226 // Replace all merged stores with the new store. 17227 for (unsigned i = 0; i < NumStores; ++i) 17228 CombineTo(StoreNodes[i].MemNode, NewStore); 17229 17230 AddToWorklist(NewChain.getNode()); 17231 return true; 17232 } 17233 17234 void DAGCombiner::getStoreMergeCandidates( 17235 StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes, 17236 SDNode *&RootNode) { 17237 // This holds the base pointer, index, and the offset in bytes from the base 17238 // pointer. We must have a base and an offset. Do not handle stores to undef 17239 // base pointers. 17240 BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 17241 if (!BasePtr.getBase().getNode() || BasePtr.getBase().isUndef()) 17242 return; 17243 17244 SDValue Val = peekThroughBitcasts(St->getValue()); 17245 StoreSource StoreSrc = getStoreSource(Val); 17246 assert(StoreSrc != StoreSource::Unknown && "Expected known source for store"); 17247 17248 // Match on loadbaseptr if relevant. 17249 EVT MemVT = St->getMemoryVT(); 17250 BaseIndexOffset LBasePtr; 17251 EVT LoadVT; 17252 if (StoreSrc == StoreSource::Load) { 17253 auto *Ld = cast<LoadSDNode>(Val); 17254 LBasePtr = BaseIndexOffset::match(Ld, DAG); 17255 LoadVT = Ld->getMemoryVT(); 17256 // Load and store should be the same type. 17257 if (MemVT != LoadVT) 17258 return; 17259 // Loads must only have one use. 17260 if (!Ld->hasNUsesOfValue(1, 0)) 17261 return; 17262 // The memory operands must not be volatile/indexed/atomic. 17263 // TODO: May be able to relax for unordered atomics (see D66309) 17264 if (!Ld->isSimple() || Ld->isIndexed()) 17265 return; 17266 } 17267 auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr, 17268 int64_t &Offset) -> bool { 17269 // The memory operands must not be volatile/indexed/atomic. 17270 // TODO: May be able to relax for unordered atomics (see D66309) 17271 if (!Other->isSimple() || Other->isIndexed()) 17272 return false; 17273 // Don't mix temporal stores with non-temporal stores. 17274 if (St->isNonTemporal() != Other->isNonTemporal()) 17275 return false; 17276 SDValue OtherBC = peekThroughBitcasts(Other->getValue()); 17277 // Allow merging constants of different types as integers. 17278 bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT()) 17279 : Other->getMemoryVT() != MemVT; 17280 switch (StoreSrc) { 17281 case StoreSource::Load: { 17282 if (NoTypeMatch) 17283 return false; 17284 // The Load's Base Ptr must also match. 17285 auto *OtherLd = dyn_cast<LoadSDNode>(OtherBC); 17286 if (!OtherLd) 17287 return false; 17288 BaseIndexOffset LPtr = BaseIndexOffset::match(OtherLd, DAG); 17289 if (LoadVT != OtherLd->getMemoryVT()) 17290 return false; 17291 // Loads must only have one use. 17292 if (!OtherLd->hasNUsesOfValue(1, 0)) 17293 return false; 17294 // The memory operands must not be volatile/indexed/atomic. 17295 // TODO: May be able to relax for unordered atomics (see D66309) 17296 if (!OtherLd->isSimple() || OtherLd->isIndexed()) 17297 return false; 17298 // Don't mix temporal loads with non-temporal loads. 17299 if (cast<LoadSDNode>(Val)->isNonTemporal() != OtherLd->isNonTemporal()) 17300 return false; 17301 if (!(LBasePtr.equalBaseIndex(LPtr, DAG))) 17302 return false; 17303 break; 17304 } 17305 case StoreSource::Constant: 17306 if (NoTypeMatch) 17307 return false; 17308 if (!isIntOrFPConstant(OtherBC)) 17309 return false; 17310 break; 17311 case StoreSource::Extract: 17312 // Do not merge truncated stores here. 17313 if (Other->isTruncatingStore()) 17314 return false; 17315 if (!MemVT.bitsEq(OtherBC.getValueType())) 17316 return false; 17317 if (OtherBC.getOpcode() != ISD::EXTRACT_VECTOR_ELT && 17318 OtherBC.getOpcode() != ISD::EXTRACT_SUBVECTOR) 17319 return false; 17320 break; 17321 default: 17322 llvm_unreachable("Unhandled store source for merging"); 17323 } 17324 Ptr = BaseIndexOffset::match(Other, DAG); 17325 return (BasePtr.equalBaseIndex(Ptr, DAG, Offset)); 17326 }; 17327 17328 // Check if the pair of StoreNode and the RootNode already bail out many 17329 // times which is over the limit in dependence check. 17330 auto OverLimitInDependenceCheck = [&](SDNode *StoreNode, 17331 SDNode *RootNode) -> bool { 17332 auto RootCount = StoreRootCountMap.find(StoreNode); 17333 return RootCount != StoreRootCountMap.end() && 17334 RootCount->second.first == RootNode && 17335 RootCount->second.second > StoreMergeDependenceLimit; 17336 }; 17337 17338 auto TryToAddCandidate = [&](SDNode::use_iterator UseIter) { 17339 // This must be a chain use. 17340 if (UseIter.getOperandNo() != 0) 17341 return; 17342 if (auto *OtherStore = dyn_cast<StoreSDNode>(*UseIter)) { 17343 BaseIndexOffset Ptr; 17344 int64_t PtrDiff; 17345 if (CandidateMatch(OtherStore, Ptr, PtrDiff) && 17346 !OverLimitInDependenceCheck(OtherStore, RootNode)) 17347 StoreNodes.push_back(MemOpLink(OtherStore, PtrDiff)); 17348 } 17349 }; 17350 17351 // We looking for a root node which is an ancestor to all mergable 17352 // stores. We search up through a load, to our root and then down 17353 // through all children. For instance we will find Store{1,2,3} if 17354 // St is Store1, Store2. or Store3 where the root is not a load 17355 // which always true for nonvolatile ops. TODO: Expand 17356 // the search to find all valid candidates through multiple layers of loads. 17357 // 17358 // Root 17359 // |-------|-------| 17360 // Load Load Store3 17361 // | | 17362 // Store1 Store2 17363 // 17364 // FIXME: We should be able to climb and 17365 // descend TokenFactors to find candidates as well. 17366 17367 RootNode = St->getChain().getNode(); 17368 17369 unsigned NumNodesExplored = 0; 17370 const unsigned MaxSearchNodes = 1024; 17371 if (auto *Ldn = dyn_cast<LoadSDNode>(RootNode)) { 17372 RootNode = Ldn->getChain().getNode(); 17373 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); 17374 I != E && NumNodesExplored < MaxSearchNodes; ++I, ++NumNodesExplored) { 17375 if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) { // walk down chain 17376 for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2) 17377 TryToAddCandidate(I2); 17378 } 17379 } 17380 } else { 17381 for (auto I = RootNode->use_begin(), E = RootNode->use_end(); 17382 I != E && NumNodesExplored < MaxSearchNodes; ++I, ++NumNodesExplored) 17383 TryToAddCandidate(I); 17384 } 17385 } 17386 17387 // We need to check that merging these stores does not cause a loop in 17388 // the DAG. Any store candidate may depend on another candidate 17389 // indirectly through its operand (we already consider dependencies 17390 // through the chain). Check in parallel by searching up from 17391 // non-chain operands of candidates. 17392 bool DAGCombiner::checkMergeStoreCandidatesForDependencies( 17393 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores, 17394 SDNode *RootNode) { 17395 // FIXME: We should be able to truncate a full search of 17396 // predecessors by doing a BFS and keeping tabs the originating 17397 // stores from which worklist nodes come from in a similar way to 17398 // TokenFactor simplfication. 17399 17400 SmallPtrSet<const SDNode *, 32> Visited; 17401 SmallVector<const SDNode *, 8> Worklist; 17402 17403 // RootNode is a predecessor to all candidates so we need not search 17404 // past it. Add RootNode (peeking through TokenFactors). Do not count 17405 // these towards size check. 17406 17407 Worklist.push_back(RootNode); 17408 while (!Worklist.empty()) { 17409 auto N = Worklist.pop_back_val(); 17410 if (!Visited.insert(N).second) 17411 continue; // Already present in Visited. 17412 if (N->getOpcode() == ISD::TokenFactor) { 17413 for (SDValue Op : N->ops()) 17414 Worklist.push_back(Op.getNode()); 17415 } 17416 } 17417 17418 // Don't count pruning nodes towards max. 17419 unsigned int Max = 1024 + Visited.size(); 17420 // Search Ops of store candidates. 17421 for (unsigned i = 0; i < NumStores; ++i) { 17422 SDNode *N = StoreNodes[i].MemNode; 17423 // Of the 4 Store Operands: 17424 // * Chain (Op 0) -> We have already considered these 17425 // in candidate selection and can be 17426 // safely ignored 17427 // * Value (Op 1) -> Cycles may happen (e.g. through load chains) 17428 // * Address (Op 2) -> Merged addresses may only vary by a fixed constant, 17429 // but aren't necessarily fromt the same base node, so 17430 // cycles possible (e.g. via indexed store). 17431 // * (Op 3) -> Represents the pre or post-indexing offset (or undef for 17432 // non-indexed stores). Not constant on all targets (e.g. ARM) 17433 // and so can participate in a cycle. 17434 for (unsigned j = 1; j < N->getNumOperands(); ++j) 17435 Worklist.push_back(N->getOperand(j).getNode()); 17436 } 17437 // Search through DAG. We can stop early if we find a store node. 17438 for (unsigned i = 0; i < NumStores; ++i) 17439 if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist, 17440 Max)) { 17441 // If the searching bail out, record the StoreNode and RootNode in the 17442 // StoreRootCountMap. If we have seen the pair many times over a limit, 17443 // we won't add the StoreNode into StoreNodes set again. 17444 if (Visited.size() >= Max) { 17445 auto &RootCount = StoreRootCountMap[StoreNodes[i].MemNode]; 17446 if (RootCount.first == RootNode) 17447 RootCount.second++; 17448 else 17449 RootCount = {RootNode, 1}; 17450 } 17451 return false; 17452 } 17453 return true; 17454 } 17455 17456 unsigned 17457 DAGCombiner::getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes, 17458 int64_t ElementSizeBytes) const { 17459 while (true) { 17460 // Find a store past the width of the first store. 17461 size_t StartIdx = 0; 17462 while ((StartIdx + 1 < StoreNodes.size()) && 17463 StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes != 17464 StoreNodes[StartIdx + 1].OffsetFromBase) 17465 ++StartIdx; 17466 17467 // Bail if we don't have enough candidates to merge. 17468 if (StartIdx + 1 >= StoreNodes.size()) 17469 return 0; 17470 17471 // Trim stores that overlapped with the first store. 17472 if (StartIdx) 17473 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx); 17474 17475 // Scan the memory operations on the chain and find the first 17476 // non-consecutive store memory address. 17477 unsigned NumConsecutiveStores = 1; 17478 int64_t StartAddress = StoreNodes[0].OffsetFromBase; 17479 // Check that the addresses are consecutive starting from the second 17480 // element in the list of stores. 17481 for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) { 17482 int64_t CurrAddress = StoreNodes[i].OffsetFromBase; 17483 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 17484 break; 17485 NumConsecutiveStores = i + 1; 17486 } 17487 if (NumConsecutiveStores > 1) 17488 return NumConsecutiveStores; 17489 17490 // There are no consecutive stores at the start of the list. 17491 // Remove the first store and try again. 17492 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1); 17493 } 17494 } 17495 17496 bool DAGCombiner::tryStoreMergeOfConstants( 17497 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumConsecutiveStores, 17498 EVT MemVT, SDNode *RootNode, bool AllowVectors) { 17499 LLVMContext &Context = *DAG.getContext(); 17500 const DataLayout &DL = DAG.getDataLayout(); 17501 int64_t ElementSizeBytes = MemVT.getStoreSize(); 17502 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 17503 bool MadeChange = false; 17504 17505 // Store the constants into memory as one consecutive store. 17506 while (NumConsecutiveStores >= 2) { 17507 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 17508 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 17509 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 17510 unsigned LastLegalType = 1; 17511 unsigned LastLegalVectorType = 1; 17512 bool LastIntegerTrunc = false; 17513 bool NonZero = false; 17514 unsigned FirstZeroAfterNonZero = NumConsecutiveStores; 17515 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 17516 StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode); 17517 SDValue StoredVal = ST->getValue(); 17518 bool IsElementZero = false; 17519 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) 17520 IsElementZero = C->isZero(); 17521 else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) 17522 IsElementZero = C->getConstantFPValue()->isNullValue(); 17523 if (IsElementZero) { 17524 if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores) 17525 FirstZeroAfterNonZero = i; 17526 } 17527 NonZero |= !IsElementZero; 17528 17529 // Find a legal type for the constant store. 17530 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 17531 EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits); 17532 bool IsFast = false; 17533 17534 // Break early when size is too large to be legal. 17535 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 17536 break; 17537 17538 if (TLI.isTypeLegal(StoreTy) && 17539 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, 17540 DAG.getMachineFunction()) && 17541 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17542 *FirstInChain->getMemOperand(), &IsFast) && 17543 IsFast) { 17544 LastIntegerTrunc = false; 17545 LastLegalType = i + 1; 17546 // Or check whether a truncstore is legal. 17547 } else if (TLI.getTypeAction(Context, StoreTy) == 17548 TargetLowering::TypePromoteInteger) { 17549 EVT LegalizedStoredValTy = 17550 TLI.getTypeToTransformTo(Context, StoredVal.getValueType()); 17551 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 17552 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, 17553 DAG.getMachineFunction()) && 17554 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17555 *FirstInChain->getMemOperand(), &IsFast) && 17556 IsFast) { 17557 LastIntegerTrunc = true; 17558 LastLegalType = i + 1; 17559 } 17560 } 17561 17562 // We only use vectors if the constant is known to be zero or the 17563 // target allows it and the function is not marked with the 17564 // noimplicitfloat attribute. 17565 if ((!NonZero || 17566 TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) && 17567 AllowVectors) { 17568 // Find a legal type for the vector store. 17569 unsigned Elts = (i + 1) * NumMemElts; 17570 EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 17571 if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) && 17572 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG.getMachineFunction()) && 17573 TLI.allowsMemoryAccess(Context, DL, Ty, 17574 *FirstInChain->getMemOperand(), &IsFast) && 17575 IsFast) 17576 LastLegalVectorType = i + 1; 17577 } 17578 } 17579 17580 bool UseVector = (LastLegalVectorType > LastLegalType) && AllowVectors; 17581 unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType; 17582 bool UseTrunc = LastIntegerTrunc && !UseVector; 17583 17584 // Check if we found a legal integer type that creates a meaningful 17585 // merge. 17586 if (NumElem < 2) { 17587 // We know that candidate stores are in order and of correct 17588 // shape. While there is no mergeable sequence from the 17589 // beginning one may start later in the sequence. The only 17590 // reason a merge of size N could have failed where another of 17591 // the same size would not have, is if the alignment has 17592 // improved or we've dropped a non-zero value. Drop as many 17593 // candidates as we can here. 17594 unsigned NumSkip = 1; 17595 while ((NumSkip < NumConsecutiveStores) && 17596 (NumSkip < FirstZeroAfterNonZero) && 17597 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 17598 NumSkip++; 17599 17600 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 17601 NumConsecutiveStores -= NumSkip; 17602 continue; 17603 } 17604 17605 // Check that we can merge these candidates without causing a cycle. 17606 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 17607 RootNode)) { 17608 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 17609 NumConsecutiveStores -= NumElem; 17610 continue; 17611 } 17612 17613 MadeChange |= mergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem, 17614 /*IsConstantSrc*/ true, 17615 UseVector, UseTrunc); 17616 17617 // Remove merged stores for next iteration. 17618 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 17619 NumConsecutiveStores -= NumElem; 17620 } 17621 return MadeChange; 17622 } 17623 17624 bool DAGCombiner::tryStoreMergeOfExtracts( 17625 SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumConsecutiveStores, 17626 EVT MemVT, SDNode *RootNode) { 17627 LLVMContext &Context = *DAG.getContext(); 17628 const DataLayout &DL = DAG.getDataLayout(); 17629 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 17630 bool MadeChange = false; 17631 17632 // Loop on Consecutive Stores on success. 17633 while (NumConsecutiveStores >= 2) { 17634 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 17635 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 17636 unsigned FirstStoreAlign = FirstInChain->getAlignment(); 17637 unsigned NumStoresToMerge = 1; 17638 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 17639 // Find a legal type for the vector store. 17640 unsigned Elts = (i + 1) * NumMemElts; 17641 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts); 17642 bool IsFast = false; 17643 17644 // Break early when size is too large to be legal. 17645 if (Ty.getSizeInBits() > MaximumLegalStoreInBits) 17646 break; 17647 17648 if (TLI.isTypeLegal(Ty) && 17649 TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG.getMachineFunction()) && 17650 TLI.allowsMemoryAccess(Context, DL, Ty, 17651 *FirstInChain->getMemOperand(), &IsFast) && 17652 IsFast) 17653 NumStoresToMerge = i + 1; 17654 } 17655 17656 // Check if we found a legal integer type creating a meaningful 17657 // merge. 17658 if (NumStoresToMerge < 2) { 17659 // We know that candidate stores are in order and of correct 17660 // shape. While there is no mergeable sequence from the 17661 // beginning one may start later in the sequence. The only 17662 // reason a merge of size N could have failed where another of 17663 // the same size would not have, is if the alignment has 17664 // improved. Drop as many candidates as we can here. 17665 unsigned NumSkip = 1; 17666 while ((NumSkip < NumConsecutiveStores) && 17667 (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign)) 17668 NumSkip++; 17669 17670 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 17671 NumConsecutiveStores -= NumSkip; 17672 continue; 17673 } 17674 17675 // Check that we can merge these candidates without causing a cycle. 17676 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumStoresToMerge, 17677 RootNode)) { 17678 StoreNodes.erase(StoreNodes.begin(), 17679 StoreNodes.begin() + NumStoresToMerge); 17680 NumConsecutiveStores -= NumStoresToMerge; 17681 continue; 17682 } 17683 17684 MadeChange |= mergeStoresOfConstantsOrVecElts( 17685 StoreNodes, MemVT, NumStoresToMerge, /*IsConstantSrc*/ false, 17686 /*UseVector*/ true, /*UseTrunc*/ false); 17687 17688 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumStoresToMerge); 17689 NumConsecutiveStores -= NumStoresToMerge; 17690 } 17691 return MadeChange; 17692 } 17693 17694 bool DAGCombiner::tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes, 17695 unsigned NumConsecutiveStores, EVT MemVT, 17696 SDNode *RootNode, bool AllowVectors, 17697 bool IsNonTemporalStore, 17698 bool IsNonTemporalLoad) { 17699 LLVMContext &Context = *DAG.getContext(); 17700 const DataLayout &DL = DAG.getDataLayout(); 17701 int64_t ElementSizeBytes = MemVT.getStoreSize(); 17702 unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1; 17703 bool MadeChange = false; 17704 17705 // Look for load nodes which are used by the stored values. 17706 SmallVector<MemOpLink, 8> LoadNodes; 17707 17708 // Find acceptable loads. Loads need to have the same chain (token factor), 17709 // must not be zext, volatile, indexed, and they must be consecutive. 17710 BaseIndexOffset LdBasePtr; 17711 17712 for (unsigned i = 0; i < NumConsecutiveStores; ++i) { 17713 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode); 17714 SDValue Val = peekThroughBitcasts(St->getValue()); 17715 LoadSDNode *Ld = cast<LoadSDNode>(Val); 17716 17717 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG); 17718 // If this is not the first ptr that we check. 17719 int64_t LdOffset = 0; 17720 if (LdBasePtr.getBase().getNode()) { 17721 // The base ptr must be the same. 17722 if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset)) 17723 break; 17724 } else { 17725 // Check that all other base pointers are the same as this one. 17726 LdBasePtr = LdPtr; 17727 } 17728 17729 // We found a potential memory operand to merge. 17730 LoadNodes.push_back(MemOpLink(Ld, LdOffset)); 17731 } 17732 17733 while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) { 17734 Align RequiredAlignment; 17735 bool NeedRotate = false; 17736 if (LoadNodes.size() == 2) { 17737 // If we have load/store pair instructions and we only have two values, 17738 // don't bother merging. 17739 if (TLI.hasPairedLoad(MemVT, RequiredAlignment) && 17740 StoreNodes[0].MemNode->getAlign() >= RequiredAlignment) { 17741 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2); 17742 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2); 17743 break; 17744 } 17745 // If the loads are reversed, see if we can rotate the halves into place. 17746 int64_t Offset0 = LoadNodes[0].OffsetFromBase; 17747 int64_t Offset1 = LoadNodes[1].OffsetFromBase; 17748 EVT PairVT = EVT::getIntegerVT(Context, ElementSizeBytes * 8 * 2); 17749 if (Offset0 - Offset1 == ElementSizeBytes && 17750 (hasOperation(ISD::ROTL, PairVT) || 17751 hasOperation(ISD::ROTR, PairVT))) { 17752 std::swap(LoadNodes[0], LoadNodes[1]); 17753 NeedRotate = true; 17754 } 17755 } 17756 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode; 17757 unsigned FirstStoreAS = FirstInChain->getAddressSpace(); 17758 Align FirstStoreAlign = FirstInChain->getAlign(); 17759 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode); 17760 17761 // Scan the memory operations on the chain and find the first 17762 // non-consecutive load memory address. These variables hold the index in 17763 // the store node array. 17764 17765 unsigned LastConsecutiveLoad = 1; 17766 17767 // This variable refers to the size and not index in the array. 17768 unsigned LastLegalVectorType = 1; 17769 unsigned LastLegalIntegerType = 1; 17770 bool isDereferenceable = true; 17771 bool DoIntegerTruncate = false; 17772 int64_t StartAddress = LoadNodes[0].OffsetFromBase; 17773 SDValue LoadChain = FirstLoad->getChain(); 17774 for (unsigned i = 1; i < LoadNodes.size(); ++i) { 17775 // All loads must share the same chain. 17776 if (LoadNodes[i].MemNode->getChain() != LoadChain) 17777 break; 17778 17779 int64_t CurrAddress = LoadNodes[i].OffsetFromBase; 17780 if (CurrAddress - StartAddress != (ElementSizeBytes * i)) 17781 break; 17782 LastConsecutiveLoad = i; 17783 17784 if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable()) 17785 isDereferenceable = false; 17786 17787 // Find a legal type for the vector store. 17788 unsigned Elts = (i + 1) * NumMemElts; 17789 EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 17790 17791 // Break early when size is too large to be legal. 17792 if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits) 17793 break; 17794 17795 bool IsFastSt = false; 17796 bool IsFastLd = false; 17797 // Don't try vector types if we need a rotate. We may still fail the 17798 // legality checks for the integer type, but we can't handle the rotate 17799 // case with vectors. 17800 // FIXME: We could use a shuffle in place of the rotate. 17801 if (!NeedRotate && TLI.isTypeLegal(StoreTy) && 17802 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, 17803 DAG.getMachineFunction()) && 17804 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17805 *FirstInChain->getMemOperand(), &IsFastSt) && 17806 IsFastSt && 17807 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17808 *FirstLoad->getMemOperand(), &IsFastLd) && 17809 IsFastLd) { 17810 LastLegalVectorType = i + 1; 17811 } 17812 17813 // Find a legal type for the integer store. 17814 unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8; 17815 StoreTy = EVT::getIntegerVT(Context, SizeInBits); 17816 if (TLI.isTypeLegal(StoreTy) && 17817 TLI.canMergeStoresTo(FirstStoreAS, StoreTy, 17818 DAG.getMachineFunction()) && 17819 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17820 *FirstInChain->getMemOperand(), &IsFastSt) && 17821 IsFastSt && 17822 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17823 *FirstLoad->getMemOperand(), &IsFastLd) && 17824 IsFastLd) { 17825 LastLegalIntegerType = i + 1; 17826 DoIntegerTruncate = false; 17827 // Or check whether a truncstore and extload is legal. 17828 } else if (TLI.getTypeAction(Context, StoreTy) == 17829 TargetLowering::TypePromoteInteger) { 17830 EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy); 17831 if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) && 17832 TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy, 17833 DAG.getMachineFunction()) && 17834 TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy, StoreTy) && 17835 TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy, StoreTy) && 17836 TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) && 17837 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17838 *FirstInChain->getMemOperand(), &IsFastSt) && 17839 IsFastSt && 17840 TLI.allowsMemoryAccess(Context, DL, StoreTy, 17841 *FirstLoad->getMemOperand(), &IsFastLd) && 17842 IsFastLd) { 17843 LastLegalIntegerType = i + 1; 17844 DoIntegerTruncate = true; 17845 } 17846 } 17847 } 17848 17849 // Only use vector types if the vector type is larger than the integer 17850 // type. If they are the same, use integers. 17851 bool UseVectorTy = 17852 LastLegalVectorType > LastLegalIntegerType && AllowVectors; 17853 unsigned LastLegalType = 17854 std::max(LastLegalVectorType, LastLegalIntegerType); 17855 17856 // We add +1 here because the LastXXX variables refer to location while 17857 // the NumElem refers to array/index size. 17858 unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1); 17859 NumElem = std::min(LastLegalType, NumElem); 17860 Align FirstLoadAlign = FirstLoad->getAlign(); 17861 17862 if (NumElem < 2) { 17863 // We know that candidate stores are in order and of correct 17864 // shape. While there is no mergeable sequence from the 17865 // beginning one may start later in the sequence. The only 17866 // reason a merge of size N could have failed where another of 17867 // the same size would not have is if the alignment or either 17868 // the load or store has improved. Drop as many candidates as we 17869 // can here. 17870 unsigned NumSkip = 1; 17871 while ((NumSkip < LoadNodes.size()) && 17872 (LoadNodes[NumSkip].MemNode->getAlign() <= FirstLoadAlign) && 17873 (StoreNodes[NumSkip].MemNode->getAlign() <= FirstStoreAlign)) 17874 NumSkip++; 17875 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip); 17876 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip); 17877 NumConsecutiveStores -= NumSkip; 17878 continue; 17879 } 17880 17881 // Check that we can merge these candidates without causing a cycle. 17882 if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem, 17883 RootNode)) { 17884 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 17885 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 17886 NumConsecutiveStores -= NumElem; 17887 continue; 17888 } 17889 17890 // Find if it is better to use vectors or integers to load and store 17891 // to memory. 17892 EVT JointMemOpVT; 17893 if (UseVectorTy) { 17894 // Find a legal type for the vector store. 17895 unsigned Elts = NumElem * NumMemElts; 17896 JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts); 17897 } else { 17898 unsigned SizeInBits = NumElem * ElementSizeBytes * 8; 17899 JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits); 17900 } 17901 17902 SDLoc LoadDL(LoadNodes[0].MemNode); 17903 SDLoc StoreDL(StoreNodes[0].MemNode); 17904 17905 // The merged loads are required to have the same incoming chain, so 17906 // using the first's chain is acceptable. 17907 17908 SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem); 17909 AddToWorklist(NewStoreChain.getNode()); 17910 17911 MachineMemOperand::Flags LdMMOFlags = 17912 isDereferenceable ? MachineMemOperand::MODereferenceable 17913 : MachineMemOperand::MONone; 17914 if (IsNonTemporalLoad) 17915 LdMMOFlags |= MachineMemOperand::MONonTemporal; 17916 17917 MachineMemOperand::Flags StMMOFlags = IsNonTemporalStore 17918 ? MachineMemOperand::MONonTemporal 17919 : MachineMemOperand::MONone; 17920 17921 SDValue NewLoad, NewStore; 17922 if (UseVectorTy || !DoIntegerTruncate) { 17923 NewLoad = DAG.getLoad( 17924 JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(), 17925 FirstLoad->getPointerInfo(), FirstLoadAlign, LdMMOFlags); 17926 SDValue StoreOp = NewLoad; 17927 if (NeedRotate) { 17928 unsigned LoadWidth = ElementSizeBytes * 8 * 2; 17929 assert(JointMemOpVT == EVT::getIntegerVT(Context, LoadWidth) && 17930 "Unexpected type for rotate-able load pair"); 17931 SDValue RotAmt = 17932 DAG.getShiftAmountConstant(LoadWidth / 2, JointMemOpVT, LoadDL); 17933 // Target can convert to the identical ROTR if it does not have ROTL. 17934 StoreOp = DAG.getNode(ISD::ROTL, LoadDL, JointMemOpVT, NewLoad, RotAmt); 17935 } 17936 NewStore = DAG.getStore( 17937 NewStoreChain, StoreDL, StoreOp, FirstInChain->getBasePtr(), 17938 FirstInChain->getPointerInfo(), FirstStoreAlign, StMMOFlags); 17939 } else { // This must be the truncstore/extload case 17940 EVT ExtendedTy = 17941 TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT); 17942 NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy, 17943 FirstLoad->getChain(), FirstLoad->getBasePtr(), 17944 FirstLoad->getPointerInfo(), JointMemOpVT, 17945 FirstLoadAlign, LdMMOFlags); 17946 NewStore = DAG.getTruncStore( 17947 NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(), 17948 FirstInChain->getPointerInfo(), JointMemOpVT, 17949 FirstInChain->getAlign(), FirstInChain->getMemOperand()->getFlags()); 17950 } 17951 17952 // Transfer chain users from old loads to the new load. 17953 for (unsigned i = 0; i < NumElem; ++i) { 17954 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode); 17955 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), 17956 SDValue(NewLoad.getNode(), 1)); 17957 } 17958 17959 // Replace all stores with the new store. Recursively remove corresponding 17960 // values if they are no longer used. 17961 for (unsigned i = 0; i < NumElem; ++i) { 17962 SDValue Val = StoreNodes[i].MemNode->getOperand(1); 17963 CombineTo(StoreNodes[i].MemNode, NewStore); 17964 if (Val.getNode()->use_empty()) 17965 recursivelyDeleteUnusedNodes(Val.getNode()); 17966 } 17967 17968 MadeChange = true; 17969 StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem); 17970 LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem); 17971 NumConsecutiveStores -= NumElem; 17972 } 17973 return MadeChange; 17974 } 17975 17976 bool DAGCombiner::mergeConsecutiveStores(StoreSDNode *St) { 17977 if (OptLevel == CodeGenOpt::None || !EnableStoreMerging) 17978 return false; 17979 17980 // TODO: Extend this function to merge stores of scalable vectors. 17981 // (i.e. two <vscale x 8 x i8> stores can be merged to one <vscale x 16 x i8> 17982 // store since we know <vscale x 16 x i8> is exactly twice as large as 17983 // <vscale x 8 x i8>). Until then, bail out for scalable vectors. 17984 EVT MemVT = St->getMemoryVT(); 17985 if (MemVT.isScalableVector()) 17986 return false; 17987 if (!MemVT.isSimple() || MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits) 17988 return false; 17989 17990 // This function cannot currently deal with non-byte-sized memory sizes. 17991 int64_t ElementSizeBytes = MemVT.getStoreSize(); 17992 if (ElementSizeBytes * 8 != (int64_t)MemVT.getSizeInBits()) 17993 return false; 17994 17995 // Do not bother looking at stored values that are not constants, loads, or 17996 // extracted vector elements. 17997 SDValue StoredVal = peekThroughBitcasts(St->getValue()); 17998 const StoreSource StoreSrc = getStoreSource(StoredVal); 17999 if (StoreSrc == StoreSource::Unknown) 18000 return false; 18001 18002 SmallVector<MemOpLink, 8> StoreNodes; 18003 SDNode *RootNode; 18004 // Find potential store merge candidates by searching through chain sub-DAG 18005 getStoreMergeCandidates(St, StoreNodes, RootNode); 18006 18007 // Check if there is anything to merge. 18008 if (StoreNodes.size() < 2) 18009 return false; 18010 18011 // Sort the memory operands according to their distance from the 18012 // base pointer. 18013 llvm::sort(StoreNodes, [](MemOpLink LHS, MemOpLink RHS) { 18014 return LHS.OffsetFromBase < RHS.OffsetFromBase; 18015 }); 18016 18017 bool AllowVectors = !DAG.getMachineFunction().getFunction().hasFnAttribute( 18018 Attribute::NoImplicitFloat); 18019 bool IsNonTemporalStore = St->isNonTemporal(); 18020 bool IsNonTemporalLoad = StoreSrc == StoreSource::Load && 18021 cast<LoadSDNode>(StoredVal)->isNonTemporal(); 18022 18023 // Store Merge attempts to merge the lowest stores. This generally 18024 // works out as if successful, as the remaining stores are checked 18025 // after the first collection of stores is merged. However, in the 18026 // case that a non-mergeable store is found first, e.g., {p[-2], 18027 // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent 18028 // mergeable cases. To prevent this, we prune such stores from the 18029 // front of StoreNodes here. 18030 bool MadeChange = false; 18031 while (StoreNodes.size() > 1) { 18032 unsigned NumConsecutiveStores = 18033 getConsecutiveStores(StoreNodes, ElementSizeBytes); 18034 // There are no more stores in the list to examine. 18035 if (NumConsecutiveStores == 0) 18036 return MadeChange; 18037 18038 // We have at least 2 consecutive stores. Try to merge them. 18039 assert(NumConsecutiveStores >= 2 && "Expected at least 2 stores"); 18040 switch (StoreSrc) { 18041 case StoreSource::Constant: 18042 MadeChange |= tryStoreMergeOfConstants(StoreNodes, NumConsecutiveStores, 18043 MemVT, RootNode, AllowVectors); 18044 break; 18045 18046 case StoreSource::Extract: 18047 MadeChange |= tryStoreMergeOfExtracts(StoreNodes, NumConsecutiveStores, 18048 MemVT, RootNode); 18049 break; 18050 18051 case StoreSource::Load: 18052 MadeChange |= tryStoreMergeOfLoads(StoreNodes, NumConsecutiveStores, 18053 MemVT, RootNode, AllowVectors, 18054 IsNonTemporalStore, IsNonTemporalLoad); 18055 break; 18056 18057 default: 18058 llvm_unreachable("Unhandled store source type"); 18059 } 18060 } 18061 return MadeChange; 18062 } 18063 18064 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) { 18065 SDLoc SL(ST); 18066 SDValue ReplStore; 18067 18068 // Replace the chain to avoid dependency. 18069 if (ST->isTruncatingStore()) { 18070 ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(), 18071 ST->getBasePtr(), ST->getMemoryVT(), 18072 ST->getMemOperand()); 18073 } else { 18074 ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(), 18075 ST->getMemOperand()); 18076 } 18077 18078 // Create token to keep both nodes around. 18079 SDValue Token = DAG.getNode(ISD::TokenFactor, SL, 18080 MVT::Other, ST->getChain(), ReplStore); 18081 18082 // Make sure the new and old chains are cleaned up. 18083 AddToWorklist(Token.getNode()); 18084 18085 // Don't add users to work list. 18086 return CombineTo(ST, Token, false); 18087 } 18088 18089 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) { 18090 SDValue Value = ST->getValue(); 18091 if (Value.getOpcode() == ISD::TargetConstantFP) 18092 return SDValue(); 18093 18094 if (!ISD::isNormalStore(ST)) 18095 return SDValue(); 18096 18097 SDLoc DL(ST); 18098 18099 SDValue Chain = ST->getChain(); 18100 SDValue Ptr = ST->getBasePtr(); 18101 18102 const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value); 18103 18104 // NOTE: If the original store is volatile, this transform must not increase 18105 // the number of stores. For example, on x86-32 an f64 can be stored in one 18106 // processor operation but an i64 (which is not legal) requires two. So the 18107 // transform should not be done in this case. 18108 18109 SDValue Tmp; 18110 switch (CFP->getSimpleValueType(0).SimpleTy) { 18111 default: 18112 llvm_unreachable("Unknown FP type"); 18113 case MVT::f16: // We don't do this for these yet. 18114 case MVT::f80: 18115 case MVT::f128: 18116 case MVT::ppcf128: 18117 return SDValue(); 18118 case MVT::f32: 18119 if ((isTypeLegal(MVT::i32) && !LegalOperations && ST->isSimple()) || 18120 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 18121 ; 18122 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF(). 18123 bitcastToAPInt().getZExtValue(), SDLoc(CFP), 18124 MVT::i32); 18125 return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand()); 18126 } 18127 18128 return SDValue(); 18129 case MVT::f64: 18130 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations && 18131 ST->isSimple()) || 18132 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) { 18133 ; 18134 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt(). 18135 getZExtValue(), SDLoc(CFP), MVT::i64); 18136 return DAG.getStore(Chain, DL, Tmp, 18137 Ptr, ST->getMemOperand()); 18138 } 18139 18140 if (ST->isSimple() && 18141 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) { 18142 // Many FP stores are not made apparent until after legalize, e.g. for 18143 // argument passing. Since this is so common, custom legalize the 18144 // 64-bit integer store into two 32-bit stores. 18145 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 18146 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32); 18147 SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32); 18148 if (DAG.getDataLayout().isBigEndian()) 18149 std::swap(Lo, Hi); 18150 18151 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 18152 AAMDNodes AAInfo = ST->getAAInfo(); 18153 18154 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 18155 ST->getOriginalAlign(), MMOFlags, AAInfo); 18156 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(4), DL); 18157 SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr, 18158 ST->getPointerInfo().getWithOffset(4), 18159 ST->getOriginalAlign(), MMOFlags, AAInfo); 18160 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, 18161 St0, St1); 18162 } 18163 18164 return SDValue(); 18165 } 18166 } 18167 18168 SDValue DAGCombiner::visitSTORE(SDNode *N) { 18169 StoreSDNode *ST = cast<StoreSDNode>(N); 18170 SDValue Chain = ST->getChain(); 18171 SDValue Value = ST->getValue(); 18172 SDValue Ptr = ST->getBasePtr(); 18173 18174 // If this is a store of a bit convert, store the input value if the 18175 // resultant store does not need a higher alignment than the original. 18176 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() && 18177 ST->isUnindexed()) { 18178 EVT SVT = Value.getOperand(0).getValueType(); 18179 // If the store is volatile, we only want to change the store type if the 18180 // resulting store is legal. Otherwise we might increase the number of 18181 // memory accesses. We don't care if the original type was legal or not 18182 // as we assume software couldn't rely on the number of accesses of an 18183 // illegal type. 18184 // TODO: May be able to relax for unordered atomics (see D66309) 18185 if (((!LegalOperations && ST->isSimple()) || 18186 TLI.isOperationLegal(ISD::STORE, SVT)) && 18187 TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT, 18188 DAG, *ST->getMemOperand())) { 18189 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr, 18190 ST->getMemOperand()); 18191 } 18192 } 18193 18194 // Turn 'store undef, Ptr' -> nothing. 18195 if (Value.isUndef() && ST->isUnindexed()) 18196 return Chain; 18197 18198 // Try to infer better alignment information than the store already has. 18199 if (OptLevel != CodeGenOpt::None && ST->isUnindexed() && !ST->isAtomic()) { 18200 if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) { 18201 if (*Alignment > ST->getAlign() && 18202 isAligned(*Alignment, ST->getSrcValueOffset())) { 18203 SDValue NewStore = 18204 DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(), 18205 ST->getMemoryVT(), *Alignment, 18206 ST->getMemOperand()->getFlags(), ST->getAAInfo()); 18207 // NewStore will always be N as we are only refining the alignment 18208 assert(NewStore.getNode() == N); 18209 (void)NewStore; 18210 } 18211 } 18212 } 18213 18214 // Try transforming a pair floating point load / store ops to integer 18215 // load / store ops. 18216 if (SDValue NewST = TransformFPLoadStorePair(N)) 18217 return NewST; 18218 18219 // Try transforming several stores into STORE (BSWAP). 18220 if (SDValue Store = mergeTruncStores(ST)) 18221 return Store; 18222 18223 if (ST->isUnindexed()) { 18224 // Walk up chain skipping non-aliasing memory nodes, on this store and any 18225 // adjacent stores. 18226 if (findBetterNeighborChains(ST)) { 18227 // replaceStoreChain uses CombineTo, which handled all of the worklist 18228 // manipulation. Return the original node to not do anything else. 18229 return SDValue(ST, 0); 18230 } 18231 Chain = ST->getChain(); 18232 } 18233 18234 // FIXME: is there such a thing as a truncating indexed store? 18235 if (ST->isTruncatingStore() && ST->isUnindexed() && 18236 Value.getValueType().isInteger() && 18237 (!isa<ConstantSDNode>(Value) || 18238 !cast<ConstantSDNode>(Value)->isOpaque())) { 18239 APInt TruncDemandedBits = 18240 APInt::getLowBitsSet(Value.getScalarValueSizeInBits(), 18241 ST->getMemoryVT().getScalarSizeInBits()); 18242 18243 // See if we can simplify the input to this truncstore with knowledge that 18244 // only the low bits are being used. For example: 18245 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8" 18246 AddToWorklist(Value.getNode()); 18247 if (SDValue Shorter = DAG.GetDemandedBits(Value, TruncDemandedBits)) 18248 return DAG.getTruncStore(Chain, SDLoc(N), Shorter, Ptr, ST->getMemoryVT(), 18249 ST->getMemOperand()); 18250 18251 // Otherwise, see if we can simplify the operation with 18252 // SimplifyDemandedBits, which only works if the value has a single use. 18253 if (SimplifyDemandedBits(Value, TruncDemandedBits)) { 18254 // Re-visit the store if anything changed and the store hasn't been merged 18255 // with another node (N is deleted) SimplifyDemandedBits will add Value's 18256 // node back to the worklist if necessary, but we also need to re-visit 18257 // the Store node itself. 18258 if (N->getOpcode() != ISD::DELETED_NODE) 18259 AddToWorklist(N); 18260 return SDValue(N, 0); 18261 } 18262 } 18263 18264 // If this is a load followed by a store to the same location, then the store 18265 // is dead/noop. 18266 // TODO: Can relax for unordered atomics (see D66309) 18267 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) { 18268 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() && 18269 ST->isUnindexed() && ST->isSimple() && 18270 Ld->getAddressSpace() == ST->getAddressSpace() && 18271 // There can't be any side effects between the load and store, such as 18272 // a call or store. 18273 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) { 18274 // The store is dead, remove it. 18275 return Chain; 18276 } 18277 } 18278 18279 // TODO: Can relax for unordered atomics (see D66309) 18280 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) { 18281 if (ST->isUnindexed() && ST->isSimple() && 18282 ST1->isUnindexed() && ST1->isSimple()) { 18283 if (ST1->getBasePtr() == Ptr && ST1->getValue() == Value && 18284 ST->getMemoryVT() == ST1->getMemoryVT() && 18285 ST->getAddressSpace() == ST1->getAddressSpace()) { 18286 // If this is a store followed by a store with the same value to the 18287 // same location, then the store is dead/noop. 18288 return Chain; 18289 } 18290 18291 if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() && 18292 !ST1->getBasePtr().isUndef() && 18293 // BaseIndexOffset and the code below requires knowing the size 18294 // of a vector, so bail out if MemoryVT is scalable. 18295 !ST->getMemoryVT().isScalableVector() && 18296 !ST1->getMemoryVT().isScalableVector() && 18297 ST->getAddressSpace() == ST1->getAddressSpace()) { 18298 const BaseIndexOffset STBase = BaseIndexOffset::match(ST, DAG); 18299 const BaseIndexOffset ChainBase = BaseIndexOffset::match(ST1, DAG); 18300 unsigned STBitSize = ST->getMemoryVT().getFixedSizeInBits(); 18301 unsigned ChainBitSize = ST1->getMemoryVT().getFixedSizeInBits(); 18302 // If this is a store who's preceding store to a subset of the current 18303 // location and no one other node is chained to that store we can 18304 // effectively drop the store. Do not remove stores to undef as they may 18305 // be used as data sinks. 18306 if (STBase.contains(DAG, STBitSize, ChainBase, ChainBitSize)) { 18307 CombineTo(ST1, ST1->getChain()); 18308 return SDValue(); 18309 } 18310 } 18311 } 18312 } 18313 18314 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a 18315 // truncating store. We can do this even if this is already a truncstore. 18316 if ((Value.getOpcode() == ISD::FP_ROUND || 18317 Value.getOpcode() == ISD::TRUNCATE) && 18318 Value.getNode()->hasOneUse() && ST->isUnindexed() && 18319 TLI.canCombineTruncStore(Value.getOperand(0).getValueType(), 18320 ST->getMemoryVT(), LegalOperations)) { 18321 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), 18322 Ptr, ST->getMemoryVT(), ST->getMemOperand()); 18323 } 18324 18325 // Always perform this optimization before types are legal. If the target 18326 // prefers, also try this after legalization to catch stores that were created 18327 // by intrinsics or other nodes. 18328 if (!LegalTypes || (TLI.mergeStoresAfterLegalization(ST->getMemoryVT()))) { 18329 while (true) { 18330 // There can be multiple store sequences on the same chain. 18331 // Keep trying to merge store sequences until we are unable to do so 18332 // or until we merge the last store on the chain. 18333 bool Changed = mergeConsecutiveStores(ST); 18334 if (!Changed) break; 18335 // Return N as merge only uses CombineTo and no worklist clean 18336 // up is necessary. 18337 if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N)) 18338 return SDValue(N, 0); 18339 } 18340 } 18341 18342 // Try transforming N to an indexed store. 18343 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N)) 18344 return SDValue(N, 0); 18345 18346 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr' 18347 // 18348 // Make sure to do this only after attempting to merge stores in order to 18349 // avoid changing the types of some subset of stores due to visit order, 18350 // preventing their merging. 18351 if (isa<ConstantFPSDNode>(ST->getValue())) { 18352 if (SDValue NewSt = replaceStoreOfFPConstant(ST)) 18353 return NewSt; 18354 } 18355 18356 if (SDValue NewSt = splitMergedValStore(ST)) 18357 return NewSt; 18358 18359 return ReduceLoadOpStoreWidth(N); 18360 } 18361 18362 SDValue DAGCombiner::visitLIFETIME_END(SDNode *N) { 18363 const auto *LifetimeEnd = cast<LifetimeSDNode>(N); 18364 if (!LifetimeEnd->hasOffset()) 18365 return SDValue(); 18366 18367 const BaseIndexOffset LifetimeEndBase(N->getOperand(1), SDValue(), 18368 LifetimeEnd->getOffset(), false); 18369 18370 // We walk up the chains to find stores. 18371 SmallVector<SDValue, 8> Chains = {N->getOperand(0)}; 18372 while (!Chains.empty()) { 18373 SDValue Chain = Chains.pop_back_val(); 18374 if (!Chain.hasOneUse()) 18375 continue; 18376 switch (Chain.getOpcode()) { 18377 case ISD::TokenFactor: 18378 for (unsigned Nops = Chain.getNumOperands(); Nops;) 18379 Chains.push_back(Chain.getOperand(--Nops)); 18380 break; 18381 case ISD::LIFETIME_START: 18382 case ISD::LIFETIME_END: 18383 // We can forward past any lifetime start/end that can be proven not to 18384 // alias the node. 18385 if (!mayAlias(Chain.getNode(), N)) 18386 Chains.push_back(Chain.getOperand(0)); 18387 break; 18388 case ISD::STORE: { 18389 StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain); 18390 // TODO: Can relax for unordered atomics (see D66309) 18391 if (!ST->isSimple() || ST->isIndexed()) 18392 continue; 18393 const TypeSize StoreSize = ST->getMemoryVT().getStoreSize(); 18394 // The bounds of a scalable store are not known until runtime, so this 18395 // store cannot be elided. 18396 if (StoreSize.isScalable()) 18397 continue; 18398 const BaseIndexOffset StoreBase = BaseIndexOffset::match(ST, DAG); 18399 // If we store purely within object bounds just before its lifetime ends, 18400 // we can remove the store. 18401 if (LifetimeEndBase.contains(DAG, LifetimeEnd->getSize() * 8, StoreBase, 18402 StoreSize.getFixedSize() * 8)) { 18403 LLVM_DEBUG(dbgs() << "\nRemoving store:"; StoreBase.dump(); 18404 dbgs() << "\nwithin LIFETIME_END of : "; 18405 LifetimeEndBase.dump(); dbgs() << "\n"); 18406 CombineTo(ST, ST->getChain()); 18407 return SDValue(N, 0); 18408 } 18409 } 18410 } 18411 } 18412 return SDValue(); 18413 } 18414 18415 /// For the instruction sequence of store below, F and I values 18416 /// are bundled together as an i64 value before being stored into memory. 18417 /// Sometimes it is more efficent to generate separate stores for F and I, 18418 /// which can remove the bitwise instructions or sink them to colder places. 18419 /// 18420 /// (store (or (zext (bitcast F to i32) to i64), 18421 /// (shl (zext I to i64), 32)), addr) --> 18422 /// (store F, addr) and (store I, addr+4) 18423 /// 18424 /// Similarly, splitting for other merged store can also be beneficial, like: 18425 /// For pair of {i32, i32}, i64 store --> two i32 stores. 18426 /// For pair of {i32, i16}, i64 store --> two i32 stores. 18427 /// For pair of {i16, i16}, i32 store --> two i16 stores. 18428 /// For pair of {i16, i8}, i32 store --> two i16 stores. 18429 /// For pair of {i8, i8}, i16 store --> two i8 stores. 18430 /// 18431 /// We allow each target to determine specifically which kind of splitting is 18432 /// supported. 18433 /// 18434 /// The store patterns are commonly seen from the simple code snippet below 18435 /// if only std::make_pair(...) is sroa transformed before inlined into hoo. 18436 /// void goo(const std::pair<int, float> &); 18437 /// hoo() { 18438 /// ... 18439 /// goo(std::make_pair(tmp, ftmp)); 18440 /// ... 18441 /// } 18442 /// 18443 SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) { 18444 if (OptLevel == CodeGenOpt::None) 18445 return SDValue(); 18446 18447 // Can't change the number of memory accesses for a volatile store or break 18448 // atomicity for an atomic one. 18449 if (!ST->isSimple()) 18450 return SDValue(); 18451 18452 SDValue Val = ST->getValue(); 18453 SDLoc DL(ST); 18454 18455 // Match OR operand. 18456 if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR) 18457 return SDValue(); 18458 18459 // Match SHL operand and get Lower and Higher parts of Val. 18460 SDValue Op1 = Val.getOperand(0); 18461 SDValue Op2 = Val.getOperand(1); 18462 SDValue Lo, Hi; 18463 if (Op1.getOpcode() != ISD::SHL) { 18464 std::swap(Op1, Op2); 18465 if (Op1.getOpcode() != ISD::SHL) 18466 return SDValue(); 18467 } 18468 Lo = Op2; 18469 Hi = Op1.getOperand(0); 18470 if (!Op1.hasOneUse()) 18471 return SDValue(); 18472 18473 // Match shift amount to HalfValBitSize. 18474 unsigned HalfValBitSize = Val.getValueSizeInBits() / 2; 18475 ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1)); 18476 if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize) 18477 return SDValue(); 18478 18479 // Lo and Hi are zero-extended from int with size less equal than 32 18480 // to i64. 18481 if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() || 18482 !Lo.getOperand(0).getValueType().isScalarInteger() || 18483 Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize || 18484 Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() || 18485 !Hi.getOperand(0).getValueType().isScalarInteger() || 18486 Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize) 18487 return SDValue(); 18488 18489 // Use the EVT of low and high parts before bitcast as the input 18490 // of target query. 18491 EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST) 18492 ? Lo.getOperand(0).getValueType() 18493 : Lo.getValueType(); 18494 EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST) 18495 ? Hi.getOperand(0).getValueType() 18496 : Hi.getValueType(); 18497 if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) 18498 return SDValue(); 18499 18500 // Start to split store. 18501 MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags(); 18502 AAMDNodes AAInfo = ST->getAAInfo(); 18503 18504 // Change the sizes of Lo and Hi's value types to HalfValBitSize. 18505 EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize); 18506 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0)); 18507 Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0)); 18508 18509 SDValue Chain = ST->getChain(); 18510 SDValue Ptr = ST->getBasePtr(); 18511 // Lower value store. 18512 SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(), 18513 ST->getOriginalAlign(), MMOFlags, AAInfo); 18514 Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(HalfValBitSize / 8), DL); 18515 // Higher value store. 18516 SDValue St1 = DAG.getStore( 18517 St0, DL, Hi, Ptr, ST->getPointerInfo().getWithOffset(HalfValBitSize / 8), 18518 ST->getOriginalAlign(), MMOFlags, AAInfo); 18519 return St1; 18520 } 18521 18522 /// Convert a disguised subvector insertion into a shuffle: 18523 SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) { 18524 assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT && 18525 "Expected extract_vector_elt"); 18526 SDValue InsertVal = N->getOperand(1); 18527 SDValue Vec = N->getOperand(0); 18528 18529 // (insert_vector_elt (vector_shuffle X, Y), (extract_vector_elt X, N), 18530 // InsIndex) 18531 // --> (vector_shuffle X, Y) and variations where shuffle operands may be 18532 // CONCAT_VECTORS. 18533 if (Vec.getOpcode() == ISD::VECTOR_SHUFFLE && Vec.hasOneUse() && 18534 InsertVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 18535 isa<ConstantSDNode>(InsertVal.getOperand(1))) { 18536 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Vec.getNode()); 18537 ArrayRef<int> Mask = SVN->getMask(); 18538 18539 SDValue X = Vec.getOperand(0); 18540 SDValue Y = Vec.getOperand(1); 18541 18542 // Vec's operand 0 is using indices from 0 to N-1 and 18543 // operand 1 from N to 2N - 1, where N is the number of 18544 // elements in the vectors. 18545 SDValue InsertVal0 = InsertVal.getOperand(0); 18546 int ElementOffset = -1; 18547 18548 // We explore the inputs of the shuffle in order to see if we find the 18549 // source of the extract_vector_elt. If so, we can use it to modify the 18550 // shuffle rather than perform an insert_vector_elt. 18551 SmallVector<std::pair<int, SDValue>, 8> ArgWorkList; 18552 ArgWorkList.emplace_back(Mask.size(), Y); 18553 ArgWorkList.emplace_back(0, X); 18554 18555 while (!ArgWorkList.empty()) { 18556 int ArgOffset; 18557 SDValue ArgVal; 18558 std::tie(ArgOffset, ArgVal) = ArgWorkList.pop_back_val(); 18559 18560 if (ArgVal == InsertVal0) { 18561 ElementOffset = ArgOffset; 18562 break; 18563 } 18564 18565 // Peek through concat_vector. 18566 if (ArgVal.getOpcode() == ISD::CONCAT_VECTORS) { 18567 int CurrentArgOffset = 18568 ArgOffset + ArgVal.getValueType().getVectorNumElements(); 18569 int Step = ArgVal.getOperand(0).getValueType().getVectorNumElements(); 18570 for (SDValue Op : reverse(ArgVal->ops())) { 18571 CurrentArgOffset -= Step; 18572 ArgWorkList.emplace_back(CurrentArgOffset, Op); 18573 } 18574 18575 // Make sure we went through all the elements and did not screw up index 18576 // computation. 18577 assert(CurrentArgOffset == ArgOffset); 18578 } 18579 } 18580 18581 if (ElementOffset != -1) { 18582 SmallVector<int, 16> NewMask(Mask.begin(), Mask.end()); 18583 18584 auto *ExtrIndex = cast<ConstantSDNode>(InsertVal.getOperand(1)); 18585 NewMask[InsIndex] = ElementOffset + ExtrIndex->getZExtValue(); 18586 assert(NewMask[InsIndex] < 18587 (int)(2 * Vec.getValueType().getVectorNumElements()) && 18588 NewMask[InsIndex] >= 0 && "NewMask[InsIndex] is out of bound"); 18589 18590 SDValue LegalShuffle = 18591 TLI.buildLegalVectorShuffle(Vec.getValueType(), SDLoc(N), X, 18592 Y, NewMask, DAG); 18593 if (LegalShuffle) 18594 return LegalShuffle; 18595 } 18596 } 18597 18598 // insert_vector_elt V, (bitcast X from vector type), IdxC --> 18599 // bitcast(shuffle (bitcast V), (extended X), Mask) 18600 // Note: We do not use an insert_subvector node because that requires a 18601 // legal subvector type. 18602 if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() || 18603 !InsertVal.getOperand(0).getValueType().isVector()) 18604 return SDValue(); 18605 18606 SDValue SubVec = InsertVal.getOperand(0); 18607 SDValue DestVec = N->getOperand(0); 18608 EVT SubVecVT = SubVec.getValueType(); 18609 EVT VT = DestVec.getValueType(); 18610 unsigned NumSrcElts = SubVecVT.getVectorNumElements(); 18611 // If the source only has a single vector element, the cost of creating adding 18612 // it to a vector is likely to exceed the cost of a insert_vector_elt. 18613 if (NumSrcElts == 1) 18614 return SDValue(); 18615 unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits(); 18616 unsigned NumMaskVals = ExtendRatio * NumSrcElts; 18617 18618 // Step 1: Create a shuffle mask that implements this insert operation. The 18619 // vector that we are inserting into will be operand 0 of the shuffle, so 18620 // those elements are just 'i'. The inserted subvector is in the first 18621 // positions of operand 1 of the shuffle. Example: 18622 // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7} 18623 SmallVector<int, 16> Mask(NumMaskVals); 18624 for (unsigned i = 0; i != NumMaskVals; ++i) { 18625 if (i / NumSrcElts == InsIndex) 18626 Mask[i] = (i % NumSrcElts) + NumMaskVals; 18627 else 18628 Mask[i] = i; 18629 } 18630 18631 // Bail out if the target can not handle the shuffle we want to create. 18632 EVT SubVecEltVT = SubVecVT.getVectorElementType(); 18633 EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals); 18634 if (!TLI.isShuffleMaskLegal(Mask, ShufVT)) 18635 return SDValue(); 18636 18637 // Step 2: Create a wide vector from the inserted source vector by appending 18638 // undefined elements. This is the same size as our destination vector. 18639 SDLoc DL(N); 18640 SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT)); 18641 ConcatOps[0] = SubVec; 18642 SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps); 18643 18644 // Step 3: Shuffle in the padded subvector. 18645 SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec); 18646 SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask); 18647 AddToWorklist(PaddedSubV.getNode()); 18648 AddToWorklist(DestVecBC.getNode()); 18649 AddToWorklist(Shuf.getNode()); 18650 return DAG.getBitcast(VT, Shuf); 18651 } 18652 18653 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) { 18654 SDValue InVec = N->getOperand(0); 18655 SDValue InVal = N->getOperand(1); 18656 SDValue EltNo = N->getOperand(2); 18657 SDLoc DL(N); 18658 18659 EVT VT = InVec.getValueType(); 18660 auto *IndexC = dyn_cast<ConstantSDNode>(EltNo); 18661 18662 // Insert into out-of-bounds element is undefined. 18663 if (IndexC && VT.isFixedLengthVector() && 18664 IndexC->getZExtValue() >= VT.getVectorNumElements()) 18665 return DAG.getUNDEF(VT); 18666 18667 // Remove redundant insertions: 18668 // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x 18669 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 18670 InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1)) 18671 return InVec; 18672 18673 if (!IndexC) { 18674 // If this is variable insert to undef vector, it might be better to splat: 18675 // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... > 18676 if (InVec.isUndef() && TLI.shouldSplatInsEltVarIndex(VT)) { 18677 if (VT.isScalableVector()) 18678 return DAG.getSplatVector(VT, DL, InVal); 18679 else { 18680 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), InVal); 18681 return DAG.getBuildVector(VT, DL, Ops); 18682 } 18683 } 18684 return SDValue(); 18685 } 18686 18687 if (VT.isScalableVector()) 18688 return SDValue(); 18689 18690 unsigned NumElts = VT.getVectorNumElements(); 18691 18692 // We must know which element is being inserted for folds below here. 18693 unsigned Elt = IndexC->getZExtValue(); 18694 if (SDValue Shuf = combineInsertEltToShuffle(N, Elt)) 18695 return Shuf; 18696 18697 // Canonicalize insert_vector_elt dag nodes. 18698 // Example: 18699 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1) 18700 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0) 18701 // 18702 // Do this only if the child insert_vector node has one use; also 18703 // do this only if indices are both constants and Idx1 < Idx0. 18704 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse() 18705 && isa<ConstantSDNode>(InVec.getOperand(2))) { 18706 unsigned OtherElt = InVec.getConstantOperandVal(2); 18707 if (Elt < OtherElt) { 18708 // Swap nodes. 18709 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, 18710 InVec.getOperand(0), InVal, EltNo); 18711 AddToWorklist(NewOp.getNode()); 18712 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()), 18713 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2)); 18714 } 18715 } 18716 18717 // If we can't generate a legal BUILD_VECTOR, exit 18718 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) 18719 return SDValue(); 18720 18721 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially 18722 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the 18723 // vector elements. 18724 SmallVector<SDValue, 8> Ops; 18725 // Do not combine these two vectors if the output vector will not replace 18726 // the input vector. 18727 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) { 18728 Ops.append(InVec.getNode()->op_begin(), 18729 InVec.getNode()->op_end()); 18730 } else if (InVec.isUndef()) { 18731 Ops.append(NumElts, DAG.getUNDEF(InVal.getValueType())); 18732 } else { 18733 return SDValue(); 18734 } 18735 assert(Ops.size() == NumElts && "Unexpected vector size"); 18736 18737 // Insert the element 18738 if (Elt < Ops.size()) { 18739 // All the operands of BUILD_VECTOR must have the same type; 18740 // we enforce that here. 18741 EVT OpVT = Ops[0].getValueType(); 18742 Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal; 18743 } 18744 18745 // Return the new vector 18746 return DAG.getBuildVector(VT, DL, Ops); 18747 } 18748 18749 SDValue DAGCombiner::scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT, 18750 SDValue EltNo, 18751 LoadSDNode *OriginalLoad) { 18752 assert(OriginalLoad->isSimple()); 18753 18754 EVT ResultVT = EVE->getValueType(0); 18755 EVT VecEltVT = InVecVT.getVectorElementType(); 18756 18757 // If the vector element type is not a multiple of a byte then we are unable 18758 // to correctly compute an address to load only the extracted element as a 18759 // scalar. 18760 if (!VecEltVT.isByteSized()) 18761 return SDValue(); 18762 18763 ISD::LoadExtType ExtTy = 18764 ResultVT.bitsGT(VecEltVT) ? ISD::NON_EXTLOAD : ISD::EXTLOAD; 18765 if (!TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT) || 18766 !TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT)) 18767 return SDValue(); 18768 18769 Align Alignment = OriginalLoad->getAlign(); 18770 MachinePointerInfo MPI; 18771 SDLoc DL(EVE); 18772 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) { 18773 int Elt = ConstEltNo->getZExtValue(); 18774 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8; 18775 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff); 18776 Alignment = commonAlignment(Alignment, PtrOff); 18777 } else { 18778 // Discard the pointer info except the address space because the memory 18779 // operand can't represent this new access since the offset is variable. 18780 MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace()); 18781 Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8); 18782 } 18783 18784 bool IsFast = false; 18785 if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT, 18786 OriginalLoad->getAddressSpace(), Alignment, 18787 OriginalLoad->getMemOperand()->getFlags(), 18788 &IsFast) || 18789 !IsFast) 18790 return SDValue(); 18791 18792 SDValue NewPtr = TLI.getVectorElementPointer(DAG, OriginalLoad->getBasePtr(), 18793 InVecVT, EltNo); 18794 18795 // The replacement we need to do here is a little tricky: we need to 18796 // replace an extractelement of a load with a load. 18797 // Use ReplaceAllUsesOfValuesWith to do the replacement. 18798 // Note that this replacement assumes that the extractvalue is the only 18799 // use of the load; that's okay because we don't want to perform this 18800 // transformation in other cases anyway. 18801 SDValue Load; 18802 SDValue Chain; 18803 if (ResultVT.bitsGT(VecEltVT)) { 18804 // If the result type of vextract is wider than the load, then issue an 18805 // extending load instead. 18806 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT, 18807 VecEltVT) 18808 ? ISD::ZEXTLOAD 18809 : ISD::EXTLOAD; 18810 Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT, 18811 OriginalLoad->getChain(), NewPtr, MPI, VecEltVT, 18812 Alignment, OriginalLoad->getMemOperand()->getFlags(), 18813 OriginalLoad->getAAInfo()); 18814 Chain = Load.getValue(1); 18815 } else { 18816 Load = DAG.getLoad( 18817 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, Alignment, 18818 OriginalLoad->getMemOperand()->getFlags(), OriginalLoad->getAAInfo()); 18819 Chain = Load.getValue(1); 18820 if (ResultVT.bitsLT(VecEltVT)) 18821 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load); 18822 else 18823 Load = DAG.getBitcast(ResultVT, Load); 18824 } 18825 WorklistRemover DeadNodes(*this); 18826 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) }; 18827 SDValue To[] = { Load, Chain }; 18828 DAG.ReplaceAllUsesOfValuesWith(From, To, 2); 18829 // Make sure to revisit this node to clean it up; it will usually be dead. 18830 AddToWorklist(EVE); 18831 // Since we're explicitly calling ReplaceAllUses, add the new node to the 18832 // worklist explicitly as well. 18833 AddToWorklistWithUsers(Load.getNode()); 18834 ++OpsNarrowed; 18835 return SDValue(EVE, 0); 18836 } 18837 18838 /// Transform a vector binary operation into a scalar binary operation by moving 18839 /// the math/logic after an extract element of a vector. 18840 static SDValue scalarizeExtractedBinop(SDNode *ExtElt, SelectionDAG &DAG, 18841 bool LegalOperations) { 18842 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 18843 SDValue Vec = ExtElt->getOperand(0); 18844 SDValue Index = ExtElt->getOperand(1); 18845 auto *IndexC = dyn_cast<ConstantSDNode>(Index); 18846 if (!IndexC || !TLI.isBinOp(Vec.getOpcode()) || !Vec.hasOneUse() || 18847 Vec.getNode()->getNumValues() != 1) 18848 return SDValue(); 18849 18850 // Targets may want to avoid this to prevent an expensive register transfer. 18851 if (!TLI.shouldScalarizeBinop(Vec)) 18852 return SDValue(); 18853 18854 // Extracting an element of a vector constant is constant-folded, so this 18855 // transform is just replacing a vector op with a scalar op while moving the 18856 // extract. 18857 SDValue Op0 = Vec.getOperand(0); 18858 SDValue Op1 = Vec.getOperand(1); 18859 if (isAnyConstantBuildVector(Op0, true) || 18860 isAnyConstantBuildVector(Op1, true)) { 18861 // extractelt (binop X, C), IndexC --> binop (extractelt X, IndexC), C' 18862 // extractelt (binop C, X), IndexC --> binop C', (extractelt X, IndexC) 18863 SDLoc DL(ExtElt); 18864 EVT VT = ExtElt->getValueType(0); 18865 SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Index); 18866 SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op1, Index); 18867 return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1); 18868 } 18869 18870 return SDValue(); 18871 } 18872 18873 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) { 18874 SDValue VecOp = N->getOperand(0); 18875 SDValue Index = N->getOperand(1); 18876 EVT ScalarVT = N->getValueType(0); 18877 EVT VecVT = VecOp.getValueType(); 18878 if (VecOp.isUndef()) 18879 return DAG.getUNDEF(ScalarVT); 18880 18881 // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val 18882 // 18883 // This only really matters if the index is non-constant since other combines 18884 // on the constant elements already work. 18885 SDLoc DL(N); 18886 if (VecOp.getOpcode() == ISD::INSERT_VECTOR_ELT && 18887 Index == VecOp.getOperand(2)) { 18888 SDValue Elt = VecOp.getOperand(1); 18889 return VecVT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, DL, ScalarVT) : Elt; 18890 } 18891 18892 // (vextract (scalar_to_vector val, 0) -> val 18893 if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR) { 18894 // Only 0'th element of SCALAR_TO_VECTOR is defined. 18895 if (DAG.isKnownNeverZero(Index)) 18896 return DAG.getUNDEF(ScalarVT); 18897 18898 // Check if the result type doesn't match the inserted element type. A 18899 // SCALAR_TO_VECTOR may truncate the inserted element and the 18900 // EXTRACT_VECTOR_ELT may widen the extracted vector. 18901 SDValue InOp = VecOp.getOperand(0); 18902 if (InOp.getValueType() != ScalarVT) { 18903 assert(InOp.getValueType().isInteger() && ScalarVT.isInteger()); 18904 return DAG.getSExtOrTrunc(InOp, DL, ScalarVT); 18905 } 18906 return InOp; 18907 } 18908 18909 // extract_vector_elt of out-of-bounds element -> UNDEF 18910 auto *IndexC = dyn_cast<ConstantSDNode>(Index); 18911 if (IndexC && VecVT.isFixedLengthVector() && 18912 IndexC->getAPIntValue().uge(VecVT.getVectorNumElements())) 18913 return DAG.getUNDEF(ScalarVT); 18914 18915 // extract_vector_elt (build_vector x, y), 1 -> y 18916 if (((IndexC && VecOp.getOpcode() == ISD::BUILD_VECTOR) || 18917 VecOp.getOpcode() == ISD::SPLAT_VECTOR) && 18918 TLI.isTypeLegal(VecVT) && 18919 (VecOp.hasOneUse() || TLI.aggressivelyPreferBuildVectorSources(VecVT))) { 18920 assert((VecOp.getOpcode() != ISD::BUILD_VECTOR || 18921 VecVT.isFixedLengthVector()) && 18922 "BUILD_VECTOR used for scalable vectors"); 18923 unsigned IndexVal = 18924 VecOp.getOpcode() == ISD::BUILD_VECTOR ? IndexC->getZExtValue() : 0; 18925 SDValue Elt = VecOp.getOperand(IndexVal); 18926 EVT InEltVT = Elt.getValueType(); 18927 18928 // Sometimes build_vector's scalar input types do not match result type. 18929 if (ScalarVT == InEltVT) 18930 return Elt; 18931 18932 // TODO: It may be useful to truncate if free if the build_vector implicitly 18933 // converts. 18934 } 18935 18936 if (VecVT.isScalableVector()) 18937 return SDValue(); 18938 18939 // All the code from this point onwards assumes fixed width vectors, but it's 18940 // possible that some of the combinations could be made to work for scalable 18941 // vectors too. 18942 unsigned NumElts = VecVT.getVectorNumElements(); 18943 unsigned VecEltBitWidth = VecVT.getScalarSizeInBits(); 18944 18945 // TODO: These transforms should not require the 'hasOneUse' restriction, but 18946 // there are regressions on multiple targets without it. We can end up with a 18947 // mess of scalar and vector code if we reduce only part of the DAG to scalar. 18948 if (IndexC && VecOp.getOpcode() == ISD::BITCAST && VecVT.isInteger() && 18949 VecOp.hasOneUse()) { 18950 // The vector index of the LSBs of the source depend on the endian-ness. 18951 bool IsLE = DAG.getDataLayout().isLittleEndian(); 18952 unsigned ExtractIndex = IndexC->getZExtValue(); 18953 // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x) 18954 unsigned BCTruncElt = IsLE ? 0 : NumElts - 1; 18955 SDValue BCSrc = VecOp.getOperand(0); 18956 if (ExtractIndex == BCTruncElt && BCSrc.getValueType().isScalarInteger()) 18957 return DAG.getNode(ISD::TRUNCATE, DL, ScalarVT, BCSrc); 18958 18959 if (LegalTypes && BCSrc.getValueType().isInteger() && 18960 BCSrc.getOpcode() == ISD::SCALAR_TO_VECTOR) { 18961 // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt --> 18962 // trunc i64 X to i32 18963 SDValue X = BCSrc.getOperand(0); 18964 assert(X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() && 18965 "Extract element and scalar to vector can't change element type " 18966 "from FP to integer."); 18967 unsigned XBitWidth = X.getValueSizeInBits(); 18968 BCTruncElt = IsLE ? 0 : XBitWidth / VecEltBitWidth - 1; 18969 18970 // An extract element return value type can be wider than its vector 18971 // operand element type. In that case, the high bits are undefined, so 18972 // it's possible that we may need to extend rather than truncate. 18973 if (ExtractIndex == BCTruncElt && XBitWidth > VecEltBitWidth) { 18974 assert(XBitWidth % VecEltBitWidth == 0 && 18975 "Scalar bitwidth must be a multiple of vector element bitwidth"); 18976 return DAG.getAnyExtOrTrunc(X, DL, ScalarVT); 18977 } 18978 } 18979 } 18980 18981 if (SDValue BO = scalarizeExtractedBinop(N, DAG, LegalOperations)) 18982 return BO; 18983 18984 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT. 18985 // We only perform this optimization before the op legalization phase because 18986 // we may introduce new vector instructions which are not backed by TD 18987 // patterns. For example on AVX, extracting elements from a wide vector 18988 // without using extract_subvector. However, if we can find an underlying 18989 // scalar value, then we can always use that. 18990 if (IndexC && VecOp.getOpcode() == ISD::VECTOR_SHUFFLE) { 18991 auto *Shuf = cast<ShuffleVectorSDNode>(VecOp); 18992 // Find the new index to extract from. 18993 int OrigElt = Shuf->getMaskElt(IndexC->getZExtValue()); 18994 18995 // Extracting an undef index is undef. 18996 if (OrigElt == -1) 18997 return DAG.getUNDEF(ScalarVT); 18998 18999 // Select the right vector half to extract from. 19000 SDValue SVInVec; 19001 if (OrigElt < (int)NumElts) { 19002 SVInVec = VecOp.getOperand(0); 19003 } else { 19004 SVInVec = VecOp.getOperand(1); 19005 OrigElt -= NumElts; 19006 } 19007 19008 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) { 19009 SDValue InOp = SVInVec.getOperand(OrigElt); 19010 if (InOp.getValueType() != ScalarVT) { 19011 assert(InOp.getValueType().isInteger() && ScalarVT.isInteger()); 19012 InOp = DAG.getSExtOrTrunc(InOp, DL, ScalarVT); 19013 } 19014 19015 return InOp; 19016 } 19017 19018 // FIXME: We should handle recursing on other vector shuffles and 19019 // scalar_to_vector here as well. 19020 19021 if (!LegalOperations || 19022 // FIXME: Should really be just isOperationLegalOrCustom. 19023 TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecVT) || 19024 TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VecVT)) { 19025 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, SVInVec, 19026 DAG.getVectorIdxConstant(OrigElt, DL)); 19027 } 19028 } 19029 19030 // If only EXTRACT_VECTOR_ELT nodes use the source vector we can 19031 // simplify it based on the (valid) extraction indices. 19032 if (llvm::all_of(VecOp->uses(), [&](SDNode *Use) { 19033 return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT && 19034 Use->getOperand(0) == VecOp && 19035 isa<ConstantSDNode>(Use->getOperand(1)); 19036 })) { 19037 APInt DemandedElts = APInt::getZero(NumElts); 19038 for (SDNode *Use : VecOp->uses()) { 19039 auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1)); 19040 if (CstElt->getAPIntValue().ult(NumElts)) 19041 DemandedElts.setBit(CstElt->getZExtValue()); 19042 } 19043 if (SimplifyDemandedVectorElts(VecOp, DemandedElts, true)) { 19044 // We simplified the vector operand of this extract element. If this 19045 // extract is not dead, visit it again so it is folded properly. 19046 if (N->getOpcode() != ISD::DELETED_NODE) 19047 AddToWorklist(N); 19048 return SDValue(N, 0); 19049 } 19050 APInt DemandedBits = APInt::getAllOnes(VecEltBitWidth); 19051 if (SimplifyDemandedBits(VecOp, DemandedBits, DemandedElts, true)) { 19052 // We simplified the vector operand of this extract element. If this 19053 // extract is not dead, visit it again so it is folded properly. 19054 if (N->getOpcode() != ISD::DELETED_NODE) 19055 AddToWorklist(N); 19056 return SDValue(N, 0); 19057 } 19058 } 19059 19060 // Everything under here is trying to match an extract of a loaded value. 19061 // If the result of load has to be truncated, then it's not necessarily 19062 // profitable. 19063 bool BCNumEltsChanged = false; 19064 EVT ExtVT = VecVT.getVectorElementType(); 19065 EVT LVT = ExtVT; 19066 if (ScalarVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, ScalarVT)) 19067 return SDValue(); 19068 19069 if (VecOp.getOpcode() == ISD::BITCAST) { 19070 // Don't duplicate a load with other uses. 19071 if (!VecOp.hasOneUse()) 19072 return SDValue(); 19073 19074 EVT BCVT = VecOp.getOperand(0).getValueType(); 19075 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType())) 19076 return SDValue(); 19077 if (NumElts != BCVT.getVectorNumElements()) 19078 BCNumEltsChanged = true; 19079 VecOp = VecOp.getOperand(0); 19080 ExtVT = BCVT.getVectorElementType(); 19081 } 19082 19083 // extract (vector load $addr), i --> load $addr + i * size 19084 if (!LegalOperations && !IndexC && VecOp.hasOneUse() && 19085 ISD::isNormalLoad(VecOp.getNode()) && 19086 !Index->hasPredecessor(VecOp.getNode())) { 19087 auto *VecLoad = dyn_cast<LoadSDNode>(VecOp); 19088 if (VecLoad && VecLoad->isSimple()) 19089 return scalarizeExtractedVectorLoad(N, VecVT, Index, VecLoad); 19090 } 19091 19092 // Perform only after legalization to ensure build_vector / vector_shuffle 19093 // optimizations have already been done. 19094 if (!LegalOperations || !IndexC) 19095 return SDValue(); 19096 19097 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size) 19098 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size) 19099 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr) 19100 int Elt = IndexC->getZExtValue(); 19101 LoadSDNode *LN0 = nullptr; 19102 if (ISD::isNormalLoad(VecOp.getNode())) { 19103 LN0 = cast<LoadSDNode>(VecOp); 19104 } else if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR && 19105 VecOp.getOperand(0).getValueType() == ExtVT && 19106 ISD::isNormalLoad(VecOp.getOperand(0).getNode())) { 19107 // Don't duplicate a load with other uses. 19108 if (!VecOp.hasOneUse()) 19109 return SDValue(); 19110 19111 LN0 = cast<LoadSDNode>(VecOp.getOperand(0)); 19112 } 19113 if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(VecOp)) { 19114 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1) 19115 // => 19116 // (load $addr+1*size) 19117 19118 // Don't duplicate a load with other uses. 19119 if (!VecOp.hasOneUse()) 19120 return SDValue(); 19121 19122 // If the bit convert changed the number of elements, it is unsafe 19123 // to examine the mask. 19124 if (BCNumEltsChanged) 19125 return SDValue(); 19126 19127 // Select the input vector, guarding against out of range extract vector. 19128 int Idx = (Elt > (int)NumElts) ? -1 : Shuf->getMaskElt(Elt); 19129 VecOp = (Idx < (int)NumElts) ? VecOp.getOperand(0) : VecOp.getOperand(1); 19130 19131 if (VecOp.getOpcode() == ISD::BITCAST) { 19132 // Don't duplicate a load with other uses. 19133 if (!VecOp.hasOneUse()) 19134 return SDValue(); 19135 19136 VecOp = VecOp.getOperand(0); 19137 } 19138 if (ISD::isNormalLoad(VecOp.getNode())) { 19139 LN0 = cast<LoadSDNode>(VecOp); 19140 Elt = (Idx < (int)NumElts) ? Idx : Idx - (int)NumElts; 19141 Index = DAG.getConstant(Elt, DL, Index.getValueType()); 19142 } 19143 } else if (VecOp.getOpcode() == ISD::CONCAT_VECTORS && !BCNumEltsChanged && 19144 VecVT.getVectorElementType() == ScalarVT && 19145 (!LegalTypes || 19146 TLI.isTypeLegal( 19147 VecOp.getOperand(0).getValueType().getVectorElementType()))) { 19148 // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 0 19149 // -> extract_vector_elt a, 0 19150 // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 1 19151 // -> extract_vector_elt a, 1 19152 // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 2 19153 // -> extract_vector_elt b, 0 19154 // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 3 19155 // -> extract_vector_elt b, 1 19156 SDLoc SL(N); 19157 EVT ConcatVT = VecOp.getOperand(0).getValueType(); 19158 unsigned ConcatNumElts = ConcatVT.getVectorNumElements(); 19159 SDValue NewIdx = DAG.getConstant(Elt % ConcatNumElts, SL, 19160 Index.getValueType()); 19161 19162 SDValue ConcatOp = VecOp.getOperand(Elt / ConcatNumElts); 19163 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, 19164 ConcatVT.getVectorElementType(), 19165 ConcatOp, NewIdx); 19166 return DAG.getNode(ISD::BITCAST, SL, ScalarVT, Elt); 19167 } 19168 19169 // Make sure we found a non-volatile load and the extractelement is 19170 // the only use. 19171 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || !LN0->isSimple()) 19172 return SDValue(); 19173 19174 // If Idx was -1 above, Elt is going to be -1, so just return undef. 19175 if (Elt == -1) 19176 return DAG.getUNDEF(LVT); 19177 19178 return scalarizeExtractedVectorLoad(N, VecVT, Index, LN0); 19179 } 19180 19181 // Simplify (build_vec (ext )) to (bitcast (build_vec )) 19182 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) { 19183 // We perform this optimization post type-legalization because 19184 // the type-legalizer often scalarizes integer-promoted vectors. 19185 // Performing this optimization before may create bit-casts which 19186 // will be type-legalized to complex code sequences. 19187 // We perform this optimization only before the operation legalizer because we 19188 // may introduce illegal operations. 19189 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes) 19190 return SDValue(); 19191 19192 unsigned NumInScalars = N->getNumOperands(); 19193 SDLoc DL(N); 19194 EVT VT = N->getValueType(0); 19195 19196 // Check to see if this is a BUILD_VECTOR of a bunch of values 19197 // which come from any_extend or zero_extend nodes. If so, we can create 19198 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR 19199 // optimizations. We do not handle sign-extend because we can't fill the sign 19200 // using shuffles. 19201 EVT SourceType = MVT::Other; 19202 bool AllAnyExt = true; 19203 19204 for (unsigned i = 0; i != NumInScalars; ++i) { 19205 SDValue In = N->getOperand(i); 19206 // Ignore undef inputs. 19207 if (In.isUndef()) continue; 19208 19209 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND; 19210 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND; 19211 19212 // Abort if the element is not an extension. 19213 if (!ZeroExt && !AnyExt) { 19214 SourceType = MVT::Other; 19215 break; 19216 } 19217 19218 // The input is a ZeroExt or AnyExt. Check the original type. 19219 EVT InTy = In.getOperand(0).getValueType(); 19220 19221 // Check that all of the widened source types are the same. 19222 if (SourceType == MVT::Other) 19223 // First time. 19224 SourceType = InTy; 19225 else if (InTy != SourceType) { 19226 // Multiple income types. Abort. 19227 SourceType = MVT::Other; 19228 break; 19229 } 19230 19231 // Check if all of the extends are ANY_EXTENDs. 19232 AllAnyExt &= AnyExt; 19233 } 19234 19235 // In order to have valid types, all of the inputs must be extended from the 19236 // same source type and all of the inputs must be any or zero extend. 19237 // Scalar sizes must be a power of two. 19238 EVT OutScalarTy = VT.getScalarType(); 19239 bool ValidTypes = SourceType != MVT::Other && 19240 isPowerOf2_32(OutScalarTy.getSizeInBits()) && 19241 isPowerOf2_32(SourceType.getSizeInBits()); 19242 19243 // Create a new simpler BUILD_VECTOR sequence which other optimizations can 19244 // turn into a single shuffle instruction. 19245 if (!ValidTypes) 19246 return SDValue(); 19247 19248 // If we already have a splat buildvector, then don't fold it if it means 19249 // introducing zeros. 19250 if (!AllAnyExt && DAG.isSplatValue(SDValue(N, 0), /*AllowUndefs*/ true)) 19251 return SDValue(); 19252 19253 bool isLE = DAG.getDataLayout().isLittleEndian(); 19254 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits(); 19255 assert(ElemRatio > 1 && "Invalid element size ratio"); 19256 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType): 19257 DAG.getConstant(0, DL, SourceType); 19258 19259 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements(); 19260 SmallVector<SDValue, 8> Ops(NewBVElems, Filler); 19261 19262 // Populate the new build_vector 19263 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 19264 SDValue Cast = N->getOperand(i); 19265 assert((Cast.getOpcode() == ISD::ANY_EXTEND || 19266 Cast.getOpcode() == ISD::ZERO_EXTEND || 19267 Cast.isUndef()) && "Invalid cast opcode"); 19268 SDValue In; 19269 if (Cast.isUndef()) 19270 In = DAG.getUNDEF(SourceType); 19271 else 19272 In = Cast->getOperand(0); 19273 unsigned Index = isLE ? (i * ElemRatio) : 19274 (i * ElemRatio + (ElemRatio - 1)); 19275 19276 assert(Index < Ops.size() && "Invalid index"); 19277 Ops[Index] = In; 19278 } 19279 19280 // The type of the new BUILD_VECTOR node. 19281 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems); 19282 assert(VecVT.getSizeInBits() == VT.getSizeInBits() && 19283 "Invalid vector size"); 19284 // Check if the new vector type is legal. 19285 if (!isTypeLegal(VecVT) || 19286 (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) && 19287 TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))) 19288 return SDValue(); 19289 19290 // Make the new BUILD_VECTOR. 19291 SDValue BV = DAG.getBuildVector(VecVT, DL, Ops); 19292 19293 // The new BUILD_VECTOR node has the potential to be further optimized. 19294 AddToWorklist(BV.getNode()); 19295 // Bitcast to the desired type. 19296 return DAG.getBitcast(VT, BV); 19297 } 19298 19299 // Simplify (build_vec (trunc $1) 19300 // (trunc (srl $1 half-width)) 19301 // (trunc (srl $1 (2 * half-width))) …) 19302 // to (bitcast $1) 19303 SDValue DAGCombiner::reduceBuildVecTruncToBitCast(SDNode *N) { 19304 assert(N->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector"); 19305 19306 // Only for little endian 19307 if (!DAG.getDataLayout().isLittleEndian()) 19308 return SDValue(); 19309 19310 SDLoc DL(N); 19311 EVT VT = N->getValueType(0); 19312 EVT OutScalarTy = VT.getScalarType(); 19313 uint64_t ScalarTypeBitsize = OutScalarTy.getSizeInBits(); 19314 19315 // Only for power of two types to be sure that bitcast works well 19316 if (!isPowerOf2_64(ScalarTypeBitsize)) 19317 return SDValue(); 19318 19319 unsigned NumInScalars = N->getNumOperands(); 19320 19321 // Look through bitcasts 19322 auto PeekThroughBitcast = [](SDValue Op) { 19323 if (Op.getOpcode() == ISD::BITCAST) 19324 return Op.getOperand(0); 19325 return Op; 19326 }; 19327 19328 // The source value where all the parts are extracted. 19329 SDValue Src; 19330 for (unsigned i = 0; i != NumInScalars; ++i) { 19331 SDValue In = PeekThroughBitcast(N->getOperand(i)); 19332 // Ignore undef inputs. 19333 if (In.isUndef()) continue; 19334 19335 if (In.getOpcode() != ISD::TRUNCATE) 19336 return SDValue(); 19337 19338 In = PeekThroughBitcast(In.getOperand(0)); 19339 19340 if (In.getOpcode() != ISD::SRL) { 19341 // For now only build_vec without shuffling, handle shifts here in the 19342 // future. 19343 if (i != 0) 19344 return SDValue(); 19345 19346 Src = In; 19347 } else { 19348 // In is SRL 19349 SDValue part = PeekThroughBitcast(In.getOperand(0)); 19350 19351 if (!Src) { 19352 Src = part; 19353 } else if (Src != part) { 19354 // Vector parts do not stem from the same variable 19355 return SDValue(); 19356 } 19357 19358 SDValue ShiftAmtVal = In.getOperand(1); 19359 if (!isa<ConstantSDNode>(ShiftAmtVal)) 19360 return SDValue(); 19361 19362 uint64_t ShiftAmt = In.getNode()->getConstantOperandVal(1); 19363 19364 // The extracted value is not extracted at the right position 19365 if (ShiftAmt != i * ScalarTypeBitsize) 19366 return SDValue(); 19367 } 19368 } 19369 19370 // Only cast if the size is the same 19371 if (Src.getValueType().getSizeInBits() != VT.getSizeInBits()) 19372 return SDValue(); 19373 19374 return DAG.getBitcast(VT, Src); 19375 } 19376 19377 SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N, 19378 ArrayRef<int> VectorMask, 19379 SDValue VecIn1, SDValue VecIn2, 19380 unsigned LeftIdx, bool DidSplitVec) { 19381 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL); 19382 19383 EVT VT = N->getValueType(0); 19384 EVT InVT1 = VecIn1.getValueType(); 19385 EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1; 19386 19387 unsigned NumElems = VT.getVectorNumElements(); 19388 unsigned ShuffleNumElems = NumElems; 19389 19390 // If we artificially split a vector in two already, then the offsets in the 19391 // operands will all be based off of VecIn1, even those in VecIn2. 19392 unsigned Vec2Offset = DidSplitVec ? 0 : InVT1.getVectorNumElements(); 19393 19394 uint64_t VTSize = VT.getFixedSizeInBits(); 19395 uint64_t InVT1Size = InVT1.getFixedSizeInBits(); 19396 uint64_t InVT2Size = InVT2.getFixedSizeInBits(); 19397 19398 assert(InVT2Size <= InVT1Size && 19399 "Inputs must be sorted to be in non-increasing vector size order."); 19400 19401 // We can't generate a shuffle node with mismatched input and output types. 19402 // Try to make the types match the type of the output. 19403 if (InVT1 != VT || InVT2 != VT) { 19404 if ((VTSize % InVT1Size == 0) && InVT1 == InVT2) { 19405 // If the output vector length is a multiple of both input lengths, 19406 // we can concatenate them and pad the rest with undefs. 19407 unsigned NumConcats = VTSize / InVT1Size; 19408 assert(NumConcats >= 2 && "Concat needs at least two inputs!"); 19409 SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1)); 19410 ConcatOps[0] = VecIn1; 19411 ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1); 19412 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 19413 VecIn2 = SDValue(); 19414 } else if (InVT1Size == VTSize * 2) { 19415 if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems)) 19416 return SDValue(); 19417 19418 if (!VecIn2.getNode()) { 19419 // If we only have one input vector, and it's twice the size of the 19420 // output, split it in two. 19421 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, 19422 DAG.getVectorIdxConstant(NumElems, DL)); 19423 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx); 19424 // Since we now have shorter input vectors, adjust the offset of the 19425 // second vector's start. 19426 Vec2Offset = NumElems; 19427 } else { 19428 assert(InVT2Size <= InVT1Size && 19429 "Second input is not going to be larger than the first one."); 19430 19431 // VecIn1 is wider than the output, and we have another, possibly 19432 // smaller input. Pad the smaller input with undefs, shuffle at the 19433 // input vector width, and extract the output. 19434 // The shuffle type is different than VT, so check legality again. 19435 if (LegalOperations && 19436 !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1)) 19437 return SDValue(); 19438 19439 // Legalizing INSERT_SUBVECTOR is tricky - you basically have to 19440 // lower it back into a BUILD_VECTOR. So if the inserted type is 19441 // illegal, don't even try. 19442 if (InVT1 != InVT2) { 19443 if (!TLI.isTypeLegal(InVT2)) 19444 return SDValue(); 19445 VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1, 19446 DAG.getUNDEF(InVT1), VecIn2, ZeroIdx); 19447 } 19448 ShuffleNumElems = NumElems * 2; 19449 } 19450 } else if (InVT2Size * 2 == VTSize && InVT1Size == VTSize) { 19451 SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2)); 19452 ConcatOps[0] = VecIn2; 19453 VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 19454 } else { 19455 // TODO: Support cases where the length mismatch isn't exactly by a 19456 // factor of 2. 19457 // TODO: Move this check upwards, so that if we have bad type 19458 // mismatches, we don't create any DAG nodes. 19459 return SDValue(); 19460 } 19461 } 19462 19463 // Initialize mask to undef. 19464 SmallVector<int, 8> Mask(ShuffleNumElems, -1); 19465 19466 // Only need to run up to the number of elements actually used, not the 19467 // total number of elements in the shuffle - if we are shuffling a wider 19468 // vector, the high lanes should be set to undef. 19469 for (unsigned i = 0; i != NumElems; ++i) { 19470 if (VectorMask[i] <= 0) 19471 continue; 19472 19473 unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1); 19474 if (VectorMask[i] == (int)LeftIdx) { 19475 Mask[i] = ExtIndex; 19476 } else if (VectorMask[i] == (int)LeftIdx + 1) { 19477 Mask[i] = Vec2Offset + ExtIndex; 19478 } 19479 } 19480 19481 // The type the input vectors may have changed above. 19482 InVT1 = VecIn1.getValueType(); 19483 19484 // If we already have a VecIn2, it should have the same type as VecIn1. 19485 // If we don't, get an undef/zero vector of the appropriate type. 19486 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1); 19487 assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type."); 19488 19489 SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask); 19490 if (ShuffleNumElems > NumElems) 19491 Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx); 19492 19493 return Shuffle; 19494 } 19495 19496 static SDValue reduceBuildVecToShuffleWithZero(SDNode *BV, SelectionDAG &DAG) { 19497 assert(BV->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector"); 19498 19499 // First, determine where the build vector is not undef. 19500 // TODO: We could extend this to handle zero elements as well as undefs. 19501 int NumBVOps = BV->getNumOperands(); 19502 int ZextElt = -1; 19503 for (int i = 0; i != NumBVOps; ++i) { 19504 SDValue Op = BV->getOperand(i); 19505 if (Op.isUndef()) 19506 continue; 19507 if (ZextElt == -1) 19508 ZextElt = i; 19509 else 19510 return SDValue(); 19511 } 19512 // Bail out if there's no non-undef element. 19513 if (ZextElt == -1) 19514 return SDValue(); 19515 19516 // The build vector contains some number of undef elements and exactly 19517 // one other element. That other element must be a zero-extended scalar 19518 // extracted from a vector at a constant index to turn this into a shuffle. 19519 // Also, require that the build vector does not implicitly truncate/extend 19520 // its elements. 19521 // TODO: This could be enhanced to allow ANY_EXTEND as well as ZERO_EXTEND. 19522 EVT VT = BV->getValueType(0); 19523 SDValue Zext = BV->getOperand(ZextElt); 19524 if (Zext.getOpcode() != ISD::ZERO_EXTEND || !Zext.hasOneUse() || 19525 Zext.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT || 19526 !isa<ConstantSDNode>(Zext.getOperand(0).getOperand(1)) || 19527 Zext.getValueSizeInBits() != VT.getScalarSizeInBits()) 19528 return SDValue(); 19529 19530 // The zero-extend must be a multiple of the source size, and we must be 19531 // building a vector of the same size as the source of the extract element. 19532 SDValue Extract = Zext.getOperand(0); 19533 unsigned DestSize = Zext.getValueSizeInBits(); 19534 unsigned SrcSize = Extract.getValueSizeInBits(); 19535 if (DestSize % SrcSize != 0 || 19536 Extract.getOperand(0).getValueSizeInBits() != VT.getSizeInBits()) 19537 return SDValue(); 19538 19539 // Create a shuffle mask that will combine the extracted element with zeros 19540 // and undefs. 19541 int ZextRatio = DestSize / SrcSize; 19542 int NumMaskElts = NumBVOps * ZextRatio; 19543 SmallVector<int, 32> ShufMask(NumMaskElts, -1); 19544 for (int i = 0; i != NumMaskElts; ++i) { 19545 if (i / ZextRatio == ZextElt) { 19546 // The low bits of the (potentially translated) extracted element map to 19547 // the source vector. The high bits map to zero. We will use a zero vector 19548 // as the 2nd source operand of the shuffle, so use the 1st element of 19549 // that vector (mask value is number-of-elements) for the high bits. 19550 if (i % ZextRatio == 0) 19551 ShufMask[i] = Extract.getConstantOperandVal(1); 19552 else 19553 ShufMask[i] = NumMaskElts; 19554 } 19555 19556 // Undef elements of the build vector remain undef because we initialize 19557 // the shuffle mask with -1. 19558 } 19559 19560 // buildvec undef, ..., (zext (extractelt V, IndexC)), undef... --> 19561 // bitcast (shuffle V, ZeroVec, VectorMask) 19562 SDLoc DL(BV); 19563 EVT VecVT = Extract.getOperand(0).getValueType(); 19564 SDValue ZeroVec = DAG.getConstant(0, DL, VecVT); 19565 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 19566 SDValue Shuf = TLI.buildLegalVectorShuffle(VecVT, DL, Extract.getOperand(0), 19567 ZeroVec, ShufMask, DAG); 19568 if (!Shuf) 19569 return SDValue(); 19570 return DAG.getBitcast(VT, Shuf); 19571 } 19572 19573 // FIXME: promote to STLExtras. 19574 template <typename R, typename T> 19575 static auto getFirstIndexOf(R &&Range, const T &Val) { 19576 auto I = find(Range, Val); 19577 if (I == Range.end()) 19578 return static_cast<decltype(std::distance(Range.begin(), I))>(-1); 19579 return std::distance(Range.begin(), I); 19580 } 19581 19582 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT 19583 // operations. If the types of the vectors we're extracting from allow it, 19584 // turn this into a vector_shuffle node. 19585 SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) { 19586 SDLoc DL(N); 19587 EVT VT = N->getValueType(0); 19588 19589 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes. 19590 if (!isTypeLegal(VT)) 19591 return SDValue(); 19592 19593 if (SDValue V = reduceBuildVecToShuffleWithZero(N, DAG)) 19594 return V; 19595 19596 // May only combine to shuffle after legalize if shuffle is legal. 19597 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT)) 19598 return SDValue(); 19599 19600 bool UsesZeroVector = false; 19601 unsigned NumElems = N->getNumOperands(); 19602 19603 // Record, for each element of the newly built vector, which input vector 19604 // that element comes from. -1 stands for undef, 0 for the zero vector, 19605 // and positive values for the input vectors. 19606 // VectorMask maps each element to its vector number, and VecIn maps vector 19607 // numbers to their initial SDValues. 19608 19609 SmallVector<int, 8> VectorMask(NumElems, -1); 19610 SmallVector<SDValue, 8> VecIn; 19611 VecIn.push_back(SDValue()); 19612 19613 for (unsigned i = 0; i != NumElems; ++i) { 19614 SDValue Op = N->getOperand(i); 19615 19616 if (Op.isUndef()) 19617 continue; 19618 19619 // See if we can use a blend with a zero vector. 19620 // TODO: Should we generalize this to a blend with an arbitrary constant 19621 // vector? 19622 if (isNullConstant(Op) || isNullFPConstant(Op)) { 19623 UsesZeroVector = true; 19624 VectorMask[i] = 0; 19625 continue; 19626 } 19627 19628 // Not an undef or zero. If the input is something other than an 19629 // EXTRACT_VECTOR_ELT with an in-range constant index, bail out. 19630 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 19631 !isa<ConstantSDNode>(Op.getOperand(1))) 19632 return SDValue(); 19633 SDValue ExtractedFromVec = Op.getOperand(0); 19634 19635 if (ExtractedFromVec.getValueType().isScalableVector()) 19636 return SDValue(); 19637 19638 const APInt &ExtractIdx = Op.getConstantOperandAPInt(1); 19639 if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements())) 19640 return SDValue(); 19641 19642 // All inputs must have the same element type as the output. 19643 if (VT.getVectorElementType() != 19644 ExtractedFromVec.getValueType().getVectorElementType()) 19645 return SDValue(); 19646 19647 // Have we seen this input vector before? 19648 // The vectors are expected to be tiny (usually 1 or 2 elements), so using 19649 // a map back from SDValues to numbers isn't worth it. 19650 int Idx = getFirstIndexOf(VecIn, ExtractedFromVec); 19651 if (Idx == -1) { // A new source vector? 19652 Idx = VecIn.size(); 19653 VecIn.push_back(ExtractedFromVec); 19654 } 19655 19656 VectorMask[i] = Idx; 19657 } 19658 19659 // If we didn't find at least one input vector, bail out. 19660 if (VecIn.size() < 2) 19661 return SDValue(); 19662 19663 // If all the Operands of BUILD_VECTOR extract from same 19664 // vector, then split the vector efficiently based on the maximum 19665 // vector access index and adjust the VectorMask and 19666 // VecIn accordingly. 19667 bool DidSplitVec = false; 19668 if (VecIn.size() == 2) { 19669 unsigned MaxIndex = 0; 19670 unsigned NearestPow2 = 0; 19671 SDValue Vec = VecIn.back(); 19672 EVT InVT = Vec.getValueType(); 19673 SmallVector<unsigned, 8> IndexVec(NumElems, 0); 19674 19675 for (unsigned i = 0; i < NumElems; i++) { 19676 if (VectorMask[i] <= 0) 19677 continue; 19678 unsigned Index = N->getOperand(i).getConstantOperandVal(1); 19679 IndexVec[i] = Index; 19680 MaxIndex = std::max(MaxIndex, Index); 19681 } 19682 19683 NearestPow2 = PowerOf2Ceil(MaxIndex); 19684 if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 && 19685 NumElems * 2 < NearestPow2) { 19686 unsigned SplitSize = NearestPow2 / 2; 19687 EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), 19688 InVT.getVectorElementType(), SplitSize); 19689 if (TLI.isTypeLegal(SplitVT) && 19690 SplitSize + SplitVT.getVectorNumElements() <= 19691 InVT.getVectorNumElements()) { 19692 SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 19693 DAG.getVectorIdxConstant(SplitSize, DL)); 19694 SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec, 19695 DAG.getVectorIdxConstant(0, DL)); 19696 VecIn.pop_back(); 19697 VecIn.push_back(VecIn1); 19698 VecIn.push_back(VecIn2); 19699 DidSplitVec = true; 19700 19701 for (unsigned i = 0; i < NumElems; i++) { 19702 if (VectorMask[i] <= 0) 19703 continue; 19704 VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2; 19705 } 19706 } 19707 } 19708 } 19709 19710 // Sort input vectors by decreasing vector element count, 19711 // while preserving the relative order of equally-sized vectors. 19712 // Note that we keep the first "implicit zero vector as-is. 19713 SmallVector<SDValue, 8> SortedVecIn(VecIn); 19714 llvm::stable_sort(MutableArrayRef<SDValue>(SortedVecIn).drop_front(), 19715 [](const SDValue &a, const SDValue &b) { 19716 return a.getValueType().getVectorNumElements() > 19717 b.getValueType().getVectorNumElements(); 19718 }); 19719 19720 // We now also need to rebuild the VectorMask, because it referenced element 19721 // order in VecIn, and we just sorted them. 19722 for (int &SourceVectorIndex : VectorMask) { 19723 if (SourceVectorIndex <= 0) 19724 continue; 19725 unsigned Idx = getFirstIndexOf(SortedVecIn, VecIn[SourceVectorIndex]); 19726 assert(Idx > 0 && Idx < SortedVecIn.size() && 19727 VecIn[SourceVectorIndex] == SortedVecIn[Idx] && "Remapping failure"); 19728 SourceVectorIndex = Idx; 19729 } 19730 19731 VecIn = std::move(SortedVecIn); 19732 19733 // TODO: Should this fire if some of the input vectors has illegal type (like 19734 // it does now), or should we let legalization run its course first? 19735 19736 // Shuffle phase: 19737 // Take pairs of vectors, and shuffle them so that the result has elements 19738 // from these vectors in the correct places. 19739 // For example, given: 19740 // t10: i32 = extract_vector_elt t1, Constant:i64<0> 19741 // t11: i32 = extract_vector_elt t2, Constant:i64<0> 19742 // t12: i32 = extract_vector_elt t3, Constant:i64<0> 19743 // t13: i32 = extract_vector_elt t1, Constant:i64<1> 19744 // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13 19745 // We will generate: 19746 // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2 19747 // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef 19748 SmallVector<SDValue, 4> Shuffles; 19749 for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) { 19750 unsigned LeftIdx = 2 * In + 1; 19751 SDValue VecLeft = VecIn[LeftIdx]; 19752 SDValue VecRight = 19753 (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue(); 19754 19755 if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft, 19756 VecRight, LeftIdx, DidSplitVec)) 19757 Shuffles.push_back(Shuffle); 19758 else 19759 return SDValue(); 19760 } 19761 19762 // If we need the zero vector as an "ingredient" in the blend tree, add it 19763 // to the list of shuffles. 19764 if (UsesZeroVector) 19765 Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT) 19766 : DAG.getConstantFP(0.0, DL, VT)); 19767 19768 // If we only have one shuffle, we're done. 19769 if (Shuffles.size() == 1) 19770 return Shuffles[0]; 19771 19772 // Update the vector mask to point to the post-shuffle vectors. 19773 for (int &Vec : VectorMask) 19774 if (Vec == 0) 19775 Vec = Shuffles.size() - 1; 19776 else 19777 Vec = (Vec - 1) / 2; 19778 19779 // More than one shuffle. Generate a binary tree of blends, e.g. if from 19780 // the previous step we got the set of shuffles t10, t11, t12, t13, we will 19781 // generate: 19782 // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2 19783 // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4 19784 // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6 19785 // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8 19786 // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11 19787 // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13 19788 // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21 19789 19790 // Make sure the initial size of the shuffle list is even. 19791 if (Shuffles.size() % 2) 19792 Shuffles.push_back(DAG.getUNDEF(VT)); 19793 19794 for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) { 19795 if (CurSize % 2) { 19796 Shuffles[CurSize] = DAG.getUNDEF(VT); 19797 CurSize++; 19798 } 19799 for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) { 19800 int Left = 2 * In; 19801 int Right = 2 * In + 1; 19802 SmallVector<int, 8> Mask(NumElems, -1); 19803 for (unsigned i = 0; i != NumElems; ++i) { 19804 if (VectorMask[i] == Left) { 19805 Mask[i] = i; 19806 VectorMask[i] = In; 19807 } else if (VectorMask[i] == Right) { 19808 Mask[i] = i + NumElems; 19809 VectorMask[i] = In; 19810 } 19811 } 19812 19813 Shuffles[In] = 19814 DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask); 19815 } 19816 } 19817 return Shuffles[0]; 19818 } 19819 19820 // Try to turn a build vector of zero extends of extract vector elts into a 19821 // a vector zero extend and possibly an extract subvector. 19822 // TODO: Support sign extend? 19823 // TODO: Allow undef elements? 19824 SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) { 19825 if (LegalOperations) 19826 return SDValue(); 19827 19828 EVT VT = N->getValueType(0); 19829 19830 bool FoundZeroExtend = false; 19831 SDValue Op0 = N->getOperand(0); 19832 auto checkElem = [&](SDValue Op) -> int64_t { 19833 unsigned Opc = Op.getOpcode(); 19834 FoundZeroExtend |= (Opc == ISD::ZERO_EXTEND); 19835 if ((Opc == ISD::ZERO_EXTEND || Opc == ISD::ANY_EXTEND) && 19836 Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT && 19837 Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0)) 19838 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1))) 19839 return C->getZExtValue(); 19840 return -1; 19841 }; 19842 19843 // Make sure the first element matches 19844 // (zext (extract_vector_elt X, C)) 19845 // Offset must be a constant multiple of the 19846 // known-minimum vector length of the result type. 19847 int64_t Offset = checkElem(Op0); 19848 if (Offset < 0 || (Offset % VT.getVectorNumElements()) != 0) 19849 return SDValue(); 19850 19851 unsigned NumElems = N->getNumOperands(); 19852 SDValue In = Op0.getOperand(0).getOperand(0); 19853 EVT InSVT = In.getValueType().getScalarType(); 19854 EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems); 19855 19856 // Don't create an illegal input type after type legalization. 19857 if (LegalTypes && !TLI.isTypeLegal(InVT)) 19858 return SDValue(); 19859 19860 // Ensure all the elements come from the same vector and are adjacent. 19861 for (unsigned i = 1; i != NumElems; ++i) { 19862 if ((Offset + i) != checkElem(N->getOperand(i))) 19863 return SDValue(); 19864 } 19865 19866 SDLoc DL(N); 19867 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In, 19868 Op0.getOperand(0).getOperand(1)); 19869 return DAG.getNode(FoundZeroExtend ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, DL, 19870 VT, In); 19871 } 19872 19873 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) { 19874 EVT VT = N->getValueType(0); 19875 19876 // A vector built entirely of undefs is undef. 19877 if (ISD::allOperandsUndef(N)) 19878 return DAG.getUNDEF(VT); 19879 19880 // If this is a splat of a bitcast from another vector, change to a 19881 // concat_vector. 19882 // For example: 19883 // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) -> 19884 // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X)))) 19885 // 19886 // If X is a build_vector itself, the concat can become a larger build_vector. 19887 // TODO: Maybe this is useful for non-splat too? 19888 if (!LegalOperations) { 19889 if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) { 19890 Splat = peekThroughBitcasts(Splat); 19891 EVT SrcVT = Splat.getValueType(); 19892 if (SrcVT.isVector()) { 19893 unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements(); 19894 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), 19895 SrcVT.getVectorElementType(), NumElts); 19896 if (!LegalTypes || TLI.isTypeLegal(NewVT)) { 19897 SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat); 19898 SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), 19899 NewVT, Ops); 19900 return DAG.getBitcast(VT, Concat); 19901 } 19902 } 19903 } 19904 } 19905 19906 // Check if we can express BUILD VECTOR via subvector extract. 19907 if (!LegalTypes && (N->getNumOperands() > 1)) { 19908 SDValue Op0 = N->getOperand(0); 19909 auto checkElem = [&](SDValue Op) -> uint64_t { 19910 if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) && 19911 (Op0.getOperand(0) == Op.getOperand(0))) 19912 if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1))) 19913 return CNode->getZExtValue(); 19914 return -1; 19915 }; 19916 19917 int Offset = checkElem(Op0); 19918 for (unsigned i = 0; i < N->getNumOperands(); ++i) { 19919 if (Offset + i != checkElem(N->getOperand(i))) { 19920 Offset = -1; 19921 break; 19922 } 19923 } 19924 19925 if ((Offset == 0) && 19926 (Op0.getOperand(0).getValueType() == N->getValueType(0))) 19927 return Op0.getOperand(0); 19928 if ((Offset != -1) && 19929 ((Offset % N->getValueType(0).getVectorNumElements()) == 19930 0)) // IDX must be multiple of output size. 19931 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0), 19932 Op0.getOperand(0), Op0.getOperand(1)); 19933 } 19934 19935 if (SDValue V = convertBuildVecZextToZext(N)) 19936 return V; 19937 19938 if (SDValue V = reduceBuildVecExtToExtBuildVec(N)) 19939 return V; 19940 19941 if (SDValue V = reduceBuildVecTruncToBitCast(N)) 19942 return V; 19943 19944 if (SDValue V = reduceBuildVecToShuffle(N)) 19945 return V; 19946 19947 // A splat of a single element is a SPLAT_VECTOR if supported on the target. 19948 // Do this late as some of the above may replace the splat. 19949 if (TLI.getOperationAction(ISD::SPLAT_VECTOR, VT) != TargetLowering::Expand) 19950 if (SDValue V = cast<BuildVectorSDNode>(N)->getSplatValue()) { 19951 assert(!V.isUndef() && "Splat of undef should have been handled earlier"); 19952 return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), VT, V); 19953 } 19954 19955 return SDValue(); 19956 } 19957 19958 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) { 19959 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 19960 EVT OpVT = N->getOperand(0).getValueType(); 19961 19962 // If the operands are legal vectors, leave them alone. 19963 if (TLI.isTypeLegal(OpVT)) 19964 return SDValue(); 19965 19966 SDLoc DL(N); 19967 EVT VT = N->getValueType(0); 19968 SmallVector<SDValue, 8> Ops; 19969 19970 EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits()); 19971 SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 19972 19973 // Keep track of what we encounter. 19974 bool AnyInteger = false; 19975 bool AnyFP = false; 19976 for (const SDValue &Op : N->ops()) { 19977 if (ISD::BITCAST == Op.getOpcode() && 19978 !Op.getOperand(0).getValueType().isVector()) 19979 Ops.push_back(Op.getOperand(0)); 19980 else if (ISD::UNDEF == Op.getOpcode()) 19981 Ops.push_back(ScalarUndef); 19982 else 19983 return SDValue(); 19984 19985 // Note whether we encounter an integer or floating point scalar. 19986 // If it's neither, bail out, it could be something weird like x86mmx. 19987 EVT LastOpVT = Ops.back().getValueType(); 19988 if (LastOpVT.isFloatingPoint()) 19989 AnyFP = true; 19990 else if (LastOpVT.isInteger()) 19991 AnyInteger = true; 19992 else 19993 return SDValue(); 19994 } 19995 19996 // If any of the operands is a floating point scalar bitcast to a vector, 19997 // use floating point types throughout, and bitcast everything. 19998 // Replace UNDEFs by another scalar UNDEF node, of the final desired type. 19999 if (AnyFP) { 20000 SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits()); 20001 ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT); 20002 if (AnyInteger) { 20003 for (SDValue &Op : Ops) { 20004 if (Op.getValueType() == SVT) 20005 continue; 20006 if (Op.isUndef()) 20007 Op = ScalarUndef; 20008 else 20009 Op = DAG.getBitcast(SVT, Op); 20010 } 20011 } 20012 } 20013 20014 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT, 20015 VT.getSizeInBits() / SVT.getSizeInBits()); 20016 return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops)); 20017 } 20018 20019 // Attempt to merge nested concat_vectors/undefs. 20020 // Fold concat_vectors(concat_vectors(x,y,z,w),u,u,concat_vectors(a,b,c,d)) 20021 // --> concat_vectors(x,y,z,w,u,u,u,u,u,u,u,u,a,b,c,d) 20022 static SDValue combineConcatVectorOfConcatVectors(SDNode *N, 20023 SelectionDAG &DAG) { 20024 EVT VT = N->getValueType(0); 20025 20026 // Ensure we're concatenating UNDEF and CONCAT_VECTORS nodes of similar types. 20027 EVT SubVT; 20028 SDValue FirstConcat; 20029 for (const SDValue &Op : N->ops()) { 20030 if (Op.isUndef()) 20031 continue; 20032 if (Op.getOpcode() != ISD::CONCAT_VECTORS) 20033 return SDValue(); 20034 if (!FirstConcat) { 20035 SubVT = Op.getOperand(0).getValueType(); 20036 if (!DAG.getTargetLoweringInfo().isTypeLegal(SubVT)) 20037 return SDValue(); 20038 FirstConcat = Op; 20039 continue; 20040 } 20041 if (SubVT != Op.getOperand(0).getValueType()) 20042 return SDValue(); 20043 } 20044 assert(FirstConcat && "Concat of all-undefs found"); 20045 20046 SmallVector<SDValue> ConcatOps; 20047 for (const SDValue &Op : N->ops()) { 20048 if (Op.isUndef()) { 20049 ConcatOps.append(FirstConcat->getNumOperands(), DAG.getUNDEF(SubVT)); 20050 continue; 20051 } 20052 ConcatOps.append(Op->op_begin(), Op->op_end()); 20053 } 20054 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, ConcatOps); 20055 } 20056 20057 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR 20058 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at 20059 // most two distinct vectors the same size as the result, attempt to turn this 20060 // into a legal shuffle. 20061 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) { 20062 EVT VT = N->getValueType(0); 20063 EVT OpVT = N->getOperand(0).getValueType(); 20064 20065 // We currently can't generate an appropriate shuffle for a scalable vector. 20066 if (VT.isScalableVector()) 20067 return SDValue(); 20068 20069 int NumElts = VT.getVectorNumElements(); 20070 int NumOpElts = OpVT.getVectorNumElements(); 20071 20072 SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT); 20073 SmallVector<int, 8> Mask; 20074 20075 for (SDValue Op : N->ops()) { 20076 Op = peekThroughBitcasts(Op); 20077 20078 // UNDEF nodes convert to UNDEF shuffle mask values. 20079 if (Op.isUndef()) { 20080 Mask.append((unsigned)NumOpElts, -1); 20081 continue; 20082 } 20083 20084 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 20085 return SDValue(); 20086 20087 // What vector are we extracting the subvector from and at what index? 20088 SDValue ExtVec = Op.getOperand(0); 20089 int ExtIdx = Op.getConstantOperandVal(1); 20090 20091 // We want the EVT of the original extraction to correctly scale the 20092 // extraction index. 20093 EVT ExtVT = ExtVec.getValueType(); 20094 ExtVec = peekThroughBitcasts(ExtVec); 20095 20096 // UNDEF nodes convert to UNDEF shuffle mask values. 20097 if (ExtVec.isUndef()) { 20098 Mask.append((unsigned)NumOpElts, -1); 20099 continue; 20100 } 20101 20102 // Ensure that we are extracting a subvector from a vector the same 20103 // size as the result. 20104 if (ExtVT.getSizeInBits() != VT.getSizeInBits()) 20105 return SDValue(); 20106 20107 // Scale the subvector index to account for any bitcast. 20108 int NumExtElts = ExtVT.getVectorNumElements(); 20109 if (0 == (NumExtElts % NumElts)) 20110 ExtIdx /= (NumExtElts / NumElts); 20111 else if (0 == (NumElts % NumExtElts)) 20112 ExtIdx *= (NumElts / NumExtElts); 20113 else 20114 return SDValue(); 20115 20116 // At most we can reference 2 inputs in the final shuffle. 20117 if (SV0.isUndef() || SV0 == ExtVec) { 20118 SV0 = ExtVec; 20119 for (int i = 0; i != NumOpElts; ++i) 20120 Mask.push_back(i + ExtIdx); 20121 } else if (SV1.isUndef() || SV1 == ExtVec) { 20122 SV1 = ExtVec; 20123 for (int i = 0; i != NumOpElts; ++i) 20124 Mask.push_back(i + ExtIdx + NumElts); 20125 } else { 20126 return SDValue(); 20127 } 20128 } 20129 20130 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 20131 return TLI.buildLegalVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0), 20132 DAG.getBitcast(VT, SV1), Mask, DAG); 20133 } 20134 20135 static SDValue combineConcatVectorOfCasts(SDNode *N, SelectionDAG &DAG) { 20136 unsigned CastOpcode = N->getOperand(0).getOpcode(); 20137 switch (CastOpcode) { 20138 case ISD::SINT_TO_FP: 20139 case ISD::UINT_TO_FP: 20140 case ISD::FP_TO_SINT: 20141 case ISD::FP_TO_UINT: 20142 // TODO: Allow more opcodes? 20143 // case ISD::BITCAST: 20144 // case ISD::TRUNCATE: 20145 // case ISD::ZERO_EXTEND: 20146 // case ISD::SIGN_EXTEND: 20147 // case ISD::FP_EXTEND: 20148 break; 20149 default: 20150 return SDValue(); 20151 } 20152 20153 EVT SrcVT = N->getOperand(0).getOperand(0).getValueType(); 20154 if (!SrcVT.isVector()) 20155 return SDValue(); 20156 20157 // All operands of the concat must be the same kind of cast from the same 20158 // source type. 20159 SmallVector<SDValue, 4> SrcOps; 20160 for (SDValue Op : N->ops()) { 20161 if (Op.getOpcode() != CastOpcode || !Op.hasOneUse() || 20162 Op.getOperand(0).getValueType() != SrcVT) 20163 return SDValue(); 20164 SrcOps.push_back(Op.getOperand(0)); 20165 } 20166 20167 // The wider cast must be supported by the target. This is unusual because 20168 // the operation support type parameter depends on the opcode. In addition, 20169 // check the other type in the cast to make sure this is really legal. 20170 EVT VT = N->getValueType(0); 20171 EVT SrcEltVT = SrcVT.getVectorElementType(); 20172 ElementCount NumElts = SrcVT.getVectorElementCount() * N->getNumOperands(); 20173 EVT ConcatSrcVT = EVT::getVectorVT(*DAG.getContext(), SrcEltVT, NumElts); 20174 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 20175 switch (CastOpcode) { 20176 case ISD::SINT_TO_FP: 20177 case ISD::UINT_TO_FP: 20178 if (!TLI.isOperationLegalOrCustom(CastOpcode, ConcatSrcVT) || 20179 !TLI.isTypeLegal(VT)) 20180 return SDValue(); 20181 break; 20182 case ISD::FP_TO_SINT: 20183 case ISD::FP_TO_UINT: 20184 if (!TLI.isOperationLegalOrCustom(CastOpcode, VT) || 20185 !TLI.isTypeLegal(ConcatSrcVT)) 20186 return SDValue(); 20187 break; 20188 default: 20189 llvm_unreachable("Unexpected cast opcode"); 20190 } 20191 20192 // concat (cast X), (cast Y)... -> cast (concat X, Y...) 20193 SDLoc DL(N); 20194 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatSrcVT, SrcOps); 20195 return DAG.getNode(CastOpcode, DL, VT, NewConcat); 20196 } 20197 20198 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) { 20199 // If we only have one input vector, we don't need to do any concatenation. 20200 if (N->getNumOperands() == 1) 20201 return N->getOperand(0); 20202 20203 // Check if all of the operands are undefs. 20204 EVT VT = N->getValueType(0); 20205 if (ISD::allOperandsUndef(N)) 20206 return DAG.getUNDEF(VT); 20207 20208 // Optimize concat_vectors where all but the first of the vectors are undef. 20209 if (all_of(drop_begin(N->ops()), 20210 [](const SDValue &Op) { return Op.isUndef(); })) { 20211 SDValue In = N->getOperand(0); 20212 assert(In.getValueType().isVector() && "Must concat vectors"); 20213 20214 // If the input is a concat_vectors, just make a larger concat by padding 20215 // with smaller undefs. 20216 if (In.getOpcode() == ISD::CONCAT_VECTORS && In.hasOneUse()) { 20217 unsigned NumOps = N->getNumOperands() * In.getNumOperands(); 20218 SmallVector<SDValue, 4> Ops(In->op_begin(), In->op_end()); 20219 Ops.resize(NumOps, DAG.getUNDEF(Ops[0].getValueType())); 20220 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 20221 } 20222 20223 SDValue Scalar = peekThroughOneUseBitcasts(In); 20224 20225 // concat_vectors(scalar_to_vector(scalar), undef) -> 20226 // scalar_to_vector(scalar) 20227 if (!LegalOperations && Scalar.getOpcode() == ISD::SCALAR_TO_VECTOR && 20228 Scalar.hasOneUse()) { 20229 EVT SVT = Scalar.getValueType().getVectorElementType(); 20230 if (SVT == Scalar.getOperand(0).getValueType()) 20231 Scalar = Scalar.getOperand(0); 20232 } 20233 20234 // concat_vectors(scalar, undef) -> scalar_to_vector(scalar) 20235 if (!Scalar.getValueType().isVector()) { 20236 // If the bitcast type isn't legal, it might be a trunc of a legal type; 20237 // look through the trunc so we can still do the transform: 20238 // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar) 20239 if (Scalar->getOpcode() == ISD::TRUNCATE && 20240 !TLI.isTypeLegal(Scalar.getValueType()) && 20241 TLI.isTypeLegal(Scalar->getOperand(0).getValueType())) 20242 Scalar = Scalar->getOperand(0); 20243 20244 EVT SclTy = Scalar.getValueType(); 20245 20246 if (!SclTy.isFloatingPoint() && !SclTy.isInteger()) 20247 return SDValue(); 20248 20249 // Bail out if the vector size is not a multiple of the scalar size. 20250 if (VT.getSizeInBits() % SclTy.getSizeInBits()) 20251 return SDValue(); 20252 20253 unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits(); 20254 if (VNTNumElms < 2) 20255 return SDValue(); 20256 20257 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms); 20258 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType())) 20259 return SDValue(); 20260 20261 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar); 20262 return DAG.getBitcast(VT, Res); 20263 } 20264 } 20265 20266 // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR. 20267 // We have already tested above for an UNDEF only concatenation. 20268 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...)) 20269 // -> (BUILD_VECTOR A, B, ..., C, D, ...) 20270 auto IsBuildVectorOrUndef = [](const SDValue &Op) { 20271 return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode(); 20272 }; 20273 if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) { 20274 SmallVector<SDValue, 8> Opnds; 20275 EVT SVT = VT.getScalarType(); 20276 20277 EVT MinVT = SVT; 20278 if (!SVT.isFloatingPoint()) { 20279 // If BUILD_VECTOR are from built from integer, they may have different 20280 // operand types. Get the smallest type and truncate all operands to it. 20281 bool FoundMinVT = false; 20282 for (const SDValue &Op : N->ops()) 20283 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 20284 EVT OpSVT = Op.getOperand(0).getValueType(); 20285 MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT; 20286 FoundMinVT = true; 20287 } 20288 assert(FoundMinVT && "Concat vector type mismatch"); 20289 } 20290 20291 for (const SDValue &Op : N->ops()) { 20292 EVT OpVT = Op.getValueType(); 20293 unsigned NumElts = OpVT.getVectorNumElements(); 20294 20295 if (ISD::UNDEF == Op.getOpcode()) 20296 Opnds.append(NumElts, DAG.getUNDEF(MinVT)); 20297 20298 if (ISD::BUILD_VECTOR == Op.getOpcode()) { 20299 if (SVT.isFloatingPoint()) { 20300 assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch"); 20301 Opnds.append(Op->op_begin(), Op->op_begin() + NumElts); 20302 } else { 20303 for (unsigned i = 0; i != NumElts; ++i) 20304 Opnds.push_back( 20305 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i))); 20306 } 20307 } 20308 } 20309 20310 assert(VT.getVectorNumElements() == Opnds.size() && 20311 "Concat vector type mismatch"); 20312 return DAG.getBuildVector(VT, SDLoc(N), Opnds); 20313 } 20314 20315 // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR. 20316 // FIXME: Add support for concat_vectors(bitcast(vec0),bitcast(vec1),...). 20317 if (SDValue V = combineConcatVectorOfScalars(N, DAG)) 20318 return V; 20319 20320 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) { 20321 // Fold CONCAT_VECTORS of CONCAT_VECTORS (or undef) to VECTOR_SHUFFLE. 20322 if (SDValue V = combineConcatVectorOfConcatVectors(N, DAG)) 20323 return V; 20324 20325 // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE. 20326 if (SDValue V = combineConcatVectorOfExtracts(N, DAG)) 20327 return V; 20328 } 20329 20330 if (SDValue V = combineConcatVectorOfCasts(N, DAG)) 20331 return V; 20332 20333 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR 20334 // nodes often generate nop CONCAT_VECTOR nodes. Scan the CONCAT_VECTOR 20335 // operands and look for a CONCAT operations that place the incoming vectors 20336 // at the exact same location. 20337 // 20338 // For scalable vectors, EXTRACT_SUBVECTOR indexes are implicitly scaled. 20339 SDValue SingleSource = SDValue(); 20340 unsigned PartNumElem = 20341 N->getOperand(0).getValueType().getVectorMinNumElements(); 20342 20343 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 20344 SDValue Op = N->getOperand(i); 20345 20346 if (Op.isUndef()) 20347 continue; 20348 20349 // Check if this is the identity extract: 20350 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR) 20351 return SDValue(); 20352 20353 // Find the single incoming vector for the extract_subvector. 20354 if (SingleSource.getNode()) { 20355 if (Op.getOperand(0) != SingleSource) 20356 return SDValue(); 20357 } else { 20358 SingleSource = Op.getOperand(0); 20359 20360 // Check the source type is the same as the type of the result. 20361 // If not, this concat may extend the vector, so we can not 20362 // optimize it away. 20363 if (SingleSource.getValueType() != N->getValueType(0)) 20364 return SDValue(); 20365 } 20366 20367 // Check that we are reading from the identity index. 20368 unsigned IdentityIndex = i * PartNumElem; 20369 if (Op.getConstantOperandAPInt(1) != IdentityIndex) 20370 return SDValue(); 20371 } 20372 20373 if (SingleSource.getNode()) 20374 return SingleSource; 20375 20376 return SDValue(); 20377 } 20378 20379 // Helper that peeks through INSERT_SUBVECTOR/CONCAT_VECTORS to find 20380 // if the subvector can be sourced for free. 20381 static SDValue getSubVectorSrc(SDValue V, SDValue Index, EVT SubVT) { 20382 if (V.getOpcode() == ISD::INSERT_SUBVECTOR && 20383 V.getOperand(1).getValueType() == SubVT && V.getOperand(2) == Index) { 20384 return V.getOperand(1); 20385 } 20386 auto *IndexC = dyn_cast<ConstantSDNode>(Index); 20387 if (IndexC && V.getOpcode() == ISD::CONCAT_VECTORS && 20388 V.getOperand(0).getValueType() == SubVT && 20389 (IndexC->getZExtValue() % SubVT.getVectorMinNumElements()) == 0) { 20390 uint64_t SubIdx = IndexC->getZExtValue() / SubVT.getVectorMinNumElements(); 20391 return V.getOperand(SubIdx); 20392 } 20393 return SDValue(); 20394 } 20395 20396 static SDValue narrowInsertExtractVectorBinOp(SDNode *Extract, 20397 SelectionDAG &DAG, 20398 bool LegalOperations) { 20399 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 20400 SDValue BinOp = Extract->getOperand(0); 20401 unsigned BinOpcode = BinOp.getOpcode(); 20402 if (!TLI.isBinOp(BinOpcode) || BinOp.getNode()->getNumValues() != 1) 20403 return SDValue(); 20404 20405 EVT VecVT = BinOp.getValueType(); 20406 SDValue Bop0 = BinOp.getOperand(0), Bop1 = BinOp.getOperand(1); 20407 if (VecVT != Bop0.getValueType() || VecVT != Bop1.getValueType()) 20408 return SDValue(); 20409 20410 SDValue Index = Extract->getOperand(1); 20411 EVT SubVT = Extract->getValueType(0); 20412 if (!TLI.isOperationLegalOrCustom(BinOpcode, SubVT, LegalOperations)) 20413 return SDValue(); 20414 20415 SDValue Sub0 = getSubVectorSrc(Bop0, Index, SubVT); 20416 SDValue Sub1 = getSubVectorSrc(Bop1, Index, SubVT); 20417 20418 // TODO: We could handle the case where only 1 operand is being inserted by 20419 // creating an extract of the other operand, but that requires checking 20420 // number of uses and/or costs. 20421 if (!Sub0 || !Sub1) 20422 return SDValue(); 20423 20424 // We are inserting both operands of the wide binop only to extract back 20425 // to the narrow vector size. Eliminate all of the insert/extract: 20426 // ext (binop (ins ?, X, Index), (ins ?, Y, Index)), Index --> binop X, Y 20427 return DAG.getNode(BinOpcode, SDLoc(Extract), SubVT, Sub0, Sub1, 20428 BinOp->getFlags()); 20429 } 20430 20431 /// If we are extracting a subvector produced by a wide binary operator try 20432 /// to use a narrow binary operator and/or avoid concatenation and extraction. 20433 static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG, 20434 bool LegalOperations) { 20435 // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share 20436 // some of these bailouts with other transforms. 20437 20438 if (SDValue V = narrowInsertExtractVectorBinOp(Extract, DAG, LegalOperations)) 20439 return V; 20440 20441 // The extract index must be a constant, so we can map it to a concat operand. 20442 auto *ExtractIndexC = dyn_cast<ConstantSDNode>(Extract->getOperand(1)); 20443 if (!ExtractIndexC) 20444 return SDValue(); 20445 20446 // We are looking for an optionally bitcasted wide vector binary operator 20447 // feeding an extract subvector. 20448 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 20449 SDValue BinOp = peekThroughBitcasts(Extract->getOperand(0)); 20450 unsigned BOpcode = BinOp.getOpcode(); 20451 if (!TLI.isBinOp(BOpcode) || BinOp.getNode()->getNumValues() != 1) 20452 return SDValue(); 20453 20454 // Exclude the fake form of fneg (fsub -0.0, x) because that is likely to be 20455 // reduced to the unary fneg when it is visited, and we probably want to deal 20456 // with fneg in a target-specific way. 20457 if (BOpcode == ISD::FSUB) { 20458 auto *C = isConstOrConstSplatFP(BinOp.getOperand(0), /*AllowUndefs*/ true); 20459 if (C && C->getValueAPF().isNegZero()) 20460 return SDValue(); 20461 } 20462 20463 // The binop must be a vector type, so we can extract some fraction of it. 20464 EVT WideBVT = BinOp.getValueType(); 20465 // The optimisations below currently assume we are dealing with fixed length 20466 // vectors. It is possible to add support for scalable vectors, but at the 20467 // moment we've done no analysis to prove whether they are profitable or not. 20468 if (!WideBVT.isFixedLengthVector()) 20469 return SDValue(); 20470 20471 EVT VT = Extract->getValueType(0); 20472 unsigned ExtractIndex = ExtractIndexC->getZExtValue(); 20473 assert(ExtractIndex % VT.getVectorNumElements() == 0 && 20474 "Extract index is not a multiple of the vector length."); 20475 20476 // Bail out if this is not a proper multiple width extraction. 20477 unsigned WideWidth = WideBVT.getSizeInBits(); 20478 unsigned NarrowWidth = VT.getSizeInBits(); 20479 if (WideWidth % NarrowWidth != 0) 20480 return SDValue(); 20481 20482 // Bail out if we are extracting a fraction of a single operation. This can 20483 // occur because we potentially looked through a bitcast of the binop. 20484 unsigned NarrowingRatio = WideWidth / NarrowWidth; 20485 unsigned WideNumElts = WideBVT.getVectorNumElements(); 20486 if (WideNumElts % NarrowingRatio != 0) 20487 return SDValue(); 20488 20489 // Bail out if the target does not support a narrower version of the binop. 20490 EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(), 20491 WideNumElts / NarrowingRatio); 20492 if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT)) 20493 return SDValue(); 20494 20495 // If extraction is cheap, we don't need to look at the binop operands 20496 // for concat ops. The narrow binop alone makes this transform profitable. 20497 // We can't just reuse the original extract index operand because we may have 20498 // bitcasted. 20499 unsigned ConcatOpNum = ExtractIndex / VT.getVectorNumElements(); 20500 unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements(); 20501 if (TLI.isExtractSubvectorCheap(NarrowBVT, WideBVT, ExtBOIdx) && 20502 BinOp.hasOneUse() && Extract->getOperand(0)->hasOneUse()) { 20503 // extract (binop B0, B1), N --> binop (extract B0, N), (extract B1, N) 20504 SDLoc DL(Extract); 20505 SDValue NewExtIndex = DAG.getVectorIdxConstant(ExtBOIdx, DL); 20506 SDValue X = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 20507 BinOp.getOperand(0), NewExtIndex); 20508 SDValue Y = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 20509 BinOp.getOperand(1), NewExtIndex); 20510 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y, 20511 BinOp.getNode()->getFlags()); 20512 return DAG.getBitcast(VT, NarrowBinOp); 20513 } 20514 20515 // Only handle the case where we are doubling and then halving. A larger ratio 20516 // may require more than two narrow binops to replace the wide binop. 20517 if (NarrowingRatio != 2) 20518 return SDValue(); 20519 20520 // TODO: The motivating case for this transform is an x86 AVX1 target. That 20521 // target has temptingly almost legal versions of bitwise logic ops in 256-bit 20522 // flavors, but no other 256-bit integer support. This could be extended to 20523 // handle any binop, but that may require fixing/adding other folds to avoid 20524 // codegen regressions. 20525 if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR) 20526 return SDValue(); 20527 20528 // We need at least one concatenation operation of a binop operand to make 20529 // this transform worthwhile. The concat must double the input vector sizes. 20530 auto GetSubVector = [ConcatOpNum](SDValue V) -> SDValue { 20531 if (V.getOpcode() == ISD::CONCAT_VECTORS && V.getNumOperands() == 2) 20532 return V.getOperand(ConcatOpNum); 20533 return SDValue(); 20534 }; 20535 SDValue SubVecL = GetSubVector(peekThroughBitcasts(BinOp.getOperand(0))); 20536 SDValue SubVecR = GetSubVector(peekThroughBitcasts(BinOp.getOperand(1))); 20537 20538 if (SubVecL || SubVecR) { 20539 // If a binop operand was not the result of a concat, we must extract a 20540 // half-sized operand for our new narrow binop: 20541 // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN 20542 // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, IndexC) 20543 // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, IndexC), YN 20544 SDLoc DL(Extract); 20545 SDValue IndexC = DAG.getVectorIdxConstant(ExtBOIdx, DL); 20546 SDValue X = SubVecL ? DAG.getBitcast(NarrowBVT, SubVecL) 20547 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 20548 BinOp.getOperand(0), IndexC); 20549 20550 SDValue Y = SubVecR ? DAG.getBitcast(NarrowBVT, SubVecR) 20551 : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT, 20552 BinOp.getOperand(1), IndexC); 20553 20554 SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y); 20555 return DAG.getBitcast(VT, NarrowBinOp); 20556 } 20557 20558 return SDValue(); 20559 } 20560 20561 /// If we are extracting a subvector from a wide vector load, convert to a 20562 /// narrow load to eliminate the extraction: 20563 /// (extract_subvector (load wide vector)) --> (load narrow vector) 20564 static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) { 20565 // TODO: Add support for big-endian. The offset calculation must be adjusted. 20566 if (DAG.getDataLayout().isBigEndian()) 20567 return SDValue(); 20568 20569 auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0)); 20570 if (!Ld || Ld->getExtensionType() || !Ld->isSimple()) 20571 return SDValue(); 20572 20573 // Allow targets to opt-out. 20574 EVT VT = Extract->getValueType(0); 20575 20576 // We can only create byte sized loads. 20577 if (!VT.isByteSized()) 20578 return SDValue(); 20579 20580 unsigned Index = Extract->getConstantOperandVal(1); 20581 unsigned NumElts = VT.getVectorMinNumElements(); 20582 20583 // The definition of EXTRACT_SUBVECTOR states that the index must be a 20584 // multiple of the minimum number of elements in the result type. 20585 assert(Index % NumElts == 0 && "The extract subvector index is not a " 20586 "multiple of the result's element count"); 20587 20588 // It's fine to use TypeSize here as we know the offset will not be negative. 20589 TypeSize Offset = VT.getStoreSize() * (Index / NumElts); 20590 20591 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 20592 if (!TLI.shouldReduceLoadWidth(Ld, Ld->getExtensionType(), VT)) 20593 return SDValue(); 20594 20595 // The narrow load will be offset from the base address of the old load if 20596 // we are extracting from something besides index 0 (little-endian). 20597 SDLoc DL(Extract); 20598 20599 // TODO: Use "BaseIndexOffset" to make this more effective. 20600 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), Offset, DL); 20601 20602 uint64_t StoreSize = MemoryLocation::getSizeOrUnknown(VT.getStoreSize()); 20603 MachineFunction &MF = DAG.getMachineFunction(); 20604 MachineMemOperand *MMO; 20605 if (Offset.isScalable()) { 20606 MachinePointerInfo MPI = 20607 MachinePointerInfo(Ld->getPointerInfo().getAddrSpace()); 20608 MMO = MF.getMachineMemOperand(Ld->getMemOperand(), MPI, StoreSize); 20609 } else 20610 MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset.getFixedSize(), 20611 StoreSize); 20612 20613 SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO); 20614 DAG.makeEquivalentMemoryOrdering(Ld, NewLd); 20615 return NewLd; 20616 } 20617 20618 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode *N) { 20619 EVT NVT = N->getValueType(0); 20620 SDValue V = N->getOperand(0); 20621 uint64_t ExtIdx = N->getConstantOperandVal(1); 20622 20623 // Extract from UNDEF is UNDEF. 20624 if (V.isUndef()) 20625 return DAG.getUNDEF(NVT); 20626 20627 if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT)) 20628 if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG)) 20629 return NarrowLoad; 20630 20631 // Combine an extract of an extract into a single extract_subvector. 20632 // ext (ext X, C), 0 --> ext X, C 20633 if (ExtIdx == 0 && V.getOpcode() == ISD::EXTRACT_SUBVECTOR && V.hasOneUse()) { 20634 if (TLI.isExtractSubvectorCheap(NVT, V.getOperand(0).getValueType(), 20635 V.getConstantOperandVal(1)) && 20636 TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NVT)) { 20637 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, V.getOperand(0), 20638 V.getOperand(1)); 20639 } 20640 } 20641 20642 // Try to move vector bitcast after extract_subv by scaling extraction index: 20643 // extract_subv (bitcast X), Index --> bitcast (extract_subv X, Index') 20644 if (V.getOpcode() == ISD::BITCAST && 20645 V.getOperand(0).getValueType().isVector() && 20646 (!LegalOperations || TLI.isOperationLegal(ISD::BITCAST, NVT))) { 20647 SDValue SrcOp = V.getOperand(0); 20648 EVT SrcVT = SrcOp.getValueType(); 20649 unsigned SrcNumElts = SrcVT.getVectorMinNumElements(); 20650 unsigned DestNumElts = V.getValueType().getVectorMinNumElements(); 20651 if ((SrcNumElts % DestNumElts) == 0) { 20652 unsigned SrcDestRatio = SrcNumElts / DestNumElts; 20653 ElementCount NewExtEC = NVT.getVectorElementCount() * SrcDestRatio; 20654 EVT NewExtVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(), 20655 NewExtEC); 20656 if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) { 20657 SDLoc DL(N); 20658 SDValue NewIndex = DAG.getVectorIdxConstant(ExtIdx * SrcDestRatio, DL); 20659 SDValue NewExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT, 20660 V.getOperand(0), NewIndex); 20661 return DAG.getBitcast(NVT, NewExtract); 20662 } 20663 } 20664 if ((DestNumElts % SrcNumElts) == 0) { 20665 unsigned DestSrcRatio = DestNumElts / SrcNumElts; 20666 if (NVT.getVectorElementCount().isKnownMultipleOf(DestSrcRatio)) { 20667 ElementCount NewExtEC = 20668 NVT.getVectorElementCount().divideCoefficientBy(DestSrcRatio); 20669 EVT ScalarVT = SrcVT.getScalarType(); 20670 if ((ExtIdx % DestSrcRatio) == 0) { 20671 SDLoc DL(N); 20672 unsigned IndexValScaled = ExtIdx / DestSrcRatio; 20673 EVT NewExtVT = 20674 EVT::getVectorVT(*DAG.getContext(), ScalarVT, NewExtEC); 20675 if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) { 20676 SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL); 20677 SDValue NewExtract = 20678 DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT, 20679 V.getOperand(0), NewIndex); 20680 return DAG.getBitcast(NVT, NewExtract); 20681 } 20682 if (NewExtEC.isScalar() && 20683 TLI.isOperationLegalOrCustom(ISD::EXTRACT_VECTOR_ELT, ScalarVT)) { 20684 SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL); 20685 SDValue NewExtract = 20686 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, 20687 V.getOperand(0), NewIndex); 20688 return DAG.getBitcast(NVT, NewExtract); 20689 } 20690 } 20691 } 20692 } 20693 } 20694 20695 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 20696 unsigned ExtNumElts = NVT.getVectorMinNumElements(); 20697 EVT ConcatSrcVT = V.getOperand(0).getValueType(); 20698 assert(ConcatSrcVT.getVectorElementType() == NVT.getVectorElementType() && 20699 "Concat and extract subvector do not change element type"); 20700 assert((ExtIdx % ExtNumElts) == 0 && 20701 "Extract index is not a multiple of the input vector length."); 20702 20703 unsigned ConcatSrcNumElts = ConcatSrcVT.getVectorMinNumElements(); 20704 unsigned ConcatOpIdx = ExtIdx / ConcatSrcNumElts; 20705 20706 // If the concatenated source types match this extract, it's a direct 20707 // simplification: 20708 // extract_subvec (concat V1, V2, ...), i --> Vi 20709 if (NVT.getVectorElementCount() == ConcatSrcVT.getVectorElementCount()) 20710 return V.getOperand(ConcatOpIdx); 20711 20712 // If the concatenated source vectors are a multiple length of this extract, 20713 // then extract a fraction of one of those source vectors directly from a 20714 // concat operand. Example: 20715 // v2i8 extract_subvec (v16i8 concat (v8i8 X), (v8i8 Y), 14 --> 20716 // v2i8 extract_subvec v8i8 Y, 6 20717 if (NVT.isFixedLengthVector() && ConcatSrcVT.isFixedLengthVector() && 20718 ConcatSrcNumElts % ExtNumElts == 0) { 20719 SDLoc DL(N); 20720 unsigned NewExtIdx = ExtIdx - ConcatOpIdx * ConcatSrcNumElts; 20721 assert(NewExtIdx + ExtNumElts <= ConcatSrcNumElts && 20722 "Trying to extract from >1 concat operand?"); 20723 assert(NewExtIdx % ExtNumElts == 0 && 20724 "Extract index is not a multiple of the input vector length."); 20725 SDValue NewIndexC = DAG.getVectorIdxConstant(NewExtIdx, DL); 20726 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NVT, 20727 V.getOperand(ConcatOpIdx), NewIndexC); 20728 } 20729 } 20730 20731 V = peekThroughBitcasts(V); 20732 20733 // If the input is a build vector. Try to make a smaller build vector. 20734 if (V.getOpcode() == ISD::BUILD_VECTOR) { 20735 EVT InVT = V.getValueType(); 20736 unsigned ExtractSize = NVT.getSizeInBits(); 20737 unsigned EltSize = InVT.getScalarSizeInBits(); 20738 // Only do this if we won't split any elements. 20739 if (ExtractSize % EltSize == 0) { 20740 unsigned NumElems = ExtractSize / EltSize; 20741 EVT EltVT = InVT.getVectorElementType(); 20742 EVT ExtractVT = 20743 NumElems == 1 ? EltVT 20744 : EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems); 20745 if ((Level < AfterLegalizeDAG || 20746 (NumElems == 1 || 20747 TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) && 20748 (!LegalTypes || TLI.isTypeLegal(ExtractVT))) { 20749 unsigned IdxVal = (ExtIdx * NVT.getScalarSizeInBits()) / EltSize; 20750 20751 if (NumElems == 1) { 20752 SDValue Src = V->getOperand(IdxVal); 20753 if (EltVT != Src.getValueType()) 20754 Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src); 20755 return DAG.getBitcast(NVT, Src); 20756 } 20757 20758 // Extract the pieces from the original build_vector. 20759 SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N), 20760 V->ops().slice(IdxVal, NumElems)); 20761 return DAG.getBitcast(NVT, BuildVec); 20762 } 20763 } 20764 } 20765 20766 if (V.getOpcode() == ISD::INSERT_SUBVECTOR) { 20767 // Handle only simple case where vector being inserted and vector 20768 // being extracted are of same size. 20769 EVT SmallVT = V.getOperand(1).getValueType(); 20770 if (!NVT.bitsEq(SmallVT)) 20771 return SDValue(); 20772 20773 // Combine: 20774 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx) 20775 // Into: 20776 // indices are equal or bit offsets are equal => V1 20777 // otherwise => (extract_subvec V1, ExtIdx) 20778 uint64_t InsIdx = V.getConstantOperandVal(2); 20779 if (InsIdx * SmallVT.getScalarSizeInBits() == 20780 ExtIdx * NVT.getScalarSizeInBits()) { 20781 if (LegalOperations && !TLI.isOperationLegal(ISD::BITCAST, NVT)) 20782 return SDValue(); 20783 20784 return DAG.getBitcast(NVT, V.getOperand(1)); 20785 } 20786 return DAG.getNode( 20787 ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, 20788 DAG.getBitcast(N->getOperand(0).getValueType(), V.getOperand(0)), 20789 N->getOperand(1)); 20790 } 20791 20792 if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG, LegalOperations)) 20793 return NarrowBOp; 20794 20795 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 20796 return SDValue(N, 0); 20797 20798 return SDValue(); 20799 } 20800 20801 /// Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles 20802 /// followed by concatenation. Narrow vector ops may have better performance 20803 /// than wide ops, and this can unlock further narrowing of other vector ops. 20804 /// Targets can invert this transform later if it is not profitable. 20805 static SDValue foldShuffleOfConcatUndefs(ShuffleVectorSDNode *Shuf, 20806 SelectionDAG &DAG) { 20807 SDValue N0 = Shuf->getOperand(0), N1 = Shuf->getOperand(1); 20808 if (N0.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 || 20809 N1.getOpcode() != ISD::CONCAT_VECTORS || N1.getNumOperands() != 2 || 20810 !N0.getOperand(1).isUndef() || !N1.getOperand(1).isUndef()) 20811 return SDValue(); 20812 20813 // Split the wide shuffle mask into halves. Any mask element that is accessing 20814 // operand 1 is offset down to account for narrowing of the vectors. 20815 ArrayRef<int> Mask = Shuf->getMask(); 20816 EVT VT = Shuf->getValueType(0); 20817 unsigned NumElts = VT.getVectorNumElements(); 20818 unsigned HalfNumElts = NumElts / 2; 20819 SmallVector<int, 16> Mask0(HalfNumElts, -1); 20820 SmallVector<int, 16> Mask1(HalfNumElts, -1); 20821 for (unsigned i = 0; i != NumElts; ++i) { 20822 if (Mask[i] == -1) 20823 continue; 20824 // If we reference the upper (undef) subvector then the element is undef. 20825 if ((Mask[i] % NumElts) >= HalfNumElts) 20826 continue; 20827 int M = Mask[i] < (int)NumElts ? Mask[i] : Mask[i] - (int)HalfNumElts; 20828 if (i < HalfNumElts) 20829 Mask0[i] = M; 20830 else 20831 Mask1[i - HalfNumElts] = M; 20832 } 20833 20834 // Ask the target if this is a valid transform. 20835 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 20836 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(), 20837 HalfNumElts); 20838 if (!TLI.isShuffleMaskLegal(Mask0, HalfVT) || 20839 !TLI.isShuffleMaskLegal(Mask1, HalfVT)) 20840 return SDValue(); 20841 20842 // shuffle (concat X, undef), (concat Y, undef), Mask --> 20843 // concat (shuffle X, Y, Mask0), (shuffle X, Y, Mask1) 20844 SDValue X = N0.getOperand(0), Y = N1.getOperand(0); 20845 SDLoc DL(Shuf); 20846 SDValue Shuf0 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask0); 20847 SDValue Shuf1 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask1); 20848 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Shuf0, Shuf1); 20849 } 20850 20851 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat, 20852 // or turn a shuffle of a single concat into simpler shuffle then concat. 20853 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) { 20854 EVT VT = N->getValueType(0); 20855 unsigned NumElts = VT.getVectorNumElements(); 20856 20857 SDValue N0 = N->getOperand(0); 20858 SDValue N1 = N->getOperand(1); 20859 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 20860 ArrayRef<int> Mask = SVN->getMask(); 20861 20862 SmallVector<SDValue, 4> Ops; 20863 EVT ConcatVT = N0.getOperand(0).getValueType(); 20864 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements(); 20865 unsigned NumConcats = NumElts / NumElemsPerConcat; 20866 20867 auto IsUndefMaskElt = [](int i) { return i == -1; }; 20868 20869 // Special case: shuffle(concat(A,B)) can be more efficiently represented 20870 // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high 20871 // half vector elements. 20872 if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() && 20873 llvm::all_of(Mask.slice(NumElemsPerConcat, NumElemsPerConcat), 20874 IsUndefMaskElt)) { 20875 N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), 20876 N0.getOperand(1), 20877 Mask.slice(0, NumElemsPerConcat)); 20878 N1 = DAG.getUNDEF(ConcatVT); 20879 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1); 20880 } 20881 20882 // Look at every vector that's inserted. We're looking for exact 20883 // subvector-sized copies from a concatenated vector 20884 for (unsigned I = 0; I != NumConcats; ++I) { 20885 unsigned Begin = I * NumElemsPerConcat; 20886 ArrayRef<int> SubMask = Mask.slice(Begin, NumElemsPerConcat); 20887 20888 // Make sure we're dealing with a copy. 20889 if (llvm::all_of(SubMask, IsUndefMaskElt)) { 20890 Ops.push_back(DAG.getUNDEF(ConcatVT)); 20891 continue; 20892 } 20893 20894 int OpIdx = -1; 20895 for (int i = 0; i != (int)NumElemsPerConcat; ++i) { 20896 if (IsUndefMaskElt(SubMask[i])) 20897 continue; 20898 if ((SubMask[i] % (int)NumElemsPerConcat) != i) 20899 return SDValue(); 20900 int EltOpIdx = SubMask[i] / NumElemsPerConcat; 20901 if (0 <= OpIdx && EltOpIdx != OpIdx) 20902 return SDValue(); 20903 OpIdx = EltOpIdx; 20904 } 20905 assert(0 <= OpIdx && "Unknown concat_vectors op"); 20906 20907 if (OpIdx < (int)N0.getNumOperands()) 20908 Ops.push_back(N0.getOperand(OpIdx)); 20909 else 20910 Ops.push_back(N1.getOperand(OpIdx - N0.getNumOperands())); 20911 } 20912 20913 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 20914 } 20915 20916 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 20917 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 20918 // 20919 // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always 20920 // a simplification in some sense, but it isn't appropriate in general: some 20921 // BUILD_VECTORs are substantially cheaper than others. The general case 20922 // of a BUILD_VECTOR requires inserting each element individually (or 20923 // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of 20924 // all constants is a single constant pool load. A BUILD_VECTOR where each 20925 // element is identical is a splat. A BUILD_VECTOR where most of the operands 20926 // are undef lowers to a small number of element insertions. 20927 // 20928 // To deal with this, we currently use a bunch of mostly arbitrary heuristics. 20929 // We don't fold shuffles where one side is a non-zero constant, and we don't 20930 // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate 20931 // non-constant operands. This seems to work out reasonably well in practice. 20932 static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN, 20933 SelectionDAG &DAG, 20934 const TargetLowering &TLI) { 20935 EVT VT = SVN->getValueType(0); 20936 unsigned NumElts = VT.getVectorNumElements(); 20937 SDValue N0 = SVN->getOperand(0); 20938 SDValue N1 = SVN->getOperand(1); 20939 20940 if (!N0->hasOneUse()) 20941 return SDValue(); 20942 20943 // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as 20944 // discussed above. 20945 if (!N1.isUndef()) { 20946 if (!N1->hasOneUse()) 20947 return SDValue(); 20948 20949 bool N0AnyConst = isAnyConstantBuildVector(N0); 20950 bool N1AnyConst = isAnyConstantBuildVector(N1); 20951 if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode())) 20952 return SDValue(); 20953 if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode())) 20954 return SDValue(); 20955 } 20956 20957 // If both inputs are splats of the same value then we can safely merge this 20958 // to a single BUILD_VECTOR with undef elements based on the shuffle mask. 20959 bool IsSplat = false; 20960 auto *BV0 = dyn_cast<BuildVectorSDNode>(N0); 20961 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1); 20962 if (BV0 && BV1) 20963 if (SDValue Splat0 = BV0->getSplatValue()) 20964 IsSplat = (Splat0 == BV1->getSplatValue()); 20965 20966 SmallVector<SDValue, 8> Ops; 20967 SmallSet<SDValue, 16> DuplicateOps; 20968 for (int M : SVN->getMask()) { 20969 SDValue Op = DAG.getUNDEF(VT.getScalarType()); 20970 if (M >= 0) { 20971 int Idx = M < (int)NumElts ? M : M - NumElts; 20972 SDValue &S = (M < (int)NumElts ? N0 : N1); 20973 if (S.getOpcode() == ISD::BUILD_VECTOR) { 20974 Op = S.getOperand(Idx); 20975 } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) { 20976 SDValue Op0 = S.getOperand(0); 20977 Op = Idx == 0 ? Op0 : DAG.getUNDEF(Op0.getValueType()); 20978 } else { 20979 // Operand can't be combined - bail out. 20980 return SDValue(); 20981 } 20982 } 20983 20984 // Don't duplicate a non-constant BUILD_VECTOR operand unless we're 20985 // generating a splat; semantically, this is fine, but it's likely to 20986 // generate low-quality code if the target can't reconstruct an appropriate 20987 // shuffle. 20988 if (!Op.isUndef() && !isIntOrFPConstant(Op)) 20989 if (!IsSplat && !DuplicateOps.insert(Op).second) 20990 return SDValue(); 20991 20992 Ops.push_back(Op); 20993 } 20994 20995 // BUILD_VECTOR requires all inputs to be of the same type, find the 20996 // maximum type and extend them all. 20997 EVT SVT = VT.getScalarType(); 20998 if (SVT.isInteger()) 20999 for (SDValue &Op : Ops) 21000 SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT); 21001 if (SVT != VT.getScalarType()) 21002 for (SDValue &Op : Ops) 21003 Op = TLI.isZExtFree(Op.getValueType(), SVT) 21004 ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT) 21005 : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT); 21006 return DAG.getBuildVector(VT, SDLoc(SVN), Ops); 21007 } 21008 21009 // Match shuffles that can be converted to any_vector_extend_in_reg. 21010 // This is often generated during legalization. 21011 // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src)) 21012 // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case. 21013 static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN, 21014 SelectionDAG &DAG, 21015 const TargetLowering &TLI, 21016 bool LegalOperations) { 21017 EVT VT = SVN->getValueType(0); 21018 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 21019 21020 // TODO Add support for big-endian when we have a test case. 21021 if (!VT.isInteger() || IsBigEndian) 21022 return SDValue(); 21023 21024 unsigned NumElts = VT.getVectorNumElements(); 21025 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 21026 ArrayRef<int> Mask = SVN->getMask(); 21027 SDValue N0 = SVN->getOperand(0); 21028 21029 // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32)) 21030 auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) { 21031 for (unsigned i = 0; i != NumElts; ++i) { 21032 if (Mask[i] < 0) 21033 continue; 21034 if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale)) 21035 continue; 21036 return false; 21037 } 21038 return true; 21039 }; 21040 21041 // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for 21042 // power-of-2 extensions as they are the most likely. 21043 for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) { 21044 // Check for non power of 2 vector sizes 21045 if (NumElts % Scale != 0) 21046 continue; 21047 if (!isAnyExtend(Scale)) 21048 continue; 21049 21050 EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale); 21051 EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale); 21052 // Never create an illegal type. Only create unsupported operations if we 21053 // are pre-legalization. 21054 if (TLI.isTypeLegal(OutVT)) 21055 if (!LegalOperations || 21056 TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT)) 21057 return DAG.getBitcast(VT, 21058 DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, 21059 SDLoc(SVN), OutVT, N0)); 21060 } 21061 21062 return SDValue(); 21063 } 21064 21065 // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of 21066 // each source element of a large type into the lowest elements of a smaller 21067 // destination type. This is often generated during legalization. 21068 // If the source node itself was a '*_extend_vector_inreg' node then we should 21069 // then be able to remove it. 21070 static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN, 21071 SelectionDAG &DAG) { 21072 EVT VT = SVN->getValueType(0); 21073 bool IsBigEndian = DAG.getDataLayout().isBigEndian(); 21074 21075 // TODO Add support for big-endian when we have a test case. 21076 if (!VT.isInteger() || IsBigEndian) 21077 return SDValue(); 21078 21079 SDValue N0 = peekThroughBitcasts(SVN->getOperand(0)); 21080 21081 unsigned Opcode = N0.getOpcode(); 21082 if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG && 21083 Opcode != ISD::SIGN_EXTEND_VECTOR_INREG && 21084 Opcode != ISD::ZERO_EXTEND_VECTOR_INREG) 21085 return SDValue(); 21086 21087 SDValue N00 = N0.getOperand(0); 21088 ArrayRef<int> Mask = SVN->getMask(); 21089 unsigned NumElts = VT.getVectorNumElements(); 21090 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 21091 unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits(); 21092 unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits(); 21093 21094 if (ExtDstSizeInBits % ExtSrcSizeInBits != 0) 21095 return SDValue(); 21096 unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits; 21097 21098 // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1> 21099 // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1> 21100 // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1> 21101 auto isTruncate = [&Mask, &NumElts](unsigned Scale) { 21102 for (unsigned i = 0; i != NumElts; ++i) { 21103 if (Mask[i] < 0) 21104 continue; 21105 if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale)) 21106 continue; 21107 return false; 21108 } 21109 return true; 21110 }; 21111 21112 // At the moment we just handle the case where we've truncated back to the 21113 // same size as before the extension. 21114 // TODO: handle more extension/truncation cases as cases arise. 21115 if (EltSizeInBits != ExtSrcSizeInBits) 21116 return SDValue(); 21117 21118 // We can remove *extend_vector_inreg only if the truncation happens at 21119 // the same scale as the extension. 21120 if (isTruncate(ExtScale)) 21121 return DAG.getBitcast(VT, N00); 21122 21123 return SDValue(); 21124 } 21125 21126 // Combine shuffles of splat-shuffles of the form: 21127 // shuffle (shuffle V, undef, splat-mask), undef, M 21128 // If splat-mask contains undef elements, we need to be careful about 21129 // introducing undef's in the folded mask which are not the result of composing 21130 // the masks of the shuffles. 21131 static SDValue combineShuffleOfSplatVal(ShuffleVectorSDNode *Shuf, 21132 SelectionDAG &DAG) { 21133 if (!Shuf->getOperand(1).isUndef()) 21134 return SDValue(); 21135 auto *Splat = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0)); 21136 if (!Splat || !Splat->isSplat()) 21137 return SDValue(); 21138 21139 ArrayRef<int> ShufMask = Shuf->getMask(); 21140 ArrayRef<int> SplatMask = Splat->getMask(); 21141 assert(ShufMask.size() == SplatMask.size() && "Mask length mismatch"); 21142 21143 // Prefer simplifying to the splat-shuffle, if possible. This is legal if 21144 // every undef mask element in the splat-shuffle has a corresponding undef 21145 // element in the user-shuffle's mask or if the composition of mask elements 21146 // would result in undef. 21147 // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask): 21148 // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u] 21149 // In this case it is not legal to simplify to the splat-shuffle because we 21150 // may be exposing the users of the shuffle an undef element at index 1 21151 // which was not there before the combine. 21152 // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u] 21153 // In this case the composition of masks yields SplatMask, so it's ok to 21154 // simplify to the splat-shuffle. 21155 // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u] 21156 // In this case the composed mask includes all undef elements of SplatMask 21157 // and in addition sets element zero to undef. It is safe to simplify to 21158 // the splat-shuffle. 21159 auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask, 21160 ArrayRef<int> SplatMask) { 21161 for (unsigned i = 0, e = UserMask.size(); i != e; ++i) 21162 if (UserMask[i] != -1 && SplatMask[i] == -1 && 21163 SplatMask[UserMask[i]] != -1) 21164 return false; 21165 return true; 21166 }; 21167 if (CanSimplifyToExistingSplat(ShufMask, SplatMask)) 21168 return Shuf->getOperand(0); 21169 21170 // Create a new shuffle with a mask that is composed of the two shuffles' 21171 // masks. 21172 SmallVector<int, 32> NewMask; 21173 for (int Idx : ShufMask) 21174 NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]); 21175 21176 return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat), 21177 Splat->getOperand(0), Splat->getOperand(1), 21178 NewMask); 21179 } 21180 21181 /// Combine shuffle of shuffle of the form: 21182 /// shuf (shuf X, undef, InnerMask), undef, OuterMask --> splat X 21183 static SDValue formSplatFromShuffles(ShuffleVectorSDNode *OuterShuf, 21184 SelectionDAG &DAG) { 21185 if (!OuterShuf->getOperand(1).isUndef()) 21186 return SDValue(); 21187 auto *InnerShuf = dyn_cast<ShuffleVectorSDNode>(OuterShuf->getOperand(0)); 21188 if (!InnerShuf || !InnerShuf->getOperand(1).isUndef()) 21189 return SDValue(); 21190 21191 ArrayRef<int> OuterMask = OuterShuf->getMask(); 21192 ArrayRef<int> InnerMask = InnerShuf->getMask(); 21193 unsigned NumElts = OuterMask.size(); 21194 assert(NumElts == InnerMask.size() && "Mask length mismatch"); 21195 SmallVector<int, 32> CombinedMask(NumElts, -1); 21196 int SplatIndex = -1; 21197 for (unsigned i = 0; i != NumElts; ++i) { 21198 // Undef lanes remain undef. 21199 int OuterMaskElt = OuterMask[i]; 21200 if (OuterMaskElt == -1) 21201 continue; 21202 21203 // Peek through the shuffle masks to get the underlying source element. 21204 int InnerMaskElt = InnerMask[OuterMaskElt]; 21205 if (InnerMaskElt == -1) 21206 continue; 21207 21208 // Initialize the splatted element. 21209 if (SplatIndex == -1) 21210 SplatIndex = InnerMaskElt; 21211 21212 // Non-matching index - this is not a splat. 21213 if (SplatIndex != InnerMaskElt) 21214 return SDValue(); 21215 21216 CombinedMask[i] = InnerMaskElt; 21217 } 21218 assert((all_of(CombinedMask, [](int M) { return M == -1; }) || 21219 getSplatIndex(CombinedMask) != -1) && 21220 "Expected a splat mask"); 21221 21222 // TODO: The transform may be a win even if the mask is not legal. 21223 EVT VT = OuterShuf->getValueType(0); 21224 assert(VT == InnerShuf->getValueType(0) && "Expected matching shuffle types"); 21225 if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(CombinedMask, VT)) 21226 return SDValue(); 21227 21228 return DAG.getVectorShuffle(VT, SDLoc(OuterShuf), InnerShuf->getOperand(0), 21229 InnerShuf->getOperand(1), CombinedMask); 21230 } 21231 21232 /// If the shuffle mask is taking exactly one element from the first vector 21233 /// operand and passing through all other elements from the second vector 21234 /// operand, return the index of the mask element that is choosing an element 21235 /// from the first operand. Otherwise, return -1. 21236 static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) { 21237 int MaskSize = Mask.size(); 21238 int EltFromOp0 = -1; 21239 // TODO: This does not match if there are undef elements in the shuffle mask. 21240 // Should we ignore undefs in the shuffle mask instead? The trade-off is 21241 // removing an instruction (a shuffle), but losing the knowledge that some 21242 // vector lanes are not needed. 21243 for (int i = 0; i != MaskSize; ++i) { 21244 if (Mask[i] >= 0 && Mask[i] < MaskSize) { 21245 // We're looking for a shuffle of exactly one element from operand 0. 21246 if (EltFromOp0 != -1) 21247 return -1; 21248 EltFromOp0 = i; 21249 } else if (Mask[i] != i + MaskSize) { 21250 // Nothing from operand 1 can change lanes. 21251 return -1; 21252 } 21253 } 21254 return EltFromOp0; 21255 } 21256 21257 /// If a shuffle inserts exactly one element from a source vector operand into 21258 /// another vector operand and we can access the specified element as a scalar, 21259 /// then we can eliminate the shuffle. 21260 static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf, 21261 SelectionDAG &DAG) { 21262 // First, check if we are taking one element of a vector and shuffling that 21263 // element into another vector. 21264 ArrayRef<int> Mask = Shuf->getMask(); 21265 SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end()); 21266 SDValue Op0 = Shuf->getOperand(0); 21267 SDValue Op1 = Shuf->getOperand(1); 21268 int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask); 21269 if (ShufOp0Index == -1) { 21270 // Commute mask and check again. 21271 ShuffleVectorSDNode::commuteMask(CommutedMask); 21272 ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask); 21273 if (ShufOp0Index == -1) 21274 return SDValue(); 21275 // Commute operands to match the commuted shuffle mask. 21276 std::swap(Op0, Op1); 21277 Mask = CommutedMask; 21278 } 21279 21280 // The shuffle inserts exactly one element from operand 0 into operand 1. 21281 // Now see if we can access that element as a scalar via a real insert element 21282 // instruction. 21283 // TODO: We can try harder to locate the element as a scalar. Examples: it 21284 // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant. 21285 assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() && 21286 "Shuffle mask value must be from operand 0"); 21287 if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT) 21288 return SDValue(); 21289 21290 auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2)); 21291 if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index]) 21292 return SDValue(); 21293 21294 // There's an existing insertelement with constant insertion index, so we 21295 // don't need to check the legality/profitability of a replacement operation 21296 // that differs at most in the constant value. The target should be able to 21297 // lower any of those in a similar way. If not, legalization will expand this 21298 // to a scalar-to-vector plus shuffle. 21299 // 21300 // Note that the shuffle may move the scalar from the position that the insert 21301 // element used. Therefore, our new insert element occurs at the shuffle's 21302 // mask index value, not the insert's index value. 21303 // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C' 21304 SDValue NewInsIndex = DAG.getVectorIdxConstant(ShufOp0Index, SDLoc(Shuf)); 21305 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(), 21306 Op1, Op0.getOperand(1), NewInsIndex); 21307 } 21308 21309 /// If we have a unary shuffle of a shuffle, see if it can be folded away 21310 /// completely. This has the potential to lose undef knowledge because the first 21311 /// shuffle may not have an undef mask element where the second one does. So 21312 /// only call this after doing simplifications based on demanded elements. 21313 static SDValue simplifyShuffleOfShuffle(ShuffleVectorSDNode *Shuf) { 21314 // shuf (shuf0 X, Y, Mask0), undef, Mask 21315 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0)); 21316 if (!Shuf0 || !Shuf->getOperand(1).isUndef()) 21317 return SDValue(); 21318 21319 ArrayRef<int> Mask = Shuf->getMask(); 21320 ArrayRef<int> Mask0 = Shuf0->getMask(); 21321 for (int i = 0, e = (int)Mask.size(); i != e; ++i) { 21322 // Ignore undef elements. 21323 if (Mask[i] == -1) 21324 continue; 21325 assert(Mask[i] >= 0 && Mask[i] < e && "Unexpected shuffle mask value"); 21326 21327 // Is the element of the shuffle operand chosen by this shuffle the same as 21328 // the element chosen by the shuffle operand itself? 21329 if (Mask0[Mask[i]] != Mask0[i]) 21330 return SDValue(); 21331 } 21332 // Every element of this shuffle is identical to the result of the previous 21333 // shuffle, so we can replace this value. 21334 return Shuf->getOperand(0); 21335 } 21336 21337 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) { 21338 EVT VT = N->getValueType(0); 21339 unsigned NumElts = VT.getVectorNumElements(); 21340 21341 SDValue N0 = N->getOperand(0); 21342 SDValue N1 = N->getOperand(1); 21343 21344 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG"); 21345 21346 // Canonicalize shuffle undef, undef -> undef 21347 if (N0.isUndef() && N1.isUndef()) 21348 return DAG.getUNDEF(VT); 21349 21350 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 21351 21352 // Canonicalize shuffle v, v -> v, undef 21353 if (N0 == N1) 21354 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT), 21355 createUnaryMask(SVN->getMask(), NumElts)); 21356 21357 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask. 21358 if (N0.isUndef()) 21359 return DAG.getCommutedVectorShuffle(*SVN); 21360 21361 // Remove references to rhs if it is undef 21362 if (N1.isUndef()) { 21363 bool Changed = false; 21364 SmallVector<int, 8> NewMask; 21365 for (unsigned i = 0; i != NumElts; ++i) { 21366 int Idx = SVN->getMaskElt(i); 21367 if (Idx >= (int)NumElts) { 21368 Idx = -1; 21369 Changed = true; 21370 } 21371 NewMask.push_back(Idx); 21372 } 21373 if (Changed) 21374 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask); 21375 } 21376 21377 if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG)) 21378 return InsElt; 21379 21380 // A shuffle of a single vector that is a splatted value can always be folded. 21381 if (SDValue V = combineShuffleOfSplatVal(SVN, DAG)) 21382 return V; 21383 21384 if (SDValue V = formSplatFromShuffles(SVN, DAG)) 21385 return V; 21386 21387 // If it is a splat, check if the argument vector is another splat or a 21388 // build_vector. 21389 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) { 21390 int SplatIndex = SVN->getSplatIndex(); 21391 if (N0.hasOneUse() && TLI.isExtractVecEltCheap(VT, SplatIndex) && 21392 TLI.isBinOp(N0.getOpcode()) && N0.getNode()->getNumValues() == 1) { 21393 // splat (vector_bo L, R), Index --> 21394 // splat (scalar_bo (extelt L, Index), (extelt R, Index)) 21395 SDValue L = N0.getOperand(0), R = N0.getOperand(1); 21396 SDLoc DL(N); 21397 EVT EltVT = VT.getScalarType(); 21398 SDValue Index = DAG.getVectorIdxConstant(SplatIndex, DL); 21399 SDValue ExtL = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, L, Index); 21400 SDValue ExtR = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, R, Index); 21401 SDValue NewBO = DAG.getNode(N0.getOpcode(), DL, EltVT, ExtL, ExtR, 21402 N0.getNode()->getFlags()); 21403 SDValue Insert = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, NewBO); 21404 SmallVector<int, 16> ZeroMask(VT.getVectorNumElements(), 0); 21405 return DAG.getVectorShuffle(VT, DL, Insert, DAG.getUNDEF(VT), ZeroMask); 21406 } 21407 21408 // If this is a bit convert that changes the element type of the vector but 21409 // not the number of vector elements, look through it. Be careful not to 21410 // look though conversions that change things like v4f32 to v2f64. 21411 SDNode *V = N0.getNode(); 21412 if (V->getOpcode() == ISD::BITCAST) { 21413 SDValue ConvInput = V->getOperand(0); 21414 if (ConvInput.getValueType().isVector() && 21415 ConvInput.getValueType().getVectorNumElements() == NumElts) 21416 V = ConvInput.getNode(); 21417 } 21418 21419 if (V->getOpcode() == ISD::BUILD_VECTOR) { 21420 assert(V->getNumOperands() == NumElts && 21421 "BUILD_VECTOR has wrong number of operands"); 21422 SDValue Base; 21423 bool AllSame = true; 21424 for (unsigned i = 0; i != NumElts; ++i) { 21425 if (!V->getOperand(i).isUndef()) { 21426 Base = V->getOperand(i); 21427 break; 21428 } 21429 } 21430 // Splat of <u, u, u, u>, return <u, u, u, u> 21431 if (!Base.getNode()) 21432 return N0; 21433 for (unsigned i = 0; i != NumElts; ++i) { 21434 if (V->getOperand(i) != Base) { 21435 AllSame = false; 21436 break; 21437 } 21438 } 21439 // Splat of <x, x, x, x>, return <x, x, x, x> 21440 if (AllSame) 21441 return N0; 21442 21443 // Canonicalize any other splat as a build_vector. 21444 SDValue Splatted = V->getOperand(SplatIndex); 21445 SmallVector<SDValue, 8> Ops(NumElts, Splatted); 21446 SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops); 21447 21448 // We may have jumped through bitcasts, so the type of the 21449 // BUILD_VECTOR may not match the type of the shuffle. 21450 if (V->getValueType(0) != VT) 21451 NewBV = DAG.getBitcast(VT, NewBV); 21452 return NewBV; 21453 } 21454 } 21455 21456 // Simplify source operands based on shuffle mask. 21457 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 21458 return SDValue(N, 0); 21459 21460 // This is intentionally placed after demanded elements simplification because 21461 // it could eliminate knowledge of undef elements created by this shuffle. 21462 if (SDValue ShufOp = simplifyShuffleOfShuffle(SVN)) 21463 return ShufOp; 21464 21465 // Match shuffles that can be converted to any_vector_extend_in_reg. 21466 if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations)) 21467 return V; 21468 21469 // Combine "truncate_vector_in_reg" style shuffles. 21470 if (SDValue V = combineTruncationShuffle(SVN, DAG)) 21471 return V; 21472 21473 if (N0.getOpcode() == ISD::CONCAT_VECTORS && 21474 Level < AfterLegalizeVectorOps && 21475 (N1.isUndef() || 21476 (N1.getOpcode() == ISD::CONCAT_VECTORS && 21477 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) { 21478 if (SDValue V = partitionShuffleOfConcats(N, DAG)) 21479 return V; 21480 } 21481 21482 // A shuffle of a concat of the same narrow vector can be reduced to use 21483 // only low-half elements of a concat with undef: 21484 // shuf (concat X, X), undef, Mask --> shuf (concat X, undef), undef, Mask' 21485 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N1.isUndef() && 21486 N0.getNumOperands() == 2 && 21487 N0.getOperand(0) == N0.getOperand(1)) { 21488 int HalfNumElts = (int)NumElts / 2; 21489 SmallVector<int, 8> NewMask; 21490 for (unsigned i = 0; i != NumElts; ++i) { 21491 int Idx = SVN->getMaskElt(i); 21492 if (Idx >= HalfNumElts) { 21493 assert(Idx < (int)NumElts && "Shuffle mask chooses undef op"); 21494 Idx -= HalfNumElts; 21495 } 21496 NewMask.push_back(Idx); 21497 } 21498 if (TLI.isShuffleMaskLegal(NewMask, VT)) { 21499 SDValue UndefVec = DAG.getUNDEF(N0.getOperand(0).getValueType()); 21500 SDValue NewCat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, 21501 N0.getOperand(0), UndefVec); 21502 return DAG.getVectorShuffle(VT, SDLoc(N), NewCat, N1, NewMask); 21503 } 21504 } 21505 21506 // See if we can replace a shuffle with an insert_subvector. 21507 // e.g. v2i32 into v8i32: 21508 // shuffle(lhs,concat(rhs0,rhs1,rhs2,rhs3),0,1,2,3,10,11,6,7). 21509 // --> insert_subvector(lhs,rhs1,4). 21510 if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT) && 21511 TLI.isOperationLegalOrCustom(ISD::INSERT_SUBVECTOR, VT)) { 21512 auto ShuffleToInsert = [&](SDValue LHS, SDValue RHS, ArrayRef<int> Mask) { 21513 // Ensure RHS subvectors are legal. 21514 assert(RHS.getOpcode() == ISD::CONCAT_VECTORS && "Can't find subvectors"); 21515 EVT SubVT = RHS.getOperand(0).getValueType(); 21516 int NumSubVecs = RHS.getNumOperands(); 21517 int NumSubElts = SubVT.getVectorNumElements(); 21518 assert((NumElts % NumSubElts) == 0 && "Subvector mismatch"); 21519 if (!TLI.isTypeLegal(SubVT)) 21520 return SDValue(); 21521 21522 // Don't bother if we have an unary shuffle (matches undef + LHS elts). 21523 if (all_of(Mask, [NumElts](int M) { return M < (int)NumElts; })) 21524 return SDValue(); 21525 21526 // Search [NumSubElts] spans for RHS sequence. 21527 // TODO: Can we avoid nested loops to increase performance? 21528 SmallVector<int> InsertionMask(NumElts); 21529 for (int SubVec = 0; SubVec != NumSubVecs; ++SubVec) { 21530 for (int SubIdx = 0; SubIdx != (int)NumElts; SubIdx += NumSubElts) { 21531 // Reset mask to identity. 21532 std::iota(InsertionMask.begin(), InsertionMask.end(), 0); 21533 21534 // Add subvector insertion. 21535 std::iota(InsertionMask.begin() + SubIdx, 21536 InsertionMask.begin() + SubIdx + NumSubElts, 21537 NumElts + (SubVec * NumSubElts)); 21538 21539 // See if the shuffle mask matches the reference insertion mask. 21540 bool MatchingShuffle = true; 21541 for (int i = 0; i != (int)NumElts; ++i) { 21542 int ExpectIdx = InsertionMask[i]; 21543 int ActualIdx = Mask[i]; 21544 if (0 <= ActualIdx && ExpectIdx != ActualIdx) { 21545 MatchingShuffle = false; 21546 break; 21547 } 21548 } 21549 21550 if (MatchingShuffle) 21551 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, LHS, 21552 RHS.getOperand(SubVec), 21553 DAG.getVectorIdxConstant(SubIdx, SDLoc(N))); 21554 } 21555 } 21556 return SDValue(); 21557 }; 21558 ArrayRef<int> Mask = SVN->getMask(); 21559 if (N1.getOpcode() == ISD::CONCAT_VECTORS) 21560 if (SDValue InsertN1 = ShuffleToInsert(N0, N1, Mask)) 21561 return InsertN1; 21562 if (N0.getOpcode() == ISD::CONCAT_VECTORS) { 21563 SmallVector<int> CommuteMask(Mask.begin(), Mask.end()); 21564 ShuffleVectorSDNode::commuteMask(CommuteMask); 21565 if (SDValue InsertN0 = ShuffleToInsert(N1, N0, CommuteMask)) 21566 return InsertN0; 21567 } 21568 } 21569 21570 // Attempt to combine a shuffle of 2 inputs of 'scalar sources' - 21571 // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR. 21572 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) 21573 if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI)) 21574 return Res; 21575 21576 // If this shuffle only has a single input that is a bitcasted shuffle, 21577 // attempt to merge the 2 shuffles and suitably bitcast the inputs/output 21578 // back to their original types. 21579 if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() && 21580 N1.isUndef() && Level < AfterLegalizeVectorOps && 21581 TLI.isTypeLegal(VT)) { 21582 21583 SDValue BC0 = peekThroughOneUseBitcasts(N0); 21584 if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) { 21585 EVT SVT = VT.getScalarType(); 21586 EVT InnerVT = BC0->getValueType(0); 21587 EVT InnerSVT = InnerVT.getScalarType(); 21588 21589 // Determine which shuffle works with the smaller scalar type. 21590 EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT; 21591 EVT ScaleSVT = ScaleVT.getScalarType(); 21592 21593 if (TLI.isTypeLegal(ScaleVT) && 21594 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) && 21595 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) { 21596 int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 21597 int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits(); 21598 21599 // Scale the shuffle masks to the smaller scalar type. 21600 ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0); 21601 SmallVector<int, 8> InnerMask; 21602 SmallVector<int, 8> OuterMask; 21603 narrowShuffleMaskElts(InnerScale, InnerSVN->getMask(), InnerMask); 21604 narrowShuffleMaskElts(OuterScale, SVN->getMask(), OuterMask); 21605 21606 // Merge the shuffle masks. 21607 SmallVector<int, 8> NewMask; 21608 for (int M : OuterMask) 21609 NewMask.push_back(M < 0 ? -1 : InnerMask[M]); 21610 21611 // Test for shuffle mask legality over both commutations. 21612 SDValue SV0 = BC0->getOperand(0); 21613 SDValue SV1 = BC0->getOperand(1); 21614 bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 21615 if (!LegalMask) { 21616 std::swap(SV0, SV1); 21617 ShuffleVectorSDNode::commuteMask(NewMask); 21618 LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT); 21619 } 21620 21621 if (LegalMask) { 21622 SV0 = DAG.getBitcast(ScaleVT, SV0); 21623 SV1 = DAG.getBitcast(ScaleVT, SV1); 21624 return DAG.getBitcast( 21625 VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask)); 21626 } 21627 } 21628 } 21629 } 21630 21631 // Compute the combined shuffle mask for a shuffle with SV0 as the first 21632 // operand, and SV1 as the second operand. 21633 // i.e. Merge SVN(OtherSVN, N1) -> shuffle(SV0, SV1, Mask) iff Commute = false 21634 // Merge SVN(N1, OtherSVN) -> shuffle(SV0, SV1, Mask') iff Commute = true 21635 auto MergeInnerShuffle = 21636 [NumElts, &VT](bool Commute, ShuffleVectorSDNode *SVN, 21637 ShuffleVectorSDNode *OtherSVN, SDValue N1, 21638 const TargetLowering &TLI, SDValue &SV0, SDValue &SV1, 21639 SmallVectorImpl<int> &Mask) -> bool { 21640 // Don't try to fold splats; they're likely to simplify somehow, or they 21641 // might be free. 21642 if (OtherSVN->isSplat()) 21643 return false; 21644 21645 SV0 = SV1 = SDValue(); 21646 Mask.clear(); 21647 21648 for (unsigned i = 0; i != NumElts; ++i) { 21649 int Idx = SVN->getMaskElt(i); 21650 if (Idx < 0) { 21651 // Propagate Undef. 21652 Mask.push_back(Idx); 21653 continue; 21654 } 21655 21656 if (Commute) 21657 Idx = (Idx < (int)NumElts) ? (Idx + NumElts) : (Idx - NumElts); 21658 21659 SDValue CurrentVec; 21660 if (Idx < (int)NumElts) { 21661 // This shuffle index refers to the inner shuffle N0. Lookup the inner 21662 // shuffle mask to identify which vector is actually referenced. 21663 Idx = OtherSVN->getMaskElt(Idx); 21664 if (Idx < 0) { 21665 // Propagate Undef. 21666 Mask.push_back(Idx); 21667 continue; 21668 } 21669 CurrentVec = (Idx < (int)NumElts) ? OtherSVN->getOperand(0) 21670 : OtherSVN->getOperand(1); 21671 } else { 21672 // This shuffle index references an element within N1. 21673 CurrentVec = N1; 21674 } 21675 21676 // Simple case where 'CurrentVec' is UNDEF. 21677 if (CurrentVec.isUndef()) { 21678 Mask.push_back(-1); 21679 continue; 21680 } 21681 21682 // Canonicalize the shuffle index. We don't know yet if CurrentVec 21683 // will be the first or second operand of the combined shuffle. 21684 Idx = Idx % NumElts; 21685 if (!SV0.getNode() || SV0 == CurrentVec) { 21686 // Ok. CurrentVec is the left hand side. 21687 // Update the mask accordingly. 21688 SV0 = CurrentVec; 21689 Mask.push_back(Idx); 21690 continue; 21691 } 21692 if (!SV1.getNode() || SV1 == CurrentVec) { 21693 // Ok. CurrentVec is the right hand side. 21694 // Update the mask accordingly. 21695 SV1 = CurrentVec; 21696 Mask.push_back(Idx + NumElts); 21697 continue; 21698 } 21699 21700 // Last chance - see if the vector is another shuffle and if it 21701 // uses one of the existing candidate shuffle ops. 21702 if (auto *CurrentSVN = dyn_cast<ShuffleVectorSDNode>(CurrentVec)) { 21703 int InnerIdx = CurrentSVN->getMaskElt(Idx); 21704 if (InnerIdx < 0) { 21705 Mask.push_back(-1); 21706 continue; 21707 } 21708 SDValue InnerVec = (InnerIdx < (int)NumElts) 21709 ? CurrentSVN->getOperand(0) 21710 : CurrentSVN->getOperand(1); 21711 if (InnerVec.isUndef()) { 21712 Mask.push_back(-1); 21713 continue; 21714 } 21715 InnerIdx %= NumElts; 21716 if (InnerVec == SV0) { 21717 Mask.push_back(InnerIdx); 21718 continue; 21719 } 21720 if (InnerVec == SV1) { 21721 Mask.push_back(InnerIdx + NumElts); 21722 continue; 21723 } 21724 } 21725 21726 // Bail out if we cannot convert the shuffle pair into a single shuffle. 21727 return false; 21728 } 21729 21730 if (llvm::all_of(Mask, [](int M) { return M < 0; })) 21731 return true; 21732 21733 // Avoid introducing shuffles with illegal mask. 21734 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 21735 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 21736 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 21737 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2) 21738 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2) 21739 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2) 21740 if (TLI.isShuffleMaskLegal(Mask, VT)) 21741 return true; 21742 21743 std::swap(SV0, SV1); 21744 ShuffleVectorSDNode::commuteMask(Mask); 21745 return TLI.isShuffleMaskLegal(Mask, VT); 21746 }; 21747 21748 if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) { 21749 // Canonicalize shuffles according to rules: 21750 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A) 21751 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B) 21752 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B) 21753 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && 21754 N0.getOpcode() != ISD::VECTOR_SHUFFLE) { 21755 // The incoming shuffle must be of the same type as the result of the 21756 // current shuffle. 21757 assert(N1->getOperand(0).getValueType() == VT && 21758 "Shuffle types don't match"); 21759 21760 SDValue SV0 = N1->getOperand(0); 21761 SDValue SV1 = N1->getOperand(1); 21762 bool HasSameOp0 = N0 == SV0; 21763 bool IsSV1Undef = SV1.isUndef(); 21764 if (HasSameOp0 || IsSV1Undef || N0 == SV1) 21765 // Commute the operands of this shuffle so merging below will trigger. 21766 return DAG.getCommutedVectorShuffle(*SVN); 21767 } 21768 21769 // Canonicalize splat shuffles to the RHS to improve merging below. 21770 // shuffle(splat(A,u), shuffle(C,D)) -> shuffle'(shuffle(C,D), splat(A,u)) 21771 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && 21772 N1.getOpcode() == ISD::VECTOR_SHUFFLE && 21773 cast<ShuffleVectorSDNode>(N0)->isSplat() && 21774 !cast<ShuffleVectorSDNode>(N1)->isSplat()) { 21775 return DAG.getCommutedVectorShuffle(*SVN); 21776 } 21777 21778 // Try to fold according to rules: 21779 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2) 21780 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2) 21781 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2) 21782 // Don't try to fold shuffles with illegal type. 21783 // Only fold if this shuffle is the only user of the other shuffle. 21784 // Try matching shuffle(C,shuffle(A,B)) commutted patterns as well. 21785 for (int i = 0; i != 2; ++i) { 21786 if (N->getOperand(i).getOpcode() == ISD::VECTOR_SHUFFLE && 21787 N->isOnlyUserOf(N->getOperand(i).getNode())) { 21788 // The incoming shuffle must be of the same type as the result of the 21789 // current shuffle. 21790 auto *OtherSV = cast<ShuffleVectorSDNode>(N->getOperand(i)); 21791 assert(OtherSV->getOperand(0).getValueType() == VT && 21792 "Shuffle types don't match"); 21793 21794 SDValue SV0, SV1; 21795 SmallVector<int, 4> Mask; 21796 if (MergeInnerShuffle(i != 0, SVN, OtherSV, N->getOperand(1 - i), TLI, 21797 SV0, SV1, Mask)) { 21798 // Check if all indices in Mask are Undef. In case, propagate Undef. 21799 if (llvm::all_of(Mask, [](int M) { return M < 0; })) 21800 return DAG.getUNDEF(VT); 21801 21802 return DAG.getVectorShuffle(VT, SDLoc(N), 21803 SV0 ? SV0 : DAG.getUNDEF(VT), 21804 SV1 ? SV1 : DAG.getUNDEF(VT), Mask); 21805 } 21806 } 21807 } 21808 21809 // Merge shuffles through binops if we are able to merge it with at least 21810 // one other shuffles. 21811 // shuffle(bop(shuffle(x,y),shuffle(z,w)),undef) 21812 // shuffle(bop(shuffle(x,y),shuffle(z,w)),bop(shuffle(a,b),shuffle(c,d))) 21813 unsigned SrcOpcode = N0.getOpcode(); 21814 if (TLI.isBinOp(SrcOpcode) && N->isOnlyUserOf(N0.getNode()) && 21815 (N1.isUndef() || 21816 (SrcOpcode == N1.getOpcode() && N->isOnlyUserOf(N1.getNode())))) { 21817 // Get binop source ops, or just pass on the undef. 21818 SDValue Op00 = N0.getOperand(0); 21819 SDValue Op01 = N0.getOperand(1); 21820 SDValue Op10 = N1.isUndef() ? N1 : N1.getOperand(0); 21821 SDValue Op11 = N1.isUndef() ? N1 : N1.getOperand(1); 21822 // TODO: We might be able to relax the VT check but we don't currently 21823 // have any isBinOp() that has different result/ops VTs so play safe until 21824 // we have test coverage. 21825 if (Op00.getValueType() == VT && Op10.getValueType() == VT && 21826 Op01.getValueType() == VT && Op11.getValueType() == VT && 21827 (Op00.getOpcode() == ISD::VECTOR_SHUFFLE || 21828 Op10.getOpcode() == ISD::VECTOR_SHUFFLE || 21829 Op01.getOpcode() == ISD::VECTOR_SHUFFLE || 21830 Op11.getOpcode() == ISD::VECTOR_SHUFFLE)) { 21831 auto CanMergeInnerShuffle = [&](SDValue &SV0, SDValue &SV1, 21832 SmallVectorImpl<int> &Mask, bool LeftOp, 21833 bool Commute) { 21834 SDValue InnerN = Commute ? N1 : N0; 21835 SDValue Op0 = LeftOp ? Op00 : Op01; 21836 SDValue Op1 = LeftOp ? Op10 : Op11; 21837 if (Commute) 21838 std::swap(Op0, Op1); 21839 // Only accept the merged shuffle if we don't introduce undef elements, 21840 // or the inner shuffle already contained undef elements. 21841 auto *SVN0 = dyn_cast<ShuffleVectorSDNode>(Op0); 21842 return SVN0 && InnerN->isOnlyUserOf(SVN0) && 21843 MergeInnerShuffle(Commute, SVN, SVN0, Op1, TLI, SV0, SV1, 21844 Mask) && 21845 (llvm::any_of(SVN0->getMask(), [](int M) { return M < 0; }) || 21846 llvm::none_of(Mask, [](int M) { return M < 0; })); 21847 }; 21848 21849 // Ensure we don't increase the number of shuffles - we must merge a 21850 // shuffle from at least one of the LHS and RHS ops. 21851 bool MergedLeft = false; 21852 SDValue LeftSV0, LeftSV1; 21853 SmallVector<int, 4> LeftMask; 21854 if (CanMergeInnerShuffle(LeftSV0, LeftSV1, LeftMask, true, false) || 21855 CanMergeInnerShuffle(LeftSV0, LeftSV1, LeftMask, true, true)) { 21856 MergedLeft = true; 21857 } else { 21858 LeftMask.assign(SVN->getMask().begin(), SVN->getMask().end()); 21859 LeftSV0 = Op00, LeftSV1 = Op10; 21860 } 21861 21862 bool MergedRight = false; 21863 SDValue RightSV0, RightSV1; 21864 SmallVector<int, 4> RightMask; 21865 if (CanMergeInnerShuffle(RightSV0, RightSV1, RightMask, false, false) || 21866 CanMergeInnerShuffle(RightSV0, RightSV1, RightMask, false, true)) { 21867 MergedRight = true; 21868 } else { 21869 RightMask.assign(SVN->getMask().begin(), SVN->getMask().end()); 21870 RightSV0 = Op01, RightSV1 = Op11; 21871 } 21872 21873 if (MergedLeft || MergedRight) { 21874 SDLoc DL(N); 21875 SDValue LHS = DAG.getVectorShuffle( 21876 VT, DL, LeftSV0 ? LeftSV0 : DAG.getUNDEF(VT), 21877 LeftSV1 ? LeftSV1 : DAG.getUNDEF(VT), LeftMask); 21878 SDValue RHS = DAG.getVectorShuffle( 21879 VT, DL, RightSV0 ? RightSV0 : DAG.getUNDEF(VT), 21880 RightSV1 ? RightSV1 : DAG.getUNDEF(VT), RightMask); 21881 return DAG.getNode(SrcOpcode, DL, VT, LHS, RHS); 21882 } 21883 } 21884 } 21885 } 21886 21887 if (SDValue V = foldShuffleOfConcatUndefs(SVN, DAG)) 21888 return V; 21889 21890 return SDValue(); 21891 } 21892 21893 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) { 21894 SDValue InVal = N->getOperand(0); 21895 EVT VT = N->getValueType(0); 21896 21897 // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern 21898 // with a VECTOR_SHUFFLE and possible truncate. 21899 if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 21900 VT.isFixedLengthVector() && 21901 InVal->getOperand(0).getValueType().isFixedLengthVector()) { 21902 SDValue InVec = InVal->getOperand(0); 21903 SDValue EltNo = InVal->getOperand(1); 21904 auto InVecT = InVec.getValueType(); 21905 if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) { 21906 SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1); 21907 int Elt = C0->getZExtValue(); 21908 NewMask[0] = Elt; 21909 // If we have an implict truncate do truncate here as long as it's legal. 21910 // if it's not legal, this should 21911 if (VT.getScalarType() != InVal.getValueType() && 21912 InVal.getValueType().isScalarInteger() && 21913 isTypeLegal(VT.getScalarType())) { 21914 SDValue Val = 21915 DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal); 21916 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val); 21917 } 21918 if (VT.getScalarType() == InVecT.getScalarType() && 21919 VT.getVectorNumElements() <= InVecT.getVectorNumElements()) { 21920 SDValue LegalShuffle = 21921 TLI.buildLegalVectorShuffle(InVecT, SDLoc(N), InVec, 21922 DAG.getUNDEF(InVecT), NewMask, DAG); 21923 if (LegalShuffle) { 21924 // If the initial vector is the correct size this shuffle is a 21925 // valid result. 21926 if (VT == InVecT) 21927 return LegalShuffle; 21928 // If not we must truncate the vector. 21929 if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) { 21930 SDValue ZeroIdx = DAG.getVectorIdxConstant(0, SDLoc(N)); 21931 EVT SubVT = EVT::getVectorVT(*DAG.getContext(), 21932 InVecT.getVectorElementType(), 21933 VT.getVectorNumElements()); 21934 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT, 21935 LegalShuffle, ZeroIdx); 21936 } 21937 } 21938 } 21939 } 21940 } 21941 21942 return SDValue(); 21943 } 21944 21945 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) { 21946 EVT VT = N->getValueType(0); 21947 SDValue N0 = N->getOperand(0); 21948 SDValue N1 = N->getOperand(1); 21949 SDValue N2 = N->getOperand(2); 21950 uint64_t InsIdx = N->getConstantOperandVal(2); 21951 21952 // If inserting an UNDEF, just return the original vector. 21953 if (N1.isUndef()) 21954 return N0; 21955 21956 // If this is an insert of an extracted vector into an undef vector, we can 21957 // just use the input to the extract. 21958 if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR && 21959 N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT) 21960 return N1.getOperand(0); 21961 21962 // If we are inserting a bitcast value into an undef, with the same 21963 // number of elements, just use the bitcast input of the extract. 21964 // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 -> 21965 // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2) 21966 if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST && 21967 N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR && 21968 N1.getOperand(0).getOperand(1) == N2 && 21969 N1.getOperand(0).getOperand(0).getValueType().getVectorElementCount() == 21970 VT.getVectorElementCount() && 21971 N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() == 21972 VT.getSizeInBits()) { 21973 return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0)); 21974 } 21975 21976 // If both N1 and N2 are bitcast values on which insert_subvector 21977 // would makes sense, pull the bitcast through. 21978 // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 -> 21979 // BITCAST (INSERT_SUBVECTOR N0 N1 N2) 21980 if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) { 21981 SDValue CN0 = N0.getOperand(0); 21982 SDValue CN1 = N1.getOperand(0); 21983 EVT CN0VT = CN0.getValueType(); 21984 EVT CN1VT = CN1.getValueType(); 21985 if (CN0VT.isVector() && CN1VT.isVector() && 21986 CN0VT.getVectorElementType() == CN1VT.getVectorElementType() && 21987 CN0VT.getVectorElementCount() == VT.getVectorElementCount()) { 21988 SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), 21989 CN0.getValueType(), CN0, CN1, N2); 21990 return DAG.getBitcast(VT, NewINSERT); 21991 } 21992 } 21993 21994 // Combine INSERT_SUBVECTORs where we are inserting to the same index. 21995 // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx ) 21996 // --> INSERT_SUBVECTOR( Vec, SubNew, Idx ) 21997 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && 21998 N0.getOperand(1).getValueType() == N1.getValueType() && 21999 N0.getOperand(2) == N2) 22000 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0), 22001 N1, N2); 22002 22003 // Eliminate an intermediate insert into an undef vector: 22004 // insert_subvector undef, (insert_subvector undef, X, 0), N2 --> 22005 // insert_subvector undef, X, N2 22006 if (N0.isUndef() && N1.getOpcode() == ISD::INSERT_SUBVECTOR && 22007 N1.getOperand(0).isUndef() && isNullConstant(N1.getOperand(2))) 22008 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0, 22009 N1.getOperand(1), N2); 22010 22011 // Push subvector bitcasts to the output, adjusting the index as we go. 22012 // insert_subvector(bitcast(v), bitcast(s), c1) 22013 // -> bitcast(insert_subvector(v, s, c2)) 22014 if ((N0.isUndef() || N0.getOpcode() == ISD::BITCAST) && 22015 N1.getOpcode() == ISD::BITCAST) { 22016 SDValue N0Src = peekThroughBitcasts(N0); 22017 SDValue N1Src = peekThroughBitcasts(N1); 22018 EVT N0SrcSVT = N0Src.getValueType().getScalarType(); 22019 EVT N1SrcSVT = N1Src.getValueType().getScalarType(); 22020 if ((N0.isUndef() || N0SrcSVT == N1SrcSVT) && 22021 N0Src.getValueType().isVector() && N1Src.getValueType().isVector()) { 22022 EVT NewVT; 22023 SDLoc DL(N); 22024 SDValue NewIdx; 22025 LLVMContext &Ctx = *DAG.getContext(); 22026 ElementCount NumElts = VT.getVectorElementCount(); 22027 unsigned EltSizeInBits = VT.getScalarSizeInBits(); 22028 if ((EltSizeInBits % N1SrcSVT.getSizeInBits()) == 0) { 22029 unsigned Scale = EltSizeInBits / N1SrcSVT.getSizeInBits(); 22030 NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, NumElts * Scale); 22031 NewIdx = DAG.getVectorIdxConstant(InsIdx * Scale, DL); 22032 } else if ((N1SrcSVT.getSizeInBits() % EltSizeInBits) == 0) { 22033 unsigned Scale = N1SrcSVT.getSizeInBits() / EltSizeInBits; 22034 if (NumElts.isKnownMultipleOf(Scale) && (InsIdx % Scale) == 0) { 22035 NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, 22036 NumElts.divideCoefficientBy(Scale)); 22037 NewIdx = DAG.getVectorIdxConstant(InsIdx / Scale, DL); 22038 } 22039 } 22040 if (NewIdx && hasOperation(ISD::INSERT_SUBVECTOR, NewVT)) { 22041 SDValue Res = DAG.getBitcast(NewVT, N0Src); 22042 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, NewVT, Res, N1Src, NewIdx); 22043 return DAG.getBitcast(VT, Res); 22044 } 22045 } 22046 } 22047 22048 // Canonicalize insert_subvector dag nodes. 22049 // Example: 22050 // (insert_subvector (insert_subvector A, Idx0), Idx1) 22051 // -> (insert_subvector (insert_subvector A, Idx1), Idx0) 22052 if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() && 22053 N1.getValueType() == N0.getOperand(1).getValueType()) { 22054 unsigned OtherIdx = N0.getConstantOperandVal(2); 22055 if (InsIdx < OtherIdx) { 22056 // Swap nodes. 22057 SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, 22058 N0.getOperand(0), N1, N2); 22059 AddToWorklist(NewOp.getNode()); 22060 return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()), 22061 VT, NewOp, N0.getOperand(1), N0.getOperand(2)); 22062 } 22063 } 22064 22065 // If the input vector is a concatenation, and the insert replaces 22066 // one of the pieces, we can optimize into a single concat_vectors. 22067 if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() && 22068 N0.getOperand(0).getValueType() == N1.getValueType() && 22069 N0.getOperand(0).getValueType().isScalableVector() == 22070 N1.getValueType().isScalableVector()) { 22071 unsigned Factor = N1.getValueType().getVectorMinNumElements(); 22072 SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end()); 22073 Ops[InsIdx / Factor] = N1; 22074 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops); 22075 } 22076 22077 // Simplify source operands based on insertion. 22078 if (SimplifyDemandedVectorElts(SDValue(N, 0))) 22079 return SDValue(N, 0); 22080 22081 return SDValue(); 22082 } 22083 22084 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) { 22085 SDValue N0 = N->getOperand(0); 22086 22087 // fold (fp_to_fp16 (fp16_to_fp op)) -> op 22088 if (N0->getOpcode() == ISD::FP16_TO_FP) 22089 return N0->getOperand(0); 22090 22091 return SDValue(); 22092 } 22093 22094 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) { 22095 SDValue N0 = N->getOperand(0); 22096 22097 // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op) 22098 if (!TLI.shouldKeepZExtForFP16Conv() && N0->getOpcode() == ISD::AND) { 22099 ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1)); 22100 if (AndConst && AndConst->getAPIntValue() == 0xffff) { 22101 return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0), 22102 N0.getOperand(0)); 22103 } 22104 } 22105 22106 return SDValue(); 22107 } 22108 22109 SDValue DAGCombiner::visitVECREDUCE(SDNode *N) { 22110 SDValue N0 = N->getOperand(0); 22111 EVT VT = N0.getValueType(); 22112 unsigned Opcode = N->getOpcode(); 22113 22114 // VECREDUCE over 1-element vector is just an extract. 22115 if (VT.getVectorElementCount().isScalar()) { 22116 SDLoc dl(N); 22117 SDValue Res = 22118 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getVectorElementType(), N0, 22119 DAG.getVectorIdxConstant(0, dl)); 22120 if (Res.getValueType() != N->getValueType(0)) 22121 Res = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Res); 22122 return Res; 22123 } 22124 22125 // On an boolean vector an and/or reduction is the same as a umin/umax 22126 // reduction. Convert them if the latter is legal while the former isn't. 22127 if (Opcode == ISD::VECREDUCE_AND || Opcode == ISD::VECREDUCE_OR) { 22128 unsigned NewOpcode = Opcode == ISD::VECREDUCE_AND 22129 ? ISD::VECREDUCE_UMIN : ISD::VECREDUCE_UMAX; 22130 if (!TLI.isOperationLegalOrCustom(Opcode, VT) && 22131 TLI.isOperationLegalOrCustom(NewOpcode, VT) && 22132 DAG.ComputeNumSignBits(N0) == VT.getScalarSizeInBits()) 22133 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), N0); 22134 } 22135 22136 return SDValue(); 22137 } 22138 22139 SDValue DAGCombiner::visitVPOp(SDNode *N) { 22140 // VP operations in which all vector elements are disabled - either by 22141 // determining that the mask is all false or that the EVL is 0 - can be 22142 // eliminated. 22143 bool AreAllEltsDisabled = false; 22144 if (auto EVLIdx = ISD::getVPExplicitVectorLengthIdx(N->getOpcode())) 22145 AreAllEltsDisabled |= isNullConstant(N->getOperand(*EVLIdx)); 22146 if (auto MaskIdx = ISD::getVPMaskIdx(N->getOpcode())) 22147 AreAllEltsDisabled |= 22148 ISD::isConstantSplatVectorAllZeros(N->getOperand(*MaskIdx).getNode()); 22149 22150 // This is the only generic VP combine we support for now. 22151 if (!AreAllEltsDisabled) 22152 return SDValue(); 22153 22154 // Binary operations can be replaced by UNDEF. 22155 if (ISD::isVPBinaryOp(N->getOpcode())) 22156 return DAG.getUNDEF(N->getValueType(0)); 22157 22158 // VP Memory operations can be replaced by either the chain (stores) or the 22159 // chain + undef (loads). 22160 if (const auto *MemSD = dyn_cast<MemSDNode>(N)) { 22161 if (MemSD->writeMem()) 22162 return MemSD->getChain(); 22163 return CombineTo(N, DAG.getUNDEF(N->getValueType(0)), MemSD->getChain()); 22164 } 22165 22166 // Reduction operations return the start operand when no elements are active. 22167 if (ISD::isVPReduction(N->getOpcode())) 22168 return N->getOperand(0); 22169 22170 return SDValue(); 22171 } 22172 22173 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle 22174 /// with the destination vector and a zero vector. 22175 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==> 22176 /// vector_shuffle V, Zero, <0, 4, 2, 4> 22177 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) { 22178 assert(N->getOpcode() == ISD::AND && "Unexpected opcode!"); 22179 22180 EVT VT = N->getValueType(0); 22181 SDValue LHS = N->getOperand(0); 22182 SDValue RHS = peekThroughBitcasts(N->getOperand(1)); 22183 SDLoc DL(N); 22184 22185 // Make sure we're not running after operation legalization where it 22186 // may have custom lowered the vector shuffles. 22187 if (LegalOperations) 22188 return SDValue(); 22189 22190 if (RHS.getOpcode() != ISD::BUILD_VECTOR) 22191 return SDValue(); 22192 22193 EVT RVT = RHS.getValueType(); 22194 unsigned NumElts = RHS.getNumOperands(); 22195 22196 // Attempt to create a valid clear mask, splitting the mask into 22197 // sub elements and checking to see if each is 22198 // all zeros or all ones - suitable for shuffle masking. 22199 auto BuildClearMask = [&](int Split) { 22200 int NumSubElts = NumElts * Split; 22201 int NumSubBits = RVT.getScalarSizeInBits() / Split; 22202 22203 SmallVector<int, 8> Indices; 22204 for (int i = 0; i != NumSubElts; ++i) { 22205 int EltIdx = i / Split; 22206 int SubIdx = i % Split; 22207 SDValue Elt = RHS.getOperand(EltIdx); 22208 // X & undef --> 0 (not undef). So this lane must be converted to choose 22209 // from the zero constant vector (same as if the element had all 0-bits). 22210 if (Elt.isUndef()) { 22211 Indices.push_back(i + NumSubElts); 22212 continue; 22213 } 22214 22215 APInt Bits; 22216 if (isa<ConstantSDNode>(Elt)) 22217 Bits = cast<ConstantSDNode>(Elt)->getAPIntValue(); 22218 else if (isa<ConstantFPSDNode>(Elt)) 22219 Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt(); 22220 else 22221 return SDValue(); 22222 22223 // Extract the sub element from the constant bit mask. 22224 if (DAG.getDataLayout().isBigEndian()) 22225 Bits = Bits.extractBits(NumSubBits, (Split - SubIdx - 1) * NumSubBits); 22226 else 22227 Bits = Bits.extractBits(NumSubBits, SubIdx * NumSubBits); 22228 22229 if (Bits.isAllOnes()) 22230 Indices.push_back(i); 22231 else if (Bits == 0) 22232 Indices.push_back(i + NumSubElts); 22233 else 22234 return SDValue(); 22235 } 22236 22237 // Let's see if the target supports this vector_shuffle. 22238 EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits); 22239 EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts); 22240 if (!TLI.isVectorClearMaskLegal(Indices, ClearVT)) 22241 return SDValue(); 22242 22243 SDValue Zero = DAG.getConstant(0, DL, ClearVT); 22244 return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL, 22245 DAG.getBitcast(ClearVT, LHS), 22246 Zero, Indices)); 22247 }; 22248 22249 // Determine maximum split level (byte level masking). 22250 int MaxSplit = 1; 22251 if (RVT.getScalarSizeInBits() % 8 == 0) 22252 MaxSplit = RVT.getScalarSizeInBits() / 8; 22253 22254 for (int Split = 1; Split <= MaxSplit; ++Split) 22255 if (RVT.getScalarSizeInBits() % Split == 0) 22256 if (SDValue S = BuildClearMask(Split)) 22257 return S; 22258 22259 return SDValue(); 22260 } 22261 22262 /// If a vector binop is performed on splat values, it may be profitable to 22263 /// extract, scalarize, and insert/splat. 22264 static SDValue scalarizeBinOpOfSplats(SDNode *N, SelectionDAG &DAG, 22265 const SDLoc &DL) { 22266 SDValue N0 = N->getOperand(0); 22267 SDValue N1 = N->getOperand(1); 22268 unsigned Opcode = N->getOpcode(); 22269 EVT VT = N->getValueType(0); 22270 EVT EltVT = VT.getVectorElementType(); 22271 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 22272 22273 // TODO: Remove/replace the extract cost check? If the elements are available 22274 // as scalars, then there may be no extract cost. Should we ask if 22275 // inserting a scalar back into a vector is cheap instead? 22276 int Index0, Index1; 22277 SDValue Src0 = DAG.getSplatSourceVector(N0, Index0); 22278 SDValue Src1 = DAG.getSplatSourceVector(N1, Index1); 22279 if (!Src0 || !Src1 || Index0 != Index1 || 22280 Src0.getValueType().getVectorElementType() != EltVT || 22281 Src1.getValueType().getVectorElementType() != EltVT || 22282 !TLI.isExtractVecEltCheap(VT, Index0) || 22283 !TLI.isOperationLegalOrCustom(Opcode, EltVT)) 22284 return SDValue(); 22285 22286 SDValue IndexC = DAG.getVectorIdxConstant(Index0, DL); 22287 SDValue X = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src0, IndexC); 22288 SDValue Y = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src1, IndexC); 22289 SDValue ScalarBO = DAG.getNode(Opcode, DL, EltVT, X, Y, N->getFlags()); 22290 22291 // If all lanes but 1 are undefined, no need to splat the scalar result. 22292 // TODO: Keep track of undefs and use that info in the general case. 22293 if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getOpcode() == N1.getOpcode() && 22294 count_if(N0->ops(), [](SDValue V) { return !V.isUndef(); }) == 1 && 22295 count_if(N1->ops(), [](SDValue V) { return !V.isUndef(); }) == 1) { 22296 // bo (build_vec ..undef, X, undef...), (build_vec ..undef, Y, undef...) --> 22297 // build_vec ..undef, (bo X, Y), undef... 22298 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), DAG.getUNDEF(EltVT)); 22299 Ops[Index0] = ScalarBO; 22300 return DAG.getBuildVector(VT, DL, Ops); 22301 } 22302 22303 // bo (splat X, Index), (splat Y, Index) --> splat (bo X, Y), Index 22304 SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), ScalarBO); 22305 return DAG.getBuildVector(VT, DL, Ops); 22306 } 22307 22308 /// Visit a binary vector operation, like ADD. 22309 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N, const SDLoc &DL) { 22310 EVT VT = N->getValueType(0); 22311 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!"); 22312 22313 SDValue LHS = N->getOperand(0); 22314 SDValue RHS = N->getOperand(1); 22315 SDValue Ops[] = {LHS, RHS}; 22316 unsigned Opcode = N->getOpcode(); 22317 SDNodeFlags Flags = N->getFlags(); 22318 22319 // See if we can constant fold the vector operation. 22320 if (SDValue Fold = DAG.FoldConstantArithmetic(Opcode, SDLoc(LHS), 22321 LHS.getValueType(), Ops)) 22322 return Fold; 22323 22324 // Move unary shuffles with identical masks after a vector binop: 22325 // VBinOp (shuffle A, Undef, Mask), (shuffle B, Undef, Mask)) 22326 // --> shuffle (VBinOp A, B), Undef, Mask 22327 // This does not require type legality checks because we are creating the 22328 // same types of operations that are in the original sequence. We do have to 22329 // restrict ops like integer div that have immediate UB (eg, div-by-zero) 22330 // though. This code is adapted from the identical transform in instcombine. 22331 if (Opcode != ISD::UDIV && Opcode != ISD::SDIV && 22332 Opcode != ISD::UREM && Opcode != ISD::SREM && 22333 Opcode != ISD::UDIVREM && Opcode != ISD::SDIVREM) { 22334 auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS); 22335 auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS); 22336 if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) && 22337 LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() && 22338 (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) { 22339 SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS.getOperand(0), 22340 RHS.getOperand(0), Flags); 22341 SDValue UndefV = LHS.getOperand(1); 22342 return DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask()); 22343 } 22344 22345 // Try to sink a splat shuffle after a binop with a uniform constant. 22346 // This is limited to cases where neither the shuffle nor the constant have 22347 // undefined elements because that could be poison-unsafe or inhibit 22348 // demanded elements analysis. It is further limited to not change a splat 22349 // of an inserted scalar because that may be optimized better by 22350 // load-folding or other target-specific behaviors. 22351 if (isConstOrConstSplat(RHS) && Shuf0 && is_splat(Shuf0->getMask()) && 22352 Shuf0->hasOneUse() && Shuf0->getOperand(1).isUndef() && 22353 Shuf0->getOperand(0).getOpcode() != ISD::INSERT_VECTOR_ELT) { 22354 // binop (splat X), (splat C) --> splat (binop X, C) 22355 SDValue X = Shuf0->getOperand(0); 22356 SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, X, RHS, Flags); 22357 return DAG.getVectorShuffle(VT, DL, NewBinOp, DAG.getUNDEF(VT), 22358 Shuf0->getMask()); 22359 } 22360 if (isConstOrConstSplat(LHS) && Shuf1 && is_splat(Shuf1->getMask()) && 22361 Shuf1->hasOneUse() && Shuf1->getOperand(1).isUndef() && 22362 Shuf1->getOperand(0).getOpcode() != ISD::INSERT_VECTOR_ELT) { 22363 // binop (splat C), (splat X) --> splat (binop C, X) 22364 SDValue X = Shuf1->getOperand(0); 22365 SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS, X, Flags); 22366 return DAG.getVectorShuffle(VT, DL, NewBinOp, DAG.getUNDEF(VT), 22367 Shuf1->getMask()); 22368 } 22369 } 22370 22371 // The following pattern is likely to emerge with vector reduction ops. Moving 22372 // the binary operation ahead of insertion may allow using a narrower vector 22373 // instruction that has better performance than the wide version of the op: 22374 // VBinOp (ins undef, X, Z), (ins undef, Y, Z) --> ins VecC, (VBinOp X, Y), Z 22375 if (LHS.getOpcode() == ISD::INSERT_SUBVECTOR && LHS.getOperand(0).isUndef() && 22376 RHS.getOpcode() == ISD::INSERT_SUBVECTOR && RHS.getOperand(0).isUndef() && 22377 LHS.getOperand(2) == RHS.getOperand(2) && 22378 (LHS.hasOneUse() || RHS.hasOneUse())) { 22379 SDValue X = LHS.getOperand(1); 22380 SDValue Y = RHS.getOperand(1); 22381 SDValue Z = LHS.getOperand(2); 22382 EVT NarrowVT = X.getValueType(); 22383 if (NarrowVT == Y.getValueType() && 22384 TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT, 22385 LegalOperations)) { 22386 // (binop undef, undef) may not return undef, so compute that result. 22387 SDValue VecC = 22388 DAG.getNode(Opcode, DL, VT, DAG.getUNDEF(VT), DAG.getUNDEF(VT)); 22389 SDValue NarrowBO = DAG.getNode(Opcode, DL, NarrowVT, X, Y); 22390 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, VecC, NarrowBO, Z); 22391 } 22392 } 22393 22394 // Make sure all but the first op are undef or constant. 22395 auto ConcatWithConstantOrUndef = [](SDValue Concat) { 22396 return Concat.getOpcode() == ISD::CONCAT_VECTORS && 22397 all_of(drop_begin(Concat->ops()), [](const SDValue &Op) { 22398 return Op.isUndef() || 22399 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()); 22400 }); 22401 }; 22402 22403 // The following pattern is likely to emerge with vector reduction ops. Moving 22404 // the binary operation ahead of the concat may allow using a narrower vector 22405 // instruction that has better performance than the wide version of the op: 22406 // VBinOp (concat X, undef/constant), (concat Y, undef/constant) --> 22407 // concat (VBinOp X, Y), VecC 22408 if (ConcatWithConstantOrUndef(LHS) && ConcatWithConstantOrUndef(RHS) && 22409 (LHS.hasOneUse() || RHS.hasOneUse())) { 22410 EVT NarrowVT = LHS.getOperand(0).getValueType(); 22411 if (NarrowVT == RHS.getOperand(0).getValueType() && 22412 TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT)) { 22413 unsigned NumOperands = LHS.getNumOperands(); 22414 SmallVector<SDValue, 4> ConcatOps; 22415 for (unsigned i = 0; i != NumOperands; ++i) { 22416 // This constant fold for operands 1 and up. 22417 ConcatOps.push_back(DAG.getNode(Opcode, DL, NarrowVT, LHS.getOperand(i), 22418 RHS.getOperand(i))); 22419 } 22420 22421 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps); 22422 } 22423 } 22424 22425 if (SDValue V = scalarizeBinOpOfSplats(N, DAG, DL)) 22426 return V; 22427 22428 return SDValue(); 22429 } 22430 22431 SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, 22432 SDValue N2) { 22433 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!"); 22434 22435 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2, 22436 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 22437 22438 // If we got a simplified select_cc node back from SimplifySelectCC, then 22439 // break it down into a new SETCC node, and a new SELECT node, and then return 22440 // the SELECT node, since we were called with a SELECT node. 22441 if (SCC.getNode()) { 22442 // Check to see if we got a select_cc back (to turn into setcc/select). 22443 // Otherwise, just return whatever node we got back, like fabs. 22444 if (SCC.getOpcode() == ISD::SELECT_CC) { 22445 const SDNodeFlags Flags = N0.getNode()->getFlags(); 22446 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0), 22447 N0.getValueType(), 22448 SCC.getOperand(0), SCC.getOperand(1), 22449 SCC.getOperand(4), Flags); 22450 AddToWorklist(SETCC.getNode()); 22451 SDValue SelectNode = DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC, 22452 SCC.getOperand(2), SCC.getOperand(3)); 22453 SelectNode->setFlags(Flags); 22454 return SelectNode; 22455 } 22456 22457 return SCC; 22458 } 22459 return SDValue(); 22460 } 22461 22462 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values 22463 /// being selected between, see if we can simplify the select. Callers of this 22464 /// should assume that TheSelect is deleted if this returns true. As such, they 22465 /// should return the appropriate thing (e.g. the node) back to the top-level of 22466 /// the DAG combiner loop to avoid it being looked at. 22467 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 22468 SDValue RHS) { 22469 // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 22470 // The select + setcc is redundant, because fsqrt returns NaN for X < 0. 22471 if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) { 22472 if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) { 22473 // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?)) 22474 SDValue Sqrt = RHS; 22475 ISD::CondCode CC; 22476 SDValue CmpLHS; 22477 const ConstantFPSDNode *Zero = nullptr; 22478 22479 if (TheSelect->getOpcode() == ISD::SELECT_CC) { 22480 CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get(); 22481 CmpLHS = TheSelect->getOperand(0); 22482 Zero = isConstOrConstSplatFP(TheSelect->getOperand(1)); 22483 } else { 22484 // SELECT or VSELECT 22485 SDValue Cmp = TheSelect->getOperand(0); 22486 if (Cmp.getOpcode() == ISD::SETCC) { 22487 CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get(); 22488 CmpLHS = Cmp.getOperand(0); 22489 Zero = isConstOrConstSplatFP(Cmp.getOperand(1)); 22490 } 22491 } 22492 if (Zero && Zero->isZero() && 22493 Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT || 22494 CC == ISD::SETULT || CC == ISD::SETLT)) { 22495 // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x)) 22496 CombineTo(TheSelect, Sqrt); 22497 return true; 22498 } 22499 } 22500 } 22501 // Cannot simplify select with vector condition 22502 if (TheSelect->getOperand(0).getValueType().isVector()) return false; 22503 22504 // If this is a select from two identical things, try to pull the operation 22505 // through the select. 22506 if (LHS.getOpcode() != RHS.getOpcode() || 22507 !LHS.hasOneUse() || !RHS.hasOneUse()) 22508 return false; 22509 22510 // If this is a load and the token chain is identical, replace the select 22511 // of two loads with a load through a select of the address to load from. 22512 // This triggers in things like "select bool X, 10.0, 123.0" after the FP 22513 // constants have been dropped into the constant pool. 22514 if (LHS.getOpcode() == ISD::LOAD) { 22515 LoadSDNode *LLD = cast<LoadSDNode>(LHS); 22516 LoadSDNode *RLD = cast<LoadSDNode>(RHS); 22517 22518 // Token chains must be identical. 22519 if (LHS.getOperand(0) != RHS.getOperand(0) || 22520 // Do not let this transformation reduce the number of volatile loads. 22521 // Be conservative for atomics for the moment 22522 // TODO: This does appear to be legal for unordered atomics (see D66309) 22523 !LLD->isSimple() || !RLD->isSimple() || 22524 // FIXME: If either is a pre/post inc/dec load, 22525 // we'd need to split out the address adjustment. 22526 LLD->isIndexed() || RLD->isIndexed() || 22527 // If this is an EXTLOAD, the VT's must match. 22528 LLD->getMemoryVT() != RLD->getMemoryVT() || 22529 // If this is an EXTLOAD, the kind of extension must match. 22530 (LLD->getExtensionType() != RLD->getExtensionType() && 22531 // The only exception is if one of the extensions is anyext. 22532 LLD->getExtensionType() != ISD::EXTLOAD && 22533 RLD->getExtensionType() != ISD::EXTLOAD) || 22534 // FIXME: this discards src value information. This is 22535 // over-conservative. It would be beneficial to be able to remember 22536 // both potential memory locations. Since we are discarding 22537 // src value info, don't do the transformation if the memory 22538 // locations are not in the default address space. 22539 LLD->getPointerInfo().getAddrSpace() != 0 || 22540 RLD->getPointerInfo().getAddrSpace() != 0 || 22541 // We can't produce a CMOV of a TargetFrameIndex since we won't 22542 // generate the address generation required. 22543 LLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex || 22544 RLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex || 22545 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(), 22546 LLD->getBasePtr().getValueType())) 22547 return false; 22548 22549 // The loads must not depend on one another. 22550 if (LLD->isPredecessorOf(RLD) || RLD->isPredecessorOf(LLD)) 22551 return false; 22552 22553 // Check that the select condition doesn't reach either load. If so, 22554 // folding this will induce a cycle into the DAG. If not, this is safe to 22555 // xform, so create a select of the addresses. 22556 22557 SmallPtrSet<const SDNode *, 32> Visited; 22558 SmallVector<const SDNode *, 16> Worklist; 22559 22560 // Always fail if LLD and RLD are not independent. TheSelect is a 22561 // predecessor to all Nodes in question so we need not search past it. 22562 22563 Visited.insert(TheSelect); 22564 Worklist.push_back(LLD); 22565 Worklist.push_back(RLD); 22566 22567 if (SDNode::hasPredecessorHelper(LLD, Visited, Worklist) || 22568 SDNode::hasPredecessorHelper(RLD, Visited, Worklist)) 22569 return false; 22570 22571 SDValue Addr; 22572 if (TheSelect->getOpcode() == ISD::SELECT) { 22573 // We cannot do this optimization if any pair of {RLD, LLD} is a 22574 // predecessor to {RLD, LLD, CondNode}. As we've already compared the 22575 // Loads, we only need to check if CondNode is a successor to one of the 22576 // loads. We can further avoid this if there's no use of their chain 22577 // value. 22578 SDNode *CondNode = TheSelect->getOperand(0).getNode(); 22579 Worklist.push_back(CondNode); 22580 22581 if ((LLD->hasAnyUseOfValue(1) && 22582 SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) || 22583 (RLD->hasAnyUseOfValue(1) && 22584 SDNode::hasPredecessorHelper(RLD, Visited, Worklist))) 22585 return false; 22586 22587 Addr = DAG.getSelect(SDLoc(TheSelect), 22588 LLD->getBasePtr().getValueType(), 22589 TheSelect->getOperand(0), LLD->getBasePtr(), 22590 RLD->getBasePtr()); 22591 } else { // Otherwise SELECT_CC 22592 // We cannot do this optimization if any pair of {RLD, LLD} is a 22593 // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared 22594 // the Loads, we only need to check if CondLHS/CondRHS is a successor to 22595 // one of the loads. We can further avoid this if there's no use of their 22596 // chain value. 22597 22598 SDNode *CondLHS = TheSelect->getOperand(0).getNode(); 22599 SDNode *CondRHS = TheSelect->getOperand(1).getNode(); 22600 Worklist.push_back(CondLHS); 22601 Worklist.push_back(CondRHS); 22602 22603 if ((LLD->hasAnyUseOfValue(1) && 22604 SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) || 22605 (RLD->hasAnyUseOfValue(1) && 22606 SDNode::hasPredecessorHelper(RLD, Visited, Worklist))) 22607 return false; 22608 22609 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect), 22610 LLD->getBasePtr().getValueType(), 22611 TheSelect->getOperand(0), 22612 TheSelect->getOperand(1), 22613 LLD->getBasePtr(), RLD->getBasePtr(), 22614 TheSelect->getOperand(4)); 22615 } 22616 22617 SDValue Load; 22618 // It is safe to replace the two loads if they have different alignments, 22619 // but the new load must be the minimum (most restrictive) alignment of the 22620 // inputs. 22621 Align Alignment = std::min(LLD->getAlign(), RLD->getAlign()); 22622 MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags(); 22623 if (!RLD->isInvariant()) 22624 MMOFlags &= ~MachineMemOperand::MOInvariant; 22625 if (!RLD->isDereferenceable()) 22626 MMOFlags &= ~MachineMemOperand::MODereferenceable; 22627 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) { 22628 // FIXME: Discards pointer and AA info. 22629 Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect), 22630 LLD->getChain(), Addr, MachinePointerInfo(), Alignment, 22631 MMOFlags); 22632 } else { 22633 // FIXME: Discards pointer and AA info. 22634 Load = DAG.getExtLoad( 22635 LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType() 22636 : LLD->getExtensionType(), 22637 SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr, 22638 MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags); 22639 } 22640 22641 // Users of the select now use the result of the load. 22642 CombineTo(TheSelect, Load); 22643 22644 // Users of the old loads now use the new load's chain. We know the 22645 // old-load value is dead now. 22646 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1)); 22647 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1)); 22648 return true; 22649 } 22650 22651 return false; 22652 } 22653 22654 /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and 22655 /// bitwise 'and'. 22656 SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, 22657 SDValue N1, SDValue N2, SDValue N3, 22658 ISD::CondCode CC) { 22659 // If this is a select where the false operand is zero and the compare is a 22660 // check of the sign bit, see if we can perform the "gzip trick": 22661 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A 22662 // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A 22663 EVT XType = N0.getValueType(); 22664 EVT AType = N2.getValueType(); 22665 if (!isNullConstant(N3) || !XType.bitsGE(AType)) 22666 return SDValue(); 22667 22668 // If the comparison is testing for a positive value, we have to invert 22669 // the sign bit mask, so only do that transform if the target has a bitwise 22670 // 'and not' instruction (the invert is free). 22671 if (CC == ISD::SETGT && TLI.hasAndNot(N2)) { 22672 // (X > -1) ? A : 0 22673 // (X > 0) ? X : 0 <-- This is canonical signed max. 22674 if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2))) 22675 return SDValue(); 22676 } else if (CC == ISD::SETLT) { 22677 // (X < 0) ? A : 0 22678 // (X < 1) ? X : 0 <-- This is un-canonicalized signed min. 22679 if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2))) 22680 return SDValue(); 22681 } else { 22682 return SDValue(); 22683 } 22684 22685 // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit 22686 // constant. 22687 EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType()); 22688 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 22689 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) { 22690 unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1; 22691 if (!TLI.shouldAvoidTransformToShift(XType, ShCt)) { 22692 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 22693 SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt); 22694 AddToWorklist(Shift.getNode()); 22695 22696 if (XType.bitsGT(AType)) { 22697 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 22698 AddToWorklist(Shift.getNode()); 22699 } 22700 22701 if (CC == ISD::SETGT) 22702 Shift = DAG.getNOT(DL, Shift, AType); 22703 22704 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 22705 } 22706 } 22707 22708 unsigned ShCt = XType.getSizeInBits() - 1; 22709 if (TLI.shouldAvoidTransformToShift(XType, ShCt)) 22710 return SDValue(); 22711 22712 SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy); 22713 SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt); 22714 AddToWorklist(Shift.getNode()); 22715 22716 if (XType.bitsGT(AType)) { 22717 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift); 22718 AddToWorklist(Shift.getNode()); 22719 } 22720 22721 if (CC == ISD::SETGT) 22722 Shift = DAG.getNOT(DL, Shift, AType); 22723 22724 return DAG.getNode(ISD::AND, DL, AType, Shift, N2); 22725 } 22726 22727 // Fold select(cc, binop(), binop()) -> binop(select(), select()) etc. 22728 SDValue DAGCombiner::foldSelectOfBinops(SDNode *N) { 22729 SDValue N0 = N->getOperand(0); 22730 SDValue N1 = N->getOperand(1); 22731 SDValue N2 = N->getOperand(2); 22732 EVT VT = N->getValueType(0); 22733 SDLoc DL(N); 22734 22735 unsigned BinOpc = N1.getOpcode(); 22736 if (!TLI.isBinOp(BinOpc) || (N2.getOpcode() != BinOpc)) 22737 return SDValue(); 22738 22739 // The use checks are intentionally on SDNode because we may be dealing 22740 // with opcodes that produce more than one SDValue. 22741 // TODO: Do we really need to check N0 (the condition operand of the select)? 22742 // But removing that clause could cause an infinite loop... 22743 if (!N0->hasOneUse() || !N1->hasOneUse() || !N2->hasOneUse()) 22744 return SDValue(); 22745 22746 // Binops may include opcodes that return multiple values, so all values 22747 // must be created/propagated from the newly created binops below. 22748 SDVTList OpVTs = N1->getVTList(); 22749 22750 // Fold select(cond, binop(x, y), binop(z, y)) 22751 // --> binop(select(cond, x, z), y) 22752 if (N1.getOperand(1) == N2.getOperand(1)) { 22753 SDValue NewSel = 22754 DAG.getSelect(DL, VT, N0, N1.getOperand(0), N2.getOperand(0)); 22755 SDValue NewBinOp = DAG.getNode(BinOpc, DL, OpVTs, NewSel, N1.getOperand(1)); 22756 NewBinOp->setFlags(N1->getFlags()); 22757 NewBinOp->intersectFlagsWith(N2->getFlags()); 22758 return NewBinOp; 22759 } 22760 22761 // Fold select(cond, binop(x, y), binop(x, z)) 22762 // --> binop(x, select(cond, y, z)) 22763 // Second op VT might be different (e.g. shift amount type) 22764 if (N1.getOperand(0) == N2.getOperand(0) && 22765 VT == N1.getOperand(1).getValueType() && 22766 VT == N2.getOperand(1).getValueType()) { 22767 SDValue NewSel = 22768 DAG.getSelect(DL, VT, N0, N1.getOperand(1), N2.getOperand(1)); 22769 SDValue NewBinOp = DAG.getNode(BinOpc, DL, OpVTs, N1.getOperand(0), NewSel); 22770 NewBinOp->setFlags(N1->getFlags()); 22771 NewBinOp->intersectFlagsWith(N2->getFlags()); 22772 return NewBinOp; 22773 } 22774 22775 // TODO: Handle isCommutativeBinOp patterns as well? 22776 return SDValue(); 22777 } 22778 22779 // Transform (fneg/fabs (bitconvert x)) to avoid loading constant pool values. 22780 SDValue DAGCombiner::foldSignChangeInBitcast(SDNode *N) { 22781 SDValue N0 = N->getOperand(0); 22782 EVT VT = N->getValueType(0); 22783 bool IsFabs = N->getOpcode() == ISD::FABS; 22784 bool IsFree = IsFabs ? TLI.isFAbsFree(VT) : TLI.isFNegFree(VT); 22785 22786 if (IsFree || N0.getOpcode() != ISD::BITCAST || !N0.hasOneUse()) 22787 return SDValue(); 22788 22789 SDValue Int = N0.getOperand(0); 22790 EVT IntVT = Int.getValueType(); 22791 22792 // The operand to cast should be integer. 22793 if (!IntVT.isInteger() || IntVT.isVector()) 22794 return SDValue(); 22795 22796 // (fneg (bitconvert x)) -> (bitconvert (xor x sign)) 22797 // (fabs (bitconvert x)) -> (bitconvert (and x ~sign)) 22798 APInt SignMask; 22799 if (N0.getValueType().isVector()) { 22800 // For vector, create a sign mask (0x80...) or its inverse (for fabs, 22801 // 0x7f...) per element and splat it. 22802 SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits()); 22803 if (IsFabs) 22804 SignMask = ~SignMask; 22805 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask); 22806 } else { 22807 // For scalar, just use the sign mask (0x80... or the inverse, 0x7f...) 22808 SignMask = APInt::getSignMask(IntVT.getSizeInBits()); 22809 if (IsFabs) 22810 SignMask = ~SignMask; 22811 } 22812 SDLoc DL(N0); 22813 Int = DAG.getNode(IsFabs ? ISD::AND : ISD::XOR, DL, IntVT, Int, 22814 DAG.getConstant(SignMask, DL, IntVT)); 22815 AddToWorklist(Int.getNode()); 22816 return DAG.getBitcast(VT, Int); 22817 } 22818 22819 /// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)" 22820 /// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0 22821 /// in it. This may be a win when the constant is not otherwise available 22822 /// because it replaces two constant pool loads with one. 22823 SDValue DAGCombiner::convertSelectOfFPConstantsToLoadOffset( 22824 const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3, 22825 ISD::CondCode CC) { 22826 if (!TLI.reduceSelectOfFPConstantLoads(N0.getValueType())) 22827 return SDValue(); 22828 22829 // If we are before legalize types, we want the other legalization to happen 22830 // first (for example, to avoid messing with soft float). 22831 auto *TV = dyn_cast<ConstantFPSDNode>(N2); 22832 auto *FV = dyn_cast<ConstantFPSDNode>(N3); 22833 EVT VT = N2.getValueType(); 22834 if (!TV || !FV || !TLI.isTypeLegal(VT)) 22835 return SDValue(); 22836 22837 // If a constant can be materialized without loads, this does not make sense. 22838 if (TLI.getOperationAction(ISD::ConstantFP, VT) == TargetLowering::Legal || 22839 TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0), ForCodeSize) || 22840 TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0), ForCodeSize)) 22841 return SDValue(); 22842 22843 // If both constants have multiple uses, then we won't need to do an extra 22844 // load. The values are likely around in registers for other users. 22845 if (!TV->hasOneUse() && !FV->hasOneUse()) 22846 return SDValue(); 22847 22848 Constant *Elts[] = { const_cast<ConstantFP*>(FV->getConstantFPValue()), 22849 const_cast<ConstantFP*>(TV->getConstantFPValue()) }; 22850 Type *FPTy = Elts[0]->getType(); 22851 const DataLayout &TD = DAG.getDataLayout(); 22852 22853 // Create a ConstantArray of the two constants. 22854 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts); 22855 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()), 22856 TD.getPrefTypeAlign(FPTy)); 22857 Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign(); 22858 22859 // Get offsets to the 0 and 1 elements of the array, so we can select between 22860 // them. 22861 SDValue Zero = DAG.getIntPtrConstant(0, DL); 22862 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType()); 22863 SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV)); 22864 SDValue Cond = 22865 DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), N0, N1, CC); 22866 AddToWorklist(Cond.getNode()); 22867 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), Cond, One, Zero); 22868 AddToWorklist(CstOffset.getNode()); 22869 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, CstOffset); 22870 AddToWorklist(CPIdx.getNode()); 22871 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx, 22872 MachinePointerInfo::getConstantPool( 22873 DAG.getMachineFunction()), Alignment); 22874 } 22875 22876 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3 22877 /// where 'cond' is the comparison specified by CC. 22878 SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1, 22879 SDValue N2, SDValue N3, ISD::CondCode CC, 22880 bool NotExtCompare) { 22881 // (x ? y : y) -> y. 22882 if (N2 == N3) return N2; 22883 22884 EVT CmpOpVT = N0.getValueType(); 22885 EVT CmpResVT = getSetCCResultType(CmpOpVT); 22886 EVT VT = N2.getValueType(); 22887 auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()); 22888 auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode()); 22889 auto *N3C = dyn_cast<ConstantSDNode>(N3.getNode()); 22890 22891 // Determine if the condition we're dealing with is constant. 22892 if (SDValue SCC = DAG.FoldSetCC(CmpResVT, N0, N1, CC, DL)) { 22893 AddToWorklist(SCC.getNode()); 22894 if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC)) { 22895 // fold select_cc true, x, y -> x 22896 // fold select_cc false, x, y -> y 22897 return !(SCCC->isZero()) ? N2 : N3; 22898 } 22899 } 22900 22901 if (SDValue V = 22902 convertSelectOfFPConstantsToLoadOffset(DL, N0, N1, N2, N3, CC)) 22903 return V; 22904 22905 if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC)) 22906 return V; 22907 22908 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A) 22909 // where y is has a single bit set. 22910 // A plaintext description would be, we can turn the SELECT_CC into an AND 22911 // when the condition can be materialized as an all-ones register. Any 22912 // single bit-test can be materialized as an all-ones register with 22913 // shift-left and shift-right-arith. 22914 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND && 22915 N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) { 22916 SDValue AndLHS = N0->getOperand(0); 22917 auto *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 22918 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) { 22919 // Shift the tested bit over the sign bit. 22920 const APInt &AndMask = ConstAndRHS->getAPIntValue(); 22921 unsigned ShCt = AndMask.getBitWidth() - 1; 22922 if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) { 22923 SDValue ShlAmt = 22924 DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS), 22925 getShiftAmountTy(AndLHS.getValueType())); 22926 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt); 22927 22928 // Now arithmetic right shift it all the way over, so the result is 22929 // either all-ones, or zero. 22930 SDValue ShrAmt = 22931 DAG.getConstant(ShCt, SDLoc(Shl), 22932 getShiftAmountTy(Shl.getValueType())); 22933 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt); 22934 22935 return DAG.getNode(ISD::AND, DL, VT, Shr, N3); 22936 } 22937 } 22938 } 22939 22940 // fold select C, 16, 0 -> shl C, 4 22941 bool Fold = N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2(); 22942 bool Swap = N3C && isNullConstant(N2) && N3C->getAPIntValue().isPowerOf2(); 22943 22944 if ((Fold || Swap) && 22945 TLI.getBooleanContents(CmpOpVT) == 22946 TargetLowering::ZeroOrOneBooleanContent && 22947 (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, CmpOpVT))) { 22948 22949 if (Swap) { 22950 CC = ISD::getSetCCInverse(CC, CmpOpVT); 22951 std::swap(N2C, N3C); 22952 } 22953 22954 // If the caller doesn't want us to simplify this into a zext of a compare, 22955 // don't do it. 22956 if (NotExtCompare && N2C->isOne()) 22957 return SDValue(); 22958 22959 SDValue Temp, SCC; 22960 // zext (setcc n0, n1) 22961 if (LegalTypes) { 22962 SCC = DAG.getSetCC(DL, CmpResVT, N0, N1, CC); 22963 if (VT.bitsLT(SCC.getValueType())) 22964 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), VT); 22965 else 22966 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC); 22967 } else { 22968 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC); 22969 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC); 22970 } 22971 22972 AddToWorklist(SCC.getNode()); 22973 AddToWorklist(Temp.getNode()); 22974 22975 if (N2C->isOne()) 22976 return Temp; 22977 22978 unsigned ShCt = N2C->getAPIntValue().logBase2(); 22979 if (TLI.shouldAvoidTransformToShift(VT, ShCt)) 22980 return SDValue(); 22981 22982 // shl setcc result by log2 n2c 22983 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp, 22984 DAG.getConstant(ShCt, SDLoc(Temp), 22985 getShiftAmountTy(Temp.getValueType()))); 22986 } 22987 22988 // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X) 22989 // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X) 22990 // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X) 22991 // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X) 22992 // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X) 22993 // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X) 22994 // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X) 22995 // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X) 22996 if (N1C && N1C->isZero() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 22997 SDValue ValueOnZero = N2; 22998 SDValue Count = N3; 22999 // If the condition is NE instead of E, swap the operands. 23000 if (CC == ISD::SETNE) 23001 std::swap(ValueOnZero, Count); 23002 // Check if the value on zero is a constant equal to the bits in the type. 23003 if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) { 23004 if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) { 23005 // If the other operand is cttz/cttz_zero_undef of N0, and cttz is 23006 // legal, combine to just cttz. 23007 if ((Count.getOpcode() == ISD::CTTZ || 23008 Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) && 23009 N0 == Count.getOperand(0) && 23010 (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT))) 23011 return DAG.getNode(ISD::CTTZ, DL, VT, N0); 23012 // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is 23013 // legal, combine to just ctlz. 23014 if ((Count.getOpcode() == ISD::CTLZ || 23015 Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) && 23016 N0 == Count.getOperand(0) && 23017 (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT))) 23018 return DAG.getNode(ISD::CTLZ, DL, VT, N0); 23019 } 23020 } 23021 } 23022 23023 // Fold select_cc setgt X, -1, C, ~C -> xor (ashr X, BW-1), C 23024 // Fold select_cc setlt X, 0, C, ~C -> xor (ashr X, BW-1), ~C 23025 if (!NotExtCompare && N1C && N2C && N3C && 23026 N2C->getAPIntValue() == ~N3C->getAPIntValue() && 23027 ((N1C->isAllOnes() && CC == ISD::SETGT) || 23028 (N1C->isZero() && CC == ISD::SETLT)) && 23029 !TLI.shouldAvoidTransformToShift(VT, CmpOpVT.getScalarSizeInBits() - 1)) { 23030 SDValue ASR = DAG.getNode( 23031 ISD::SRA, DL, CmpOpVT, N0, 23032 DAG.getConstant(CmpOpVT.getScalarSizeInBits() - 1, DL, CmpOpVT)); 23033 return DAG.getNode(ISD::XOR, DL, VT, DAG.getSExtOrTrunc(ASR, DL, VT), 23034 DAG.getSExtOrTrunc(CC == ISD::SETLT ? N3 : N2, DL, VT)); 23035 } 23036 23037 return SDValue(); 23038 } 23039 23040 /// This is a stub for TargetLowering::SimplifySetCC. 23041 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1, 23042 ISD::CondCode Cond, const SDLoc &DL, 23043 bool foldBooleans) { 23044 TargetLowering::DAGCombinerInfo 23045 DagCombineInfo(DAG, Level, false, this); 23046 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL); 23047 } 23048 23049 /// Given an ISD::SDIV node expressing a divide by constant, return 23050 /// a DAG expression to select that will generate the same value by multiplying 23051 /// by a magic number. 23052 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 23053 SDValue DAGCombiner::BuildSDIV(SDNode *N) { 23054 // when optimising for minimum size, we don't want to expand a div to a mul 23055 // and a shift. 23056 if (DAG.getMachineFunction().getFunction().hasMinSize()) 23057 return SDValue(); 23058 23059 SmallVector<SDNode *, 8> Built; 23060 if (SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, Built)) { 23061 for (SDNode *N : Built) 23062 AddToWorklist(N); 23063 return S; 23064 } 23065 23066 return SDValue(); 23067 } 23068 23069 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a 23070 /// DAG expression that will generate the same value by right shifting. 23071 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) { 23072 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1)); 23073 if (!C) 23074 return SDValue(); 23075 23076 // Avoid division by zero. 23077 if (C->isZero()) 23078 return SDValue(); 23079 23080 SmallVector<SDNode *, 8> Built; 23081 if (SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built)) { 23082 for (SDNode *N : Built) 23083 AddToWorklist(N); 23084 return S; 23085 } 23086 23087 return SDValue(); 23088 } 23089 23090 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG 23091 /// expression that will generate the same value by multiplying by a magic 23092 /// number. 23093 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide". 23094 SDValue DAGCombiner::BuildUDIV(SDNode *N) { 23095 // when optimising for minimum size, we don't want to expand a div to a mul 23096 // and a shift. 23097 if (DAG.getMachineFunction().getFunction().hasMinSize()) 23098 return SDValue(); 23099 23100 SmallVector<SDNode *, 8> Built; 23101 if (SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, Built)) { 23102 for (SDNode *N : Built) 23103 AddToWorklist(N); 23104 return S; 23105 } 23106 23107 return SDValue(); 23108 } 23109 23110 /// Determines the LogBase2 value for a non-null input value using the 23111 /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V). 23112 SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) { 23113 EVT VT = V.getValueType(); 23114 SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V); 23115 SDValue Base = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT); 23116 SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz); 23117 return LogBase2; 23118 } 23119 23120 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 23121 /// For the reciprocal, we need to find the zero of the function: 23122 /// F(X) = 1/X - A [which has a zero at X = 1/A] 23123 /// => 23124 /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form 23125 /// does not require additional intermediate precision] 23126 /// For the last iteration, put numerator N into it to gain more precision: 23127 /// Result = N X_i + X_i (N - N A X_i) 23128 SDValue DAGCombiner::BuildDivEstimate(SDValue N, SDValue Op, 23129 SDNodeFlags Flags) { 23130 if (LegalDAG) 23131 return SDValue(); 23132 23133 // TODO: Handle extended types? 23134 EVT VT = Op.getValueType(); 23135 if (VT.getScalarType() != MVT::f16 && VT.getScalarType() != MVT::f32 && 23136 VT.getScalarType() != MVT::f64) 23137 return SDValue(); 23138 23139 // If estimates are explicitly disabled for this function, we're done. 23140 MachineFunction &MF = DAG.getMachineFunction(); 23141 int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF); 23142 if (Enabled == TLI.ReciprocalEstimate::Disabled) 23143 return SDValue(); 23144 23145 // Estimates may be explicitly enabled for this type with a custom number of 23146 // refinement steps. 23147 int Iterations = TLI.getDivRefinementSteps(VT, MF); 23148 if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) { 23149 AddToWorklist(Est.getNode()); 23150 23151 SDLoc DL(Op); 23152 if (Iterations) { 23153 SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); 23154 23155 // Newton iterations: Est = Est + Est (N - Arg * Est) 23156 // If this is the last iteration, also multiply by the numerator. 23157 for (int i = 0; i < Iterations; ++i) { 23158 SDValue MulEst = Est; 23159 23160 if (i == Iterations - 1) { 23161 MulEst = DAG.getNode(ISD::FMUL, DL, VT, N, Est, Flags); 23162 AddToWorklist(MulEst.getNode()); 23163 } 23164 23165 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, MulEst, Flags); 23166 AddToWorklist(NewEst.getNode()); 23167 23168 NewEst = DAG.getNode(ISD::FSUB, DL, VT, 23169 (i == Iterations - 1 ? N : FPOne), NewEst, Flags); 23170 AddToWorklist(NewEst.getNode()); 23171 23172 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 23173 AddToWorklist(NewEst.getNode()); 23174 23175 Est = DAG.getNode(ISD::FADD, DL, VT, MulEst, NewEst, Flags); 23176 AddToWorklist(Est.getNode()); 23177 } 23178 } else { 23179 // If no iterations are available, multiply with N. 23180 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, N, Flags); 23181 AddToWorklist(Est.getNode()); 23182 } 23183 23184 return Est; 23185 } 23186 23187 return SDValue(); 23188 } 23189 23190 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 23191 /// For the reciprocal sqrt, we need to find the zero of the function: 23192 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 23193 /// => 23194 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2) 23195 /// As a result, we precompute A/2 prior to the iteration loop. 23196 SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est, 23197 unsigned Iterations, 23198 SDNodeFlags Flags, bool Reciprocal) { 23199 EVT VT = Arg.getValueType(); 23200 SDLoc DL(Arg); 23201 SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT); 23202 23203 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that 23204 // this entire sequence requires only one FP constant. 23205 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags); 23206 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags); 23207 23208 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est) 23209 for (unsigned i = 0; i < Iterations; ++i) { 23210 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags); 23211 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags); 23212 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags); 23213 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags); 23214 } 23215 23216 // If non-reciprocal square root is requested, multiply the result by Arg. 23217 if (!Reciprocal) 23218 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags); 23219 23220 return Est; 23221 } 23222 23223 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i) 23224 /// For the reciprocal sqrt, we need to find the zero of the function: 23225 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)] 23226 /// => 23227 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0)) 23228 SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est, 23229 unsigned Iterations, 23230 SDNodeFlags Flags, bool Reciprocal) { 23231 EVT VT = Arg.getValueType(); 23232 SDLoc DL(Arg); 23233 SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT); 23234 SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT); 23235 23236 // This routine must enter the loop below to work correctly 23237 // when (Reciprocal == false). 23238 assert(Iterations > 0); 23239 23240 // Newton iterations for reciprocal square root: 23241 // E = (E * -0.5) * ((A * E) * E + -3.0) 23242 for (unsigned i = 0; i < Iterations; ++i) { 23243 SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags); 23244 SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags); 23245 SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags); 23246 23247 // When calculating a square root at the last iteration build: 23248 // S = ((A * E) * -0.5) * ((A * E) * E + -3.0) 23249 // (notice a common subexpression) 23250 SDValue LHS; 23251 if (Reciprocal || (i + 1) < Iterations) { 23252 // RSQRT: LHS = (E * -0.5) 23253 LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags); 23254 } else { 23255 // SQRT: LHS = (A * E) * -0.5 23256 LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags); 23257 } 23258 23259 Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags); 23260 } 23261 23262 return Est; 23263 } 23264 23265 /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case 23266 /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if 23267 /// Op can be zero. 23268 SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, 23269 bool Reciprocal) { 23270 if (LegalDAG) 23271 return SDValue(); 23272 23273 // TODO: Handle extended types? 23274 EVT VT = Op.getValueType(); 23275 if (VT.getScalarType() != MVT::f16 && VT.getScalarType() != MVT::f32 && 23276 VT.getScalarType() != MVT::f64) 23277 return SDValue(); 23278 23279 // If estimates are explicitly disabled for this function, we're done. 23280 MachineFunction &MF = DAG.getMachineFunction(); 23281 int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF); 23282 if (Enabled == TLI.ReciprocalEstimate::Disabled) 23283 return SDValue(); 23284 23285 // Estimates may be explicitly enabled for this type with a custom number of 23286 // refinement steps. 23287 int Iterations = TLI.getSqrtRefinementSteps(VT, MF); 23288 23289 bool UseOneConstNR = false; 23290 if (SDValue Est = 23291 TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR, 23292 Reciprocal)) { 23293 AddToWorklist(Est.getNode()); 23294 23295 if (Iterations) 23296 Est = UseOneConstNR 23297 ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal) 23298 : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal); 23299 if (!Reciprocal) { 23300 SDLoc DL(Op); 23301 // Try the target specific test first. 23302 SDValue Test = TLI.getSqrtInputTest(Op, DAG, DAG.getDenormalMode(VT)); 23303 23304 // The estimate is now completely wrong if the input was exactly 0.0 or 23305 // possibly a denormal. Force the answer to 0.0 or value provided by 23306 // target for those cases. 23307 Est = DAG.getNode( 23308 Test.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT, 23309 Test, TLI.getSqrtResultForDenormInput(Op, DAG), Est); 23310 } 23311 return Est; 23312 } 23313 23314 return SDValue(); 23315 } 23316 23317 SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) { 23318 return buildSqrtEstimateImpl(Op, Flags, true); 23319 } 23320 23321 SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) { 23322 return buildSqrtEstimateImpl(Op, Flags, false); 23323 } 23324 23325 /// Return true if there is any possibility that the two addresses overlap. 23326 bool DAGCombiner::mayAlias(SDNode *Op0, SDNode *Op1) const { 23327 23328 struct MemUseCharacteristics { 23329 bool IsVolatile; 23330 bool IsAtomic; 23331 SDValue BasePtr; 23332 int64_t Offset; 23333 Optional<int64_t> NumBytes; 23334 MachineMemOperand *MMO; 23335 }; 23336 23337 auto getCharacteristics = [](SDNode *N) -> MemUseCharacteristics { 23338 if (const auto *LSN = dyn_cast<LSBaseSDNode>(N)) { 23339 int64_t Offset = 0; 23340 if (auto *C = dyn_cast<ConstantSDNode>(LSN->getOffset())) 23341 Offset = (LSN->getAddressingMode() == ISD::PRE_INC) 23342 ? C->getSExtValue() 23343 : (LSN->getAddressingMode() == ISD::PRE_DEC) 23344 ? -1 * C->getSExtValue() 23345 : 0; 23346 uint64_t Size = 23347 MemoryLocation::getSizeOrUnknown(LSN->getMemoryVT().getStoreSize()); 23348 return {LSN->isVolatile(), LSN->isAtomic(), LSN->getBasePtr(), 23349 Offset /*base offset*/, 23350 Optional<int64_t>(Size), 23351 LSN->getMemOperand()}; 23352 } 23353 if (const auto *LN = cast<LifetimeSDNode>(N)) 23354 return {false /*isVolatile*/, /*isAtomic*/ false, LN->getOperand(1), 23355 (LN->hasOffset()) ? LN->getOffset() : 0, 23356 (LN->hasOffset()) ? Optional<int64_t>(LN->getSize()) 23357 : Optional<int64_t>(), 23358 (MachineMemOperand *)nullptr}; 23359 // Default. 23360 return {false /*isvolatile*/, /*isAtomic*/ false, SDValue(), 23361 (int64_t)0 /*offset*/, 23362 Optional<int64_t>() /*size*/, (MachineMemOperand *)nullptr}; 23363 }; 23364 23365 MemUseCharacteristics MUC0 = getCharacteristics(Op0), 23366 MUC1 = getCharacteristics(Op1); 23367 23368 // If they are to the same address, then they must be aliases. 23369 if (MUC0.BasePtr.getNode() && MUC0.BasePtr == MUC1.BasePtr && 23370 MUC0.Offset == MUC1.Offset) 23371 return true; 23372 23373 // If they are both volatile then they cannot be reordered. 23374 if (MUC0.IsVolatile && MUC1.IsVolatile) 23375 return true; 23376 23377 // Be conservative about atomics for the moment 23378 // TODO: This is way overconservative for unordered atomics (see D66309) 23379 if (MUC0.IsAtomic && MUC1.IsAtomic) 23380 return true; 23381 23382 if (MUC0.MMO && MUC1.MMO) { 23383 if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) || 23384 (MUC1.MMO->isInvariant() && MUC0.MMO->isStore())) 23385 return false; 23386 } 23387 23388 // Try to prove that there is aliasing, or that there is no aliasing. Either 23389 // way, we can return now. If nothing can be proved, proceed with more tests. 23390 bool IsAlias; 23391 if (BaseIndexOffset::computeAliasing(Op0, MUC0.NumBytes, Op1, MUC1.NumBytes, 23392 DAG, IsAlias)) 23393 return IsAlias; 23394 23395 // The following all rely on MMO0 and MMO1 being valid. Fail conservatively if 23396 // either are not known. 23397 if (!MUC0.MMO || !MUC1.MMO) 23398 return true; 23399 23400 // If one operation reads from invariant memory, and the other may store, they 23401 // cannot alias. These should really be checking the equivalent of mayWrite, 23402 // but it only matters for memory nodes other than load /store. 23403 if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) || 23404 (MUC1.MMO->isInvariant() && MUC0.MMO->isStore())) 23405 return false; 23406 23407 // If we know required SrcValue1 and SrcValue2 have relatively large 23408 // alignment compared to the size and offset of the access, we may be able 23409 // to prove they do not alias. This check is conservative for now to catch 23410 // cases created by splitting vector types, it only works when the offsets are 23411 // multiples of the size of the data. 23412 int64_t SrcValOffset0 = MUC0.MMO->getOffset(); 23413 int64_t SrcValOffset1 = MUC1.MMO->getOffset(); 23414 Align OrigAlignment0 = MUC0.MMO->getBaseAlign(); 23415 Align OrigAlignment1 = MUC1.MMO->getBaseAlign(); 23416 auto &Size0 = MUC0.NumBytes; 23417 auto &Size1 = MUC1.NumBytes; 23418 if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 && 23419 Size0.hasValue() && Size1.hasValue() && *Size0 == *Size1 && 23420 OrigAlignment0 > *Size0 && SrcValOffset0 % *Size0 == 0 && 23421 SrcValOffset1 % *Size1 == 0) { 23422 int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0.value(); 23423 int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1.value(); 23424 23425 // There is no overlap between these relatively aligned accesses of 23426 // similar size. Return no alias. 23427 if ((OffAlign0 + *Size0) <= OffAlign1 || (OffAlign1 + *Size1) <= OffAlign0) 23428 return false; 23429 } 23430 23431 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 23432 ? CombinerGlobalAA 23433 : DAG.getSubtarget().useAA(); 23434 #ifndef NDEBUG 23435 if (CombinerAAOnlyFunc.getNumOccurrences() && 23436 CombinerAAOnlyFunc != DAG.getMachineFunction().getName()) 23437 UseAA = false; 23438 #endif 23439 23440 if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() && 23441 Size0.hasValue() && Size1.hasValue()) { 23442 // Use alias analysis information. 23443 int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1); 23444 int64_t Overlap0 = *Size0 + SrcValOffset0 - MinOffset; 23445 int64_t Overlap1 = *Size1 + SrcValOffset1 - MinOffset; 23446 if (AA->isNoAlias( 23447 MemoryLocation(MUC0.MMO->getValue(), Overlap0, 23448 UseTBAA ? MUC0.MMO->getAAInfo() : AAMDNodes()), 23449 MemoryLocation(MUC1.MMO->getValue(), Overlap1, 23450 UseTBAA ? MUC1.MMO->getAAInfo() : AAMDNodes()))) 23451 return false; 23452 } 23453 23454 // Otherwise we have to assume they alias. 23455 return true; 23456 } 23457 23458 /// Walk up chain skipping non-aliasing memory nodes, 23459 /// looking for aliasing nodes and adding them to the Aliases vector. 23460 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain, 23461 SmallVectorImpl<SDValue> &Aliases) { 23462 SmallVector<SDValue, 8> Chains; // List of chains to visit. 23463 SmallPtrSet<SDNode *, 16> Visited; // Visited node set. 23464 23465 // Get alias information for node. 23466 // TODO: relax aliasing for unordered atomics (see D66309) 23467 const bool IsLoad = isa<LoadSDNode>(N) && cast<LoadSDNode>(N)->isSimple(); 23468 23469 // Starting off. 23470 Chains.push_back(OriginalChain); 23471 unsigned Depth = 0; 23472 23473 // Attempt to improve chain by a single step 23474 std::function<bool(SDValue &)> ImproveChain = [&](SDValue &C) -> bool { 23475 switch (C.getOpcode()) { 23476 case ISD::EntryToken: 23477 // No need to mark EntryToken. 23478 C = SDValue(); 23479 return true; 23480 case ISD::LOAD: 23481 case ISD::STORE: { 23482 // Get alias information for C. 23483 // TODO: Relax aliasing for unordered atomics (see D66309) 23484 bool IsOpLoad = isa<LoadSDNode>(C.getNode()) && 23485 cast<LSBaseSDNode>(C.getNode())->isSimple(); 23486 if ((IsLoad && IsOpLoad) || !mayAlias(N, C.getNode())) { 23487 // Look further up the chain. 23488 C = C.getOperand(0); 23489 return true; 23490 } 23491 // Alias, so stop here. 23492 return false; 23493 } 23494 23495 case ISD::CopyFromReg: 23496 // Always forward past past CopyFromReg. 23497 C = C.getOperand(0); 23498 return true; 23499 23500 case ISD::LIFETIME_START: 23501 case ISD::LIFETIME_END: { 23502 // We can forward past any lifetime start/end that can be proven not to 23503 // alias the memory access. 23504 if (!mayAlias(N, C.getNode())) { 23505 // Look further up the chain. 23506 C = C.getOperand(0); 23507 return true; 23508 } 23509 return false; 23510 } 23511 default: 23512 return false; 23513 } 23514 }; 23515 23516 // Look at each chain and determine if it is an alias. If so, add it to the 23517 // aliases list. If not, then continue up the chain looking for the next 23518 // candidate. 23519 while (!Chains.empty()) { 23520 SDValue Chain = Chains.pop_back_val(); 23521 23522 // Don't bother if we've seen Chain before. 23523 if (!Visited.insert(Chain.getNode()).second) 23524 continue; 23525 23526 // For TokenFactor nodes, look at each operand and only continue up the 23527 // chain until we reach the depth limit. 23528 // 23529 // FIXME: The depth check could be made to return the last non-aliasing 23530 // chain we found before we hit a tokenfactor rather than the original 23531 // chain. 23532 if (Depth > TLI.getGatherAllAliasesMaxDepth()) { 23533 Aliases.clear(); 23534 Aliases.push_back(OriginalChain); 23535 return; 23536 } 23537 23538 if (Chain.getOpcode() == ISD::TokenFactor) { 23539 // We have to check each of the operands of the token factor for "small" 23540 // token factors, so we queue them up. Adding the operands to the queue 23541 // (stack) in reverse order maintains the original order and increases the 23542 // likelihood that getNode will find a matching token factor (CSE.) 23543 if (Chain.getNumOperands() > 16) { 23544 Aliases.push_back(Chain); 23545 continue; 23546 } 23547 for (unsigned n = Chain.getNumOperands(); n;) 23548 Chains.push_back(Chain.getOperand(--n)); 23549 ++Depth; 23550 continue; 23551 } 23552 // Everything else 23553 if (ImproveChain(Chain)) { 23554 // Updated Chain Found, Consider new chain if one exists. 23555 if (Chain.getNode()) 23556 Chains.push_back(Chain); 23557 ++Depth; 23558 continue; 23559 } 23560 // No Improved Chain Possible, treat as Alias. 23561 Aliases.push_back(Chain); 23562 } 23563 } 23564 23565 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain 23566 /// (aliasing node.) 23567 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) { 23568 if (OptLevel == CodeGenOpt::None) 23569 return OldChain; 23570 23571 // Ops for replacing token factor. 23572 SmallVector<SDValue, 8> Aliases; 23573 23574 // Accumulate all the aliases to this node. 23575 GatherAllAliases(N, OldChain, Aliases); 23576 23577 // If no operands then chain to entry token. 23578 if (Aliases.size() == 0) 23579 return DAG.getEntryNode(); 23580 23581 // If a single operand then chain to it. We don't need to revisit it. 23582 if (Aliases.size() == 1) 23583 return Aliases[0]; 23584 23585 // Construct a custom tailored token factor. 23586 return DAG.getTokenFactor(SDLoc(N), Aliases); 23587 } 23588 23589 namespace { 23590 // TODO: Replace with with std::monostate when we move to C++17. 23591 struct UnitT { } Unit; 23592 bool operator==(const UnitT &, const UnitT &) { return true; } 23593 bool operator!=(const UnitT &, const UnitT &) { return false; } 23594 } // namespace 23595 23596 // This function tries to collect a bunch of potentially interesting 23597 // nodes to improve the chains of, all at once. This might seem 23598 // redundant, as this function gets called when visiting every store 23599 // node, so why not let the work be done on each store as it's visited? 23600 // 23601 // I believe this is mainly important because mergeConsecutiveStores 23602 // is unable to deal with merging stores of different sizes, so unless 23603 // we improve the chains of all the potential candidates up-front 23604 // before running mergeConsecutiveStores, it might only see some of 23605 // the nodes that will eventually be candidates, and then not be able 23606 // to go from a partially-merged state to the desired final 23607 // fully-merged state. 23608 23609 bool DAGCombiner::parallelizeChainedStores(StoreSDNode *St) { 23610 SmallVector<StoreSDNode *, 8> ChainedStores; 23611 StoreSDNode *STChain = St; 23612 // Intervals records which offsets from BaseIndex have been covered. In 23613 // the common case, every store writes to the immediately previous address 23614 // space and thus merged with the previous interval at insertion time. 23615 23616 using IMap = 23617 llvm::IntervalMap<int64_t, UnitT, 8, IntervalMapHalfOpenInfo<int64_t>>; 23618 IMap::Allocator A; 23619 IMap Intervals(A); 23620 23621 // This holds the base pointer, index, and the offset in bytes from the base 23622 // pointer. 23623 const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 23624 23625 // We must have a base and an offset. 23626 if (!BasePtr.getBase().getNode()) 23627 return false; 23628 23629 // Do not handle stores to undef base pointers. 23630 if (BasePtr.getBase().isUndef()) 23631 return false; 23632 23633 // Do not handle stores to opaque types 23634 if (St->getMemoryVT().isZeroSized()) 23635 return false; 23636 23637 // BaseIndexOffset assumes that offsets are fixed-size, which 23638 // is not valid for scalable vectors where the offsets are 23639 // scaled by `vscale`, so bail out early. 23640 if (St->getMemoryVT().isScalableVector()) 23641 return false; 23642 23643 // Add ST's interval. 23644 Intervals.insert(0, (St->getMemoryVT().getSizeInBits() + 7) / 8, Unit); 23645 23646 while (StoreSDNode *Chain = dyn_cast<StoreSDNode>(STChain->getChain())) { 23647 if (Chain->getMemoryVT().isScalableVector()) 23648 return false; 23649 23650 // If the chain has more than one use, then we can't reorder the mem ops. 23651 if (!SDValue(Chain, 0)->hasOneUse()) 23652 break; 23653 // TODO: Relax for unordered atomics (see D66309) 23654 if (!Chain->isSimple() || Chain->isIndexed()) 23655 break; 23656 23657 // Find the base pointer and offset for this memory node. 23658 const BaseIndexOffset Ptr = BaseIndexOffset::match(Chain, DAG); 23659 // Check that the base pointer is the same as the original one. 23660 int64_t Offset; 23661 if (!BasePtr.equalBaseIndex(Ptr, DAG, Offset)) 23662 break; 23663 int64_t Length = (Chain->getMemoryVT().getSizeInBits() + 7) / 8; 23664 // Make sure we don't overlap with other intervals by checking the ones to 23665 // the left or right before inserting. 23666 auto I = Intervals.find(Offset); 23667 // If there's a next interval, we should end before it. 23668 if (I != Intervals.end() && I.start() < (Offset + Length)) 23669 break; 23670 // If there's a previous interval, we should start after it. 23671 if (I != Intervals.begin() && (--I).stop() <= Offset) 23672 break; 23673 Intervals.insert(Offset, Offset + Length, Unit); 23674 23675 ChainedStores.push_back(Chain); 23676 STChain = Chain; 23677 } 23678 23679 // If we didn't find a chained store, exit. 23680 if (ChainedStores.size() == 0) 23681 return false; 23682 23683 // Improve all chained stores (St and ChainedStores members) starting from 23684 // where the store chain ended and return single TokenFactor. 23685 SDValue NewChain = STChain->getChain(); 23686 SmallVector<SDValue, 8> TFOps; 23687 for (unsigned I = ChainedStores.size(); I;) { 23688 StoreSDNode *S = ChainedStores[--I]; 23689 SDValue BetterChain = FindBetterChain(S, NewChain); 23690 S = cast<StoreSDNode>(DAG.UpdateNodeOperands( 23691 S, BetterChain, S->getOperand(1), S->getOperand(2), S->getOperand(3))); 23692 TFOps.push_back(SDValue(S, 0)); 23693 ChainedStores[I] = S; 23694 } 23695 23696 // Improve St's chain. Use a new node to avoid creating a loop from CombineTo. 23697 SDValue BetterChain = FindBetterChain(St, NewChain); 23698 SDValue NewST; 23699 if (St->isTruncatingStore()) 23700 NewST = DAG.getTruncStore(BetterChain, SDLoc(St), St->getValue(), 23701 St->getBasePtr(), St->getMemoryVT(), 23702 St->getMemOperand()); 23703 else 23704 NewST = DAG.getStore(BetterChain, SDLoc(St), St->getValue(), 23705 St->getBasePtr(), St->getMemOperand()); 23706 23707 TFOps.push_back(NewST); 23708 23709 // If we improved every element of TFOps, then we've lost the dependence on 23710 // NewChain to successors of St and we need to add it back to TFOps. Do so at 23711 // the beginning to keep relative order consistent with FindBetterChains. 23712 auto hasImprovedChain = [&](SDValue ST) -> bool { 23713 return ST->getOperand(0) != NewChain; 23714 }; 23715 bool AddNewChain = llvm::all_of(TFOps, hasImprovedChain); 23716 if (AddNewChain) 23717 TFOps.insert(TFOps.begin(), NewChain); 23718 23719 SDValue TF = DAG.getTokenFactor(SDLoc(STChain), TFOps); 23720 CombineTo(St, TF); 23721 23722 // Add TF and its operands to the worklist. 23723 AddToWorklist(TF.getNode()); 23724 for (const SDValue &Op : TF->ops()) 23725 AddToWorklist(Op.getNode()); 23726 AddToWorklist(STChain); 23727 return true; 23728 } 23729 23730 bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) { 23731 if (OptLevel == CodeGenOpt::None) 23732 return false; 23733 23734 const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG); 23735 23736 // We must have a base and an offset. 23737 if (!BasePtr.getBase().getNode()) 23738 return false; 23739 23740 // Do not handle stores to undef base pointers. 23741 if (BasePtr.getBase().isUndef()) 23742 return false; 23743 23744 // Directly improve a chain of disjoint stores starting at St. 23745 if (parallelizeChainedStores(St)) 23746 return true; 23747 23748 // Improve St's Chain.. 23749 SDValue BetterChain = FindBetterChain(St, St->getChain()); 23750 if (St->getChain() != BetterChain) { 23751 replaceStoreChain(St, BetterChain); 23752 return true; 23753 } 23754 return false; 23755 } 23756 23757 /// This is the entry point for the file. 23758 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA, 23759 CodeGenOpt::Level OptLevel) { 23760 /// This is the main entry point to this class. 23761 DAGCombiner(*this, AA, OptLevel).Run(Level); 23762 } 23763